hush.c 341 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * A prototype Bourne shell grammar parser.
  4. * Intended to follow the original Thompson and Ritchie
  5. * "small and simple is beautiful" philosophy, which
  6. * incidentally is a good match to today's BusyBox.
  7. *
  8. * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
  9. * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
  10. *
  11. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  12. *
  13. * Credits:
  14. * The parser routines proper are all original material, first
  15. * written Dec 2000 and Jan 2001 by Larry Doolittle. The
  16. * execution engine, the builtins, and much of the underlying
  17. * support has been adapted from busybox-0.49pre's lash, which is
  18. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  19. * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
  20. * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
  21. * Troan, which they placed in the public domain. I don't know
  22. * how much of the Johnson/Troan code has survived the repeated
  23. * rewrites.
  24. *
  25. * Other credits:
  26. * o_addchr derived from similar w_addchar function in glibc-2.2.
  27. * parse_redirect, redirect_opt_num, and big chunks of main
  28. * and many builtins derived from contributions by Erik Andersen.
  29. * Miscellaneous bugfixes from Matt Kraai.
  30. *
  31. * There are two big (and related) architecture differences between
  32. * this parser and the lash parser. One is that this version is
  33. * actually designed from the ground up to understand nearly all
  34. * of the Bourne grammar. The second, consequential change is that
  35. * the parser and input reader have been turned inside out. Now,
  36. * the parser is in control, and asks for input as needed. The old
  37. * way had the input reader in control, and it asked for parsing to
  38. * take place as needed. The new way makes it much easier to properly
  39. * handle the recursion implicit in the various substitutions, especially
  40. * across continuation lines.
  41. *
  42. * TODOs:
  43. * grep for "TODO" and fix (some of them are easy)
  44. * make complex ${var%...} constructs support optional
  45. * make here documents optional
  46. * special variables (done: PWD, PPID, RANDOM)
  47. * follow IFS rules more precisely, including update semantics
  48. * tilde expansion
  49. * aliases
  50. * "command" missing features:
  51. * command -p CMD: run CMD using default $PATH
  52. * (can use this to override standalone shell as well?)
  53. * command BLTIN: disables special-ness (e.g. errors do not abort)
  54. * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
  55. * builtins mandated by standards we don't support:
  56. * [un]alias, fc:
  57. * fc -l[nr] [BEG] [END]: list range of commands in history
  58. * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
  59. * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
  60. *
  61. * Bash compat TODO:
  62. * redirection of stdout+stderr: &> and >&
  63. * reserved words: function select
  64. * advanced test: [[ ]]
  65. * process substitution: <(list) and >(list)
  66. * let EXPR [EXPR...]
  67. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  68. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  69. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  70. * ((EXPR))
  71. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  72. * This is exactly equivalent to let "EXPR".
  73. * $[EXPR]: synonym for $((EXPR))
  74. * indirect expansion: ${!VAR}
  75. * substring op on @: ${@:n:m}
  76. *
  77. * Won't do:
  78. * Some builtins mandated by standards:
  79. * newgrp [GRP]: not a builtin in bash but a suid binary
  80. * which spawns a new shell with new group ID
  81. *
  82. * Status of [[ support:
  83. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  84. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  85. * [[ /bin/n* ]]; echo 0:$?
  86. * = is glob match operator, not equality operator: STR = GLOB
  87. * == same as =
  88. * =~ is regex match operator: STR =~ REGEX
  89. * TODO:
  90. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  91. * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
  92. */
  93. //config:config HUSH
  94. //config: bool "hush (70 kb)"
  95. //config: default y
  96. //config: select SHELL_HUSH
  97. //config: help
  98. //config: hush is a small shell. It handles the normal flow control
  99. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  100. //config: case/esac. Redirections, here documents, $((arithmetic))
  101. //config: and functions are supported.
  102. //config:
  103. //config: It will compile and work on no-mmu systems.
  104. //config:
  105. //config: It does not handle select, aliases, tilde expansion,
  106. //config: &>file and >&file redirection of stdout+stderr.
  107. //config:
  108. // This option is visible (has a description) to make it possible to select
  109. // a "scripted" applet (such as NOLOGIN) but avoid selecting any shells:
  110. //config:config SHELL_HUSH
  111. //config: bool "Internal shell for embedded script support"
  112. //config: default n
  113. //config:
  114. //config:# hush options
  115. //config:# It's only needed to get "nice" menuconfig indenting.
  116. //config:if SHELL_HUSH || HUSH || SH_IS_HUSH || BASH_IS_HUSH
  117. //config:
  118. //config:config HUSH_BASH_COMPAT
  119. //config: bool "bash-compatible extensions"
  120. //config: default y
  121. //config: depends on SHELL_HUSH
  122. //config:
  123. //config:config HUSH_BRACE_EXPANSION
  124. //config: bool "Brace expansion"
  125. //config: default y
  126. //config: depends on HUSH_BASH_COMPAT
  127. //config: help
  128. //config: Enable {abc,def} extension.
  129. //config:
  130. //config:config HUSH_BASH_SOURCE_CURDIR
  131. //config: bool "'source' and '.' builtins search current directory after $PATH"
  132. //config: default n # do not encourage non-standard behavior
  133. //config: depends on HUSH_BASH_COMPAT
  134. //config: help
  135. //config: This is not compliant with standards. Avoid if possible.
  136. //config:
  137. //config:config HUSH_LINENO_VAR
  138. //config: bool "$LINENO variable (bashism)"
  139. //config: default y
  140. //config: depends on SHELL_HUSH
  141. //config:
  142. //config:config HUSH_INTERACTIVE
  143. //config: bool "Interactive mode"
  144. //config: default y
  145. //config: depends on SHELL_HUSH
  146. //config: help
  147. //config: Enable interactive mode (prompt and command editing).
  148. //config: Without this, hush simply reads and executes commands
  149. //config: from stdin just like a shell script from a file.
  150. //config: No prompt, no PS1/PS2 magic shell variables.
  151. //config:
  152. //config:config HUSH_SAVEHISTORY
  153. //config: bool "Save command history to .hush_history"
  154. //config: default y
  155. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  156. //config:
  157. //config:config HUSH_JOB
  158. //config: bool "Job control"
  159. //config: default y
  160. //config: depends on HUSH_INTERACTIVE
  161. //config: help
  162. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  163. //config: command (not entire shell), fg/bg builtins work. Without this option,
  164. //config: "cmd &" still works by simply spawning a process and immediately
  165. //config: prompting for next command (or executing next command in a script),
  166. //config: but no separate process group is formed.
  167. //config:
  168. //config:config HUSH_TICK
  169. //config: bool "Support command substitution"
  170. //config: default y
  171. //config: depends on SHELL_HUSH
  172. //config: help
  173. //config: Enable `command` and $(command).
  174. //config:
  175. //config:config HUSH_IF
  176. //config: bool "Support if/then/elif/else/fi"
  177. //config: default y
  178. //config: depends on SHELL_HUSH
  179. //config:
  180. //config:config HUSH_LOOPS
  181. //config: bool "Support for, while and until loops"
  182. //config: default y
  183. //config: depends on SHELL_HUSH
  184. //config:
  185. //config:config HUSH_CASE
  186. //config: bool "Support case ... esac statement"
  187. //config: default y
  188. //config: depends on SHELL_HUSH
  189. //config: help
  190. //config: Enable case ... esac statement. +400 bytes.
  191. //config:
  192. //config:config HUSH_FUNCTIONS
  193. //config: bool "Support funcname() { commands; } syntax"
  194. //config: default y
  195. //config: depends on SHELL_HUSH
  196. //config: help
  197. //config: Enable support for shell functions. +800 bytes.
  198. //config:
  199. //config:config HUSH_LOCAL
  200. //config: bool "local builtin"
  201. //config: default y
  202. //config: depends on HUSH_FUNCTIONS
  203. //config: help
  204. //config: Enable support for local variables in functions.
  205. //config:
  206. //config:config HUSH_RANDOM_SUPPORT
  207. //config: bool "Pseudorandom generator and $RANDOM variable"
  208. //config: default y
  209. //config: depends on SHELL_HUSH
  210. //config: help
  211. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  212. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  213. //config:
  214. //config:config HUSH_MODE_X
  215. //config: bool "Support 'hush -x' option and 'set -x' command"
  216. //config: default y
  217. //config: depends on SHELL_HUSH
  218. //config: help
  219. //config: This instructs hush to print commands before execution.
  220. //config: Adds ~300 bytes.
  221. //config:
  222. //config:config HUSH_ECHO
  223. //config: bool "echo builtin"
  224. //config: default y
  225. //config: depends on SHELL_HUSH
  226. //config:
  227. //config:config HUSH_PRINTF
  228. //config: bool "printf builtin"
  229. //config: default y
  230. //config: depends on SHELL_HUSH
  231. //config:
  232. //config:config HUSH_TEST
  233. //config: bool "test builtin"
  234. //config: default y
  235. //config: depends on SHELL_HUSH
  236. //config:
  237. //config:config HUSH_HELP
  238. //config: bool "help builtin"
  239. //config: default y
  240. //config: depends on SHELL_HUSH
  241. //config:
  242. //config:config HUSH_EXPORT
  243. //config: bool "export builtin"
  244. //config: default y
  245. //config: depends on SHELL_HUSH
  246. //config:
  247. //config:config HUSH_EXPORT_N
  248. //config: bool "Support 'export -n' option"
  249. //config: default y
  250. //config: depends on HUSH_EXPORT
  251. //config: help
  252. //config: export -n unexports variables. It is a bash extension.
  253. //config:
  254. //config:config HUSH_READONLY
  255. //config: bool "readonly builtin"
  256. //config: default y
  257. //config: depends on SHELL_HUSH
  258. //config: help
  259. //config: Enable support for read-only variables.
  260. //config:
  261. //config:config HUSH_KILL
  262. //config: bool "kill builtin (supports kill %jobspec)"
  263. //config: default y
  264. //config: depends on SHELL_HUSH
  265. //config:
  266. //config:config HUSH_WAIT
  267. //config: bool "wait builtin"
  268. //config: default y
  269. //config: depends on SHELL_HUSH
  270. //config:
  271. //config:config HUSH_COMMAND
  272. //config: bool "command builtin"
  273. //config: default y
  274. //config: depends on SHELL_HUSH
  275. //config:
  276. //config:config HUSH_TRAP
  277. //config: bool "trap builtin"
  278. //config: default y
  279. //config: depends on SHELL_HUSH
  280. //config:
  281. //config:config HUSH_TYPE
  282. //config: bool "type builtin"
  283. //config: default y
  284. //config: depends on SHELL_HUSH
  285. //config:
  286. //config:config HUSH_TIMES
  287. //config: bool "times builtin"
  288. //config: default y
  289. //config: depends on SHELL_HUSH
  290. //config:
  291. //config:config HUSH_READ
  292. //config: bool "read builtin"
  293. //config: default y
  294. //config: depends on SHELL_HUSH
  295. //config:
  296. //config:config HUSH_SET
  297. //config: bool "set builtin"
  298. //config: default y
  299. //config: depends on SHELL_HUSH
  300. //config:
  301. //config:config HUSH_UNSET
  302. //config: bool "unset builtin"
  303. //config: default y
  304. //config: depends on SHELL_HUSH
  305. //config:
  306. //config:config HUSH_ULIMIT
  307. //config: bool "ulimit builtin"
  308. //config: default y
  309. //config: depends on SHELL_HUSH
  310. //config:
  311. //config:config HUSH_UMASK
  312. //config: bool "umask builtin"
  313. //config: default y
  314. //config: depends on SHELL_HUSH
  315. //config:
  316. //config:config HUSH_GETOPTS
  317. //config: bool "getopts builtin"
  318. //config: default y
  319. //config: depends on SHELL_HUSH
  320. //config:
  321. //config:config HUSH_MEMLEAK
  322. //config: bool "memleak builtin (debugging)"
  323. //config: default n
  324. //config: depends on SHELL_HUSH
  325. //config:
  326. //config:endif # hush options
  327. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  328. // APPLET_ODDNAME:name main location suid_type help
  329. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  330. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  331. //kbuild:lib-$(CONFIG_SHELL_HUSH) += hush.o match.o shell_common.o
  332. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  333. /* -i (interactive) is also accepted,
  334. * but does nothing, therefore not shown in help.
  335. * NOMMU-specific options are not meant to be used by users,
  336. * therefore we don't show them either.
  337. */
  338. //usage:#define hush_trivial_usage
  339. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 ARGS] | FILE ARGS | -s ARGS]"
  340. //usage:#define hush_full_usage "\n\n"
  341. //usage: "Unix shell interpreter"
  342. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  343. || defined(__APPLE__) \
  344. )
  345. # include <malloc.h> /* for malloc_trim */
  346. #endif
  347. #include <glob.h>
  348. /* #include <dmalloc.h> */
  349. #if ENABLE_HUSH_CASE
  350. # include <fnmatch.h>
  351. #endif
  352. #include <sys/times.h>
  353. #include <sys/utsname.h> /* for setting $HOSTNAME */
  354. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  355. #include "unicode.h"
  356. #include "shell_common.h"
  357. #include "math.h"
  358. #include "match.h"
  359. #if ENABLE_HUSH_RANDOM_SUPPORT
  360. # include "random.h"
  361. #else
  362. # define CLEAR_RANDOM_T(rnd) ((void)0)
  363. #endif
  364. #ifndef O_CLOEXEC
  365. # define O_CLOEXEC 0
  366. #endif
  367. #ifndef F_DUPFD_CLOEXEC
  368. # define F_DUPFD_CLOEXEC F_DUPFD
  369. #endif
  370. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !ENABLE_SHELL_ASH
  371. # include "embedded_scripts.h"
  372. #else
  373. # define NUM_SCRIPTS 0
  374. #endif
  375. /* So far, all bash compat is controlled by one config option */
  376. /* Separate defines document which part of code implements what */
  377. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  378. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  379. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  380. #define BASH_DOLLAR_SQUOTE ENABLE_HUSH_BASH_COMPAT
  381. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  382. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  383. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  384. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  385. /* Build knobs */
  386. #define LEAK_HUNTING 0
  387. #define BUILD_AS_NOMMU 0
  388. /* Enable/disable sanity checks. Ok to enable in production,
  389. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  390. * Keeping 1 for now even in released versions.
  391. */
  392. #define HUSH_DEBUG 1
  393. /* Slightly bigger (+200 bytes), but faster hush.
  394. * So far it only enables a trick with counting SIGCHLDs and forks,
  395. * which allows us to do fewer waitpid's.
  396. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  397. * and therefore waitpid will return the same result as last time)
  398. */
  399. #define ENABLE_HUSH_FAST 0
  400. /* TODO: implement simplified code for users which do not need ${var%...} ops
  401. * So far ${var%...} ops are always enabled:
  402. */
  403. #define ENABLE_HUSH_DOLLAR_OPS 1
  404. #if BUILD_AS_NOMMU
  405. # undef BB_MMU
  406. # undef USE_FOR_NOMMU
  407. # undef USE_FOR_MMU
  408. # define BB_MMU 0
  409. # define USE_FOR_NOMMU(...) __VA_ARGS__
  410. # define USE_FOR_MMU(...)
  411. #endif
  412. #include "NUM_APPLETS.h"
  413. #if NUM_APPLETS == 1
  414. /* STANDALONE does not make sense, and won't compile */
  415. # undef CONFIG_FEATURE_SH_STANDALONE
  416. # undef ENABLE_FEATURE_SH_STANDALONE
  417. # undef IF_FEATURE_SH_STANDALONE
  418. # undef IF_NOT_FEATURE_SH_STANDALONE
  419. # define ENABLE_FEATURE_SH_STANDALONE 0
  420. # define IF_FEATURE_SH_STANDALONE(...)
  421. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  422. #endif
  423. #if !ENABLE_HUSH_INTERACTIVE
  424. # undef ENABLE_FEATURE_EDITING
  425. # define ENABLE_FEATURE_EDITING 0
  426. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  427. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  428. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  429. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  430. #endif
  431. /* Do we support ANY keywords? */
  432. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  433. # define HAS_KEYWORDS 1
  434. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  435. # define IF_HAS_NO_KEYWORDS(...)
  436. #else
  437. # define HAS_KEYWORDS 0
  438. # define IF_HAS_KEYWORDS(...)
  439. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  440. #endif
  441. /* If you comment out one of these below, it will be #defined later
  442. * to perform debug printfs to stderr: */
  443. #define debug_printf(...) do {} while (0)
  444. /* Finer-grained debug switches */
  445. #define debug_printf_parse(...) do {} while (0)
  446. #define debug_printf_heredoc(...) do {} while (0)
  447. #define debug_print_tree(a, b) do {} while (0)
  448. #define debug_printf_exec(...) do {} while (0)
  449. #define debug_printf_env(...) do {} while (0)
  450. #define debug_printf_jobs(...) do {} while (0)
  451. #define debug_printf_expand(...) do {} while (0)
  452. #define debug_printf_varexp(...) do {} while (0)
  453. #define debug_printf_glob(...) do {} while (0)
  454. #define debug_printf_redir(...) do {} while (0)
  455. #define debug_printf_list(...) do {} while (0)
  456. #define debug_printf_subst(...) do {} while (0)
  457. #define debug_printf_prompt(...) do {} while (0)
  458. #define debug_printf_clean(...) do {} while (0)
  459. #define ERR_PTR ((void*)(long)1)
  460. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  461. #define _SPECIAL_VARS_STR "_*@$!?#-"
  462. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  463. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  464. #if BASH_PATTERN_SUBST
  465. /* Support / and // replace ops */
  466. /* Note that // is stored as \ in "encoded" string representation */
  467. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  468. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  469. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  470. #else
  471. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  472. # define VAR_SUBST_OPS "%#:-=+?"
  473. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  474. #endif
  475. #define SPECIAL_VAR_SYMBOL_STR "\3"
  476. #define SPECIAL_VAR_SYMBOL 3
  477. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  478. #define SPECIAL_VAR_QUOTED_SVS 1
  479. struct variable;
  480. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  481. /* This supports saving pointers malloced in vfork child,
  482. * to be freed in the parent.
  483. */
  484. #if !BB_MMU
  485. typedef struct nommu_save_t {
  486. struct variable *old_vars;
  487. char **argv;
  488. char **argv_from_re_execing;
  489. } nommu_save_t;
  490. #endif
  491. enum {
  492. RES_NONE = 0,
  493. #if ENABLE_HUSH_IF
  494. RES_IF ,
  495. RES_THEN ,
  496. RES_ELIF ,
  497. RES_ELSE ,
  498. RES_FI ,
  499. #endif
  500. #if ENABLE_HUSH_LOOPS
  501. RES_FOR ,
  502. RES_WHILE ,
  503. RES_UNTIL ,
  504. RES_DO ,
  505. RES_DONE ,
  506. #endif
  507. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  508. RES_IN ,
  509. #endif
  510. #if ENABLE_HUSH_CASE
  511. RES_CASE ,
  512. /* three pseudo-keywords support contrived "case" syntax: */
  513. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  514. RES_MATCH , /* "word)" */
  515. RES_CASE_BODY, /* "this command is inside CASE" */
  516. RES_ESAC ,
  517. #endif
  518. RES_XXXX ,
  519. RES_SNTX
  520. };
  521. typedef struct o_string {
  522. char *data;
  523. int length; /* position where data is appended */
  524. int maxlen;
  525. int o_expflags;
  526. /* At least some part of the string was inside '' or "",
  527. * possibly empty one: word"", wo''rd etc. */
  528. smallint has_quoted_part;
  529. smallint has_empty_slot;
  530. smallint ended_in_ifs;
  531. } o_string;
  532. enum {
  533. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  534. EXP_FLAG_GLOB = 0x2,
  535. /* Protect newly added chars against globbing
  536. * by prepending \ to *, ?, [, \ */
  537. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  538. };
  539. /* Used for initialization: o_string foo = NULL_O_STRING; */
  540. #define NULL_O_STRING { NULL }
  541. #ifndef debug_printf_parse
  542. static const char *const assignment_flag[] ALIGN_PTR = {
  543. "MAYBE_ASSIGNMENT",
  544. "DEFINITELY_ASSIGNMENT",
  545. "NOT_ASSIGNMENT",
  546. "WORD_IS_KEYWORD",
  547. };
  548. #endif
  549. /* We almost can use standard FILE api, but we need an ability to move
  550. * its fd when redirects coincide with it. No api exists for that
  551. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  552. * HFILE is our internal alternative. Only supports reading.
  553. * Since we now can, we incorporate linked list of all opened HFILEs
  554. * into the struct (used to be a separate mini-list).
  555. */
  556. typedef struct HFILE {
  557. char *cur;
  558. char *end;
  559. struct HFILE *next_hfile;
  560. int fd;
  561. char buf[1024];
  562. } HFILE;
  563. typedef struct in_str {
  564. const char *p;
  565. int peek_buf[2];
  566. int last_char;
  567. HFILE *file;
  568. } in_str;
  569. /* The descrip member of this structure is only used to make
  570. * debugging output pretty */
  571. static const struct {
  572. int32_t mode;
  573. signed char default_fd;
  574. char descrip[3];
  575. } redir_table[] ALIGN4 = {
  576. { O_RDONLY, 0, "<" },
  577. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  578. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  579. { O_CREAT|O_RDWR, 1, "<>" },
  580. { O_RDONLY, 0, "<<" },
  581. /* Should not be needed. Bogus default_fd helps in debugging */
  582. /* { O_RDONLY, 77, "<<" }, */
  583. };
  584. struct redir_struct {
  585. struct redir_struct *next;
  586. char *rd_filename; /* filename */
  587. int rd_fd; /* fd to redirect */
  588. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  589. int rd_dup;
  590. smallint rd_type; /* (enum redir_type) */
  591. /* note: for heredocs, rd_filename contains heredoc delimiter,
  592. * and subsequently heredoc itself; and rd_dup is a bitmask:
  593. * bit 0: do we need to trim leading tabs?
  594. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  595. */
  596. };
  597. typedef enum redir_type {
  598. REDIRECT_INPUT = 0,
  599. REDIRECT_OVERWRITE = 1,
  600. REDIRECT_APPEND = 2,
  601. REDIRECT_IO = 3,
  602. REDIRECT_HEREDOC = 4,
  603. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  604. REDIRFD_CLOSE = -3,
  605. REDIRFD_SYNTAX_ERR = -2,
  606. REDIRFD_TO_FILE = -1,
  607. /* otherwise, rd_fd is redirected to rd_dup */
  608. HEREDOC_SKIPTABS = 1,
  609. HEREDOC_QUOTED = 2,
  610. } redir_type;
  611. struct command {
  612. pid_t pid; /* 0 if exited */
  613. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  614. #if ENABLE_HUSH_LINENO_VAR
  615. unsigned lineno;
  616. #endif
  617. smallint cmd_type; /* CMD_xxx */
  618. #define CMD_NORMAL 0
  619. #define CMD_SUBSHELL 1
  620. #if BASH_TEST2
  621. /* used for "[[ EXPR ]]" */
  622. # define CMD_TEST2_SINGLEWORD_NOGLOB 2
  623. #endif
  624. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  625. /* used to prevent word splitting and globbing in "export v=t*" */
  626. # define CMD_SINGLEWORD_NOGLOB 3
  627. #endif
  628. #if ENABLE_HUSH_FUNCTIONS
  629. # define CMD_FUNCDEF 4
  630. #endif
  631. smalluint cmd_exitcode;
  632. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  633. struct pipe *group;
  634. #if !BB_MMU
  635. char *group_as_string;
  636. #endif
  637. #if ENABLE_HUSH_FUNCTIONS
  638. struct function *child_func;
  639. /* This field is used to prevent a bug here:
  640. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  641. * When we execute "f1() {a;}" cmd, we create new function and clear
  642. * cmd->group, cmd->group_as_string, cmd->argv[0].
  643. * When we execute "f1() {b;}", we notice that f1 exists,
  644. * and that its "parent cmd" struct is still "alive",
  645. * we put those fields back into cmd->xxx
  646. * (struct function has ->parent_cmd ptr to facilitate that).
  647. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  648. * Without this trick, loop would execute a;b;b;b;...
  649. * instead of correct sequence a;b;a;b;...
  650. * When command is freed, it severs the link
  651. * (sets ->child_func->parent_cmd to NULL).
  652. */
  653. #endif
  654. char **argv; /* command name and arguments */
  655. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  656. * and on execution these are substituted with their values.
  657. * Substitution can make _several_ words out of one argv[n]!
  658. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  659. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  660. */
  661. struct redir_struct *redirects; /* I/O redirections */
  662. };
  663. /* Is there anything in this command at all? */
  664. #define IS_NULL_CMD(cmd) \
  665. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  666. struct pipe {
  667. struct pipe *next;
  668. int num_cmds; /* total number of commands in pipe */
  669. int alive_cmds; /* number of commands running (not exited) */
  670. int stopped_cmds; /* number of commands alive, but stopped */
  671. #if ENABLE_HUSH_JOB
  672. unsigned jobid; /* job number */
  673. pid_t pgrp; /* process group ID for the job */
  674. char *cmdtext; /* name of job */
  675. #endif
  676. struct command *cmds; /* array of commands in pipe */
  677. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  678. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  679. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  680. };
  681. typedef enum pipe_style {
  682. PIPE_SEQ = 0,
  683. PIPE_AND = 1,
  684. PIPE_OR = 2,
  685. PIPE_BG = 3,
  686. } pipe_style;
  687. /* Is there anything in this pipe at all? */
  688. #define IS_NULL_PIPE(pi) \
  689. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  690. /* This holds pointers to the various results of parsing */
  691. struct parse_context {
  692. /* linked list of pipes */
  693. struct pipe *list_head;
  694. /* last pipe (being constructed right now) */
  695. struct pipe *pipe;
  696. /* last command in pipe (being constructed right now) */
  697. struct command *command;
  698. /* last redirect in command->redirects list */
  699. struct redir_struct *pending_redirect;
  700. o_string word;
  701. #if !BB_MMU
  702. o_string as_string;
  703. #endif
  704. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  705. #if HAS_KEYWORDS
  706. smallint ctx_res_w;
  707. smallint ctx_inverted; /* "! cmd | cmd" */
  708. #if ENABLE_HUSH_CASE
  709. smallint ctx_dsemicolon; /* ";;" seen */
  710. #endif
  711. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  712. int old_flag;
  713. /* group we are enclosed in:
  714. * example: "if pipe1; pipe2; then pipe3; fi"
  715. * when we see "if" or "then", we malloc and copy current context,
  716. * and make ->stack point to it. then we parse pipeN.
  717. * when closing "then" / fi" / whatever is found,
  718. * we move list_head into ->stack->command->group,
  719. * copy ->stack into current context, and delete ->stack.
  720. * (parsing of { list } and ( list ) doesn't use this method)
  721. */
  722. struct parse_context *stack;
  723. #endif
  724. };
  725. enum {
  726. MAYBE_ASSIGNMENT = 0,
  727. DEFINITELY_ASSIGNMENT = 1,
  728. NOT_ASSIGNMENT = 2,
  729. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  730. WORD_IS_KEYWORD = 3,
  731. };
  732. /* On program start, environ points to initial environment.
  733. * putenv adds new pointers into it, unsetenv removes them.
  734. * Neither of these (de)allocates the strings.
  735. * setenv allocates new strings in malloc space and does putenv,
  736. * and thus setenv is unusable (leaky) for shell's purposes */
  737. #define setenv(...) setenv_is_leaky_dont_use()
  738. struct variable {
  739. struct variable *next;
  740. char *varstr; /* points to "name=" portion */
  741. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  742. uint16_t var_nest_level;
  743. smallint flg_export; /* putenv should be done on this var */
  744. smallint flg_read_only;
  745. };
  746. enum {
  747. BC_BREAK = 1,
  748. BC_CONTINUE = 2,
  749. };
  750. #if ENABLE_HUSH_FUNCTIONS
  751. struct function {
  752. struct function *next;
  753. char *name;
  754. struct command *parent_cmd;
  755. struct pipe *body;
  756. # if !BB_MMU
  757. char *body_as_string;
  758. # endif
  759. };
  760. #endif
  761. /* set -/+o OPT support. (TODO: make it optional)
  762. * bash supports the following opts:
  763. * allexport off
  764. * braceexpand on
  765. * emacs on
  766. * errexit off
  767. * errtrace off
  768. * functrace off
  769. * hashall on
  770. * histexpand off
  771. * history on
  772. * ignoreeof off
  773. * interactive-comments on
  774. * keyword off
  775. * monitor on
  776. * noclobber off
  777. * noexec off
  778. * noglob off
  779. * nolog off
  780. * notify off
  781. * nounset off
  782. * onecmd off
  783. * physical off
  784. * pipefail off
  785. * posix off
  786. * privileged off
  787. * verbose off
  788. * vi off
  789. * xtrace off
  790. */
  791. static const char o_opt_strings[] ALIGN1 =
  792. "pipefail\0"
  793. "noexec\0"
  794. "errexit\0"
  795. #if ENABLE_HUSH_MODE_X
  796. "xtrace\0"
  797. #endif
  798. ;
  799. enum {
  800. OPT_O_PIPEFAIL,
  801. OPT_O_NOEXEC,
  802. OPT_O_ERREXIT,
  803. #if ENABLE_HUSH_MODE_X
  804. OPT_O_XTRACE,
  805. #endif
  806. NUM_OPT_O
  807. };
  808. /* "Globals" within this file */
  809. /* Sorted roughly by size (smaller offsets == smaller code) */
  810. struct globals {
  811. /* interactive_fd != 0 means we are an interactive shell.
  812. * If we are, then saved_tty_pgrp can also be != 0, meaning
  813. * that controlling tty is available. With saved_tty_pgrp == 0,
  814. * job control still works, but terminal signals
  815. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  816. * process groups can only be created with "cmd &".
  817. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  818. * to give tty to the foreground process group,
  819. * and will take it back when the group is stopped (^Z)
  820. * or killed (^C).
  821. */
  822. #if ENABLE_HUSH_INTERACTIVE
  823. /* 'interactive_fd' is a fd# open to ctty, if we have one
  824. * _AND_ if we decided to act interactively */
  825. int interactive_fd;
  826. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  827. # define G_interactive_fd (G.interactive_fd)
  828. #else
  829. # define G_interactive_fd 0
  830. #endif
  831. #if ENABLE_FEATURE_EDITING
  832. line_input_t *line_input_state;
  833. #endif
  834. pid_t root_pid;
  835. pid_t root_ppid;
  836. pid_t last_bg_pid;
  837. #if ENABLE_HUSH_RANDOM_SUPPORT
  838. random_t random_gen;
  839. #endif
  840. #if ENABLE_HUSH_JOB
  841. int run_list_level;
  842. unsigned last_jobid;
  843. pid_t saved_tty_pgrp;
  844. struct pipe *job_list;
  845. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  846. #else
  847. # define G_saved_tty_pgrp 0
  848. #endif
  849. /* How deeply are we in context where "set -e" is ignored */
  850. int errexit_depth;
  851. /* "set -e" rules (do we follow them correctly?):
  852. * Exit if pipe, list, or compound command exits with a non-zero status.
  853. * Shell does not exit if failed command is part of condition in
  854. * if/while, part of && or || list except the last command, any command
  855. * in a pipe but the last, or if the command's return value is being
  856. * inverted with !. If a compound command other than a subshell returns a
  857. * non-zero status because a command failed while -e was being ignored, the
  858. * shell does not exit. A trap on ERR, if set, is executed before the shell
  859. * exits [ERR is a bashism].
  860. *
  861. * If a compound command or function executes in a context where -e is
  862. * ignored, none of the commands executed within are affected by the -e
  863. * setting. If a compound command or function sets -e while executing in a
  864. * context where -e is ignored, that setting does not have any effect until
  865. * the compound command or the command containing the function call completes.
  866. */
  867. char o_opt[NUM_OPT_O];
  868. #if ENABLE_HUSH_MODE_X
  869. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  870. #else
  871. # define G_x_mode 0
  872. #endif
  873. char opt_s;
  874. char opt_c;
  875. #if ENABLE_HUSH_INTERACTIVE
  876. smallint promptmode; /* 0: PS1, 1: PS2 */
  877. #endif
  878. /* set by signal handler if SIGINT is received _and_ its trap is not set */
  879. smallint flag_SIGINT;
  880. #if ENABLE_HUSH_LOOPS
  881. smallint flag_break_continue;
  882. #endif
  883. #if ENABLE_HUSH_FUNCTIONS
  884. /* 0: outside of a function (or sourced file)
  885. * -1: inside of a function, ok to use return builtin
  886. * 1: return is invoked, skip all till end of func
  887. */
  888. smallint flag_return_in_progress;
  889. # define G_flag_return_in_progress (G.flag_return_in_progress)
  890. #else
  891. # define G_flag_return_in_progress 0
  892. #endif
  893. smallint exiting; /* used to prevent EXIT trap recursion */
  894. /* These support $? */
  895. smalluint last_exitcode;
  896. smalluint expand_exitcode;
  897. smalluint last_bg_pid_exitcode;
  898. #if ENABLE_HUSH_SET
  899. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  900. smalluint global_args_malloced;
  901. # define G_global_args_malloced (G.global_args_malloced)
  902. #else
  903. # define G_global_args_malloced 0
  904. #endif
  905. #if ENABLE_HUSH_BASH_COMPAT
  906. int dead_job_exitcode; /* for "wait -n" */
  907. #endif
  908. /* how many non-NULL argv's we have. NB: $# + 1 */
  909. int global_argc;
  910. char **global_argv;
  911. #if !BB_MMU
  912. char *argv0_for_re_execing;
  913. #endif
  914. #if ENABLE_HUSH_LOOPS
  915. unsigned depth_break_continue;
  916. unsigned depth_of_loop;
  917. #endif
  918. #if ENABLE_HUSH_GETOPTS
  919. unsigned getopt_count;
  920. #endif
  921. const char *ifs;
  922. char *ifs_whitespace; /* = G.ifs or malloced */
  923. const char *cwd;
  924. struct variable *top_var;
  925. char **expanded_assignments;
  926. struct variable **shadowed_vars_pp;
  927. unsigned var_nest_level;
  928. #if ENABLE_HUSH_FUNCTIONS
  929. # if ENABLE_HUSH_LOCAL
  930. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  931. # endif
  932. struct function *top_func;
  933. #endif
  934. /* Signal and trap handling */
  935. #if ENABLE_HUSH_FAST
  936. unsigned count_SIGCHLD;
  937. unsigned handled_SIGCHLD;
  938. smallint we_have_children;
  939. #endif
  940. #if ENABLE_HUSH_LINENO_VAR
  941. unsigned parse_lineno;
  942. unsigned execute_lineno;
  943. #endif
  944. HFILE *HFILE_list;
  945. HFILE *HFILE_stdin;
  946. /* Which signals have non-DFL handler (even with no traps set)?
  947. * Set at the start to:
  948. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  949. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  950. * The rest is cleared right before execv syscalls.
  951. * Other than these two times, never modified.
  952. */
  953. unsigned special_sig_mask;
  954. #if ENABLE_HUSH_JOB
  955. unsigned fatal_sig_mask;
  956. # define G_fatal_sig_mask (G.fatal_sig_mask)
  957. #else
  958. # define G_fatal_sig_mask 0
  959. #endif
  960. #if ENABLE_HUSH_TRAP
  961. int pre_trap_exitcode;
  962. # if ENABLE_HUSH_FUNCTIONS
  963. int return_exitcode;
  964. # endif
  965. char **traps; /* char *traps[NSIG] */
  966. # define G_traps G.traps
  967. #else
  968. # define G_traps ((char**)NULL)
  969. #endif
  970. sigset_t pending_set;
  971. #if ENABLE_HUSH_MEMLEAK
  972. unsigned long memleak_value;
  973. #endif
  974. #if ENABLE_HUSH_MODE_X
  975. unsigned x_mode_depth;
  976. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  977. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  978. * for all subsequent output.
  979. */
  980. int x_mode_fd;
  981. o_string x_mode_buf;
  982. #endif
  983. #if HUSH_DEBUG >= 2
  984. int debug_indent;
  985. #endif
  986. struct sigaction sa;
  987. char optstring_buf[sizeof("eixcs")];
  988. #if BASH_EPOCH_VARS
  989. char epoch_buf[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
  990. #endif
  991. #if ENABLE_FEATURE_EDITING
  992. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  993. #endif
  994. };
  995. #define G (*ptr_to_globals)
  996. /* Not #defining name to G.name - this quickly gets unwieldy
  997. * (too many defines). Also, I actually prefer to see when a variable
  998. * is global, thus "G." prefix is a useful hint */
  999. #define INIT_G() do { \
  1000. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  1001. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  1002. sigfillset(&G.sa.sa_mask); \
  1003. G.sa.sa_flags = SA_RESTART; \
  1004. } while (0)
  1005. /* Function prototypes for builtins */
  1006. static int builtin_cd(char **argv) FAST_FUNC;
  1007. #if ENABLE_HUSH_ECHO
  1008. static int builtin_echo(char **argv) FAST_FUNC;
  1009. #endif
  1010. static int builtin_eval(char **argv) FAST_FUNC;
  1011. static int builtin_exec(char **argv) FAST_FUNC;
  1012. static int builtin_exit(char **argv) FAST_FUNC;
  1013. #if ENABLE_HUSH_EXPORT
  1014. static int builtin_export(char **argv) FAST_FUNC;
  1015. #endif
  1016. #if ENABLE_HUSH_READONLY
  1017. static int builtin_readonly(char **argv) FAST_FUNC;
  1018. #endif
  1019. static int builtin_false(char **argv) FAST_FUNC;
  1020. #if ENABLE_HUSH_JOB
  1021. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1022. static int builtin_jobs(char **argv) FAST_FUNC;
  1023. #endif
  1024. #if ENABLE_HUSH_GETOPTS
  1025. static int builtin_getopts(char **argv) FAST_FUNC;
  1026. #endif
  1027. #if ENABLE_HUSH_HELP
  1028. static int builtin_help(char **argv) FAST_FUNC;
  1029. #endif
  1030. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1031. static int builtin_history(char **argv) FAST_FUNC;
  1032. #endif
  1033. #if ENABLE_HUSH_LOCAL
  1034. static int builtin_local(char **argv) FAST_FUNC;
  1035. #endif
  1036. #if ENABLE_HUSH_MEMLEAK
  1037. static int builtin_memleak(char **argv) FAST_FUNC;
  1038. #endif
  1039. #if ENABLE_HUSH_PRINTF
  1040. static int builtin_printf(char **argv) FAST_FUNC;
  1041. #endif
  1042. static int builtin_pwd(char **argv) FAST_FUNC;
  1043. #if ENABLE_HUSH_READ
  1044. static int builtin_read(char **argv) FAST_FUNC;
  1045. #endif
  1046. #if ENABLE_HUSH_SET
  1047. static int builtin_set(char **argv) FAST_FUNC;
  1048. #endif
  1049. static int builtin_shift(char **argv) FAST_FUNC;
  1050. static int builtin_source(char **argv) FAST_FUNC;
  1051. #if ENABLE_HUSH_TEST || BASH_TEST2
  1052. static int builtin_test(char **argv) FAST_FUNC;
  1053. #endif
  1054. #if ENABLE_HUSH_TRAP
  1055. static int builtin_trap(char **argv) FAST_FUNC;
  1056. #endif
  1057. #if ENABLE_HUSH_TYPE
  1058. static int builtin_type(char **argv) FAST_FUNC;
  1059. #endif
  1060. #if ENABLE_HUSH_TIMES
  1061. static int builtin_times(char **argv) FAST_FUNC;
  1062. #endif
  1063. static int builtin_true(char **argv) FAST_FUNC;
  1064. #if ENABLE_HUSH_UMASK
  1065. static int builtin_umask(char **argv) FAST_FUNC;
  1066. #endif
  1067. #if ENABLE_HUSH_UNSET
  1068. static int builtin_unset(char **argv) FAST_FUNC;
  1069. #endif
  1070. #if ENABLE_HUSH_KILL
  1071. static int builtin_kill(char **argv) FAST_FUNC;
  1072. #endif
  1073. #if ENABLE_HUSH_WAIT
  1074. static int builtin_wait(char **argv) FAST_FUNC;
  1075. #endif
  1076. #if ENABLE_HUSH_LOOPS
  1077. static int builtin_break(char **argv) FAST_FUNC;
  1078. static int builtin_continue(char **argv) FAST_FUNC;
  1079. #endif
  1080. #if ENABLE_HUSH_FUNCTIONS
  1081. static int builtin_return(char **argv) FAST_FUNC;
  1082. #endif
  1083. /* Table of built-in functions. They can be forked or not, depending on
  1084. * context: within pipes, they fork. As simple commands, they do not.
  1085. * When used in non-forking context, they can change global variables
  1086. * in the parent shell process. If forked, of course they cannot.
  1087. * For example, 'unset foo | whatever' will parse and run, but foo will
  1088. * still be set at the end. */
  1089. struct built_in_command {
  1090. const char *b_cmd;
  1091. int (*b_function)(char **argv) FAST_FUNC;
  1092. #if ENABLE_HUSH_HELP
  1093. const char *b_descr;
  1094. # define BLTIN(cmd, func, help) { cmd, func, help }
  1095. #else
  1096. # define BLTIN(cmd, func, help) { cmd, func }
  1097. #endif
  1098. };
  1099. static const struct built_in_command bltins1[] ALIGN_PTR = {
  1100. BLTIN("." , builtin_source , "Run commands in file"),
  1101. BLTIN(":" , builtin_true , NULL),
  1102. #if ENABLE_HUSH_JOB
  1103. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1104. #endif
  1105. #if ENABLE_HUSH_LOOPS
  1106. BLTIN("break" , builtin_break , "Exit loop"),
  1107. #endif
  1108. BLTIN("cd" , builtin_cd , "Change directory"),
  1109. #if ENABLE_HUSH_LOOPS
  1110. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1111. #endif
  1112. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1113. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1114. BLTIN("exit" , builtin_exit , NULL),
  1115. #if ENABLE_HUSH_EXPORT
  1116. BLTIN("export" , builtin_export , "Set environment variables"),
  1117. #endif
  1118. BLTIN("false" , builtin_false , NULL),
  1119. #if ENABLE_HUSH_JOB
  1120. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1121. #endif
  1122. #if ENABLE_HUSH_GETOPTS
  1123. BLTIN("getopts" , builtin_getopts , NULL),
  1124. #endif
  1125. #if ENABLE_HUSH_HELP
  1126. BLTIN("help" , builtin_help , NULL),
  1127. #endif
  1128. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1129. BLTIN("history" , builtin_history , "Show history"),
  1130. #endif
  1131. #if ENABLE_HUSH_JOB
  1132. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1133. #endif
  1134. #if ENABLE_HUSH_KILL
  1135. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1136. #endif
  1137. #if ENABLE_HUSH_LOCAL
  1138. BLTIN("local" , builtin_local , "Set local variables"),
  1139. #endif
  1140. #if ENABLE_HUSH_MEMLEAK
  1141. BLTIN("memleak" , builtin_memleak , NULL),
  1142. #endif
  1143. #if ENABLE_HUSH_READ
  1144. BLTIN("read" , builtin_read , "Input into variable"),
  1145. #endif
  1146. #if ENABLE_HUSH_READONLY
  1147. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1148. #endif
  1149. #if ENABLE_HUSH_FUNCTIONS
  1150. BLTIN("return" , builtin_return , "Return from function"),
  1151. #endif
  1152. #if ENABLE_HUSH_SET
  1153. BLTIN("set" , builtin_set , "Set positional parameters"),
  1154. #endif
  1155. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1156. #if BASH_SOURCE
  1157. BLTIN("source" , builtin_source , NULL),
  1158. #endif
  1159. #if ENABLE_HUSH_TIMES
  1160. BLTIN("times" , builtin_times , NULL),
  1161. #endif
  1162. #if ENABLE_HUSH_TRAP
  1163. BLTIN("trap" , builtin_trap , "Trap signals"),
  1164. #endif
  1165. BLTIN("true" , builtin_true , NULL),
  1166. #if ENABLE_HUSH_TYPE
  1167. BLTIN("type" , builtin_type , "Show command type"),
  1168. #endif
  1169. #if ENABLE_HUSH_ULIMIT
  1170. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1171. #endif
  1172. #if ENABLE_HUSH_UMASK
  1173. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1174. #endif
  1175. #if ENABLE_HUSH_UNSET
  1176. BLTIN("unset" , builtin_unset , "Unset variables"),
  1177. #endif
  1178. #if ENABLE_HUSH_WAIT
  1179. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1180. #endif
  1181. };
  1182. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1183. * (it's cheaper to run an external program in this case):
  1184. */
  1185. static const struct built_in_command bltins2[] ALIGN_PTR = {
  1186. #if ENABLE_HUSH_TEST
  1187. BLTIN("[" , builtin_test , NULL),
  1188. #endif
  1189. #if BASH_TEST2
  1190. BLTIN("[[" , builtin_test , NULL),
  1191. #endif
  1192. #if ENABLE_HUSH_ECHO
  1193. BLTIN("echo" , builtin_echo , NULL),
  1194. #endif
  1195. #if ENABLE_HUSH_PRINTF
  1196. BLTIN("printf" , builtin_printf , NULL),
  1197. #endif
  1198. BLTIN("pwd" , builtin_pwd , NULL),
  1199. #if ENABLE_HUSH_TEST
  1200. BLTIN("test" , builtin_test , NULL),
  1201. #endif
  1202. };
  1203. /* Debug printouts.
  1204. */
  1205. #if HUSH_DEBUG >= 2
  1206. /* prevent disasters with G.debug_indent < 0 */
  1207. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1208. # define debug_enter() (G.debug_indent++)
  1209. # define debug_leave() (G.debug_indent--)
  1210. #else
  1211. # define indent() ((void)0)
  1212. # define debug_enter() ((void)0)
  1213. # define debug_leave() ((void)0)
  1214. #endif
  1215. #ifndef debug_printf
  1216. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1217. #endif
  1218. #ifndef debug_printf_parse
  1219. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1220. #endif
  1221. #ifndef debug_printf_heredoc
  1222. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1223. #endif
  1224. #ifndef debug_printf_exec
  1225. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1226. #endif
  1227. #ifndef debug_printf_env
  1228. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1229. #endif
  1230. #ifndef debug_printf_jobs
  1231. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1232. # define DEBUG_JOBS 1
  1233. #else
  1234. # define DEBUG_JOBS 0
  1235. #endif
  1236. #ifndef debug_printf_expand
  1237. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1238. # define DEBUG_EXPAND 1
  1239. #else
  1240. # define DEBUG_EXPAND 0
  1241. #endif
  1242. #ifndef debug_printf_varexp
  1243. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1244. #endif
  1245. #ifndef debug_printf_glob
  1246. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1247. # define DEBUG_GLOB 1
  1248. #else
  1249. # define DEBUG_GLOB 0
  1250. #endif
  1251. #ifndef debug_printf_redir
  1252. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1253. #endif
  1254. #ifndef debug_printf_list
  1255. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1256. #endif
  1257. #ifndef debug_printf_subst
  1258. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1259. #endif
  1260. #ifndef debug_printf_prompt
  1261. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1262. #endif
  1263. #ifndef debug_printf_clean
  1264. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1265. # define DEBUG_CLEAN 1
  1266. #else
  1267. # define DEBUG_CLEAN 0
  1268. #endif
  1269. #if DEBUG_EXPAND
  1270. static void debug_print_strings(const char *prefix, char **vv)
  1271. {
  1272. indent();
  1273. fdprintf(2, "%s:\n", prefix);
  1274. while (*vv)
  1275. fdprintf(2, " '%s'\n", *vv++);
  1276. }
  1277. #else
  1278. # define debug_print_strings(prefix, vv) ((void)0)
  1279. #endif
  1280. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1281. */
  1282. #if LEAK_HUNTING
  1283. static void *xxmalloc(int lineno, size_t size)
  1284. {
  1285. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1286. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1287. return ptr;
  1288. }
  1289. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1290. {
  1291. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1292. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1293. return ptr;
  1294. }
  1295. static char *xxstrdup(int lineno, const char *str)
  1296. {
  1297. char *ptr = xstrdup(str);
  1298. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1299. return ptr;
  1300. }
  1301. static void xxfree(void *ptr)
  1302. {
  1303. fdprintf(2, "free %p\n", ptr);
  1304. free(ptr);
  1305. }
  1306. # define xmalloc(s) xxmalloc(__LINE__, s)
  1307. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1308. # define xstrdup(s) xxstrdup(__LINE__, s)
  1309. # define free(p) xxfree(p)
  1310. #endif
  1311. /* Syntax and runtime errors. They always abort scripts.
  1312. * In interactive use they usually discard unparsed and/or unexecuted commands
  1313. * and return to the prompt.
  1314. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1315. */
  1316. #if HUSH_DEBUG < 2
  1317. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1318. # define syntax_error(lineno, msg) syntax_error(msg)
  1319. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1320. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1321. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1322. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1323. #endif
  1324. static void die_if_script(void)
  1325. {
  1326. if (!G_interactive_fd) {
  1327. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1328. xfunc_error_retval = G.last_exitcode;
  1329. xfunc_die();
  1330. }
  1331. }
  1332. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1333. {
  1334. va_list p;
  1335. #if HUSH_DEBUG >= 2
  1336. bb_error_msg("hush.c:%u", lineno);
  1337. #endif
  1338. va_start(p, fmt);
  1339. bb_verror_msg(fmt, p, NULL);
  1340. va_end(p);
  1341. die_if_script();
  1342. }
  1343. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1344. {
  1345. if (msg)
  1346. bb_error_msg("syntax error: %s", msg);
  1347. else
  1348. bb_simple_error_msg("syntax error");
  1349. die_if_script();
  1350. }
  1351. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1352. {
  1353. bb_error_msg("syntax error at '%s'", msg);
  1354. die_if_script();
  1355. }
  1356. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1357. {
  1358. bb_error_msg("syntax error: unterminated %s", s);
  1359. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1360. // (but bash --posix, or if bash is run as "sh", does terminate in script, so maybe uncomment this?)
  1361. // die_if_script();
  1362. }
  1363. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1364. {
  1365. char msg[2] = { ch, '\0' };
  1366. syntax_error_unterm_str(lineno, msg);
  1367. }
  1368. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1369. {
  1370. char msg[2];
  1371. msg[0] = ch;
  1372. msg[1] = '\0';
  1373. #if HUSH_DEBUG >= 2
  1374. bb_error_msg("hush.c:%u", lineno);
  1375. #endif
  1376. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1377. die_if_script();
  1378. }
  1379. #if HUSH_DEBUG < 2
  1380. # undef msg_and_die_if_script
  1381. # undef syntax_error
  1382. # undef syntax_error_at
  1383. # undef syntax_error_unterm_ch
  1384. # undef syntax_error_unterm_str
  1385. # undef syntax_error_unexpected_ch
  1386. #else
  1387. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1388. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1389. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1390. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1391. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1392. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1393. #endif
  1394. /* Utility functions
  1395. */
  1396. /* Replace each \x with x in place, return ptr past NUL. */
  1397. static char *unbackslash(char *src)
  1398. {
  1399. char *dst = src = strchrnul(src, '\\');
  1400. while (1) {
  1401. if (*src == '\\') {
  1402. src++;
  1403. if (*src != '\0') {
  1404. /* \x -> x */
  1405. *dst++ = *src++;
  1406. continue;
  1407. }
  1408. /* else: "\<nul>". Do not delete this backslash.
  1409. * Testcase: eval 'echo ok\'
  1410. */
  1411. *dst++ = '\\';
  1412. /* fallthrough */
  1413. }
  1414. if ((*dst++ = *src++) == '\0')
  1415. break;
  1416. }
  1417. return dst;
  1418. }
  1419. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1420. {
  1421. int i;
  1422. unsigned count1;
  1423. unsigned count2;
  1424. char **v;
  1425. v = strings;
  1426. count1 = 0;
  1427. if (v) {
  1428. while (*v) {
  1429. count1++;
  1430. v++;
  1431. }
  1432. }
  1433. count2 = 0;
  1434. v = add;
  1435. while (*v) {
  1436. count2++;
  1437. v++;
  1438. }
  1439. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1440. v[count1 + count2] = NULL;
  1441. i = count2;
  1442. while (--i >= 0)
  1443. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1444. return v;
  1445. }
  1446. #if LEAK_HUNTING
  1447. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1448. {
  1449. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1450. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1451. return ptr;
  1452. }
  1453. #define add_strings_to_strings(strings, add, need_to_dup) \
  1454. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1455. #endif
  1456. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1457. static char **add_string_to_strings(char **strings, char *add)
  1458. {
  1459. char *v[2];
  1460. v[0] = add;
  1461. v[1] = NULL;
  1462. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1463. }
  1464. #if LEAK_HUNTING
  1465. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1466. {
  1467. char **ptr = add_string_to_strings(strings, add);
  1468. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1469. return ptr;
  1470. }
  1471. #define add_string_to_strings(strings, add) \
  1472. xx_add_string_to_strings(__LINE__, strings, add)
  1473. #endif
  1474. static void free_strings(char **strings)
  1475. {
  1476. char **v;
  1477. if (!strings)
  1478. return;
  1479. v = strings;
  1480. while (*v) {
  1481. free(*v);
  1482. v++;
  1483. }
  1484. free(strings);
  1485. }
  1486. static int dup_CLOEXEC(int fd, int avoid_fd)
  1487. {
  1488. int newfd;
  1489. repeat:
  1490. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1491. if (newfd >= 0) {
  1492. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1493. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1494. } else { /* newfd < 0 */
  1495. if (errno == EBUSY)
  1496. goto repeat;
  1497. if (errno == EINTR)
  1498. goto repeat;
  1499. }
  1500. return newfd;
  1501. }
  1502. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1503. {
  1504. int newfd;
  1505. repeat:
  1506. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1507. if (newfd < 0) {
  1508. if (errno == EBUSY)
  1509. goto repeat;
  1510. if (errno == EINTR)
  1511. goto repeat;
  1512. /* fd was not open? */
  1513. if (errno == EBADF)
  1514. return fd;
  1515. xfunc_die();
  1516. }
  1517. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1518. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1519. close(fd);
  1520. return newfd;
  1521. }
  1522. /* Manipulating HFILEs */
  1523. static HFILE *hfopen(const char *name)
  1524. {
  1525. HFILE *fp;
  1526. int fd;
  1527. fd = STDIN_FILENO;
  1528. if (name) {
  1529. fd = open(name, O_RDONLY | O_CLOEXEC);
  1530. if (fd < 0)
  1531. return NULL;
  1532. if (O_CLOEXEC == 0) /* ancient libc */
  1533. close_on_exec_on(fd);
  1534. }
  1535. fp = xmalloc(sizeof(*fp));
  1536. if (name == NULL)
  1537. G.HFILE_stdin = fp;
  1538. fp->fd = fd;
  1539. fp->cur = fp->end = fp->buf;
  1540. fp->next_hfile = G.HFILE_list;
  1541. G.HFILE_list = fp;
  1542. return fp;
  1543. }
  1544. static void hfclose(HFILE *fp)
  1545. {
  1546. HFILE **pp = &G.HFILE_list;
  1547. while (*pp) {
  1548. HFILE *cur = *pp;
  1549. if (cur == fp) {
  1550. *pp = cur->next_hfile;
  1551. break;
  1552. }
  1553. pp = &cur->next_hfile;
  1554. }
  1555. if (fp->fd >= 0)
  1556. close(fp->fd);
  1557. free(fp);
  1558. }
  1559. static int refill_HFILE_and_getc(HFILE *fp)
  1560. {
  1561. int n;
  1562. if (fp->fd < 0) {
  1563. /* Already saw EOF */
  1564. return EOF;
  1565. }
  1566. #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
  1567. /* If user presses ^C, read() restarts after SIGINT (we use SA_RESTART).
  1568. * IOW: ^C will not immediately stop line input.
  1569. * But poll() is different: it does NOT restart after signals.
  1570. */
  1571. if (fp == G.HFILE_stdin) {
  1572. struct pollfd pfd[1];
  1573. pfd[0].fd = fp->fd;
  1574. pfd[0].events = POLLIN;
  1575. n = poll(pfd, 1, -1);
  1576. if (n < 0
  1577. /*&& errno == EINTR - assumed true */
  1578. && sigismember(&G.pending_set, SIGINT)
  1579. ) {
  1580. return '\0';
  1581. }
  1582. }
  1583. #else
  1584. /* if FEATURE_EDITING=y, we do not use this routine for interactive input */
  1585. #endif
  1586. /* Try to buffer more input */
  1587. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1588. if (n < 0) {
  1589. bb_simple_perror_msg("read error");
  1590. n = 0;
  1591. }
  1592. fp->cur = fp->buf;
  1593. fp->end = fp->buf + n;
  1594. if (n == 0) {
  1595. /* EOF/error */
  1596. close(fp->fd);
  1597. fp->fd = -1;
  1598. return EOF;
  1599. }
  1600. return (unsigned char)(*fp->cur++);
  1601. }
  1602. /* Inlined for common case of non-empty buffer.
  1603. */
  1604. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1605. {
  1606. if (fp->cur < fp->end)
  1607. return (unsigned char)(*fp->cur++);
  1608. /* Buffer empty */
  1609. return refill_HFILE_and_getc(fp);
  1610. }
  1611. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1612. {
  1613. HFILE *fl = G.HFILE_list;
  1614. while (fl) {
  1615. if (fd == fl->fd) {
  1616. /* We use it only on script files, they are all CLOEXEC */
  1617. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1618. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1619. return 1; /* "found and moved" */
  1620. }
  1621. fl = fl->next_hfile;
  1622. }
  1623. #if ENABLE_HUSH_MODE_X
  1624. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1625. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1626. return 1; /* "found and moved" */
  1627. }
  1628. #endif
  1629. return 0; /* "not in the list" */
  1630. }
  1631. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1632. static void close_all_HFILE_list(void)
  1633. {
  1634. HFILE *fl = G.HFILE_list;
  1635. while (fl) {
  1636. /* hfclose would also free HFILE object.
  1637. * It is disastrous if we share memory with a vforked parent.
  1638. * I'm not sure we never come here after vfork.
  1639. * Therefore just close fd, nothing more.
  1640. *
  1641. * ">" instead of ">=": we don't close fd#0,
  1642. * interactive shell uses hfopen(NULL) as stdin input
  1643. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1644. * If we'd close it here, then e.g. interactive "set | sort"
  1645. * with NOFORKed sort, would have sort's input fd closed.
  1646. */
  1647. if (fl->fd > 0)
  1648. /*hfclose(fl); - unsafe */
  1649. close(fl->fd);
  1650. fl = fl->next_hfile;
  1651. }
  1652. }
  1653. #endif
  1654. static int fd_in_HFILEs(int fd)
  1655. {
  1656. HFILE *fl = G.HFILE_list;
  1657. while (fl) {
  1658. if (fl->fd == fd)
  1659. return 1;
  1660. fl = fl->next_hfile;
  1661. }
  1662. return 0;
  1663. }
  1664. /* Helpers for setting new $n and restoring them back
  1665. */
  1666. typedef struct save_arg_t {
  1667. char *sv_argv0;
  1668. char **sv_g_argv;
  1669. int sv_g_argc;
  1670. IF_HUSH_SET(smallint sv_g_malloced;)
  1671. } save_arg_t;
  1672. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1673. {
  1674. sv->sv_argv0 = argv[0];
  1675. sv->sv_g_argv = G.global_argv;
  1676. sv->sv_g_argc = G.global_argc;
  1677. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1678. argv[0] = G.global_argv[0]; /* retain $0 */
  1679. G.global_argv = argv;
  1680. IF_HUSH_SET(G.global_args_malloced = 0;)
  1681. G.global_argc = 1 + string_array_len(argv + 1);
  1682. }
  1683. static void restore_G_args(save_arg_t *sv, char **argv)
  1684. {
  1685. #if ENABLE_HUSH_SET
  1686. if (G.global_args_malloced) {
  1687. /* someone ran "set -- arg1 arg2 ...", undo */
  1688. char **pp = G.global_argv;
  1689. while (*++pp) /* note: does not free $0 */
  1690. free(*pp);
  1691. free(G.global_argv);
  1692. }
  1693. #endif
  1694. argv[0] = sv->sv_argv0;
  1695. G.global_argv = sv->sv_g_argv;
  1696. G.global_argc = sv->sv_g_argc;
  1697. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1698. }
  1699. /* Basic theory of signal handling in shell
  1700. * ========================================
  1701. * This does not describe what hush does, rather, it is current understanding
  1702. * what it _should_ do. If it doesn't, it's a bug.
  1703. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1704. *
  1705. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1706. * is finished or backgrounded. It is the same in interactive and
  1707. * non-interactive shells, and is the same regardless of whether
  1708. * a user trap handler is installed or a shell special one is in effect.
  1709. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1710. * backgrounds (i.e. stops) or kills all members of currently running
  1711. * pipe.
  1712. *
  1713. * Wait builtin is interruptible by signals for which user trap is set
  1714. * or by SIGINT in interactive shell.
  1715. *
  1716. * Trap handlers will execute even within trap handlers. (right?)
  1717. *
  1718. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1719. * except for handlers set to '' (empty string).
  1720. *
  1721. * If job control is off, backgrounded commands ("cmd &")
  1722. * have SIGINT, SIGQUIT set to SIG_IGN.
  1723. *
  1724. * Commands which are run in command substitution ("`cmd`")
  1725. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1726. *
  1727. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1728. * by the shell from its parent.
  1729. *
  1730. * Signals which differ from SIG_DFL action
  1731. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1732. *
  1733. * SIGQUIT: ignore
  1734. * SIGTERM (interactive): ignore
  1735. * SIGHUP (interactive):
  1736. * Send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit.
  1737. * Kernel would do this for us ("orphaned process group" handling
  1738. * according to POSIX) if we are a session leader and thus our death
  1739. * frees the controlling tty, but to be bash-compatible, we also do it
  1740. * for every interactive shell's death by SIGHUP.
  1741. * (Also, we need to restore tty pgrp, otherwise e.g. Midnight Commander
  1742. * backgrounds when hush started from it gets killed by SIGHUP).
  1743. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1744. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1745. * that all pipe members are stopped. Try this in bash:
  1746. * while :; do :; done - ^Z does not background it
  1747. * (while :; do :; done) - ^Z backgrounds it
  1748. * SIGINT (interactive): wait for last pipe, ignore the rest
  1749. * of the command line, show prompt. NB: ^C does not send SIGINT
  1750. * to interactive shell while shell is waiting for a pipe,
  1751. * since shell is bg'ed (is not in foreground process group).
  1752. * Example 1: this waits 5 sec, but does not execute ls:
  1753. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1754. * Example 2: this does not wait and does not execute ls:
  1755. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1756. * Example 3: this does not wait 5 sec, but executes ls:
  1757. * "sleep 5; ls -l" + press ^C
  1758. * Example 4: this does not wait and does not execute ls:
  1759. * "sleep 5 & wait; ls -l" + press ^C
  1760. *
  1761. * (What happens to signals which are IGN on shell start?)
  1762. * (What happens with signal mask on shell start?)
  1763. *
  1764. * Old implementation
  1765. * ==================
  1766. * We use in-kernel pending signal mask to determine which signals were sent.
  1767. * We block all signals which we don't want to take action immediately,
  1768. * i.e. we block all signals which need to have special handling as described
  1769. * above, and all signals which have traps set.
  1770. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1771. * and act on them.
  1772. *
  1773. * unsigned special_sig_mask: a mask of such "special" signals
  1774. * sigset_t blocked_set: current blocked signal set
  1775. *
  1776. * "trap - SIGxxx":
  1777. * clear bit in blocked_set unless it is also in special_sig_mask
  1778. * "trap 'cmd' SIGxxx":
  1779. * set bit in blocked_set (even if 'cmd' is '')
  1780. * after [v]fork, if we plan to be a shell:
  1781. * unblock signals with special interactive handling
  1782. * (child shell is not interactive),
  1783. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1784. * after [v]fork, if we plan to exec:
  1785. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1786. * Restore blocked signal set to one inherited by shell just prior to exec.
  1787. *
  1788. * Note: as a result, we do not use signal handlers much. The only uses
  1789. * are to count SIGCHLDs
  1790. * and to restore tty pgrp on signal-induced exit.
  1791. *
  1792. * Note 2 (compat):
  1793. * Standard says "When a subshell is entered, traps that are not being ignored
  1794. * are set to the default actions". bash interprets it so that traps which
  1795. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1796. *
  1797. * Problem: the above approach makes it unwieldy to catch signals while
  1798. * we are in read builtin, or while we read commands from stdin:
  1799. * masked signals are not visible!
  1800. *
  1801. * New implementation
  1802. * ==================
  1803. * We record each signal we are interested in by installing signal handler
  1804. * for them - a bit like emulating kernel pending signal mask in userspace.
  1805. * We are interested in: signals which need to have special handling
  1806. * as described above, and all signals which have traps set.
  1807. * Signals are recorded in pending_set.
  1808. * After each pipe execution, we extract any pending signals
  1809. * and act on them.
  1810. *
  1811. * unsigned special_sig_mask: a mask of shell-special signals.
  1812. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1813. * char *traps[sig] if trap for sig is set (even if it's '').
  1814. * sigset_t pending_set: set of sigs we received.
  1815. *
  1816. * "trap - SIGxxx":
  1817. * if sig is in special_sig_mask, set handler back to:
  1818. * record_pending_signo, or to IGN if it's a tty stop signal
  1819. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1820. * else: set handler back to SIG_DFL
  1821. * "trap 'cmd' SIGxxx":
  1822. * set handler to record_pending_signo.
  1823. * "trap '' SIGxxx":
  1824. * set handler to SIG_IGN.
  1825. * after [v]fork, if we plan to be a shell:
  1826. * set signals with special interactive handling to SIG_DFL
  1827. * (because child shell is not interactive),
  1828. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1829. * after [v]fork, if we plan to exec:
  1830. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1831. *
  1832. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1833. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1834. *
  1835. * Note (compat):
  1836. * Standard says "When a subshell is entered, traps that are not being ignored
  1837. * are set to the default actions". bash interprets it so that traps which
  1838. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1839. */
  1840. enum {
  1841. SPECIAL_INTERACTIVE_SIGS = 0
  1842. | (1 << SIGTERM)
  1843. | (1 << SIGINT)
  1844. | (1 << SIGHUP)
  1845. ,
  1846. SPECIAL_JOBSTOP_SIGS = 0
  1847. #if ENABLE_HUSH_JOB
  1848. | (1 << SIGTTIN)
  1849. | (1 << SIGTTOU)
  1850. | (1 << SIGTSTP)
  1851. #endif
  1852. ,
  1853. };
  1854. static void record_pending_signo(int sig)
  1855. {
  1856. sigaddset(&G.pending_set, sig);
  1857. #if ENABLE_FEATURE_EDITING
  1858. if (sig != SIGCHLD
  1859. || (G_traps && G_traps[SIGCHLD] && G_traps[SIGCHLD][0])
  1860. /* ^^^ if SIGCHLD, interrupt line reading only if it has a trap */
  1861. ) {
  1862. bb_got_signal = sig; /* for read_line_input: "we got a signal" */
  1863. }
  1864. #endif
  1865. #if ENABLE_HUSH_FAST
  1866. if (sig == SIGCHLD) {
  1867. G.count_SIGCHLD++;
  1868. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1869. }
  1870. #endif
  1871. }
  1872. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1873. {
  1874. struct sigaction old_sa;
  1875. /* We could use signal() to install handlers... almost:
  1876. * except that we need to mask ALL signals while handlers run.
  1877. * I saw signal nesting in strace, race window isn't small.
  1878. * SA_RESTART is also needed, but in Linux, signal()
  1879. * sets SA_RESTART too.
  1880. */
  1881. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1882. /* sigfillset(&G.sa.sa_mask); - already done */
  1883. /* G.sa.sa_flags = SA_RESTART; - already done */
  1884. G.sa.sa_handler = handler;
  1885. sigaction(sig, &G.sa, &old_sa);
  1886. return old_sa.sa_handler;
  1887. }
  1888. static void hush_exit(int exitcode) NORETURN;
  1889. static void restore_ttypgrp_and__exit(void) NORETURN;
  1890. static void restore_ttypgrp_and__exit(void)
  1891. {
  1892. /* xfunc has failed! die die die */
  1893. /* no EXIT traps, this is an escape hatch! */
  1894. G.exiting = 1;
  1895. hush_exit(xfunc_error_retval);
  1896. }
  1897. #if ENABLE_HUSH_JOB
  1898. /* Needed only on some libc:
  1899. * It was observed that on exit(), fgetc'ed buffered data
  1900. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1901. * With the net effect that even after fork(), not vfork(),
  1902. * exit() in NOEXECed applet in "sh SCRIPT":
  1903. * noexec_applet_here
  1904. * echo END_OF_SCRIPT
  1905. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1906. * This makes "echo END_OF_SCRIPT" executed twice.
  1907. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1908. * and in `cmd` handling.
  1909. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1910. */
  1911. static void fflush_and__exit(void) NORETURN;
  1912. static void fflush_and__exit(void)
  1913. {
  1914. fflush_all();
  1915. _exit(xfunc_error_retval);
  1916. }
  1917. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1918. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1919. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1920. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1921. /* Restores tty foreground process group, and exits.
  1922. * May be called as signal handler for fatal signal
  1923. * (will resend signal to itself, producing correct exit state)
  1924. * or called directly with -EXITCODE.
  1925. * We also call it if xfunc is exiting.
  1926. */
  1927. static void sigexit(int sig) NORETURN;
  1928. static void sigexit(int sig)
  1929. {
  1930. /* Careful: we can end up here after [v]fork. Do not restore
  1931. * tty pgrp then, only top-level shell process does that */
  1932. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1933. /* Disable all signals: job control, SIGPIPE, etc.
  1934. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1935. */
  1936. sigprocmask_allsigs(SIG_BLOCK);
  1937. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1938. }
  1939. /* Not a signal, just exit */
  1940. if (sig <= 0)
  1941. _exit(- sig);
  1942. kill_myself_with_sig(sig); /* does not return */
  1943. }
  1944. #else
  1945. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1946. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1947. #endif
  1948. static sighandler_t pick_sighandler(unsigned sig)
  1949. {
  1950. sighandler_t handler = SIG_DFL;
  1951. if (sig < sizeof(unsigned)*8) {
  1952. unsigned sigmask = (1 << sig);
  1953. #if ENABLE_HUSH_JOB
  1954. /* is sig fatal? */
  1955. if (G_fatal_sig_mask & sigmask)
  1956. handler = sigexit;
  1957. else
  1958. #endif
  1959. /* sig has special handling? */
  1960. if (G.special_sig_mask & sigmask) {
  1961. handler = record_pending_signo;
  1962. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1963. * in order to ignore them: they will be raised
  1964. * in an endless loop when we try to do some
  1965. * terminal ioctls! We do have to _ignore_ these.
  1966. */
  1967. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1968. handler = SIG_IGN;
  1969. }
  1970. }
  1971. return handler;
  1972. }
  1973. /* Restores tty foreground process group, and exits. */
  1974. static void hush_exit(int exitcode)
  1975. {
  1976. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1977. save_history(G.line_input_state); /* may be NULL */
  1978. #endif
  1979. fflush_all();
  1980. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1981. char *argv[3];
  1982. /* argv[0] is unused */
  1983. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1984. argv[2] = NULL;
  1985. G.exiting = 1; /* prevent EXIT trap recursion */
  1986. /* Note: G_traps[0] is not cleared!
  1987. * "trap" will still show it, if executed
  1988. * in the handler */
  1989. builtin_eval(argv);
  1990. }
  1991. #if ENABLE_FEATURE_CLEAN_UP
  1992. {
  1993. struct variable *cur_var;
  1994. if (G.cwd != bb_msg_unknown)
  1995. free((char*)G.cwd);
  1996. cur_var = G.top_var;
  1997. while (cur_var) {
  1998. struct variable *tmp = cur_var;
  1999. if (!cur_var->max_len)
  2000. free(cur_var->varstr);
  2001. cur_var = cur_var->next;
  2002. free(tmp);
  2003. }
  2004. }
  2005. #endif
  2006. fflush_all();
  2007. #if ENABLE_HUSH_JOB
  2008. sigexit(- (exitcode & 0xff));
  2009. #else
  2010. _exit(exitcode);
  2011. #endif
  2012. }
  2013. //TODO: return a mask of ALL handled sigs?
  2014. static int check_and_run_traps(void)
  2015. {
  2016. int last_sig = 0;
  2017. while (1) {
  2018. int sig;
  2019. if (sigisemptyset(&G.pending_set))
  2020. break;
  2021. sig = 0;
  2022. do {
  2023. sig++;
  2024. if (sigismember(&G.pending_set, sig)) {
  2025. sigdelset(&G.pending_set, sig);
  2026. goto got_sig;
  2027. }
  2028. } while (sig < NSIG);
  2029. break;
  2030. got_sig:
  2031. #if ENABLE_HUSH_TRAP
  2032. if (G_traps && G_traps[sig]) {
  2033. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  2034. if (G_traps[sig][0]) {
  2035. /* We have user-defined handler */
  2036. smalluint save_rcode;
  2037. int save_pre;
  2038. char *argv[3];
  2039. /* argv[0] is unused */
  2040. argv[1] = xstrdup(G_traps[sig]);
  2041. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  2042. argv[2] = NULL;
  2043. save_pre = G.pre_trap_exitcode;
  2044. G.pre_trap_exitcode = save_rcode = G.last_exitcode;
  2045. builtin_eval(argv);
  2046. free(argv[1]);
  2047. G.pre_trap_exitcode = save_pre;
  2048. G.last_exitcode = save_rcode;
  2049. # if ENABLE_HUSH_FUNCTIONS
  2050. if (G.return_exitcode >= 0) {
  2051. debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
  2052. G.last_exitcode = G.return_exitcode;
  2053. }
  2054. # endif
  2055. last_sig = sig;
  2056. } /* else: "" trap, ignoring signal */
  2057. continue;
  2058. }
  2059. #endif
  2060. /* not a trap: special action */
  2061. switch (sig) {
  2062. case SIGINT:
  2063. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2064. G.flag_SIGINT = 1;
  2065. last_sig = sig;
  2066. break;
  2067. #if ENABLE_HUSH_JOB
  2068. case SIGHUP: {
  2069. /* if (G_interactive_fd) - no need to check, the handler
  2070. * is only installed if we *are* interactive */
  2071. {
  2072. /* bash compat: "Before exiting, an interactive
  2073. * shell resends the SIGHUP to all jobs, running
  2074. * or stopped. Stopped jobs are sent SIGCONT
  2075. * to ensure that they receive the SIGHUP."
  2076. */
  2077. struct pipe *job;
  2078. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2079. /* bash is observed to signal whole process groups,
  2080. * not individual processes */
  2081. for (job = G.job_list; job; job = job->next) {
  2082. if (job->pgrp <= 0)
  2083. continue;
  2084. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2085. if (kill(- job->pgrp, SIGHUP) == 0)
  2086. kill(- job->pgrp, SIGCONT);
  2087. }
  2088. }
  2089. /* this restores tty pgrp, then kills us with SIGHUP */
  2090. sigexit(SIGHUP);
  2091. }
  2092. #endif
  2093. #if ENABLE_HUSH_FAST
  2094. case SIGCHLD:
  2095. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2096. G.count_SIGCHLD++;
  2097. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2098. /* Note:
  2099. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2100. * This simplifies wait builtin a bit.
  2101. */
  2102. break;
  2103. #endif
  2104. default: /* ignored: */
  2105. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2106. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2107. /* Note:
  2108. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2109. * Example: wait is not interrupted by TERM
  2110. * in interactive shell, because TERM is ignored.
  2111. */
  2112. break;
  2113. }
  2114. }
  2115. return last_sig;
  2116. }
  2117. static const char *get_cwd(int force)
  2118. {
  2119. if (force || G.cwd == NULL) {
  2120. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2121. * we must not try to free(bb_msg_unknown) */
  2122. if (G.cwd == bb_msg_unknown)
  2123. G.cwd = NULL;
  2124. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2125. if (!G.cwd)
  2126. G.cwd = bb_msg_unknown;
  2127. }
  2128. return G.cwd;
  2129. }
  2130. /*
  2131. * Shell and environment variable support
  2132. */
  2133. static struct variable **get_ptr_to_local_var(const char *name)
  2134. {
  2135. struct variable **pp;
  2136. struct variable *cur;
  2137. pp = &G.top_var;
  2138. while ((cur = *pp) != NULL) {
  2139. if (varcmp(cur->varstr, name) == 0)
  2140. return pp;
  2141. pp = &cur->next;
  2142. }
  2143. return NULL;
  2144. }
  2145. static const char* FAST_FUNC get_local_var_value(const char *name)
  2146. {
  2147. struct variable **vpp;
  2148. if (G.expanded_assignments) {
  2149. char **cpp = G.expanded_assignments;
  2150. while (*cpp) {
  2151. char *cp = *cpp;
  2152. if (varcmp(cp, name) == 0)
  2153. return strchr(cp, '=') + 1;
  2154. cpp++;
  2155. }
  2156. }
  2157. vpp = get_ptr_to_local_var(name);
  2158. if (vpp)
  2159. return strchr((*vpp)->varstr, '=') + 1;
  2160. if (strcmp(name, "PPID") == 0)
  2161. return utoa(G.root_ppid);
  2162. // bash compat: UID? EUID?
  2163. #if ENABLE_HUSH_RANDOM_SUPPORT
  2164. if (strcmp(name, "RANDOM") == 0)
  2165. return utoa(next_random(&G.random_gen));
  2166. #endif
  2167. #if ENABLE_HUSH_LINENO_VAR
  2168. if (strcmp(name, "LINENO") == 0)
  2169. return utoa(G.execute_lineno);
  2170. #endif
  2171. #if BASH_EPOCH_VARS
  2172. {
  2173. const char *fmt = NULL;
  2174. if (strcmp(name, "EPOCHSECONDS") == 0)
  2175. fmt = "%llu";
  2176. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2177. fmt = "%llu.%06u";
  2178. if (fmt) {
  2179. struct timeval tv;
  2180. xgettimeofday(&tv);
  2181. sprintf(G.epoch_buf, fmt, (unsigned long long)tv.tv_sec,
  2182. (unsigned)tv.tv_usec);
  2183. return G.epoch_buf;
  2184. }
  2185. }
  2186. #endif
  2187. return NULL;
  2188. }
  2189. #if ENABLE_HUSH_GETOPTS
  2190. static void handle_changed_special_names(const char *name)
  2191. {
  2192. if (varcmp(name, "OPTIND") == 0) {
  2193. G.getopt_count = 0;
  2194. return;
  2195. }
  2196. }
  2197. #else
  2198. /* Do not even bother evaluating arguments */
  2199. # define handle_changed_special_names(...) ((void)0)
  2200. #endif
  2201. /* str holds "NAME=VAL" and is expected to be malloced.
  2202. * We take ownership of it.
  2203. */
  2204. #define SETFLAG_EXPORT (1 << 0)
  2205. #define SETFLAG_UNEXPORT (1 << 1)
  2206. #define SETFLAG_MAKE_RO (1 << 2)
  2207. #define SETFLAG_VARLVL_SHIFT 3
  2208. static int set_local_var(char *str, unsigned flags)
  2209. {
  2210. struct variable **cur_pp;
  2211. struct variable *cur;
  2212. char *free_me = NULL;
  2213. char *eq_sign;
  2214. int name_len;
  2215. int retval;
  2216. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2217. eq_sign = strchr(str, '=');
  2218. if (HUSH_DEBUG && !eq_sign)
  2219. bb_simple_error_msg_and_die("BUG in setvar");
  2220. name_len = eq_sign - str + 1; /* including '=' */
  2221. cur_pp = &G.top_var;
  2222. while ((cur = *cur_pp) != NULL) {
  2223. if (strncmp(cur->varstr, str, name_len) != 0) {
  2224. cur_pp = &cur->next;
  2225. continue;
  2226. }
  2227. /* We found an existing var with this name */
  2228. if (cur->flg_read_only) {
  2229. bb_error_msg("%s: readonly variable", str);
  2230. free(str);
  2231. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2232. //but export per se succeeds (does put the var in env). We don't mimic that.
  2233. return -1;
  2234. }
  2235. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2236. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2237. *eq_sign = '\0';
  2238. unsetenv(str);
  2239. *eq_sign = '=';
  2240. }
  2241. if (cur->var_nest_level < local_lvl) {
  2242. /* bash 3.2.33(1) and exported vars:
  2243. * # export z=z
  2244. * # f() { local z=a; env | grep ^z; }
  2245. * # f
  2246. * z=a
  2247. * # env | grep ^z
  2248. * z=z
  2249. */
  2250. if (cur->flg_export)
  2251. flags |= SETFLAG_EXPORT;
  2252. /* New variable is local ("local VAR=VAL" or
  2253. * "VAR=VAL cmd")
  2254. * and existing one is global, or local
  2255. * on a lower level that new one.
  2256. * Remove it from global variable list:
  2257. */
  2258. *cur_pp = cur->next;
  2259. if (G.shadowed_vars_pp) {
  2260. /* Save in "shadowed" list */
  2261. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2262. cur->flg_export ? "exported " : "",
  2263. cur->varstr, cur->var_nest_level, str, local_lvl
  2264. );
  2265. cur->next = *G.shadowed_vars_pp;
  2266. *G.shadowed_vars_pp = cur;
  2267. } else {
  2268. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2269. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2270. cur->flg_export ? "exported " : "",
  2271. cur->varstr, cur->var_nest_level, str, local_lvl
  2272. );
  2273. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2274. free_me = cur->varstr; /* then free it later */
  2275. free(cur);
  2276. }
  2277. break;
  2278. }
  2279. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2280. debug_printf_env("assignement '%s' does not change anything\n", str);
  2281. free_and_exp:
  2282. free(str);
  2283. goto exp;
  2284. }
  2285. /* Replace the value in the found "struct variable" */
  2286. if (cur->max_len != 0) {
  2287. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2288. /* This one is from startup env, reuse space */
  2289. debug_printf_env("reusing startup env for '%s'\n", str);
  2290. strcpy(cur->varstr, str);
  2291. goto free_and_exp;
  2292. }
  2293. /* Can't reuse */
  2294. cur->max_len = 0;
  2295. goto set_str_and_exp;
  2296. }
  2297. /* max_len == 0 signifies "malloced" var, which we can
  2298. * (and have to) free. But we can't free(cur->varstr) here:
  2299. * if cur->flg_export is 1, it is in the environment.
  2300. * We should either unsetenv+free, or wait until putenv,
  2301. * then putenv(new)+free(old).
  2302. */
  2303. free_me = cur->varstr;
  2304. goto set_str_and_exp;
  2305. }
  2306. /* Not found or shadowed - create new variable struct */
  2307. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2308. cur = xzalloc(sizeof(*cur));
  2309. cur->var_nest_level = local_lvl;
  2310. cur->next = *cur_pp;
  2311. *cur_pp = cur;
  2312. set_str_and_exp:
  2313. cur->varstr = str;
  2314. exp:
  2315. #if !BB_MMU || ENABLE_HUSH_READONLY
  2316. if (flags & SETFLAG_MAKE_RO) {
  2317. cur->flg_read_only = 1;
  2318. }
  2319. #endif
  2320. if (flags & SETFLAG_EXPORT)
  2321. cur->flg_export = 1;
  2322. retval = 0;
  2323. if (cur->flg_export) {
  2324. if (flags & SETFLAG_UNEXPORT) {
  2325. cur->flg_export = 0;
  2326. /* unsetenv was already done */
  2327. } else {
  2328. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2329. retval = putenv(cur->varstr);
  2330. /* fall through to "free(free_me)" -
  2331. * only now we can free old exported malloced string
  2332. */
  2333. }
  2334. }
  2335. free(free_me);
  2336. handle_changed_special_names(cur->varstr);
  2337. return retval;
  2338. }
  2339. static int set_local_var0(char *str)
  2340. {
  2341. return set_local_var(str, 0);
  2342. }
  2343. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2344. {
  2345. char *var = xasprintf("%s=%s", name, val);
  2346. set_local_var0(var);
  2347. }
  2348. /* Used at startup and after each cd */
  2349. static void set_pwd_var(unsigned flag)
  2350. {
  2351. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2352. }
  2353. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2354. static int unset_local_var(const char *name)
  2355. {
  2356. struct variable *cur;
  2357. struct variable **cur_pp;
  2358. cur_pp = &G.top_var;
  2359. while ((cur = *cur_pp) != NULL) {
  2360. if (varcmp(cur->varstr, name) == 0) {
  2361. if (cur->flg_read_only) {
  2362. bb_error_msg("%s: readonly variable", name);
  2363. return EXIT_FAILURE;
  2364. }
  2365. *cur_pp = cur->next;
  2366. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2367. bb_unsetenv(cur->varstr);
  2368. if (!cur->max_len)
  2369. free(cur->varstr);
  2370. free(cur);
  2371. break;
  2372. }
  2373. cur_pp = &cur->next;
  2374. }
  2375. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2376. handle_changed_special_names(name);
  2377. return EXIT_SUCCESS;
  2378. }
  2379. #endif
  2380. /*
  2381. * Helpers for "var1=val1 var2=val2 cmd" feature
  2382. */
  2383. static void add_vars(struct variable *var)
  2384. {
  2385. struct variable *next;
  2386. while (var) {
  2387. next = var->next;
  2388. var->next = G.top_var;
  2389. G.top_var = var;
  2390. if (var->flg_export) {
  2391. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2392. putenv(var->varstr);
  2393. } else {
  2394. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2395. }
  2396. var = next;
  2397. }
  2398. }
  2399. /* We put strings[i] into variable table and possibly putenv them.
  2400. * If variable is read only, we can free the strings[i]
  2401. * which attempts to overwrite it.
  2402. * The strings[] vector itself is freed.
  2403. */
  2404. static void set_vars_and_save_old(char **strings)
  2405. {
  2406. char **s;
  2407. if (!strings)
  2408. return;
  2409. s = strings;
  2410. while (*s) {
  2411. struct variable *var_p;
  2412. struct variable **var_pp;
  2413. char *eq;
  2414. eq = strchr(*s, '=');
  2415. if (HUSH_DEBUG && !eq)
  2416. bb_simple_error_msg_and_die("BUG in varexp4");
  2417. var_pp = get_ptr_to_local_var(*s);
  2418. if (var_pp) {
  2419. var_p = *var_pp;
  2420. if (var_p->flg_read_only) {
  2421. char **p;
  2422. bb_error_msg("%s: readonly variable", *s);
  2423. /*
  2424. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2425. * If VAR is readonly, leaving it in the list
  2426. * after asssignment error (msg above)
  2427. * causes doubled error message later, on unset.
  2428. */
  2429. debug_printf_env("removing/freeing '%s' element\n", *s);
  2430. free(*s);
  2431. p = s;
  2432. do { *p = p[1]; p++; } while (*p);
  2433. goto next;
  2434. }
  2435. /* below, set_local_var() with nest level will
  2436. * "shadow" (remove) this variable from
  2437. * global linked list.
  2438. */
  2439. }
  2440. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2441. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2442. s++;
  2443. next: ;
  2444. }
  2445. free(strings);
  2446. }
  2447. /*
  2448. * Unicode helper
  2449. */
  2450. static void reinit_unicode_for_hush(void)
  2451. {
  2452. /* Unicode support should be activated even if LANG is set
  2453. * _during_ shell execution, not only if it was set when
  2454. * shell was started. Therefore, re-check LANG every time:
  2455. */
  2456. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2457. || ENABLE_UNICODE_USING_LOCALE
  2458. ) {
  2459. const char *s = get_local_var_value("LC_ALL");
  2460. if (!s) s = get_local_var_value("LC_CTYPE");
  2461. if (!s) s = get_local_var_value("LANG");
  2462. reinit_unicode(s);
  2463. }
  2464. }
  2465. /*
  2466. * in_str support (strings, and "strings" read from files).
  2467. */
  2468. #if ENABLE_HUSH_INTERACTIVE
  2469. /* To test correct lineedit/interactive behavior, type from command line:
  2470. * echo $P\
  2471. * \
  2472. * AT\
  2473. * H\
  2474. * \
  2475. * It exercises a lot of corner cases.
  2476. */
  2477. static const char *setup_prompt_string(void)
  2478. {
  2479. const char *prompt_str;
  2480. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2481. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2482. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2483. if (!prompt_str)
  2484. prompt_str = "";
  2485. # else
  2486. prompt_str = "> "; /* if PS2, else... */
  2487. if (G.promptmode == 0) { /* PS1 */
  2488. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2489. free(G.PS1);
  2490. /* bash uses $PWD value, even if it is set by user.
  2491. * It uses current dir only if PWD is unset.
  2492. * We always use current dir. */
  2493. prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2494. }
  2495. # endif
  2496. debug_printf("prompt_str '%s'\n", prompt_str);
  2497. return prompt_str;
  2498. }
  2499. static int get_user_input(struct in_str *i)
  2500. {
  2501. # if ENABLE_FEATURE_EDITING
  2502. /* In EDITING case, this function reads next input line,
  2503. * saves it in i->p, then returns 1st char of it.
  2504. */
  2505. int r;
  2506. const char *prompt_str;
  2507. prompt_str = setup_prompt_string();
  2508. for (;;) {
  2509. reinit_unicode_for_hush();
  2510. G.flag_SIGINT = 0;
  2511. bb_got_signal = 0;
  2512. if (!sigisemptyset(&G.pending_set)) {
  2513. /* Whoops, already got a signal, do not call read_line_input */
  2514. bb_got_signal = r = -1;
  2515. } else {
  2516. /* For shell, LI_INTERRUPTIBLE is set:
  2517. * read_line_input will abort on either
  2518. * getting EINTR in poll() and bb_got_signal became != 0,
  2519. * or if it sees bb_got_signal != 0
  2520. * (IOW: if signal arrives before poll() is reached).
  2521. * Interactive testcases:
  2522. * (while kill -INT $$; do sleep 1; done) &
  2523. * #^^^ prints ^C, prints prompt, repeats
  2524. * trap 'echo I' int; (while kill -INT $$; do sleep 1; done) &
  2525. * #^^^ prints ^C, prints "I", prints prompt, repeats
  2526. * trap 'echo T' term; (while kill $$; do sleep 1; done) &
  2527. * #^^^ prints "T", prints prompt, repeats
  2528. * #(bash 5.0.17 exits after first "T", looks like a bug)
  2529. */
  2530. r = read_line_input(G.line_input_state, prompt_str,
  2531. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2532. );
  2533. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2534. if (r == 0)
  2535. raise(SIGINT);
  2536. }
  2537. /* bash prints ^C (before running a trap, if any)
  2538. * both on keyboard ^C and on real SIGINT (non-kbd generated).
  2539. */
  2540. if (sigismember(&G.pending_set, SIGINT)) {
  2541. write(STDOUT_FILENO, "^C\n", 3);
  2542. G.last_exitcode = 128 | SIGINT;
  2543. }
  2544. check_and_run_traps();
  2545. if (r == 0) /* keyboard ^C? */
  2546. continue; /* go back, read another input line */
  2547. if (r > 0) /* normal input? (no ^C, no ^D, no signals) */
  2548. break;
  2549. if (!bb_got_signal) {
  2550. /* r < 0: ^D/EOF/error detected (but not signal) */
  2551. /* ^D on interactive input goes to next line before exiting: */
  2552. write(STDOUT_FILENO, "\n", 1);
  2553. i->p = NULL;
  2554. i->peek_buf[0] = r = EOF;
  2555. return r;
  2556. }
  2557. /* it was a signal: go back, read another input line */
  2558. }
  2559. i->p = G.user_input_buf;
  2560. return (unsigned char)*i->p++;
  2561. # else
  2562. /* In !EDITING case, this function gets called for every char.
  2563. * Buffering happens deeper in the call chain, in hfgetc(i->file).
  2564. */
  2565. int r;
  2566. for (;;) {
  2567. G.flag_SIGINT = 0;
  2568. if (i->last_char == '\0' || i->last_char == '\n') {
  2569. const char *prompt_str = setup_prompt_string();
  2570. /* Why check_and_run_traps here? Try this interactively:
  2571. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2572. * $ <[enter], repeatedly...>
  2573. * Without check_and_run_traps, handler never runs.
  2574. */
  2575. check_and_run_traps();
  2576. fputs_stdout(prompt_str);
  2577. fflush_all();
  2578. }
  2579. r = hfgetc(i->file);
  2580. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2581. * no ^C masking happens during fgetc, no special code for ^C:
  2582. * it generates SIGINT as usual.
  2583. */
  2584. check_and_run_traps();
  2585. if (r != '\0' && !G.flag_SIGINT)
  2586. break;
  2587. if (G.flag_SIGINT) {
  2588. /* ^C or SIGINT: repeat */
  2589. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2590. /* kernel prints "^C" itself, just print newline: */
  2591. write(STDOUT_FILENO, "\n", 1);
  2592. G.last_exitcode = 128 | SIGINT;
  2593. }
  2594. }
  2595. return r;
  2596. # endif
  2597. }
  2598. /* This is the magic location that prints prompts
  2599. * and gets data back from the user */
  2600. static int fgetc_interactive(struct in_str *i)
  2601. {
  2602. int ch;
  2603. /* If it's interactive stdin, get new line. */
  2604. if (G_interactive_fd && i->file == G.HFILE_stdin) {
  2605. /* Returns first char (or EOF), the rest is in i->p[] */
  2606. ch = get_user_input(i);
  2607. G.promptmode = 1; /* PS2 */
  2608. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2609. } else {
  2610. /* Not stdin: script file, sourced file, etc */
  2611. do ch = hfgetc(i->file); while (ch == '\0');
  2612. }
  2613. return ch;
  2614. }
  2615. #else /* !INTERACTIVE */
  2616. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2617. {
  2618. int ch;
  2619. do ch = hfgetc(i->file); while (ch == '\0');
  2620. return ch;
  2621. }
  2622. #endif /* !INTERACTIVE */
  2623. static int i_getch(struct in_str *i)
  2624. {
  2625. int ch;
  2626. if (!i->file) {
  2627. /* string-based in_str */
  2628. ch = (unsigned char)*i->p;
  2629. if (ch != '\0') {
  2630. i->p++;
  2631. i->last_char = ch;
  2632. #if ENABLE_HUSH_LINENO_VAR
  2633. if (ch == '\n') {
  2634. G.parse_lineno++;
  2635. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2636. }
  2637. #endif
  2638. return ch;
  2639. }
  2640. return EOF;
  2641. }
  2642. /* FILE-based in_str */
  2643. #if ENABLE_FEATURE_EDITING
  2644. /* This can be stdin, check line editing char[] buffer */
  2645. if (i->p && *i->p != '\0') {
  2646. ch = (unsigned char)*i->p++;
  2647. goto out;
  2648. }
  2649. #endif
  2650. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2651. ch = i->peek_buf[0];
  2652. if (ch != 0) {
  2653. int ch2 = i->peek_buf[1];
  2654. i->peek_buf[0] = ch2;
  2655. if (ch2 == 0) /* very likely, avoid redundant write */
  2656. goto out;
  2657. i->peek_buf[1] = 0;
  2658. goto out;
  2659. }
  2660. ch = fgetc_interactive(i);
  2661. out:
  2662. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2663. i->last_char = ch;
  2664. #if ENABLE_HUSH_LINENO_VAR
  2665. if (ch == '\n') {
  2666. G.parse_lineno++;
  2667. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2668. }
  2669. #endif
  2670. return ch;
  2671. }
  2672. static int i_peek(struct in_str *i)
  2673. {
  2674. int ch;
  2675. if (!i->file) {
  2676. /* string-based in_str */
  2677. /* Doesn't report EOF on NUL. None of the callers care. */
  2678. return (unsigned char)*i->p;
  2679. }
  2680. /* FILE-based in_str */
  2681. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2682. /* This can be stdin, check line editing char[] buffer */
  2683. if (i->p && *i->p != '\0')
  2684. return (unsigned char)*i->p;
  2685. #endif
  2686. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2687. ch = i->peek_buf[0];
  2688. if (ch != 0)
  2689. return ch;
  2690. /* Need to get a new char */
  2691. ch = fgetc_interactive(i);
  2692. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2693. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2694. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2695. if (i->p) {
  2696. i->p -= 1;
  2697. return ch;
  2698. }
  2699. #endif
  2700. i->peek_buf[0] = ch;
  2701. /*i->peek_buf[1] = 0; - already is */
  2702. return ch;
  2703. }
  2704. /* Only ever called if i_peek() was called, and did not return EOF.
  2705. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2706. * not end-of-line. Therefore we never need to read a new editing line here.
  2707. */
  2708. static int i_peek2(struct in_str *i)
  2709. {
  2710. int ch;
  2711. /* There are two cases when i->p[] buffer exists.
  2712. * (1) it's a string in_str.
  2713. * (2) It's a file, and we have a saved line editing buffer.
  2714. * In both cases, we know that i->p[0] exists and not NUL, and
  2715. * the peek2 result is in i->p[1].
  2716. */
  2717. if (i->p)
  2718. return (unsigned char)i->p[1];
  2719. /* Now we know it is a file-based in_str. */
  2720. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2721. /* Is there 2nd char? */
  2722. ch = i->peek_buf[1];
  2723. if (ch == 0) {
  2724. /* We did not read it yet, get it now */
  2725. do ch = hfgetc(i->file); while (ch == '\0');
  2726. i->peek_buf[1] = ch;
  2727. }
  2728. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2729. return ch;
  2730. }
  2731. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2732. {
  2733. for (;;) {
  2734. int ch, ch2;
  2735. ch = i_getch(input);
  2736. if (ch != '\\')
  2737. return ch;
  2738. ch2 = i_peek(input);
  2739. if (ch2 != '\n')
  2740. return ch;
  2741. /* backslash+newline, skip it */
  2742. i_getch(input);
  2743. }
  2744. }
  2745. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2746. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2747. */
  2748. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2749. {
  2750. for (;;) {
  2751. int ch, ch2;
  2752. ch = i_peek(input);
  2753. if (ch != '\\')
  2754. return ch;
  2755. ch2 = i_peek2(input);
  2756. if (ch2 != '\n')
  2757. return ch;
  2758. /* backslash+newline, skip it */
  2759. i_getch(input);
  2760. i_getch(input);
  2761. }
  2762. }
  2763. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2764. {
  2765. memset(i, 0, sizeof(*i));
  2766. i->file = fp;
  2767. /* i->p = NULL; */
  2768. }
  2769. static void setup_string_in_str(struct in_str *i, const char *s)
  2770. {
  2771. memset(i, 0, sizeof(*i));
  2772. /*i->file = NULL */;
  2773. i->p = s;
  2774. }
  2775. /*
  2776. * o_string support
  2777. */
  2778. #define B_CHUNK (32 * sizeof(char*))
  2779. static void o_reset_to_empty_unquoted(o_string *o)
  2780. {
  2781. o->length = 0;
  2782. o->has_quoted_part = 0;
  2783. if (o->data)
  2784. o->data[0] = '\0';
  2785. }
  2786. static void o_free_and_set_NULL(o_string *o)
  2787. {
  2788. free(o->data);
  2789. memset(o, 0, sizeof(*o));
  2790. }
  2791. static ALWAYS_INLINE void o_free(o_string *o)
  2792. {
  2793. free(o->data);
  2794. }
  2795. static void o_grow_by(o_string *o, int len)
  2796. {
  2797. if (o->length + len > o->maxlen) {
  2798. o->maxlen += (2 * len) | (B_CHUNK-1);
  2799. o->data = xrealloc(o->data, 1 + o->maxlen);
  2800. }
  2801. }
  2802. static void o_addchr(o_string *o, int ch)
  2803. {
  2804. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2805. if (o->length < o->maxlen) {
  2806. /* likely. avoid o_grow_by() call */
  2807. add:
  2808. o->data[o->length] = ch;
  2809. o->length++;
  2810. o->data[o->length] = '\0';
  2811. return;
  2812. }
  2813. o_grow_by(o, 1);
  2814. goto add;
  2815. }
  2816. #if 0
  2817. /* Valid only if we know o_string is not empty */
  2818. static void o_delchr(o_string *o)
  2819. {
  2820. o->length--;
  2821. o->data[o->length] = '\0';
  2822. }
  2823. #endif
  2824. static void o_addblock(o_string *o, const char *str, int len)
  2825. {
  2826. o_grow_by(o, len);
  2827. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2828. o->length += len;
  2829. }
  2830. static void o_addstr(o_string *o, const char *str)
  2831. {
  2832. o_addblock(o, str, strlen(str));
  2833. }
  2834. static void o_addstr_with_NUL(o_string *o, const char *str)
  2835. {
  2836. o_addblock(o, str, strlen(str) + 1);
  2837. }
  2838. #if !BB_MMU
  2839. static void nommu_addchr(o_string *o, int ch)
  2840. {
  2841. if (o)
  2842. o_addchr(o, ch);
  2843. }
  2844. #else
  2845. # define nommu_addchr(o, str) ((void)0)
  2846. #endif
  2847. #if ENABLE_HUSH_MODE_X
  2848. static void x_mode_addchr(int ch)
  2849. {
  2850. o_addchr(&G.x_mode_buf, ch);
  2851. }
  2852. static void x_mode_addstr(const char *str)
  2853. {
  2854. o_addstr(&G.x_mode_buf, str);
  2855. }
  2856. static void x_mode_addblock(const char *str, int len)
  2857. {
  2858. o_addblock(&G.x_mode_buf, str, len);
  2859. }
  2860. static void x_mode_prefix(void)
  2861. {
  2862. int n = G.x_mode_depth;
  2863. do x_mode_addchr('+'); while (--n >= 0);
  2864. }
  2865. static void x_mode_flush(void)
  2866. {
  2867. int len = G.x_mode_buf.length;
  2868. if (len <= 0)
  2869. return;
  2870. if (G.x_mode_fd > 0) {
  2871. G.x_mode_buf.data[len] = '\n';
  2872. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2873. }
  2874. G.x_mode_buf.length = 0;
  2875. }
  2876. #endif
  2877. /*
  2878. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2879. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2880. * Apparently, on unquoted $v bash still does globbing
  2881. * ("v='*.txt'; echo $v" prints all .txt files),
  2882. * but NOT brace expansion! Thus, there should be TWO independent
  2883. * quoting mechanisms on $v expansion side: one protects
  2884. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2885. * We have only second one.
  2886. */
  2887. #if ENABLE_HUSH_BRACE_EXPANSION
  2888. # define MAYBE_BRACES "{}"
  2889. #else
  2890. # define MAYBE_BRACES ""
  2891. #endif
  2892. /* My analysis of quoting semantics tells me that state information
  2893. * is associated with a destination, not a source.
  2894. */
  2895. static void o_addqchr(o_string *o, int ch)
  2896. {
  2897. int sz = 1;
  2898. /* '-' is included because of this case:
  2899. * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
  2900. */
  2901. char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
  2902. if (found)
  2903. sz++;
  2904. o_grow_by(o, sz);
  2905. if (found) {
  2906. o->data[o->length] = '\\';
  2907. o->length++;
  2908. }
  2909. o->data[o->length] = ch;
  2910. o->length++;
  2911. o->data[o->length] = '\0';
  2912. }
  2913. static void o_addQchr(o_string *o, int ch)
  2914. {
  2915. int sz = 1;
  2916. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2917. && strchr("*?[-\\" MAYBE_BRACES, ch)
  2918. ) {
  2919. sz++;
  2920. o->data[o->length] = '\\';
  2921. o->length++;
  2922. }
  2923. o_grow_by(o, sz);
  2924. o->data[o->length] = ch;
  2925. o->length++;
  2926. o->data[o->length] = '\0';
  2927. }
  2928. static void o_addqblock(o_string *o, const char *str, int len)
  2929. {
  2930. while (len) {
  2931. char ch;
  2932. int sz;
  2933. int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
  2934. if (ordinary_cnt > len) /* paranoia */
  2935. ordinary_cnt = len;
  2936. o_addblock(o, str, ordinary_cnt);
  2937. if (ordinary_cnt == len)
  2938. return; /* NUL is already added by o_addblock */
  2939. str += ordinary_cnt;
  2940. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2941. ch = *str++;
  2942. sz = 1;
  2943. if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
  2944. sz++;
  2945. o->data[o->length] = '\\';
  2946. o->length++;
  2947. }
  2948. o_grow_by(o, sz);
  2949. o->data[o->length] = ch;
  2950. o->length++;
  2951. }
  2952. o->data[o->length] = '\0';
  2953. }
  2954. static void o_addQblock(o_string *o, const char *str, int len)
  2955. {
  2956. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2957. o_addblock(o, str, len);
  2958. return;
  2959. }
  2960. o_addqblock(o, str, len);
  2961. }
  2962. static void o_addQstr(o_string *o, const char *str)
  2963. {
  2964. o_addQblock(o, str, strlen(str));
  2965. }
  2966. /* A special kind of o_string for $VAR and `cmd` expansion.
  2967. * It contains char* list[] at the beginning, which is grown in 16 element
  2968. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2969. * list[i] contains an INDEX (int!) into this string data.
  2970. * It means that if list[] needs to grow, data needs to be moved higher up
  2971. * but list[i]'s need not be modified.
  2972. * NB: remembering how many list[i]'s you have there is crucial.
  2973. * o_finalize_list() operation post-processes this structure - calculates
  2974. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2975. */
  2976. #if DEBUG_EXPAND || DEBUG_GLOB
  2977. static void debug_print_list(const char *prefix, o_string *o, int n)
  2978. {
  2979. char **list = (char**)o->data;
  2980. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2981. int i = 0;
  2982. indent();
  2983. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2984. prefix, list, n, string_start, o->length, o->maxlen,
  2985. !!(o->o_expflags & EXP_FLAG_GLOB),
  2986. o->has_quoted_part,
  2987. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2988. while (i < n) {
  2989. indent();
  2990. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2991. o->data + (int)(uintptr_t)list[i] + string_start,
  2992. o->data + (int)(uintptr_t)list[i] + string_start);
  2993. i++;
  2994. }
  2995. if (n) {
  2996. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2997. indent();
  2998. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2999. }
  3000. }
  3001. #else
  3002. # define debug_print_list(prefix, o, n) ((void)0)
  3003. #endif
  3004. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  3005. * in list[n] so that it points past last stored byte so far.
  3006. * It returns n+1. */
  3007. static int o_save_ptr_helper(o_string *o, int n)
  3008. {
  3009. char **list = (char**)o->data;
  3010. int string_start;
  3011. int string_len;
  3012. if (!o->has_empty_slot) {
  3013. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3014. string_len = o->length - string_start;
  3015. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  3016. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  3017. /* list[n] points to string_start, make space for 16 more pointers */
  3018. o->maxlen += 0x10 * sizeof(list[0]);
  3019. o->data = xrealloc(o->data, o->maxlen + 1);
  3020. list = (char**)o->data;
  3021. memmove(list + n + 0x10, list + n, string_len);
  3022. /*
  3023. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  3024. * check. (grep for -prev-ifs-check-).
  3025. * Ensure that argv[-1][last] is not garbage
  3026. * but zero bytes, to save index check there.
  3027. */
  3028. list[n + 0x10 - 1] = 0;
  3029. o->length += 0x10 * sizeof(list[0]);
  3030. } else {
  3031. debug_printf_list("list[%d]=%d string_start=%d\n",
  3032. n, string_len, string_start);
  3033. }
  3034. } else {
  3035. /* We have empty slot at list[n], reuse without growth */
  3036. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  3037. string_len = o->length - string_start;
  3038. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  3039. n, string_len, string_start);
  3040. o->has_empty_slot = 0;
  3041. }
  3042. o->has_quoted_part = 0;
  3043. list[n] = (char*)(uintptr_t)string_len;
  3044. return n + 1;
  3045. }
  3046. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  3047. static int o_get_last_ptr(o_string *o, int n)
  3048. {
  3049. char **list = (char**)o->data;
  3050. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3051. return ((int)(uintptr_t)list[n-1]) + string_start;
  3052. }
  3053. /*
  3054. * Globbing routines.
  3055. *
  3056. * Most words in commands need to be globbed, even ones which are
  3057. * (single or double) quoted. This stems from the possiblity of
  3058. * constructs like "abc"* and 'abc'* - these should be globbed.
  3059. * Having a different code path for fully-quoted strings ("abc",
  3060. * 'abc') would only help performance-wise, but we still need
  3061. * code for partially-quoted strings.
  3062. *
  3063. * Unfortunately, if we want to match bash and ash behavior in all cases,
  3064. * the logic can't be "shell-syntax argument is first transformed
  3065. * to a string, then globbed, and if globbing does not match anything,
  3066. * it is used verbatim". Here are two examples where it fails:
  3067. *
  3068. * echo 'b\*'?
  3069. *
  3070. * The globbing can't be avoided (because of '?' at the end).
  3071. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  3072. * and are glob-escaped. If this does not match, bash/ash print b\*?
  3073. * - IOW: they "unbackslash" the glob pattern.
  3074. * Now, look at this:
  3075. *
  3076. * v='\\\*'; echo b$v?
  3077. *
  3078. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  3079. * should be used as glob pattern with no changes. However, if glob
  3080. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  3081. *
  3082. * ash implements this by having an encoded representation of the word
  3083. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  3084. * Glob pattern is derived from it. If glob fails, the decision what result
  3085. * should be is made using that encoded representation. Not glob pattern.
  3086. */
  3087. #if ENABLE_HUSH_BRACE_EXPANSION
  3088. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  3089. * first, it processes even {a} (no commas), second,
  3090. * I didn't manage to make it return strings when they don't match
  3091. * existing files. Need to re-implement it.
  3092. */
  3093. /* Helper */
  3094. static int glob_needed(const char *s)
  3095. {
  3096. while (*s) {
  3097. if (*s == '\\') {
  3098. if (!s[1])
  3099. return 0;
  3100. s += 2;
  3101. continue;
  3102. }
  3103. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  3104. return 1;
  3105. s++;
  3106. }
  3107. return 0;
  3108. }
  3109. /* Return pointer to next closing brace or to comma */
  3110. static const char *next_brace_sub(const char *cp)
  3111. {
  3112. unsigned depth = 0;
  3113. cp++;
  3114. while (*cp != '\0') {
  3115. if (*cp == '\\') {
  3116. if (*++cp == '\0')
  3117. break;
  3118. cp++;
  3119. continue;
  3120. }
  3121. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3122. break;
  3123. if (*cp++ == '{')
  3124. depth++;
  3125. }
  3126. return *cp != '\0' ? cp : NULL;
  3127. }
  3128. /* Recursive brace globber. Note: may garble pattern[]. */
  3129. static int glob_brace(char *pattern, o_string *o, int n)
  3130. {
  3131. char *new_pattern_buf;
  3132. const char *begin;
  3133. const char *next;
  3134. const char *rest;
  3135. const char *p;
  3136. size_t rest_len;
  3137. debug_printf_glob("glob_brace('%s')\n", pattern);
  3138. begin = pattern;
  3139. while (1) {
  3140. if (*begin == '\0')
  3141. goto simple_glob;
  3142. if (*begin == '{') {
  3143. /* Find the first sub-pattern and at the same time
  3144. * find the rest after the closing brace */
  3145. next = next_brace_sub(begin);
  3146. if (next == NULL) {
  3147. /* An illegal expression */
  3148. goto simple_glob;
  3149. }
  3150. if (*next == '}') {
  3151. /* "{abc}" with no commas - illegal
  3152. * brace expr, disregard and skip it */
  3153. begin = next + 1;
  3154. continue;
  3155. }
  3156. break;
  3157. }
  3158. if (*begin == '\\' && begin[1] != '\0')
  3159. begin++;
  3160. begin++;
  3161. }
  3162. debug_printf_glob("begin:%s\n", begin);
  3163. debug_printf_glob("next:%s\n", next);
  3164. /* Now find the end of the whole brace expression */
  3165. rest = next;
  3166. while (*rest != '}') {
  3167. rest = next_brace_sub(rest);
  3168. if (rest == NULL) {
  3169. /* An illegal expression */
  3170. goto simple_glob;
  3171. }
  3172. debug_printf_glob("rest:%s\n", rest);
  3173. }
  3174. rest_len = strlen(++rest) + 1;
  3175. /* We are sure the brace expression is well-formed */
  3176. /* Allocate working buffer large enough for our work */
  3177. new_pattern_buf = xmalloc(strlen(pattern));
  3178. /* We have a brace expression. BEGIN points to the opening {,
  3179. * NEXT points past the terminator of the first element, and REST
  3180. * points past the final }. We will accumulate result names from
  3181. * recursive runs for each brace alternative in the buffer using
  3182. * GLOB_APPEND. */
  3183. p = begin + 1;
  3184. while (1) {
  3185. /* Construct the new glob expression */
  3186. memcpy(
  3187. mempcpy(
  3188. mempcpy(new_pattern_buf,
  3189. /* We know the prefix for all sub-patterns */
  3190. pattern, begin - pattern),
  3191. p, next - p),
  3192. rest, rest_len);
  3193. /* Note: glob_brace() may garble new_pattern_buf[].
  3194. * That's why we re-copy prefix every time (1st memcpy above).
  3195. */
  3196. n = glob_brace(new_pattern_buf, o, n);
  3197. if (*next == '}') {
  3198. /* We saw the last entry */
  3199. break;
  3200. }
  3201. p = next + 1;
  3202. next = next_brace_sub(next);
  3203. }
  3204. free(new_pattern_buf);
  3205. return n;
  3206. simple_glob:
  3207. {
  3208. int gr;
  3209. glob_t globdata;
  3210. memset(&globdata, 0, sizeof(globdata));
  3211. gr = glob(pattern, 0, NULL, &globdata);
  3212. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3213. if (gr != 0) {
  3214. if (gr == GLOB_NOMATCH) {
  3215. globfree(&globdata);
  3216. /* NB: garbles parameter */
  3217. unbackslash(pattern);
  3218. o_addstr_with_NUL(o, pattern);
  3219. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3220. return o_save_ptr_helper(o, n);
  3221. }
  3222. if (gr == GLOB_NOSPACE)
  3223. bb_die_memory_exhausted();
  3224. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3225. * but we didn't specify it. Paranoia again. */
  3226. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3227. }
  3228. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3229. char **argv = globdata.gl_pathv;
  3230. while (1) {
  3231. o_addstr_with_NUL(o, *argv);
  3232. n = o_save_ptr_helper(o, n);
  3233. argv++;
  3234. if (!*argv)
  3235. break;
  3236. }
  3237. }
  3238. globfree(&globdata);
  3239. }
  3240. return n;
  3241. }
  3242. /* Performs globbing on last list[],
  3243. * saving each result as a new list[].
  3244. */
  3245. static int perform_glob(o_string *o, int n)
  3246. {
  3247. char *pattern, *copy;
  3248. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3249. if (!o->data)
  3250. return o_save_ptr_helper(o, n);
  3251. pattern = o->data + o_get_last_ptr(o, n);
  3252. debug_printf_glob("glob pattern '%s'\n", pattern);
  3253. if (!glob_needed(pattern)) {
  3254. /* unbackslash last string in o in place, fix length */
  3255. o->length = unbackslash(pattern) - o->data;
  3256. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3257. return o_save_ptr_helper(o, n);
  3258. }
  3259. copy = xstrdup(pattern);
  3260. /* "forget" pattern in o */
  3261. o->length = pattern - o->data;
  3262. n = glob_brace(copy, o, n);
  3263. free(copy);
  3264. if (DEBUG_GLOB)
  3265. debug_print_list("perform_glob returning", o, n);
  3266. return n;
  3267. }
  3268. #else /* !HUSH_BRACE_EXPANSION */
  3269. /* Helper */
  3270. static int glob_needed(const char *s)
  3271. {
  3272. while (*s) {
  3273. if (*s == '\\') {
  3274. if (!s[1])
  3275. return 0;
  3276. s += 2;
  3277. continue;
  3278. }
  3279. if (*s == '*' || *s == '[' || *s == '?')
  3280. return 1;
  3281. s++;
  3282. }
  3283. return 0;
  3284. }
  3285. /* Performs globbing on last list[],
  3286. * saving each result as a new list[].
  3287. */
  3288. static int perform_glob(o_string *o, int n)
  3289. {
  3290. glob_t globdata;
  3291. int gr;
  3292. char *pattern;
  3293. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3294. if (!o->data)
  3295. return o_save_ptr_helper(o, n);
  3296. pattern = o->data + o_get_last_ptr(o, n);
  3297. debug_printf_glob("glob pattern '%s'\n", pattern);
  3298. if (!glob_needed(pattern)) {
  3299. literal:
  3300. /* unbackslash last string in o in place, fix length */
  3301. o->length = unbackslash(pattern) - o->data;
  3302. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3303. return o_save_ptr_helper(o, n);
  3304. }
  3305. memset(&globdata, 0, sizeof(globdata));
  3306. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3307. * If we glob "*.\*" and don't find anything, we need
  3308. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3309. * will return "*.\*"!
  3310. */
  3311. gr = glob(pattern, 0, NULL, &globdata);
  3312. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3313. if (gr != 0) {
  3314. if (gr == GLOB_NOMATCH) {
  3315. globfree(&globdata);
  3316. goto literal;
  3317. }
  3318. if (gr == GLOB_NOSPACE)
  3319. bb_die_memory_exhausted();
  3320. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3321. * but we didn't specify it. Paranoia again. */
  3322. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3323. }
  3324. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3325. char **argv = globdata.gl_pathv;
  3326. /* "forget" pattern in o */
  3327. o->length = pattern - o->data;
  3328. while (1) {
  3329. o_addstr_with_NUL(o, *argv);
  3330. n = o_save_ptr_helper(o, n);
  3331. argv++;
  3332. if (!*argv)
  3333. break;
  3334. }
  3335. }
  3336. globfree(&globdata);
  3337. if (DEBUG_GLOB)
  3338. debug_print_list("perform_glob returning", o, n);
  3339. return n;
  3340. }
  3341. #endif /* !HUSH_BRACE_EXPANSION */
  3342. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3343. * Otherwise, just finish current list[] and start new */
  3344. static int o_save_ptr(o_string *o, int n)
  3345. {
  3346. if (o->o_expflags & EXP_FLAG_GLOB) {
  3347. /* If o->has_empty_slot, list[n] was already globbed
  3348. * (if it was requested back then when it was filled)
  3349. * so don't do that again! */
  3350. if (!o->has_empty_slot)
  3351. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3352. }
  3353. return o_save_ptr_helper(o, n);
  3354. }
  3355. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3356. static char **o_finalize_list(o_string *o, int n)
  3357. {
  3358. char **list;
  3359. int string_start;
  3360. if (DEBUG_EXPAND)
  3361. debug_print_list("finalized", o, n);
  3362. debug_printf_expand("finalized n:%d\n", n);
  3363. list = (char**)o->data;
  3364. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3365. list[--n] = NULL;
  3366. while (n) {
  3367. n--;
  3368. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3369. }
  3370. return list;
  3371. }
  3372. static void free_pipe_list(struct pipe *pi);
  3373. /* Returns pi->next - next pipe in the list */
  3374. static struct pipe *free_pipe(struct pipe *pi)
  3375. {
  3376. struct pipe *next;
  3377. int i;
  3378. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3379. for (i = 0; i < pi->num_cmds; i++) {
  3380. struct command *command;
  3381. struct redir_struct *r, *rnext;
  3382. command = &pi->cmds[i];
  3383. debug_printf_clean(" command %d:\n", i);
  3384. if (command->argv) {
  3385. if (DEBUG_CLEAN) {
  3386. int a;
  3387. char **p;
  3388. for (a = 0, p = command->argv; *p; a++, p++) {
  3389. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3390. }
  3391. }
  3392. free_strings(command->argv);
  3393. //command->argv = NULL;
  3394. }
  3395. /* not "else if": on syntax error, we may have both! */
  3396. if (command->group) {
  3397. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3398. command->cmd_type);
  3399. free_pipe_list(command->group);
  3400. debug_printf_clean(" end group\n");
  3401. //command->group = NULL;
  3402. }
  3403. /* else is crucial here.
  3404. * If group != NULL, child_func is meaningless */
  3405. #if ENABLE_HUSH_FUNCTIONS
  3406. else if (command->child_func) {
  3407. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3408. command->child_func->parent_cmd = NULL;
  3409. }
  3410. #endif
  3411. #if !BB_MMU
  3412. free(command->group_as_string);
  3413. //command->group_as_string = NULL;
  3414. #endif
  3415. for (r = command->redirects; r; r = rnext) {
  3416. debug_printf_clean(" redirect %d%s",
  3417. r->rd_fd, redir_table[r->rd_type].descrip);
  3418. /* guard against the case >$FOO, where foo is unset or blank */
  3419. if (r->rd_filename) {
  3420. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3421. free(r->rd_filename);
  3422. //r->rd_filename = NULL;
  3423. }
  3424. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3425. rnext = r->next;
  3426. free(r);
  3427. }
  3428. //command->redirects = NULL;
  3429. }
  3430. free(pi->cmds); /* children are an array, they get freed all at once */
  3431. //pi->cmds = NULL;
  3432. #if ENABLE_HUSH_JOB
  3433. free(pi->cmdtext);
  3434. //pi->cmdtext = NULL;
  3435. #endif
  3436. next = pi->next;
  3437. free(pi);
  3438. return next;
  3439. }
  3440. static void free_pipe_list(struct pipe *pi)
  3441. {
  3442. while (pi) {
  3443. #if HAS_KEYWORDS
  3444. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3445. #endif
  3446. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3447. pi = free_pipe(pi);
  3448. }
  3449. }
  3450. /*** Parsing routines ***/
  3451. #ifndef debug_print_tree
  3452. static void debug_print_tree(struct pipe *pi, int lvl)
  3453. {
  3454. static const char *const PIPE[] ALIGN_PTR = {
  3455. [PIPE_SEQ] = "SEQ",
  3456. [PIPE_AND] = "AND",
  3457. [PIPE_OR ] = "OR" ,
  3458. [PIPE_BG ] = "BG" ,
  3459. };
  3460. static const char *RES[] = {
  3461. [RES_NONE ] = "NONE" ,
  3462. # if ENABLE_HUSH_IF
  3463. [RES_IF ] = "IF" ,
  3464. [RES_THEN ] = "THEN" ,
  3465. [RES_ELIF ] = "ELIF" ,
  3466. [RES_ELSE ] = "ELSE" ,
  3467. [RES_FI ] = "FI" ,
  3468. # endif
  3469. # if ENABLE_HUSH_LOOPS
  3470. [RES_FOR ] = "FOR" ,
  3471. [RES_WHILE] = "WHILE",
  3472. [RES_UNTIL] = "UNTIL",
  3473. [RES_DO ] = "DO" ,
  3474. [RES_DONE ] = "DONE" ,
  3475. # endif
  3476. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3477. [RES_IN ] = "IN" ,
  3478. # endif
  3479. # if ENABLE_HUSH_CASE
  3480. [RES_CASE ] = "CASE" ,
  3481. [RES_CASE_IN ] = "CASE_IN" ,
  3482. [RES_MATCH] = "MATCH",
  3483. [RES_CASE_BODY] = "CASE_BODY",
  3484. [RES_ESAC ] = "ESAC" ,
  3485. # endif
  3486. [RES_XXXX ] = "XXXX" ,
  3487. [RES_SNTX ] = "SNTX" ,
  3488. };
  3489. static const char *const CMDTYPE[] ALIGN_PTR = {
  3490. "{}",
  3491. "()",
  3492. "[noglob]",
  3493. # if ENABLE_HUSH_FUNCTIONS
  3494. "func()",
  3495. # endif
  3496. };
  3497. int pin, prn;
  3498. pin = 0;
  3499. while (pi) {
  3500. fdprintf(2, "%*spipe %d #cmds:%d %sres_word=%s followup=%d %s\n",
  3501. lvl*2, "",
  3502. pin,
  3503. pi->num_cmds,
  3504. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3505. RES[pi->res_word],
  3506. pi->followup, PIPE[pi->followup]
  3507. );
  3508. prn = 0;
  3509. while (prn < pi->num_cmds) {
  3510. struct command *command = &pi->cmds[prn];
  3511. char **argv = command->argv;
  3512. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3513. lvl*2, "", prn,
  3514. command->assignment_cnt);
  3515. # if ENABLE_HUSH_LINENO_VAR
  3516. fdprintf(2, " LINENO:%u", command->lineno);
  3517. # endif
  3518. if (command->group) {
  3519. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3520. CMDTYPE[command->cmd_type],
  3521. argv
  3522. # if !BB_MMU
  3523. , " group_as_string:", command->group_as_string
  3524. # else
  3525. , "", ""
  3526. # endif
  3527. );
  3528. debug_print_tree(command->group, lvl+1);
  3529. prn++;
  3530. continue;
  3531. }
  3532. if (argv) while (*argv) {
  3533. fdprintf(2, " '%s'", *argv);
  3534. argv++;
  3535. }
  3536. if (command->redirects)
  3537. fdprintf(2, " {redir}");
  3538. fdprintf(2, "\n");
  3539. prn++;
  3540. }
  3541. pi = pi->next;
  3542. pin++;
  3543. }
  3544. }
  3545. #endif /* debug_print_tree */
  3546. static struct pipe *new_pipe(void)
  3547. {
  3548. struct pipe *pi;
  3549. pi = xzalloc(sizeof(struct pipe));
  3550. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3551. return pi;
  3552. }
  3553. /* Command (member of a pipe) is complete, or we start a new pipe
  3554. * if ctx->command is NULL.
  3555. * No errors possible here.
  3556. */
  3557. static int done_command(struct parse_context *ctx)
  3558. {
  3559. /* The command is really already in the pipe structure, so
  3560. * advance the pipe counter and make a new, null command. */
  3561. struct pipe *pi = ctx->pipe;
  3562. struct command *command = ctx->command;
  3563. #if 0 /* Instead we emit error message at run time */
  3564. if (ctx->pending_redirect) {
  3565. /* For example, "cmd >" (no filename to redirect to) */
  3566. syntax_error("invalid redirect");
  3567. ctx->pending_redirect = NULL;
  3568. }
  3569. #endif
  3570. if (command) {
  3571. if (IS_NULL_CMD(command)) {
  3572. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3573. goto clear_and_ret;
  3574. }
  3575. pi->num_cmds++;
  3576. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3577. //debug_print_tree(ctx->list_head, 20);
  3578. } else {
  3579. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3580. }
  3581. /* Only real trickiness here is that the uncommitted
  3582. * command structure is not counted in pi->num_cmds. */
  3583. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3584. ctx->command = command = &pi->cmds[pi->num_cmds];
  3585. clear_and_ret:
  3586. memset(command, 0, sizeof(*command));
  3587. #if ENABLE_HUSH_LINENO_VAR
  3588. command->lineno = G.parse_lineno;
  3589. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3590. #endif
  3591. return pi->num_cmds; /* used only for 0/nonzero check */
  3592. }
  3593. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3594. {
  3595. int not_null;
  3596. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3597. /* Close previous command */
  3598. not_null = done_command(ctx);
  3599. #if HAS_KEYWORDS
  3600. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3601. ctx->ctx_inverted = 0;
  3602. ctx->pipe->res_word = ctx->ctx_res_w;
  3603. #endif
  3604. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3605. /* Necessary since && and || have precedence over &:
  3606. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3607. * in a backgrounded subshell.
  3608. */
  3609. struct pipe *pi;
  3610. struct command *command;
  3611. /* Is this actually this construct, all pipes end with && or ||? */
  3612. pi = ctx->list_head;
  3613. while (pi != ctx->pipe) {
  3614. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3615. goto no_conv;
  3616. pi = pi->next;
  3617. }
  3618. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3619. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3620. pi = xzalloc(sizeof(*pi));
  3621. pi->followup = PIPE_BG;
  3622. pi->num_cmds = 1;
  3623. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3624. command = &pi->cmds[0];
  3625. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3626. command->cmd_type = CMD_NORMAL;
  3627. command->group = ctx->list_head;
  3628. #if !BB_MMU
  3629. command->group_as_string = xstrndup(
  3630. ctx->as_string.data,
  3631. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3632. );
  3633. #endif
  3634. /* Replace all pipes in ctx with one newly created */
  3635. ctx->list_head = ctx->pipe = pi;
  3636. /* for cases like "cmd && &", do not be tricked by last command
  3637. * being null - the entire {...} & is NOT null! */
  3638. not_null = 1;
  3639. } else {
  3640. no_conv:
  3641. ctx->pipe->followup = type;
  3642. }
  3643. /* Without this check, even just <enter> on command line generates
  3644. * tree of three NOPs (!). Which is harmless but annoying.
  3645. * IOW: it is safe to do it unconditionally. */
  3646. if (not_null
  3647. #if ENABLE_HUSH_IF
  3648. || ctx->ctx_res_w == RES_FI
  3649. #endif
  3650. #if ENABLE_HUSH_LOOPS
  3651. || ctx->ctx_res_w == RES_DONE
  3652. || ctx->ctx_res_w == RES_FOR
  3653. || ctx->ctx_res_w == RES_IN
  3654. #endif
  3655. #if ENABLE_HUSH_CASE
  3656. || ctx->ctx_res_w == RES_ESAC
  3657. #endif
  3658. ) {
  3659. struct pipe *new_p;
  3660. debug_printf_parse("done_pipe: adding new pipe: "
  3661. "not_null:%d ctx->ctx_res_w:%d\n",
  3662. not_null, ctx->ctx_res_w);
  3663. new_p = new_pipe();
  3664. ctx->pipe->next = new_p;
  3665. ctx->pipe = new_p;
  3666. /* RES_THEN, RES_DO etc are "sticky" -
  3667. * they remain set for pipes inside if/while.
  3668. * This is used to control execution.
  3669. * RES_FOR and RES_IN are NOT sticky (needed to support
  3670. * cases where variable or value happens to match a keyword):
  3671. */
  3672. #if ENABLE_HUSH_LOOPS
  3673. if (ctx->ctx_res_w == RES_FOR
  3674. || ctx->ctx_res_w == RES_IN)
  3675. ctx->ctx_res_w = RES_NONE;
  3676. #endif
  3677. #if ENABLE_HUSH_CASE
  3678. if (ctx->ctx_res_w == RES_MATCH)
  3679. ctx->ctx_res_w = RES_CASE_BODY;
  3680. if (ctx->ctx_res_w == RES_CASE)
  3681. ctx->ctx_res_w = RES_CASE_IN;
  3682. #endif
  3683. ctx->command = NULL; /* trick done_command below */
  3684. /* Create the memory for command, roughly:
  3685. * ctx->pipe->cmds = new struct command;
  3686. * ctx->command = &ctx->pipe->cmds[0];
  3687. */
  3688. done_command(ctx);
  3689. //debug_print_tree(ctx->list_head, 10);
  3690. }
  3691. debug_printf_parse("done_pipe return\n");
  3692. }
  3693. static void initialize_context(struct parse_context *ctx)
  3694. {
  3695. memset(ctx, 0, sizeof(*ctx));
  3696. if (MAYBE_ASSIGNMENT != 0)
  3697. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3698. ctx->pipe = ctx->list_head = new_pipe();
  3699. /* Create the memory for command, roughly:
  3700. * ctx->pipe->cmds = new struct command;
  3701. * ctx->command = &ctx->pipe->cmds[0];
  3702. */
  3703. done_command(ctx);
  3704. }
  3705. /* If a reserved word is found and processed, parse context is modified
  3706. * and 1 is returned.
  3707. */
  3708. #if HAS_KEYWORDS
  3709. struct reserved_combo {
  3710. char literal[6];
  3711. unsigned char res;
  3712. unsigned char assignment_flag;
  3713. uint32_t flag;
  3714. };
  3715. enum {
  3716. FLAG_END = (1 << RES_NONE ),
  3717. # if ENABLE_HUSH_IF
  3718. FLAG_IF = (1 << RES_IF ),
  3719. FLAG_THEN = (1 << RES_THEN ),
  3720. FLAG_ELIF = (1 << RES_ELIF ),
  3721. FLAG_ELSE = (1 << RES_ELSE ),
  3722. FLAG_FI = (1 << RES_FI ),
  3723. # endif
  3724. # if ENABLE_HUSH_LOOPS
  3725. FLAG_FOR = (1 << RES_FOR ),
  3726. FLAG_WHILE = (1 << RES_WHILE),
  3727. FLAG_UNTIL = (1 << RES_UNTIL),
  3728. FLAG_DO = (1 << RES_DO ),
  3729. FLAG_DONE = (1 << RES_DONE ),
  3730. FLAG_IN = (1 << RES_IN ),
  3731. # endif
  3732. # if ENABLE_HUSH_CASE
  3733. FLAG_MATCH = (1 << RES_MATCH),
  3734. FLAG_ESAC = (1 << RES_ESAC ),
  3735. # endif
  3736. FLAG_START = (1 << RES_XXXX ),
  3737. };
  3738. static const struct reserved_combo* match_reserved_word(o_string *word)
  3739. {
  3740. /* Mostly a list of accepted follow-up reserved words.
  3741. * FLAG_END means we are done with the sequence, and are ready
  3742. * to turn the compound list into a command.
  3743. * FLAG_START means the word must start a new compound list.
  3744. */
  3745. static const struct reserved_combo reserved_list[] ALIGN4 = {
  3746. # if ENABLE_HUSH_IF
  3747. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3748. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3749. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3750. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3751. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3752. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3753. # endif
  3754. # if ENABLE_HUSH_LOOPS
  3755. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3756. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3757. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3758. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3759. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3760. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3761. # endif
  3762. # if ENABLE_HUSH_CASE
  3763. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3764. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3765. # endif
  3766. };
  3767. const struct reserved_combo *r;
  3768. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3769. if (strcmp(word->data, r->literal) == 0)
  3770. return r;
  3771. }
  3772. return NULL;
  3773. }
  3774. /* Return NULL: not a keyword, else: keyword
  3775. */
  3776. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3777. {
  3778. # if ENABLE_HUSH_CASE
  3779. static const struct reserved_combo reserved_match = {
  3780. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3781. };
  3782. # endif
  3783. const struct reserved_combo *r;
  3784. if (ctx->word.has_quoted_part)
  3785. return 0;
  3786. r = match_reserved_word(&ctx->word);
  3787. if (!r)
  3788. return r; /* NULL */
  3789. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3790. # if ENABLE_HUSH_CASE
  3791. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3792. /* "case word IN ..." - IN part starts first MATCH part */
  3793. r = &reserved_match;
  3794. } else
  3795. # endif
  3796. if (r->flag == 0) { /* '!' */
  3797. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3798. syntax_error("! ! command");
  3799. ctx->ctx_res_w = RES_SNTX;
  3800. }
  3801. ctx->ctx_inverted = 1;
  3802. return r;
  3803. }
  3804. if (r->flag & FLAG_START) {
  3805. struct parse_context *old;
  3806. old = xmemdup(ctx, sizeof(*ctx));
  3807. debug_printf_parse("push stack %p\n", old);
  3808. initialize_context(ctx);
  3809. ctx->stack = old;
  3810. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3811. syntax_error_at(ctx->word.data);
  3812. ctx->ctx_res_w = RES_SNTX;
  3813. return r;
  3814. } else {
  3815. /* "{...} fi" is ok. "{...} if" is not
  3816. * Example:
  3817. * if { echo foo; } then { echo bar; } fi */
  3818. if (ctx->command->group)
  3819. done_pipe(ctx, PIPE_SEQ);
  3820. }
  3821. ctx->ctx_res_w = r->res;
  3822. ctx->old_flag = r->flag;
  3823. ctx->is_assignment = r->assignment_flag;
  3824. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3825. if (ctx->old_flag & FLAG_END) {
  3826. struct parse_context *old;
  3827. done_pipe(ctx, PIPE_SEQ);
  3828. debug_printf_parse("pop stack %p\n", ctx->stack);
  3829. old = ctx->stack;
  3830. old->command->group = ctx->list_head;
  3831. old->command->cmd_type = CMD_NORMAL;
  3832. # if !BB_MMU
  3833. /* At this point, the compound command's string is in
  3834. * ctx->as_string... except for the leading keyword!
  3835. * Consider this example: "echo a | if true; then echo a; fi"
  3836. * ctx->as_string will contain "true; then echo a; fi",
  3837. * with "if " remaining in old->as_string!
  3838. */
  3839. {
  3840. char *str;
  3841. int len = old->as_string.length;
  3842. /* Concatenate halves */
  3843. o_addstr(&old->as_string, ctx->as_string.data);
  3844. o_free(&ctx->as_string);
  3845. /* Find where leading keyword starts in first half */
  3846. str = old->as_string.data + len;
  3847. if (str > old->as_string.data)
  3848. str--; /* skip whitespace after keyword */
  3849. while (str > old->as_string.data && isalpha(str[-1]))
  3850. str--;
  3851. /* Ugh, we're done with this horrid hack */
  3852. old->command->group_as_string = xstrdup(str);
  3853. debug_printf_parse("pop, remembering as:'%s'\n",
  3854. old->command->group_as_string);
  3855. }
  3856. # endif
  3857. *ctx = *old; /* physical copy */
  3858. free(old);
  3859. }
  3860. return r;
  3861. }
  3862. #endif /* HAS_KEYWORDS */
  3863. /* Word is complete, look at it and update parsing context.
  3864. * Normal return is 0. Syntax errors return 1.
  3865. * Note: on return, word is reset, but not o_free'd!
  3866. */
  3867. static int done_word(struct parse_context *ctx)
  3868. {
  3869. struct command *command = ctx->command;
  3870. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3871. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3872. debug_printf_parse("done_word return 0: true null, ignored\n");
  3873. return 0;
  3874. }
  3875. if (ctx->pending_redirect) {
  3876. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3877. * only if run as "bash", not "sh" */
  3878. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3879. * "2.7 Redirection
  3880. * If the redirection operator is "<<" or "<<-", the word
  3881. * that follows the redirection operator shall be
  3882. * subjected to quote removal; it is unspecified whether
  3883. * any of the other expansions occur. For the other
  3884. * redirection operators, the word that follows the
  3885. * redirection operator shall be subjected to tilde
  3886. * expansion, parameter expansion, command substitution,
  3887. * arithmetic expansion, and quote removal.
  3888. * Pathname expansion shall not be performed
  3889. * on the word by a non-interactive shell; an interactive
  3890. * shell may perform it, but shall do so only when
  3891. * the expansion would result in one word."
  3892. */
  3893. //bash does not do parameter/command substitution or arithmetic expansion
  3894. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3895. // as written:
  3896. // <<EOF$t
  3897. // <<EOF$((1))
  3898. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3899. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3900. /* Cater for >\file case:
  3901. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3902. * Same with heredocs:
  3903. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3904. */
  3905. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3906. unbackslash(ctx->pending_redirect->rd_filename);
  3907. /* Is it <<"HEREDOC"? */
  3908. if (ctx->word.has_quoted_part) {
  3909. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3910. }
  3911. }
  3912. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3913. ctx->pending_redirect = NULL;
  3914. } else {
  3915. #if HAS_KEYWORDS
  3916. # if ENABLE_HUSH_CASE
  3917. if (ctx->ctx_dsemicolon
  3918. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3919. ) {
  3920. /* already done when ctx_dsemicolon was set to 1: */
  3921. /* ctx->ctx_res_w = RES_MATCH; */
  3922. ctx->ctx_dsemicolon = 0;
  3923. } else
  3924. # endif
  3925. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3926. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
  3927. && strcmp(ctx->word.data, "]]") == 0
  3928. ) {
  3929. /* allow "[[ ]] >file" etc */
  3930. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3931. } else
  3932. # endif
  3933. if (!command->argv /* if it's the first word... */
  3934. # if ENABLE_HUSH_LOOPS
  3935. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3936. && ctx->ctx_res_w != RES_IN
  3937. # endif
  3938. # if ENABLE_HUSH_CASE
  3939. && ctx->ctx_res_w != RES_CASE
  3940. # endif
  3941. ) {
  3942. const struct reserved_combo *reserved;
  3943. reserved = reserved_word(ctx);
  3944. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3945. if (reserved) {
  3946. # if ENABLE_HUSH_LINENO_VAR
  3947. /* Case:
  3948. * "while ...; do
  3949. * cmd ..."
  3950. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3951. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3952. */
  3953. if (0
  3954. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3955. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3956. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3957. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3958. ) {
  3959. done_pipe(ctx, PIPE_SEQ);
  3960. }
  3961. # endif
  3962. o_reset_to_empty_unquoted(&ctx->word);
  3963. debug_printf_parse("done_word return %d\n",
  3964. (ctx->ctx_res_w == RES_SNTX));
  3965. return (ctx->ctx_res_w == RES_SNTX);
  3966. }
  3967. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3968. if (strcmp(ctx->word.data, "[[") == 0) {
  3969. command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
  3970. } else
  3971. # endif
  3972. # if defined(CMD_SINGLEWORD_NOGLOB)
  3973. if (0
  3974. /* In bash, local/export/readonly are special, args
  3975. * are assignments and therefore expansion of them
  3976. * should be "one-word" expansion:
  3977. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3978. * compare with:
  3979. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3980. * ls: cannot access i=a: No such file or directory
  3981. * ls: cannot access b: No such file or directory
  3982. * Note: bash 3.2.33(1) does this only if export word
  3983. * itself is not quoted:
  3984. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3985. * aaa bbb
  3986. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3987. * aaa
  3988. */
  3989. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3990. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3991. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3992. ) {
  3993. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3994. }
  3995. # else
  3996. { /* empty block to pair "if ... else" */ }
  3997. # endif
  3998. }
  3999. #endif /* HAS_KEYWORDS */
  4000. if (command->group) {
  4001. /* "{ echo foo; } echo bar" - bad */
  4002. syntax_error_at(ctx->word.data);
  4003. debug_printf_parse("done_word return 1: syntax error, "
  4004. "groups and arglists don't mix\n");
  4005. return 1;
  4006. }
  4007. /* If this word wasn't an assignment, next ones definitely
  4008. * can't be assignments. Even if they look like ones. */
  4009. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  4010. && ctx->is_assignment != WORD_IS_KEYWORD
  4011. ) {
  4012. ctx->is_assignment = NOT_ASSIGNMENT;
  4013. } else {
  4014. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  4015. command->assignment_cnt++;
  4016. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  4017. }
  4018. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  4019. ctx->is_assignment = MAYBE_ASSIGNMENT;
  4020. }
  4021. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  4022. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  4023. debug_print_strings("word appended to argv", command->argv);
  4024. }
  4025. #if ENABLE_HUSH_LOOPS
  4026. if (ctx->ctx_res_w == RES_FOR) {
  4027. if (ctx->word.has_quoted_part
  4028. || endofname(command->argv[0])[0] != '\0'
  4029. ) {
  4030. /* bash says just "not a valid identifier" */
  4031. syntax_error("bad for loop variable");
  4032. return 1;
  4033. }
  4034. /* Force FOR to have just one word (variable name) */
  4035. /* NB: basically, this makes hush see "for v in ..."
  4036. * syntax as if it is "for v; in ...". FOR and IN become
  4037. * two pipe structs in parse tree. */
  4038. done_pipe(ctx, PIPE_SEQ);
  4039. }
  4040. #endif
  4041. #if ENABLE_HUSH_CASE
  4042. /* Force CASE to have just one word */
  4043. if (ctx->ctx_res_w == RES_CASE) {
  4044. done_pipe(ctx, PIPE_SEQ);
  4045. }
  4046. #endif
  4047. o_reset_to_empty_unquoted(&ctx->word);
  4048. debug_printf_parse("done_word return 0\n");
  4049. return 0;
  4050. }
  4051. /* Peek ahead in the input to find out if we have a "&n" construct,
  4052. * as in "2>&1", that represents duplicating a file descriptor.
  4053. * Return:
  4054. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  4055. * REDIRFD_SYNTAX_ERR if syntax error,
  4056. * REDIRFD_TO_FILE if no & was seen,
  4057. * or the number found.
  4058. */
  4059. #if BB_MMU
  4060. #define parse_redir_right_fd(as_string, input) \
  4061. parse_redir_right_fd(input)
  4062. #endif
  4063. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  4064. {
  4065. int ch, d, ok;
  4066. ch = i_peek(input);
  4067. if (ch != '&')
  4068. return REDIRFD_TO_FILE;
  4069. ch = i_getch(input); /* get the & */
  4070. nommu_addchr(as_string, ch);
  4071. ch = i_peek(input);
  4072. if (ch == '-') {
  4073. ch = i_getch(input);
  4074. nommu_addchr(as_string, ch);
  4075. return REDIRFD_CLOSE;
  4076. }
  4077. d = 0;
  4078. ok = 0;
  4079. while (ch != EOF && isdigit(ch)) {
  4080. d = d*10 + (ch-'0');
  4081. ok = 1;
  4082. ch = i_getch(input);
  4083. nommu_addchr(as_string, ch);
  4084. ch = i_peek(input);
  4085. }
  4086. if (ok) return d;
  4087. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  4088. bb_simple_error_msg("ambiguous redirect");
  4089. return REDIRFD_SYNTAX_ERR;
  4090. }
  4091. /* Return code is 0 normal, 1 if a syntax error is detected
  4092. */
  4093. static int parse_redirect(struct parse_context *ctx,
  4094. int fd,
  4095. redir_type style,
  4096. struct in_str *input)
  4097. {
  4098. struct command *command = ctx->command;
  4099. struct redir_struct *redir;
  4100. struct redir_struct **redirp;
  4101. int dup_num;
  4102. dup_num = REDIRFD_TO_FILE;
  4103. if (style != REDIRECT_HEREDOC) {
  4104. /* Check for a '>&1' type redirect */
  4105. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  4106. if (dup_num == REDIRFD_SYNTAX_ERR)
  4107. return 1;
  4108. } else {
  4109. int ch = i_peek_and_eat_bkslash_nl(input);
  4110. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4111. if (dup_num) { /* <<-... */
  4112. ch = i_getch(input);
  4113. nommu_addchr(&ctx->as_string, ch);
  4114. ch = i_peek(input);
  4115. }
  4116. }
  4117. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4118. int ch = i_peek_and_eat_bkslash_nl(input);
  4119. if (ch == '|') {
  4120. /* >|FILE redirect ("clobbering" >).
  4121. * Since we do not support "set -o noclobber" yet,
  4122. * >| and > are the same for now. Just eat |.
  4123. */
  4124. ch = i_getch(input);
  4125. nommu_addchr(&ctx->as_string, ch);
  4126. }
  4127. }
  4128. /* Create a new redir_struct and append it to the linked list */
  4129. redirp = &command->redirects;
  4130. while ((redir = *redirp) != NULL) {
  4131. redirp = &(redir->next);
  4132. }
  4133. *redirp = redir = xzalloc(sizeof(*redir));
  4134. /* redir->next = NULL; */
  4135. /* redir->rd_filename = NULL; */
  4136. redir->rd_type = style;
  4137. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4138. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4139. redir_table[style].descrip);
  4140. redir->rd_dup = dup_num;
  4141. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4142. /* Erik had a check here that the file descriptor in question
  4143. * is legit; I postpone that to "run time"
  4144. * A "-" representation of "close me" shows up as a -3 here */
  4145. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4146. redir->rd_fd, redir->rd_dup);
  4147. } else {
  4148. #if 0 /* Instead we emit error message at run time */
  4149. if (ctx->pending_redirect) {
  4150. /* For example, "cmd > <file" */
  4151. syntax_error("invalid redirect");
  4152. }
  4153. #endif
  4154. /* Set ctx->pending_redirect, so we know what to do at the
  4155. * end of the next parsed word. */
  4156. ctx->pending_redirect = redir;
  4157. }
  4158. return 0;
  4159. }
  4160. /* If a redirect is immediately preceded by a number, that number is
  4161. * supposed to tell which file descriptor to redirect. This routine
  4162. * looks for such preceding numbers. In an ideal world this routine
  4163. * needs to handle all the following classes of redirects...
  4164. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4165. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4166. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4167. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4168. *
  4169. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4170. * "2.7 Redirection
  4171. * ... If n is quoted, the number shall not be recognized as part of
  4172. * the redirection expression. For example:
  4173. * echo \2>a
  4174. * writes the character 2 into file a"
  4175. * We are getting it right by setting ->has_quoted_part on any \<char>
  4176. *
  4177. * A -1 return means no valid number was found,
  4178. * the caller should use the appropriate default for this redirection.
  4179. */
  4180. static int redirect_opt_num(o_string *o)
  4181. {
  4182. int num;
  4183. if (o->data == NULL)
  4184. return -1;
  4185. num = bb_strtou(o->data, NULL, 10);
  4186. if (errno || num < 0)
  4187. return -1;
  4188. o_reset_to_empty_unquoted(o);
  4189. return num;
  4190. }
  4191. #if BB_MMU
  4192. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4193. fetch_till_str(input, word, skip_tabs)
  4194. #endif
  4195. static char *fetch_till_str(o_string *as_string,
  4196. struct in_str *input,
  4197. const char *word,
  4198. int heredoc_flags)
  4199. {
  4200. o_string heredoc = NULL_O_STRING;
  4201. unsigned past_EOL;
  4202. int prev = 0; /* not \ */
  4203. int ch;
  4204. /* Starting with "" is necessary for this case:
  4205. * cat <<EOF
  4206. *
  4207. * xxx
  4208. * EOF
  4209. */
  4210. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4211. goto jump_in;
  4212. while (1) {
  4213. ch = i_getch(input);
  4214. if (ch != EOF)
  4215. nommu_addchr(as_string, ch);
  4216. if (ch == '\n' || ch == EOF) {
  4217. check_heredoc_end:
  4218. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4219. /* End-of-line, and not a line continuation */
  4220. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4221. heredoc.data[past_EOL] = '\0';
  4222. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4223. return heredoc.data;
  4224. }
  4225. if (ch == '\n') {
  4226. /* This is a new line.
  4227. * Remember position and backslash-escaping status.
  4228. */
  4229. o_addchr(&heredoc, ch);
  4230. prev = ch;
  4231. jump_in:
  4232. past_EOL = heredoc.length;
  4233. /* Get 1st char of next line, possibly skipping leading tabs */
  4234. do {
  4235. ch = i_getch(input);
  4236. if (ch != EOF)
  4237. nommu_addchr(as_string, ch);
  4238. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4239. /* If this immediately ended the line,
  4240. * go back to end-of-line checks.
  4241. */
  4242. if (ch == '\n')
  4243. goto check_heredoc_end;
  4244. }
  4245. } else {
  4246. /* Backslash-line continuation in an unquoted
  4247. * heredoc. This does not need special handling
  4248. * for heredoc body (unquoted heredocs are
  4249. * expanded on "execution" and that would take
  4250. * care of this case too), but not the case
  4251. * of line continuation *in terminator*:
  4252. * cat <<EOF
  4253. * Ok1
  4254. * EO\
  4255. * F
  4256. */
  4257. heredoc.data[--heredoc.length] = '\0';
  4258. prev = 0; /* not '\' */
  4259. continue;
  4260. }
  4261. }
  4262. if (ch == EOF) {
  4263. o_free(&heredoc);
  4264. return NULL; /* error */
  4265. }
  4266. o_addchr(&heredoc, ch);
  4267. nommu_addchr(as_string, ch);
  4268. if (prev == '\\' && ch == '\\')
  4269. /* Correctly handle foo\\<eol> (not a line cont.) */
  4270. prev = 0; /* not '\' */
  4271. else
  4272. prev = ch;
  4273. }
  4274. }
  4275. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4276. * and load them all. There should be exactly heredoc_cnt of them.
  4277. */
  4278. #if BB_MMU
  4279. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4280. fetch_heredocs(pi, heredoc_cnt, input)
  4281. #endif
  4282. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4283. {
  4284. while (pi && heredoc_cnt) {
  4285. int i;
  4286. struct command *cmd = pi->cmds;
  4287. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4288. pi->num_cmds,
  4289. cmd->argv ? cmd->argv[0] : "NONE"
  4290. );
  4291. for (i = 0; i < pi->num_cmds; i++) {
  4292. struct redir_struct *redir = cmd->redirects;
  4293. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4294. i, cmd->argv ? cmd->argv[0] : "NONE");
  4295. while (redir) {
  4296. if (redir->rd_type == REDIRECT_HEREDOC) {
  4297. char *p;
  4298. redir->rd_type = REDIRECT_HEREDOC2;
  4299. /* redir->rd_dup is (ab)used to indicate <<- */
  4300. p = fetch_till_str(as_string, input,
  4301. redir->rd_filename, redir->rd_dup);
  4302. if (!p) {
  4303. syntax_error("unexpected EOF in here document");
  4304. return -1;
  4305. }
  4306. free(redir->rd_filename);
  4307. redir->rd_filename = p;
  4308. heredoc_cnt--;
  4309. }
  4310. redir = redir->next;
  4311. }
  4312. if (cmd->group) {
  4313. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4314. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4315. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4316. if (heredoc_cnt < 0)
  4317. return heredoc_cnt; /* error */
  4318. }
  4319. cmd++;
  4320. }
  4321. pi = pi->next;
  4322. }
  4323. return heredoc_cnt;
  4324. }
  4325. static int run_list(struct pipe *pi);
  4326. #if BB_MMU
  4327. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4328. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4329. #endif
  4330. static struct pipe *parse_stream(char **pstring,
  4331. int *heredoc_cnt_ptr,
  4332. struct in_str *input,
  4333. int end_trigger);
  4334. /* Returns number of heredocs not yet consumed,
  4335. * or -1 on error.
  4336. */
  4337. static int parse_group(struct parse_context *ctx,
  4338. struct in_str *input, int ch)
  4339. {
  4340. /* ctx->word contains characters seen prior to ( or {.
  4341. * Typically it's empty, but for function defs,
  4342. * it contains function name (without '()'). */
  4343. #if BB_MMU
  4344. # define as_string NULL
  4345. #else
  4346. char *as_string = NULL;
  4347. #endif
  4348. struct pipe *pipe_list;
  4349. int heredoc_cnt = 0;
  4350. int endch;
  4351. struct command *command = ctx->command;
  4352. debug_printf_parse("parse_group entered\n");
  4353. #if ENABLE_HUSH_FUNCTIONS
  4354. if (ch == '(' && !ctx->word.has_quoted_part) {
  4355. if (ctx->word.length)
  4356. if (done_word(ctx))
  4357. return -1;
  4358. if (!command->argv)
  4359. goto skip; /* (... */
  4360. if (command->argv[1]) { /* word word ... (... */
  4361. syntax_error_unexpected_ch('(');
  4362. return -1;
  4363. }
  4364. /* it is "word(..." or "word (..." */
  4365. do
  4366. ch = i_getch(input);
  4367. while (ch == ' ' || ch == '\t');
  4368. if (ch != ')') {
  4369. syntax_error_unexpected_ch(ch);
  4370. return -1;
  4371. }
  4372. nommu_addchr(&ctx->as_string, ch);
  4373. do
  4374. ch = i_getch(input);
  4375. while (ch == ' ' || ch == '\t' || ch == '\n');
  4376. if (ch != '{' && ch != '(') {
  4377. syntax_error_unexpected_ch(ch);
  4378. return -1;
  4379. }
  4380. //bash allows functions named "123", "..", "return"!
  4381. // if (endofname(command->argv[0])[0] != '\0') {
  4382. // syntax_error("bad function name");
  4383. // return -1;
  4384. // }
  4385. nommu_addchr(&ctx->as_string, ch);
  4386. command->cmd_type = CMD_FUNCDEF;
  4387. goto skip;
  4388. }
  4389. #endif
  4390. #if 0 /* Prevented by caller */
  4391. if (command->argv /* word [word]{... */
  4392. || ctx->word.length /* word{... */
  4393. || ctx->word.has_quoted_part /* ""{... */
  4394. ) {
  4395. syntax_error(NULL);
  4396. debug_printf_parse("parse_group return -1: "
  4397. "syntax error, groups and arglists don't mix\n");
  4398. return -1;
  4399. }
  4400. #endif
  4401. IF_HUSH_FUNCTIONS(skip:)
  4402. endch = '}';
  4403. if (ch == '(') {
  4404. endch = ')';
  4405. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4406. command->cmd_type = CMD_SUBSHELL;
  4407. } else {
  4408. /* bash does not allow "{echo...", requires whitespace */
  4409. ch = i_peek(input);
  4410. if (ch != ' ' && ch != '\t' && ch != '\n'
  4411. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4412. ) {
  4413. syntax_error_unexpected_ch(ch);
  4414. return -1;
  4415. }
  4416. if (ch != '(') {
  4417. ch = i_getch(input);
  4418. nommu_addchr(&ctx->as_string, ch);
  4419. }
  4420. }
  4421. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4422. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4423. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4424. #if !BB_MMU
  4425. if (as_string)
  4426. o_addstr(&ctx->as_string, as_string);
  4427. #endif
  4428. /* empty ()/{} or parse error? */
  4429. if (!pipe_list || pipe_list == ERR_PTR) {
  4430. /* parse_stream already emitted error msg */
  4431. if (!BB_MMU)
  4432. free(as_string);
  4433. debug_printf_parse("parse_group return -1: "
  4434. "parse_stream returned %p\n", pipe_list);
  4435. return -1;
  4436. }
  4437. #if !BB_MMU
  4438. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4439. command->group_as_string = as_string;
  4440. debug_printf_parse("end of group, remembering as:'%s'\n",
  4441. command->group_as_string);
  4442. #endif
  4443. #if ENABLE_HUSH_FUNCTIONS
  4444. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4445. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4446. struct command *cmd2;
  4447. cmd2 = xzalloc(sizeof(*cmd2));
  4448. cmd2->cmd_type = CMD_SUBSHELL;
  4449. cmd2->group = pipe_list;
  4450. # if !BB_MMU
  4451. //UNTESTED!
  4452. cmd2->group_as_string = command->group_as_string;
  4453. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4454. # endif
  4455. pipe_list = new_pipe();
  4456. pipe_list->cmds = cmd2;
  4457. pipe_list->num_cmds = 1;
  4458. }
  4459. #endif
  4460. command->group = pipe_list;
  4461. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4462. return heredoc_cnt;
  4463. /* command remains "open", available for possible redirects */
  4464. #undef as_string
  4465. }
  4466. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4467. /* Subroutines for copying $(...) and `...` things */
  4468. /* '...' */
  4469. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4470. {
  4471. while (1) {
  4472. int ch = i_getch(input);
  4473. if (ch == EOF) {
  4474. syntax_error_unterm_ch('\'');
  4475. return 0;
  4476. }
  4477. if (ch == '\'')
  4478. return 1;
  4479. o_addchr(dest, ch);
  4480. }
  4481. }
  4482. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4483. {
  4484. while (1) {
  4485. int ch = i_getch(input);
  4486. if (ch == EOF) {
  4487. syntax_error_unterm_ch('\'');
  4488. return 0;
  4489. }
  4490. if (ch == '\'')
  4491. return 1;
  4492. o_addqchr(dest, ch);
  4493. }
  4494. }
  4495. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4496. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4497. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4498. {
  4499. while (1) {
  4500. int ch = i_getch(input);
  4501. if (ch == EOF) {
  4502. syntax_error_unterm_ch('"');
  4503. return 0;
  4504. }
  4505. if (ch == '"')
  4506. return 1;
  4507. if (ch == '\\') { /* \x. Copy both chars. */
  4508. o_addchr(dest, ch);
  4509. ch = i_getch(input);
  4510. }
  4511. o_addchr(dest, ch);
  4512. if (ch == '`') {
  4513. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4514. return 0;
  4515. o_addchr(dest, ch);
  4516. continue;
  4517. }
  4518. //if (ch == '$') ...
  4519. }
  4520. }
  4521. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4522. * \` quoting.
  4523. * "Within the backquoted style of command substitution, backslash
  4524. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4525. * The search for the matching backquote shall be satisfied by the first
  4526. * backquote found without a preceding backslash; during this search,
  4527. * if a non-escaped backquote is encountered within a shell comment,
  4528. * a here-document, an embedded command substitution of the $(command)
  4529. * form, or a quoted string, undefined results occur. A single-quoted
  4530. * or double-quoted string that begins, but does not end, within the
  4531. * "`...`" sequence produces undefined results."
  4532. * Example Output
  4533. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4534. */
  4535. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4536. {
  4537. while (1) {
  4538. int ch = i_getch(input);
  4539. if (ch == '`')
  4540. return 1;
  4541. if (ch == '\\') {
  4542. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4543. ch = i_getch(input);
  4544. if (ch != '`'
  4545. && ch != '$'
  4546. && ch != '\\'
  4547. && (!in_dquote || ch != '"')
  4548. ) {
  4549. o_addchr(dest, '\\');
  4550. }
  4551. }
  4552. if (ch == EOF) {
  4553. syntax_error_unterm_ch('`');
  4554. return 0;
  4555. }
  4556. o_addchr(dest, ch);
  4557. }
  4558. }
  4559. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4560. * quoting and nested ()s.
  4561. * "With the $(command) style of command substitution, all characters
  4562. * following the open parenthesis to the matching closing parenthesis
  4563. * constitute the command. Any valid shell script can be used for command,
  4564. * except a script consisting solely of redirections which produces
  4565. * unspecified results."
  4566. * Example Output
  4567. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4568. * echo $(echo 'TEST)' BEST) TEST) BEST
  4569. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4570. *
  4571. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4572. * can contain arbitrary constructs, just like $(cmd).
  4573. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4574. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4575. */
  4576. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4577. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4578. {
  4579. int ch;
  4580. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4581. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4582. char end_char2 = end_ch >> 8;
  4583. # endif
  4584. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4585. # if ENABLE_HUSH_INTERACTIVE
  4586. G.promptmode = 1; /* PS2 */
  4587. # endif
  4588. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4589. while (1) {
  4590. ch = i_getch(input);
  4591. if (ch == EOF) {
  4592. syntax_error_unterm_ch(end_ch);
  4593. return 0;
  4594. }
  4595. if (ch == end_ch
  4596. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4597. || ch == end_char2
  4598. # endif
  4599. ) {
  4600. if (!dbl)
  4601. break;
  4602. /* we look for closing )) of $((EXPR)) */
  4603. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4604. i_getch(input); /* eat second ')' */
  4605. break;
  4606. }
  4607. }
  4608. o_addchr(dest, ch);
  4609. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4610. if (ch == '(' || ch == '{') {
  4611. ch = (ch == '(' ? ')' : '}');
  4612. if (!add_till_closing_bracket(dest, input, ch))
  4613. return 0;
  4614. o_addchr(dest, ch);
  4615. continue;
  4616. }
  4617. if (ch == '\'') {
  4618. if (!add_till_single_quote(dest, input))
  4619. return 0;
  4620. o_addchr(dest, ch);
  4621. continue;
  4622. }
  4623. if (ch == '"') {
  4624. if (!add_till_double_quote(dest, input))
  4625. return 0;
  4626. o_addchr(dest, ch);
  4627. continue;
  4628. }
  4629. if (ch == '`') {
  4630. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4631. return 0;
  4632. o_addchr(dest, ch);
  4633. continue;
  4634. }
  4635. if (ch == '\\') {
  4636. /* \x. Copy verbatim. Important for \(, \) */
  4637. ch = i_getch(input);
  4638. if (ch == EOF) {
  4639. syntax_error_unterm_ch(end_ch);
  4640. return 0;
  4641. }
  4642. # if 0
  4643. if (ch == '\n') {
  4644. /* "backslash+newline", ignore both */
  4645. o_delchr(dest); /* undo insertion of '\' */
  4646. continue;
  4647. }
  4648. # endif
  4649. o_addchr(dest, ch);
  4650. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4651. continue;
  4652. }
  4653. }
  4654. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4655. return ch;
  4656. }
  4657. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4658. #if BASH_DOLLAR_SQUOTE
  4659. /* Return code: 1 for "found and parsed", 0 for "seen something else" */
  4660. # if BB_MMU
  4661. #define parse_dollar_squote(as_string, dest, input) \
  4662. parse_dollar_squote(dest, input)
  4663. #define as_string NULL
  4664. # endif
  4665. static int parse_dollar_squote(o_string *as_string, o_string *dest, struct in_str *input)
  4666. {
  4667. int start;
  4668. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4669. debug_printf_parse("parse_dollar_squote entered: ch='%c'\n", ch);
  4670. if (ch != '\'')
  4671. return 0;
  4672. dest->has_quoted_part = 1;
  4673. start = dest->length;
  4674. ch = i_getch(input); /* eat ' */
  4675. nommu_addchr(as_string, ch);
  4676. while (1) {
  4677. ch = i_getch(input);
  4678. nommu_addchr(as_string, ch);
  4679. if (ch == EOF) {
  4680. syntax_error_unterm_ch('\'');
  4681. return 0;
  4682. }
  4683. if (ch == '\'')
  4684. break;
  4685. if (ch == SPECIAL_VAR_SYMBOL) {
  4686. /* Convert raw ^C to corresponding special variable reference */
  4687. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4688. o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
  4689. /* will addchr() another SPECIAL_VAR_SYMBOL (see after the if() block) */
  4690. } else if (ch == '\\') {
  4691. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  4692. ch = i_getch(input);
  4693. nommu_addchr(as_string, ch);
  4694. if (strchr(C_escapes, ch)) {
  4695. char buf[4];
  4696. char *p = buf;
  4697. int cnt = 2;
  4698. buf[0] = ch;
  4699. if ((unsigned char)(ch - '0') <= 7) { /* \ooo */
  4700. do {
  4701. ch = i_peek(input);
  4702. if ((unsigned char)(ch - '0') > 7)
  4703. break;
  4704. *++p = ch = i_getch(input);
  4705. nommu_addchr(as_string, ch);
  4706. } while (--cnt != 0);
  4707. } else if (ch == 'x') { /* \xHH */
  4708. do {
  4709. ch = i_peek(input);
  4710. if (!isxdigit(ch))
  4711. break;
  4712. *++p = ch = i_getch(input);
  4713. nommu_addchr(as_string, ch);
  4714. } while (--cnt != 0);
  4715. if (cnt == 2) { /* \x but next char is "bad" */
  4716. ch = 'x';
  4717. goto unrecognized;
  4718. }
  4719. } /* else simple seq like \\ or \t */
  4720. *++p = '\0';
  4721. p = buf;
  4722. ch = bb_process_escape_sequence((void*)&p);
  4723. //bb_error_msg("buf:'%s' ch:%x", buf, ch);
  4724. if (ch == '\0')
  4725. continue; /* bash compat: $'...\0...' emits nothing */
  4726. } else { /* unrecognized "\z": encode both chars unless ' or " */
  4727. if (ch != '\'' && ch != '"') {
  4728. unrecognized:
  4729. o_addqchr(dest, '\\');
  4730. }
  4731. }
  4732. } /* if (\...) */
  4733. o_addqchr(dest, ch);
  4734. }
  4735. if (dest->length == start) {
  4736. /* $'', $'\0', $'\000\x00' and the like */
  4737. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4738. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4739. }
  4740. return 1;
  4741. # undef as_string
  4742. }
  4743. #else
  4744. # define parse_dollar_squote(as_string, dest, input) 0
  4745. #endif /* BASH_DOLLAR_SQUOTE */
  4746. /* Return code: 0 for OK, 1 for syntax error */
  4747. #if BB_MMU
  4748. #define parse_dollar(as_string, dest, input, quote_mask) \
  4749. parse_dollar(dest, input, quote_mask)
  4750. #define as_string NULL
  4751. #endif
  4752. static int parse_dollar(o_string *as_string,
  4753. o_string *dest,
  4754. struct in_str *input, unsigned char quote_mask)
  4755. {
  4756. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4757. debug_printf_parse("parse_dollar entered: ch='%c' quote_mask:0x%x\n", ch, quote_mask);
  4758. if (isalpha(ch)) {
  4759. make_var:
  4760. ch = i_getch(input);
  4761. nommu_addchr(as_string, ch);
  4762. /*make_var1:*/
  4763. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4764. while (1) {
  4765. debug_printf_parse(": '%c'\n", ch);
  4766. o_addchr(dest, ch | quote_mask);
  4767. quote_mask = 0;
  4768. ch = i_peek_and_eat_bkslash_nl(input);
  4769. if (!isalnum(ch) && ch != '_') {
  4770. /* End of variable name reached */
  4771. break;
  4772. }
  4773. ch = i_getch(input);
  4774. nommu_addchr(as_string, ch);
  4775. }
  4776. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4777. } else if (isdigit(ch)) {
  4778. make_one_char_var:
  4779. ch = i_getch(input);
  4780. nommu_addchr(as_string, ch);
  4781. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4782. debug_printf_parse(": '%c'\n", ch);
  4783. o_addchr(dest, ch | quote_mask);
  4784. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4785. } else switch (ch) {
  4786. case '$': /* pid */
  4787. case '!': /* last bg pid */
  4788. case '?': /* last exit code */
  4789. case '#': /* number of args */
  4790. case '*': /* args */
  4791. case '@': /* args */
  4792. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4793. goto make_one_char_var;
  4794. case '{': {
  4795. char len_single_ch;
  4796. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4797. ch = i_getch(input); /* eat '{' */
  4798. nommu_addchr(as_string, ch);
  4799. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4800. /* It should be ${?}, or ${#var},
  4801. * or even ${?+subst} - operator acting on a special variable,
  4802. * or the beginning of variable name.
  4803. */
  4804. if (ch == EOF
  4805. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4806. ) {
  4807. bad_dollar_syntax:
  4808. syntax_error_unterm_str("${name}");
  4809. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4810. return 0;
  4811. }
  4812. nommu_addchr(as_string, ch);
  4813. len_single_ch = ch;
  4814. ch |= quote_mask;
  4815. /* It's possible to just call add_till_closing_bracket() at this point.
  4816. * However, this regresses some of our testsuite cases
  4817. * which check invalid constructs like ${%}.
  4818. * Oh well... let's check that the var name part is fine... */
  4819. if (isdigit(len_single_ch)
  4820. || (len_single_ch == '#' && isdigit(i_peek_and_eat_bkslash_nl(input)))
  4821. ) {
  4822. /* Execution engine uses plain xatoi_positive()
  4823. * to interpret ${NNN} and {#NNN},
  4824. * check syntax here in the parser.
  4825. * (bash does not support expressions in ${#NN},
  4826. * e.g. ${#$var} and {#1:+WORD} are not supported).
  4827. */
  4828. unsigned cnt = 9; /* max 9 digits for ${NN} and 8 for {#NN} */
  4829. while (1) {
  4830. o_addchr(dest, ch);
  4831. debug_printf_parse(": '%c'\n", ch);
  4832. ch = i_getch_and_eat_bkslash_nl(input);
  4833. nommu_addchr(as_string, ch);
  4834. if (ch == '}')
  4835. break;
  4836. if (--cnt == 0)
  4837. goto bad_dollar_syntax;
  4838. if (len_single_ch != '#' && strchr(VAR_SUBST_OPS, ch))
  4839. /* ${NN<op>...} is valid */
  4840. goto eat_until_closing;
  4841. if (!isdigit(ch))
  4842. goto bad_dollar_syntax;
  4843. }
  4844. } else
  4845. while (1) {
  4846. unsigned pos;
  4847. o_addchr(dest, ch);
  4848. debug_printf_parse(": '%c'\n", ch);
  4849. ch = i_getch(input);
  4850. nommu_addchr(as_string, ch);
  4851. if (ch == '}')
  4852. break;
  4853. if (!isalnum(ch) && ch != '_') {
  4854. unsigned end_ch;
  4855. unsigned char last_ch;
  4856. /* handle parameter expansions
  4857. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4858. */
  4859. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4860. if (len_single_ch != '#'
  4861. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4862. || i_peek(input) != '}'
  4863. ) {
  4864. goto bad_dollar_syntax;
  4865. }
  4866. /* else: it's "length of C" ${#C} op,
  4867. * where C is a single char
  4868. * special var name, e.g. ${#!}.
  4869. */
  4870. }
  4871. eat_until_closing:
  4872. /* Eat everything until closing '}' (or ':') */
  4873. end_ch = '}';
  4874. if (BASH_SUBSTR
  4875. && ch == ':'
  4876. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4877. ) {
  4878. /* It's ${var:N[:M]} thing */
  4879. end_ch = '}' * 0x100 + ':';
  4880. }
  4881. if (BASH_PATTERN_SUBST
  4882. && ch == '/'
  4883. ) {
  4884. /* It's ${var/[/]pattern[/repl]} thing */
  4885. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4886. i_getch(input);
  4887. nommu_addchr(as_string, '/');
  4888. ch = '\\';
  4889. }
  4890. end_ch = '}' * 0x100 + '/';
  4891. }
  4892. o_addchr(dest, ch);
  4893. /* The pattern can't be empty.
  4894. * IOW: if the first char after "${v//" is a slash,
  4895. * it does not terminate the pattern - it's the first char of the pattern:
  4896. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4897. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4898. */
  4899. if (i_peek(input) == '/') {
  4900. o_addchr(dest, i_getch(input));
  4901. }
  4902. again:
  4903. if (!BB_MMU)
  4904. pos = dest->length;
  4905. #if ENABLE_HUSH_DOLLAR_OPS
  4906. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4907. if (last_ch == 0) /* error? */
  4908. return 0;
  4909. #else
  4910. # error Simple code to only allow ${var} is not implemented
  4911. #endif
  4912. if (as_string) {
  4913. o_addstr(as_string, dest->data + pos);
  4914. o_addchr(as_string, last_ch);
  4915. }
  4916. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4917. && (end_ch & 0xff00)
  4918. ) {
  4919. /* close the first block: */
  4920. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4921. /* while parsing N from ${var:N[:M]}
  4922. * or pattern from ${var/[/]pattern[/repl]} */
  4923. if ((end_ch & 0xff) == last_ch) {
  4924. /* got ':' or '/'- parse the rest */
  4925. end_ch = '}';
  4926. goto again;
  4927. }
  4928. /* got '}' */
  4929. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4930. /* it's ${var:N} - emulate :999999999 */
  4931. o_addstr(dest, "999999999");
  4932. } /* else: it's ${var/[/]pattern} */
  4933. }
  4934. break;
  4935. }
  4936. len_single_ch = 0; /* it can't be ${#C} op */
  4937. }
  4938. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4939. break;
  4940. }
  4941. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4942. case '(': {
  4943. unsigned pos;
  4944. ch = i_getch(input);
  4945. nommu_addchr(as_string, ch);
  4946. # if ENABLE_FEATURE_SH_MATH
  4947. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4948. ch = i_getch(input);
  4949. nommu_addchr(as_string, ch);
  4950. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4951. o_addchr(dest, quote_mask | '+');
  4952. if (!BB_MMU)
  4953. pos = dest->length;
  4954. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4955. return 0; /* error */
  4956. if (as_string) {
  4957. o_addstr(as_string, dest->data + pos);
  4958. o_addchr(as_string, ')');
  4959. o_addchr(as_string, ')');
  4960. }
  4961. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4962. break;
  4963. }
  4964. # endif
  4965. # if ENABLE_HUSH_TICK
  4966. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4967. o_addchr(dest, quote_mask | '`');
  4968. if (!BB_MMU)
  4969. pos = dest->length;
  4970. if (!add_till_closing_bracket(dest, input, ')'))
  4971. return 0; /* error */
  4972. if (as_string) {
  4973. o_addstr(as_string, dest->data + pos);
  4974. o_addchr(as_string, ')');
  4975. }
  4976. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4977. # endif
  4978. break;
  4979. }
  4980. #endif
  4981. case '_':
  4982. goto make_var;
  4983. #if 0
  4984. /* TODO: $_: */
  4985. /* $_ Shell or shell script name; or last argument of last command
  4986. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4987. * but in command's env, set to full pathname used to invoke it */
  4988. ch = i_getch(input);
  4989. nommu_addchr(as_string, ch);
  4990. ch = i_peek_and_eat_bkslash_nl(input);
  4991. if (isalnum(ch)) { /* it's $_name or $_123 */
  4992. ch = '_';
  4993. goto make_var1;
  4994. }
  4995. /* else: it's $_ */
  4996. #endif
  4997. default:
  4998. o_addQchr(dest, '$');
  4999. }
  5000. debug_printf_parse("parse_dollar return 1 (ok)\n");
  5001. return 1;
  5002. #undef as_string
  5003. }
  5004. #if BB_MMU
  5005. #define encode_string(as_string, dest, input, dquote_end) \
  5006. encode_string(dest, input, dquote_end)
  5007. #define as_string NULL
  5008. #endif
  5009. static int encode_string(o_string *as_string,
  5010. o_string *dest,
  5011. struct in_str *input,
  5012. int dquote_end)
  5013. {
  5014. int ch;
  5015. int next;
  5016. again:
  5017. ch = i_getch(input);
  5018. if (ch != EOF)
  5019. nommu_addchr(as_string, ch);
  5020. if (ch == dquote_end) { /* may be only '"' or EOF */
  5021. debug_printf_parse("encode_string return 1 (ok)\n");
  5022. return 1;
  5023. }
  5024. /* note: can't move it above ch == dquote_end check! */
  5025. if (ch == EOF) {
  5026. syntax_error_unterm_ch('"');
  5027. return 0; /* error */
  5028. }
  5029. next = '\0';
  5030. if (ch != '\n') {
  5031. next = i_peek(input);
  5032. }
  5033. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  5034. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5035. if (ch == '\\') {
  5036. if (next == EOF) {
  5037. /* Testcase: in interactive shell a file with
  5038. * echo "unterminated string\<eof>
  5039. * is sourced.
  5040. */
  5041. syntax_error_unterm_ch('"');
  5042. return 0; /* error */
  5043. }
  5044. /* bash:
  5045. * "The backslash retains its special meaning [in "..."]
  5046. * only when followed by one of the following characters:
  5047. * $, `, ", \, or <newline>. A double quote may be quoted
  5048. * within double quotes by preceding it with a backslash."
  5049. * NB: in (unquoted) heredoc, above does not apply to ",
  5050. * therefore we check for it by "next == dquote_end" cond.
  5051. */
  5052. if (next == dquote_end || strchr("$`\\\n", next)) {
  5053. ch = i_getch(input); /* eat next */
  5054. if (ch == '\n')
  5055. goto again; /* skip \<newline> */
  5056. } /* else: ch remains == '\\', and we double it below: */
  5057. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  5058. nommu_addchr(as_string, ch);
  5059. goto again;
  5060. }
  5061. if (ch == '$') {
  5062. //if (parse_dollar_squote(as_string, dest, input))
  5063. // goto again;
  5064. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  5065. debug_printf_parse("encode_string return 0: "
  5066. "parse_dollar returned 0 (error)\n");
  5067. return 0;
  5068. }
  5069. goto again;
  5070. }
  5071. #if ENABLE_HUSH_TICK
  5072. if (ch == '`') {
  5073. //unsigned pos = dest->length;
  5074. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5075. o_addchr(dest, 0x80 | '`');
  5076. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  5077. return 0; /* error */
  5078. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5079. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5080. goto again;
  5081. }
  5082. #endif
  5083. o_addQchr(dest, ch);
  5084. if (ch == SPECIAL_VAR_SYMBOL) {
  5085. /* Convert "^C" to corresponding special variable reference */
  5086. o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
  5087. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5088. }
  5089. goto again;
  5090. #undef as_string
  5091. }
  5092. /*
  5093. * Scan input until EOF or end_trigger char.
  5094. * Return a list of pipes to execute, or NULL on EOF
  5095. * or if end_trigger character is met.
  5096. * On syntax error, exit if shell is not interactive,
  5097. * reset parsing machinery and start parsing anew,
  5098. * or return ERR_PTR.
  5099. */
  5100. static struct pipe *parse_stream(char **pstring,
  5101. int *heredoc_cnt_ptr,
  5102. struct in_str *input,
  5103. int end_trigger)
  5104. {
  5105. struct parse_context ctx;
  5106. int heredoc_cnt;
  5107. /* Single-quote triggers a bypass of the main loop until its mate is
  5108. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  5109. */
  5110. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  5111. end_trigger ? end_trigger : 'X');
  5112. debug_enter();
  5113. initialize_context(&ctx);
  5114. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  5115. * Preventing this:
  5116. */
  5117. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  5118. /* We used to separate words on $IFS here. This was wrong.
  5119. * $IFS is used only for word splitting when $var is expanded,
  5120. * here we should use blank chars as separators, not $IFS
  5121. */
  5122. heredoc_cnt = 0;
  5123. while (1) {
  5124. const char *is_blank;
  5125. const char *is_special;
  5126. int ch;
  5127. int next;
  5128. int redir_fd;
  5129. redir_type redir_style;
  5130. ch = i_getch(input);
  5131. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  5132. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5133. if (ch == EOF) {
  5134. struct pipe *pi;
  5135. if (heredoc_cnt) {
  5136. syntax_error_unterm_str("here document");
  5137. goto parse_error_exitcode1;
  5138. }
  5139. if (end_trigger == ')') {
  5140. syntax_error_unterm_ch('(');
  5141. goto parse_error_exitcode1;
  5142. }
  5143. if (end_trigger == '}') {
  5144. syntax_error_unterm_ch('{');
  5145. goto parse_error_exitcode1;
  5146. }
  5147. if (done_word(&ctx)) {
  5148. goto parse_error_exitcode1;
  5149. }
  5150. o_free_and_set_NULL(&ctx.word);
  5151. done_pipe(&ctx, PIPE_SEQ);
  5152. /* Do we sit inside of any if's, loops or case's? */
  5153. if (HAS_KEYWORDS
  5154. IF_HAS_KEYWORDS(&& (ctx.ctx_res_w != RES_NONE || ctx.old_flag != 0))
  5155. ) {
  5156. syntax_error_unterm_str("compound statement");
  5157. goto parse_error_exitcode1;
  5158. }
  5159. pi = ctx.list_head;
  5160. /* If we got nothing... */
  5161. /* (this makes bare "&" cmd a no-op.
  5162. * bash says: "syntax error near unexpected token '&'") */
  5163. if (pi->num_cmds == 0
  5164. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  5165. ) {
  5166. free_pipe_list(pi);
  5167. pi = NULL;
  5168. }
  5169. #if !BB_MMU
  5170. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  5171. if (pstring)
  5172. *pstring = ctx.as_string.data;
  5173. else
  5174. o_free(&ctx.as_string);
  5175. #endif
  5176. // heredoc_cnt must be 0 here anyway
  5177. //if (heredoc_cnt_ptr)
  5178. // *heredoc_cnt_ptr = heredoc_cnt;
  5179. debug_leave();
  5180. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5181. debug_printf_parse("parse_stream return %p: EOF\n", pi);
  5182. return pi;
  5183. }
  5184. /* Handle "'" and "\" first, as they won't play nice with
  5185. * i_peek_and_eat_bkslash_nl() anyway:
  5186. * echo z\\
  5187. * and
  5188. * echo '\
  5189. * '
  5190. * would break.
  5191. */
  5192. if (ch == '\\') {
  5193. ch = i_getch(input);
  5194. if (ch == '\n')
  5195. continue; /* drop \<newline>, get next char */
  5196. nommu_addchr(&ctx.as_string, '\\');
  5197. if (ch == SPECIAL_VAR_SYMBOL) {
  5198. nommu_addchr(&ctx.as_string, ch);
  5199. /* Convert \^C to corresponding special variable reference */
  5200. goto case_SPECIAL_VAR_SYMBOL;
  5201. }
  5202. o_addchr(&ctx.word, '\\');
  5203. if (ch == EOF) {
  5204. /* Testcase: eval 'echo Ok\' */
  5205. /* bash-4.3.43 was removing backslash,
  5206. * but 4.4.19 retains it, most other shells too
  5207. */
  5208. continue; /* get next char */
  5209. }
  5210. /* Example: echo Hello \2>file
  5211. * we need to know that word 2 is quoted
  5212. */
  5213. ctx.word.has_quoted_part = 1;
  5214. nommu_addchr(&ctx.as_string, ch);
  5215. o_addchr(&ctx.word, ch);
  5216. continue; /* get next char */
  5217. }
  5218. nommu_addchr(&ctx.as_string, ch);
  5219. if (ch == '\'') {
  5220. ctx.word.has_quoted_part = 1;
  5221. next = i_getch(input);
  5222. if (next == '\'' && !ctx.pending_redirect)
  5223. goto insert_empty_quoted_str_marker;
  5224. ch = next;
  5225. while (1) {
  5226. if (ch == EOF) {
  5227. syntax_error_unterm_ch('\'');
  5228. goto parse_error_exitcode1;
  5229. }
  5230. nommu_addchr(&ctx.as_string, ch);
  5231. if (ch == '\'')
  5232. break;
  5233. if (ch == SPECIAL_VAR_SYMBOL) {
  5234. /* Convert raw ^C to corresponding special variable reference */
  5235. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5236. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5237. }
  5238. o_addqchr(&ctx.word, ch);
  5239. ch = i_getch(input);
  5240. }
  5241. continue; /* get next char */
  5242. }
  5243. next = '\0';
  5244. if (ch != '\n')
  5245. next = i_peek_and_eat_bkslash_nl(input);
  5246. is_special = "{}<>&|();#" /* special outside of "str" */
  5247. "$\"" IF_HUSH_TICK("`") /* always special */
  5248. SPECIAL_VAR_SYMBOL_STR;
  5249. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  5250. if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
  5251. /* In [[ ]], {}<>&|() are not special */
  5252. is_special += 8;
  5253. } else
  5254. #endif
  5255. /* Are { and } special here? */
  5256. if (ctx.command->argv /* word [word]{... - non-special */
  5257. || ctx.word.length /* word{... - non-special */
  5258. || ctx.word.has_quoted_part /* ""{... - non-special */
  5259. || (next != ';' /* }; - special */
  5260. && next != ')' /* }) - special */
  5261. && next != '(' /* {( - special */
  5262. && next != '&' /* }& and }&& ... - special */
  5263. && next != '|' /* }|| ... - special */
  5264. && !strchr(defifs, next) /* {word - non-special */
  5265. )
  5266. ) {
  5267. /* They are not special, skip "{}" */
  5268. is_special += 2;
  5269. }
  5270. is_special = strchr(is_special, ch);
  5271. is_blank = strchr(defifs, ch);
  5272. if (!is_special && !is_blank) { /* ordinary char */
  5273. ordinary_char:
  5274. o_addQchr(&ctx.word, ch);
  5275. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5276. || ctx.is_assignment == WORD_IS_KEYWORD)
  5277. && ch == '='
  5278. && endofname(ctx.word.data)[0] == '='
  5279. ) {
  5280. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5281. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5282. }
  5283. continue;
  5284. }
  5285. if (is_blank) {
  5286. #if ENABLE_HUSH_LINENO_VAR
  5287. /* Case:
  5288. * "while ...; do<whitespace><newline>
  5289. * cmd ..."
  5290. * would think that "cmd" starts in <whitespace> -
  5291. * i.e., at the previous line.
  5292. * We need to skip all whitespace before newlines.
  5293. */
  5294. while (ch != '\n') {
  5295. next = i_peek(input);
  5296. if (next != ' ' && next != '\t' && next != '\n')
  5297. break; /* next char is not ws */
  5298. ch = i_getch(input);
  5299. }
  5300. /* ch == last eaten whitespace char */
  5301. #endif
  5302. if (done_word(&ctx)) {
  5303. goto parse_error_exitcode1;
  5304. }
  5305. if (ch == '\n') {
  5306. /* Is this a case when newline is simply ignored?
  5307. * Some examples:
  5308. * "cmd | <newline> cmd ..."
  5309. * "case ... in <newline> word) ..."
  5310. */
  5311. if (IS_NULL_CMD(ctx.command)
  5312. && ctx.word.length == 0
  5313. && !ctx.word.has_quoted_part
  5314. && heredoc_cnt == 0
  5315. ) {
  5316. /* This newline can be ignored. But...
  5317. * Without check #1, interactive shell
  5318. * ignores even bare <newline>,
  5319. * and shows the continuation prompt:
  5320. * ps1_prompt$ <enter>
  5321. * ps2> _ <=== wrong, should be ps1
  5322. * Without check #2, "cmd & <newline>"
  5323. * is similarly mistreated.
  5324. * (BTW, this makes "cmd & cmd"
  5325. * and "cmd && cmd" non-orthogonal.
  5326. * Really, ask yourself, why
  5327. * "cmd && <newline>" doesn't start
  5328. * cmd but waits for more input?
  5329. * The only reason is that it might be
  5330. * a "cmd1 && <nl> cmd2 &" construct,
  5331. * cmd1 may need to run in BG).
  5332. */
  5333. struct pipe *pi = ctx.list_head;
  5334. if (pi->num_cmds != 0 /* check #1 */
  5335. && pi->followup != PIPE_BG /* check #2 */
  5336. ) {
  5337. continue;
  5338. }
  5339. }
  5340. /* Treat newline as a command separator. */
  5341. done_pipe(&ctx, PIPE_SEQ);
  5342. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5343. if (heredoc_cnt) {
  5344. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5345. if (heredoc_cnt != 0)
  5346. goto parse_error_exitcode1;
  5347. }
  5348. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5349. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5350. ch = ';';
  5351. /* note: if (is_blank) continue;
  5352. * will still trigger for us */
  5353. }
  5354. }
  5355. /* "cmd}" or "cmd }..." without semicolon or &:
  5356. * } is an ordinary char in this case, even inside { cmd; }
  5357. * Pathological example: { ""}; } should exec "}" cmd
  5358. */
  5359. if (ch == '}') {
  5360. if (ctx.word.length != 0 /* word} */
  5361. || ctx.word.has_quoted_part /* ""} */
  5362. ) {
  5363. goto ordinary_char;
  5364. }
  5365. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5366. /* Generally, there should be semicolon: "cmd; }"
  5367. * However, bash allows to omit it if "cmd" is
  5368. * a group. Examples:
  5369. * { { echo 1; } }
  5370. * {(echo 1)}
  5371. * { echo 0 >&2 | { echo 1; } }
  5372. * { while false; do :; done }
  5373. * { case a in b) ;; esac }
  5374. */
  5375. if (ctx.command->group)
  5376. goto term_group;
  5377. goto ordinary_char;
  5378. }
  5379. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5380. /* Can't be an end of {cmd}, skip the check */
  5381. goto skip_end_trigger;
  5382. /* else: } does terminate a group */
  5383. }
  5384. term_group:
  5385. if (end_trigger && end_trigger == ch
  5386. && (ch != ';' || heredoc_cnt == 0)
  5387. #if ENABLE_HUSH_CASE
  5388. && (ch != ')'
  5389. || ctx.ctx_res_w != RES_MATCH
  5390. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5391. )
  5392. #endif
  5393. ) {
  5394. if (done_word(&ctx)) {
  5395. goto parse_error_exitcode1;
  5396. }
  5397. done_pipe(&ctx, PIPE_SEQ);
  5398. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5399. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5400. /* Do we sit outside of any if's, loops or case's? */
  5401. if (!HAS_KEYWORDS
  5402. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5403. ) {
  5404. o_free_and_set_NULL(&ctx.word);
  5405. #if !BB_MMU
  5406. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5407. if (pstring)
  5408. *pstring = ctx.as_string.data;
  5409. else
  5410. o_free(&ctx.as_string);
  5411. #endif
  5412. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5413. /* Example: bare "{ }", "()" */
  5414. G.last_exitcode = 2; /* bash compat */
  5415. syntax_error_unexpected_ch(ch);
  5416. goto parse_error;
  5417. }
  5418. if (heredoc_cnt_ptr)
  5419. *heredoc_cnt_ptr = heredoc_cnt;
  5420. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5421. debug_printf_parse("parse_stream return %p: "
  5422. "end_trigger char found\n",
  5423. ctx.list_head);
  5424. debug_leave();
  5425. return ctx.list_head;
  5426. }
  5427. }
  5428. if (is_blank)
  5429. continue;
  5430. /* Catch <, > before deciding whether this word is
  5431. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5432. switch (ch) {
  5433. case '>':
  5434. redir_fd = redirect_opt_num(&ctx.word);
  5435. if (done_word(&ctx)) {
  5436. goto parse_error_exitcode1;
  5437. }
  5438. redir_style = REDIRECT_OVERWRITE;
  5439. if (next == '>') {
  5440. redir_style = REDIRECT_APPEND;
  5441. ch = i_getch(input);
  5442. nommu_addchr(&ctx.as_string, ch);
  5443. }
  5444. #if 0
  5445. else if (next == '(') {
  5446. syntax_error(">(process) not supported");
  5447. goto parse_error_exitcode1;
  5448. }
  5449. #endif
  5450. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5451. goto parse_error_exitcode1;
  5452. continue; /* get next char */
  5453. case '<':
  5454. redir_fd = redirect_opt_num(&ctx.word);
  5455. if (done_word(&ctx)) {
  5456. goto parse_error_exitcode1;
  5457. }
  5458. redir_style = REDIRECT_INPUT;
  5459. if (next == '<') {
  5460. redir_style = REDIRECT_HEREDOC;
  5461. heredoc_cnt++;
  5462. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5463. ch = i_getch(input);
  5464. nommu_addchr(&ctx.as_string, ch);
  5465. } else if (next == '>') {
  5466. redir_style = REDIRECT_IO;
  5467. ch = i_getch(input);
  5468. nommu_addchr(&ctx.as_string, ch);
  5469. }
  5470. #if 0
  5471. else if (next == '(') {
  5472. syntax_error("<(process) not supported");
  5473. goto parse_error_exitcode1;
  5474. }
  5475. #endif
  5476. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5477. goto parse_error_exitcode1;
  5478. continue; /* get next char */
  5479. case '#':
  5480. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5481. /* skip "#comment" */
  5482. /* note: we do not add it to &ctx.as_string */
  5483. /* TODO: in bash:
  5484. * comment inside $() goes to the next \n, even inside quoted string (!):
  5485. * cmd "$(cmd2 #comment)" - syntax error
  5486. * cmd "`cmd2 #comment`" - ok
  5487. * We accept both (comment ends where command subst ends, in both cases).
  5488. */
  5489. while (1) {
  5490. ch = i_peek(input);
  5491. if (ch == '\n') {
  5492. nommu_addchr(&ctx.as_string, '\n');
  5493. break;
  5494. }
  5495. ch = i_getch(input);
  5496. if (ch == EOF)
  5497. break;
  5498. }
  5499. continue; /* get next char */
  5500. }
  5501. break;
  5502. }
  5503. skip_end_trigger:
  5504. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5505. /* check that we are not in word in "a=1 2>word b=1": */
  5506. && !ctx.pending_redirect
  5507. ) {
  5508. /* ch is a special char and thus this word
  5509. * cannot be an assignment */
  5510. ctx.is_assignment = NOT_ASSIGNMENT;
  5511. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5512. }
  5513. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5514. switch (ch) {
  5515. case_SPECIAL_VAR_SYMBOL:
  5516. case SPECIAL_VAR_SYMBOL:
  5517. /* Convert raw ^C to corresponding special variable reference */
  5518. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5519. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5520. /* fall through */
  5521. case '#':
  5522. /* non-comment #: "echo a#b" etc */
  5523. o_addchr(&ctx.word, ch);
  5524. continue; /* get next char */
  5525. case '$':
  5526. if (parse_dollar_squote(&ctx.as_string, &ctx.word, input))
  5527. continue; /* get next char */
  5528. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5529. debug_printf_parse("parse_stream parse error: "
  5530. "parse_dollar returned 0 (error)\n");
  5531. goto parse_error_exitcode1;
  5532. }
  5533. continue; /* get next char */
  5534. case '"':
  5535. ctx.word.has_quoted_part = 1;
  5536. if (next == '"' && !ctx.pending_redirect) {
  5537. i_getch(input); /* eat second " */
  5538. insert_empty_quoted_str_marker:
  5539. nommu_addchr(&ctx.as_string, next);
  5540. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5541. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5542. continue; /* get next char */
  5543. }
  5544. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5545. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5546. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5547. goto parse_error_exitcode1;
  5548. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5549. continue; /* get next char */
  5550. #if ENABLE_HUSH_TICK
  5551. case '`': {
  5552. USE_FOR_NOMMU(unsigned pos;)
  5553. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5554. o_addchr(&ctx.word, '`');
  5555. USE_FOR_NOMMU(pos = ctx.word.length;)
  5556. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5557. goto parse_error_exitcode1;
  5558. # if !BB_MMU
  5559. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5560. o_addchr(&ctx.as_string, '`');
  5561. # endif
  5562. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5563. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5564. continue; /* get next char */
  5565. }
  5566. #endif
  5567. case ';':
  5568. #if ENABLE_HUSH_CASE
  5569. case_semi:
  5570. #endif
  5571. if (done_word(&ctx)) {
  5572. goto parse_error_exitcode1;
  5573. }
  5574. done_pipe(&ctx, PIPE_SEQ);
  5575. #if ENABLE_HUSH_CASE
  5576. /* Eat multiple semicolons, detect
  5577. * whether it means something special */
  5578. while (1) {
  5579. ch = i_peek_and_eat_bkslash_nl(input);
  5580. if (ch != ';')
  5581. break;
  5582. ch = i_getch(input);
  5583. nommu_addchr(&ctx.as_string, ch);
  5584. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5585. ctx.ctx_dsemicolon = 1;
  5586. ctx.ctx_res_w = RES_MATCH;
  5587. break;
  5588. }
  5589. }
  5590. #endif
  5591. new_cmd:
  5592. /* We just finished a cmd. New one may start
  5593. * with an assignment */
  5594. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5595. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5596. continue; /* get next char */
  5597. case '&':
  5598. if (done_word(&ctx)) {
  5599. goto parse_error_exitcode1;
  5600. }
  5601. if (next == '&') {
  5602. ch = i_getch(input);
  5603. nommu_addchr(&ctx.as_string, ch);
  5604. done_pipe(&ctx, PIPE_AND);
  5605. } else {
  5606. done_pipe(&ctx, PIPE_BG);
  5607. }
  5608. goto new_cmd;
  5609. case '|':
  5610. if (done_word(&ctx)) {
  5611. goto parse_error_exitcode1;
  5612. }
  5613. #if ENABLE_HUSH_CASE
  5614. if (ctx.ctx_res_w == RES_MATCH)
  5615. break; /* we are in case's "word | word)" */
  5616. #endif
  5617. if (next == '|') { /* || */
  5618. ch = i_getch(input);
  5619. nommu_addchr(&ctx.as_string, ch);
  5620. done_pipe(&ctx, PIPE_OR);
  5621. } else {
  5622. /* we could pick up a file descriptor choice here
  5623. * with redirect_opt_num(), but bash doesn't do it.
  5624. * "echo foo 2| cat" yields "foo 2". */
  5625. done_command(&ctx);
  5626. }
  5627. goto new_cmd;
  5628. case '(':
  5629. #if ENABLE_HUSH_CASE
  5630. /* "case... in [(]word)..." - skip '(' */
  5631. if (ctx.ctx_res_w == RES_MATCH
  5632. && ctx.command->argv == NULL /* not (word|(... */
  5633. && ctx.word.length == 0 /* not word(... */
  5634. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5635. ) {
  5636. continue; /* get next char */
  5637. }
  5638. #endif
  5639. /* fall through */
  5640. case '{': {
  5641. int n = parse_group(&ctx, input, ch);
  5642. if (n < 0) {
  5643. goto parse_error_exitcode1;
  5644. }
  5645. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5646. heredoc_cnt += n;
  5647. goto new_cmd;
  5648. }
  5649. case ')':
  5650. #if ENABLE_HUSH_CASE
  5651. if (ctx.ctx_res_w == RES_MATCH)
  5652. goto case_semi;
  5653. #endif
  5654. case '}':
  5655. /* proper use of this character is caught by end_trigger:
  5656. * if we see {, we call parse_group(..., end_trigger='}')
  5657. * and it will match } earlier (not here). */
  5658. G.last_exitcode = 2;
  5659. syntax_error_unexpected_ch(ch);
  5660. goto parse_error;
  5661. default:
  5662. if (HUSH_DEBUG)
  5663. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5664. }
  5665. } /* while (1) */
  5666. parse_error_exitcode1:
  5667. G.last_exitcode = 1;
  5668. parse_error:
  5669. {
  5670. struct parse_context *pctx;
  5671. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5672. /* Clean up allocated tree.
  5673. * Sample for finding leaks on syntax error recovery path.
  5674. * Run it from interactive shell, watch pmap `pidof hush`.
  5675. * while if false; then false; fi; do break; fi
  5676. * Samples to catch leaks at execution:
  5677. * while if (true | { true;}); then echo ok; fi; do break; done
  5678. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5679. */
  5680. pctx = &ctx;
  5681. do {
  5682. /* Update pipe/command counts,
  5683. * otherwise freeing may miss some */
  5684. done_pipe(pctx, PIPE_SEQ);
  5685. debug_printf_clean("freeing list %p from ctx %p\n",
  5686. pctx->list_head, pctx);
  5687. debug_print_tree(pctx->list_head, 0);
  5688. free_pipe_list(pctx->list_head);
  5689. debug_printf_clean("freed list %p\n", pctx->list_head);
  5690. #if !BB_MMU
  5691. o_free(&pctx->as_string);
  5692. #endif
  5693. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5694. if (pctx != &ctx) {
  5695. free(pctx);
  5696. }
  5697. IF_HAS_KEYWORDS(pctx = p2;)
  5698. } while (HAS_KEYWORDS && pctx);
  5699. o_free(&ctx.word);
  5700. #if !BB_MMU
  5701. if (pstring)
  5702. *pstring = NULL;
  5703. #endif
  5704. debug_leave();
  5705. return ERR_PTR;
  5706. }
  5707. }
  5708. /*** Execution routines ***/
  5709. /* Expansion can recurse, need forward decls: */
  5710. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5711. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5712. expand_string_to_string(str)
  5713. #endif
  5714. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5715. #if ENABLE_HUSH_TICK
  5716. static int process_command_subs(o_string *dest, const char *s);
  5717. #endif
  5718. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5719. /* expand_strvec_to_strvec() takes a list of strings, expands
  5720. * all variable references within and returns a pointer to
  5721. * a list of expanded strings, possibly with larger number
  5722. * of strings. (Think VAR="a b"; echo $VAR).
  5723. * This new list is allocated as a single malloc block.
  5724. * NULL-terminated list of char* pointers is at the beginning of it,
  5725. * followed by strings themselves.
  5726. * Caller can deallocate entire list by single free(list). */
  5727. /* A horde of its helpers come first: */
  5728. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5729. {
  5730. while (--len >= 0) {
  5731. char c = *str++;
  5732. #if ENABLE_HUSH_BRACE_EXPANSION
  5733. if (c == '{' || c == '}') {
  5734. /* { -> \{, } -> \} */
  5735. o_addchr(o, '\\');
  5736. /* And now we want to add { or } and continue:
  5737. * o_addchr(o, c);
  5738. * continue;
  5739. * luckily, just falling through achieves this.
  5740. */
  5741. }
  5742. #endif
  5743. o_addchr(o, c);
  5744. if (c == '\\') {
  5745. /* \z -> \\\z; \<eol> -> \\<eol> */
  5746. o_addchr(o, '\\');
  5747. if (len) {
  5748. len--;
  5749. o_addchr(o, '\\');
  5750. o_addchr(o, *str++);
  5751. }
  5752. }
  5753. }
  5754. }
  5755. /* Store given string, finalizing the word and starting new one whenever
  5756. * we encounter IFS char(s). This is used for expanding variable values.
  5757. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5758. * Return in output->ended_in_ifs:
  5759. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5760. */
  5761. static int expand_on_ifs(o_string *output, int n, const char *str)
  5762. {
  5763. int last_is_ifs = 0;
  5764. while (1) {
  5765. int word_len;
  5766. if (!*str) /* EOL - do not finalize word */
  5767. break;
  5768. word_len = strcspn(str, G.ifs);
  5769. if (word_len) {
  5770. /* We have WORD_LEN leading non-IFS chars */
  5771. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5772. o_addblock(output, str, word_len);
  5773. } else {
  5774. /* Protect backslashes against globbing up :)
  5775. * Example: "v='\*'; echo b$v" prints "b\*"
  5776. * (and does not try to glob on "*")
  5777. */
  5778. o_addblock_duplicate_backslash(output, str, word_len);
  5779. /*/ Why can't we do it easier? */
  5780. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5781. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5782. }
  5783. last_is_ifs = 0;
  5784. str += word_len;
  5785. if (!*str) /* EOL - do not finalize word */
  5786. break;
  5787. }
  5788. /* We know str here points to at least one IFS char */
  5789. last_is_ifs = 1;
  5790. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5791. if (!*str) /* EOL - do not finalize word */
  5792. break;
  5793. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5794. && strchr(G.ifs, *str) /* the second check would fail */
  5795. ) {
  5796. /* This is a non-whitespace $IFS char */
  5797. /* Skip it and IFS whitespace chars, start new word */
  5798. str++;
  5799. str += strspn(str, G.ifs_whitespace);
  5800. goto new_word;
  5801. }
  5802. /* Start new word... but not always! */
  5803. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5804. if (output->has_quoted_part
  5805. /*
  5806. * Case "v=' a'; echo $v":
  5807. * here nothing precedes the space in $v expansion,
  5808. * therefore we should not finish the word
  5809. * (IOW: if there *is* word to finalize, only then do it):
  5810. * It's okay if this accesses the byte before first argv[]:
  5811. * past call to o_save_ptr() cleared it to zero byte
  5812. * (grep for -prev-ifs-check-).
  5813. */
  5814. || output->data[output->length - 1]
  5815. ) {
  5816. new_word:
  5817. o_addchr(output, '\0');
  5818. debug_print_list("expand_on_ifs", output, n);
  5819. n = o_save_ptr(output, n);
  5820. }
  5821. }
  5822. output->ended_in_ifs = last_is_ifs;
  5823. debug_print_list("expand_on_ifs[1]", output, n);
  5824. return n;
  5825. }
  5826. /* Helper to expand $((...)) and heredoc body. These act as if
  5827. * they are in double quotes, with the exception that they are not :).
  5828. * Just the rules are similar: "expand only $var and `cmd`"
  5829. *
  5830. * Returns malloced string.
  5831. * As an optimization, we return NULL if expansion is not needed.
  5832. */
  5833. static char *encode_then_expand_string(const char *str)
  5834. {
  5835. char *exp_str;
  5836. struct in_str input;
  5837. o_string dest = NULL_O_STRING;
  5838. const char *cp;
  5839. cp = str;
  5840. for (;;) {
  5841. if (!*cp) return NULL; /* string has no special chars */
  5842. if (*cp == '$') break;
  5843. if (*cp == '\\') break;
  5844. #if ENABLE_HUSH_TICK
  5845. if (*cp == '`') break;
  5846. #endif
  5847. cp++;
  5848. }
  5849. /* We need to expand. Example:
  5850. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5851. */
  5852. setup_string_in_str(&input, str);
  5853. encode_string(NULL, &dest, &input, EOF);
  5854. //TODO: error check (encode_string returns 0 on error)?
  5855. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5856. exp_str = expand_string_to_string(dest.data,
  5857. EXP_FLAG_ESC_GLOB_CHARS,
  5858. /*unbackslash:*/ 1
  5859. );
  5860. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5861. o_free(&dest);
  5862. return exp_str;
  5863. }
  5864. static const char *first_special_char_in_vararg(const char *cp)
  5865. {
  5866. for (;;) {
  5867. if (!*cp) return NULL; /* string has no special chars */
  5868. if (*cp == '$') return cp;
  5869. if (*cp == '\\') return cp;
  5870. if (*cp == '\'') return cp;
  5871. if (*cp == '"') return cp;
  5872. #if ENABLE_HUSH_TICK
  5873. if (*cp == '`') return cp;
  5874. #endif
  5875. /* dquoted "${x:+ARG}" should not glob, therefore
  5876. * '*' et al require some non-literal processing: */
  5877. if (*cp == '*') return cp;
  5878. if (*cp == '?') return cp;
  5879. if (*cp == '[') return cp;
  5880. cp++;
  5881. }
  5882. }
  5883. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5884. * These can contain single- and double-quoted strings,
  5885. * and treated as if the ARG string is initially unquoted. IOW:
  5886. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5887. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5888. * (word splitting and globbing of the ${var...} result).
  5889. */
  5890. #if !BASH_PATTERN_SUBST
  5891. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5892. encode_then_expand_vararg(str, handle_squotes)
  5893. #endif
  5894. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5895. {
  5896. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5897. const int do_unbackslash = 0;
  5898. #endif
  5899. char *exp_str;
  5900. struct in_str input;
  5901. o_string dest = NULL_O_STRING;
  5902. if (!first_special_char_in_vararg(str)) {
  5903. /* string has no special chars */
  5904. return NULL;
  5905. }
  5906. setup_string_in_str(&input, str);
  5907. dest.data = xzalloc(1); /* start as "", not as NULL */
  5908. exp_str = NULL;
  5909. for (;;) {
  5910. int ch;
  5911. ch = i_getch(&input);
  5912. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5913. __func__, ch, ch, !!dest.o_expflags);
  5914. if (!dest.o_expflags) {
  5915. if (ch == EOF)
  5916. break;
  5917. if (handle_squotes && ch == '\'') {
  5918. if (!add_till_single_quote_dquoted(&dest, &input))
  5919. goto ret; /* error */
  5920. continue;
  5921. }
  5922. }
  5923. if (ch == EOF) {
  5924. syntax_error_unterm_ch('"');
  5925. goto ret; /* error */
  5926. }
  5927. if (ch == '"') {
  5928. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5929. continue;
  5930. }
  5931. if (ch == '\\') {
  5932. ch = i_getch(&input);
  5933. if (ch == EOF) {
  5934. //example? error message? syntax_error_unterm_ch('"');
  5935. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5936. goto ret;
  5937. }
  5938. o_addqchr(&dest, ch);
  5939. continue;
  5940. }
  5941. if (ch == '$') {
  5942. if (parse_dollar_squote(NULL, &dest, &input))
  5943. continue;
  5944. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5945. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5946. goto ret;
  5947. }
  5948. continue;
  5949. }
  5950. #if ENABLE_HUSH_TICK
  5951. if (ch == '`') {
  5952. //unsigned pos = dest->length;
  5953. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5954. o_addchr(&dest, 0x80 | '`');
  5955. if (!add_till_backquote(&dest, &input,
  5956. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5957. )
  5958. ) {
  5959. goto ret; /* error */
  5960. }
  5961. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5962. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5963. continue;
  5964. }
  5965. #endif
  5966. o_addQchr(&dest, ch);
  5967. } /* for (;;) */
  5968. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5969. exp_str = expand_string_to_string(dest.data,
  5970. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5971. do_unbackslash
  5972. );
  5973. ret:
  5974. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5975. o_free(&dest);
  5976. return exp_str;
  5977. }
  5978. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5979. */
  5980. static NOINLINE int encode_then_append_var_plusminus(o_string *output, int n,
  5981. char *str, int dquoted)
  5982. {
  5983. struct in_str input;
  5984. o_string dest = NULL_O_STRING;
  5985. if (!first_special_char_in_vararg(str)
  5986. && '\0' == str[strcspn(str, G.ifs)]
  5987. ) {
  5988. /* string has no special chars
  5989. * && string has no $IFS chars
  5990. */
  5991. if (dquoted) {
  5992. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5993. * set -- "${notexist-}"; echo $#
  5994. */
  5995. output->has_quoted_part = 1;
  5996. }
  5997. return expand_vars_to_list(output, n, str);
  5998. }
  5999. setup_string_in_str(&input, str);
  6000. for (;;) {
  6001. int ch;
  6002. ch = i_getch(&input);
  6003. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  6004. __func__, ch, ch, dest.o_expflags);
  6005. if (!dest.o_expflags) {
  6006. if (ch == EOF)
  6007. break;
  6008. if (!dquoted && !(output->o_expflags & EXP_FLAG_SINGLEWORD) && strchr(G.ifs, ch)) {
  6009. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  6010. * do not assume we are at the start of the word (PREFIX above).
  6011. */
  6012. if (dest.data) {
  6013. n = expand_vars_to_list(output, n, dest.data);
  6014. o_free_and_set_NULL(&dest);
  6015. o_addchr(output, '\0');
  6016. n = o_save_ptr(output, n); /* create next word */
  6017. } else
  6018. if (output->length != o_get_last_ptr(output, n)
  6019. || output->has_quoted_part
  6020. ) {
  6021. /* For these cases:
  6022. * f() { for i; do echo "|$i|"; done; }; x=x
  6023. * f a${x:+ }b # 1st condition
  6024. * |a|
  6025. * |b|
  6026. * f ""${x:+ }b # 2nd condition
  6027. * ||
  6028. * |b|
  6029. */
  6030. o_addchr(output, '\0');
  6031. n = o_save_ptr(output, n); /* create next word */
  6032. }
  6033. continue;
  6034. }
  6035. if (!dquoted && ch == '\'') {
  6036. if (!add_till_single_quote_dquoted(&dest, &input))
  6037. goto ret; /* error */
  6038. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6039. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6040. continue;
  6041. }
  6042. }
  6043. if (ch == EOF) {
  6044. syntax_error_unterm_ch('"');
  6045. goto ret; /* error */
  6046. }
  6047. if (ch == '"') {
  6048. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  6049. if (dest.o_expflags) {
  6050. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6051. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6052. }
  6053. continue;
  6054. }
  6055. if (ch == '\\') {
  6056. ch = i_getch(&input);
  6057. if (ch == EOF) {
  6058. //example? error message? syntax_error_unterm_ch('"');
  6059. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  6060. goto ret;
  6061. }
  6062. o_addqchr(&dest, ch);
  6063. continue;
  6064. }
  6065. if (ch == '$') {
  6066. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  6067. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  6068. goto ret;
  6069. }
  6070. continue;
  6071. }
  6072. #if ENABLE_HUSH_TICK
  6073. if (ch == '`') {
  6074. //unsigned pos = dest->length;
  6075. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6076. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  6077. if (!add_till_backquote(&dest, &input,
  6078. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  6079. )
  6080. ) {
  6081. goto ret; /* error */
  6082. }
  6083. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6084. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  6085. continue;
  6086. }
  6087. #endif
  6088. if (dquoted) {
  6089. /* Always glob-protect if in dquotes:
  6090. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  6091. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  6092. */
  6093. o_addqchr(&dest, ch);
  6094. } else {
  6095. /* Glob-protect only if char is quoted:
  6096. * x=x; echo ${x:+/bin/c*} - prints many filenames
  6097. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  6098. */
  6099. o_addQchr(&dest, ch);
  6100. }
  6101. } /* for (;;) */
  6102. if (dest.data) {
  6103. n = expand_vars_to_list(output, n, dest.data);
  6104. }
  6105. ret:
  6106. o_free(&dest);
  6107. return n;
  6108. }
  6109. #if ENABLE_FEATURE_SH_MATH
  6110. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  6111. {
  6112. arith_state_t math_state;
  6113. arith_t res;
  6114. char *exp_str;
  6115. math_state.lookupvar = get_local_var_value;
  6116. math_state.setvar = set_local_var_from_halves;
  6117. //math_state.endofname = endofname;
  6118. exp_str = encode_then_expand_string(arg);
  6119. res = arith(&math_state, exp_str ? exp_str : arg);
  6120. free(exp_str);
  6121. if (errmsg_p)
  6122. *errmsg_p = math_state.errmsg;
  6123. if (math_state.errmsg)
  6124. msg_and_die_if_script(math_state.errmsg);
  6125. return res;
  6126. }
  6127. #endif
  6128. #if BASH_PATTERN_SUBST
  6129. /* ${var/[/]pattern[/repl]} helpers */
  6130. static char *strstr_pattern(char *val, const char *pattern, int *size)
  6131. {
  6132. int first_escaped = (pattern[0] == '\\' && pattern[1]);
  6133. /* "first_escaped" trick allows to treat e.g. "\*no_glob_chars"
  6134. * as literal too (as it is semi-common, and easy to accomodate
  6135. * by just using str + 1).
  6136. */
  6137. int sz = strcspn(pattern + first_escaped * 2, "*?[\\");
  6138. if ((pattern + first_escaped * 2)[sz] == '\0') {
  6139. /* Optimization for trivial patterns.
  6140. * Testcase for very slow replace (performs about 22k replaces):
  6141. * x=::::::::::::::::::::::
  6142. * x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;echo ${#x}
  6143. * echo "${x//:/|}"
  6144. */
  6145. *size = sz + first_escaped;
  6146. return strstr(val, pattern + first_escaped);
  6147. }
  6148. while (1) {
  6149. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  6150. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  6151. if (end) {
  6152. *size = end - val;
  6153. return val;
  6154. }
  6155. if (*val == '\0')
  6156. return NULL;
  6157. /* Optimization: if "*pat" did not match the start of "string",
  6158. * we know that "tring", "ring" etc will not match too:
  6159. */
  6160. if (pattern[0] == '*')
  6161. return NULL;
  6162. val++;
  6163. }
  6164. }
  6165. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  6166. {
  6167. char *result = NULL;
  6168. unsigned res_len = 0;
  6169. unsigned repl_len = strlen(repl);
  6170. /* Null pattern never matches, including if "var" is empty */
  6171. if (!pattern[0])
  6172. return result; /* NULL, no replaces happened */
  6173. while (1) {
  6174. int size;
  6175. char *s = strstr_pattern(val, pattern, &size);
  6176. if (!s)
  6177. break;
  6178. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  6179. strcpy(mempcpy(result + res_len, val, s - val), repl);
  6180. res_len += (s - val) + repl_len;
  6181. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  6182. val = s + size;
  6183. if (exp_op == '/')
  6184. break;
  6185. }
  6186. if (*val && result) {
  6187. result = xrealloc(result, res_len + strlen(val) + 1);
  6188. strcpy(result + res_len, val);
  6189. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  6190. }
  6191. debug_printf_varexp("result:'%s'\n", result);
  6192. return result;
  6193. }
  6194. #endif /* BASH_PATTERN_SUBST */
  6195. static int append_str_maybe_ifs_split(o_string *output, int n,
  6196. int first_ch, const char *val)
  6197. {
  6198. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  6199. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  6200. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6201. if (val && val[0])
  6202. n = expand_on_ifs(output, n, val);
  6203. } else { /* quoted "$VAR" */
  6204. output->has_quoted_part = 1;
  6205. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  6206. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6207. if (val && val[0])
  6208. o_addQstr(output, val);
  6209. }
  6210. return n;
  6211. }
  6212. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  6213. */
  6214. static NOINLINE int expand_one_var(o_string *output, int n,
  6215. int first_ch, char *arg, char **pp)
  6216. {
  6217. const char *val;
  6218. char *to_be_freed;
  6219. char *p;
  6220. char *var;
  6221. char exp_op;
  6222. char exp_save = exp_save; /* for compiler */
  6223. char *exp_saveptr; /* points to expansion operator */
  6224. char *exp_word = exp_word; /* for compiler */
  6225. char arg0;
  6226. val = NULL;
  6227. to_be_freed = NULL;
  6228. p = *pp;
  6229. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  6230. var = arg;
  6231. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  6232. arg0 = arg[0];
  6233. arg[0] = (arg0 & 0x7f);
  6234. exp_op = 0;
  6235. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  6236. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  6237. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  6238. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  6239. ) {
  6240. /* It must be length operator: ${#var} */
  6241. var++;
  6242. exp_op = 'L';
  6243. } else {
  6244. /* Maybe handle parameter expansion */
  6245. if (exp_saveptr /* if 2nd char is one of expansion operators */
  6246. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  6247. ) {
  6248. /* ${?:0}, ${#[:]%0} etc */
  6249. exp_saveptr = var + 1;
  6250. } else {
  6251. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  6252. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  6253. }
  6254. exp_op = exp_save = *exp_saveptr;
  6255. if (exp_op) {
  6256. exp_word = exp_saveptr + 1;
  6257. if (exp_op == ':') {
  6258. exp_op = *exp_word++;
  6259. //TODO: try ${var:} and ${var:bogus} in non-bash config
  6260. if (BASH_SUBSTR
  6261. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  6262. ) {
  6263. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  6264. exp_op = ':';
  6265. exp_word--;
  6266. }
  6267. }
  6268. *exp_saveptr = '\0';
  6269. } /* else: it's not an expansion op, but bare ${var} */
  6270. }
  6271. /* Look up the variable in question */
  6272. if (isdigit(var[0])) {
  6273. /* parse_dollar should have vetted var for us */
  6274. int nn = xatoi_positive(var);
  6275. if (nn < G.global_argc)
  6276. val = G.global_argv[nn];
  6277. /* else val remains NULL: $N with too big N */
  6278. } else {
  6279. switch (var[0]) {
  6280. case '$': /* pid */
  6281. val = utoa(G.root_pid);
  6282. break;
  6283. case '!': /* bg pid */
  6284. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6285. break;
  6286. case '?': /* exitcode */
  6287. val = utoa(G.last_exitcode);
  6288. break;
  6289. case '#': /* argc */
  6290. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6291. break;
  6292. case '-': { /* active options */
  6293. /* Check set_mode() to see what option chars we support */
  6294. char *cp;
  6295. val = cp = G.optstring_buf;
  6296. if (G.o_opt[OPT_O_ERREXIT])
  6297. *cp++ = 'e';
  6298. if (G_interactive_fd)
  6299. *cp++ = 'i';
  6300. if (G_x_mode)
  6301. *cp++ = 'x';
  6302. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6303. * commands read but are not executed,
  6304. * so $- can not execute too, 'n' is never seen in $-.
  6305. */
  6306. if (G.opt_c)
  6307. *cp++ = 'c';
  6308. if (G.opt_s)
  6309. *cp++ = 's';
  6310. *cp = '\0';
  6311. break;
  6312. }
  6313. default:
  6314. val = get_local_var_value(var);
  6315. }
  6316. }
  6317. /* Handle any expansions */
  6318. if (exp_op == 'L') {
  6319. reinit_unicode_for_hush();
  6320. debug_printf_expand("expand: length(%s)=", val);
  6321. val = utoa(val ? unicode_strlen(val) : 0);
  6322. debug_printf_expand("%s\n", val);
  6323. } else if (exp_op) {
  6324. if (exp_op == '%' || exp_op == '#') {
  6325. /* Standard-mandated substring removal ops:
  6326. * ${parameter%word} - remove smallest suffix pattern
  6327. * ${parameter%%word} - remove largest suffix pattern
  6328. * ${parameter#word} - remove smallest prefix pattern
  6329. * ${parameter##word} - remove largest prefix pattern
  6330. *
  6331. * Word is expanded to produce a glob pattern.
  6332. * Then var's value is matched to it and matching part removed.
  6333. */
  6334. /* bash compat: if x is "" and no shrinking of it is possible,
  6335. * inner ${...} is not evaluated. Example:
  6336. * unset b; : ${a%${b=B}}; echo $b
  6337. * assignment b=B only happens if $a is not "".
  6338. */
  6339. if (val && val[0]) {
  6340. char *t;
  6341. char *exp_exp_word;
  6342. char *loc;
  6343. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6344. if (exp_op == *exp_word) /* ## or %% */
  6345. exp_word++;
  6346. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6347. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6348. if (exp_exp_word)
  6349. exp_word = exp_exp_word;
  6350. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6351. /*
  6352. * HACK ALERT. We depend here on the fact that
  6353. * G.global_argv and results of utoa and get_local_var_value
  6354. * are actually in writable memory:
  6355. * scan_and_match momentarily stores NULs there.
  6356. */
  6357. t = (char*)val;
  6358. loc = scan_and_match(t, exp_word, scan_flags);
  6359. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6360. free(exp_exp_word);
  6361. if (loc) { /* match was found */
  6362. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6363. val = loc; /* take right part */
  6364. else /* %[%] */
  6365. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6366. }
  6367. }
  6368. }
  6369. #if BASH_PATTERN_SUBST
  6370. else if (exp_op == '/' || exp_op == '\\') {
  6371. /* It's ${var/[/]pattern[/repl]} thing.
  6372. * Note that in encoded form it has TWO parts:
  6373. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6374. * and if // is used, it is encoded as \:
  6375. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6376. */
  6377. /* bash compat: if var is "", both pattern and repl
  6378. * are still evaluated, if it is unset, then not:
  6379. * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
  6380. * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
  6381. */
  6382. if (val /*&& val[0]*/) {
  6383. /* pattern uses non-standard expansion.
  6384. * repl should be unbackslashed and globbed
  6385. * by the usual expansion rules:
  6386. * >az >bz
  6387. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6388. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6389. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6390. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6391. * (note that a*z _pattern_ is never globbed!)
  6392. */
  6393. char *pattern, *repl, *t;
  6394. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6395. if (!pattern)
  6396. pattern = xstrdup(exp_word);
  6397. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6398. *p++ = SPECIAL_VAR_SYMBOL;
  6399. exp_word = p;
  6400. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6401. *p = '\0';
  6402. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6403. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6404. /* HACK ALERT. We depend here on the fact that
  6405. * G.global_argv and results of utoa and get_local_var_value
  6406. * are actually in writable memory:
  6407. * replace_pattern momentarily stores NULs there. */
  6408. t = (char*)val;
  6409. to_be_freed = replace_pattern(t,
  6410. pattern,
  6411. (repl ? repl : exp_word),
  6412. exp_op);
  6413. if (to_be_freed) /* at least one replace happened */
  6414. val = to_be_freed;
  6415. free(pattern);
  6416. free(repl);
  6417. } else {
  6418. /* Unset variable always gives nothing */
  6419. // a=; echo ${a/*/w} # "w"
  6420. // unset a; echo ${a/*/w} # ""
  6421. /* Just skip "replace" part */
  6422. *p++ = SPECIAL_VAR_SYMBOL;
  6423. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6424. *p = '\0';
  6425. }
  6426. }
  6427. #endif /* BASH_PATTERN_SUBST */
  6428. else if (exp_op == ':') {
  6429. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6430. /* It's ${var:N[:M]} bashism.
  6431. * Note that in encoded form it has TWO parts:
  6432. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6433. */
  6434. arith_t beg, len;
  6435. unsigned vallen;
  6436. const char *errmsg;
  6437. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6438. if (errmsg)
  6439. goto empty_result;
  6440. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6441. *p++ = SPECIAL_VAR_SYMBOL;
  6442. exp_word = p;
  6443. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6444. *p = '\0';
  6445. vallen = val ? strlen(val) : 0;
  6446. if (beg < 0) {
  6447. /* negative beg counts from the end */
  6448. beg = (arith_t)vallen + beg;
  6449. }
  6450. /* If expansion will be empty, do not even evaluate len */
  6451. if (!val || beg < 0 || beg > vallen) {
  6452. /* Why > vallen, not >=? bash:
  6453. * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
  6454. * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
  6455. */
  6456. goto empty_result;
  6457. }
  6458. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6459. if (errmsg)
  6460. goto empty_result;
  6461. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6462. debug_printf_varexp("from val:'%s'\n", val);
  6463. if (len < 0) {
  6464. /* in bash, len=-n means strlen()-n */
  6465. len = (arith_t)vallen - beg + len;
  6466. if (len < 0) /* bash compat */
  6467. msg_and_die_if_script("%s: substring expression < 0", var);
  6468. }
  6469. if (len <= 0 || !val /*|| beg >= vallen*/) {
  6470. empty_result:
  6471. val = NULL;
  6472. } else {
  6473. /* Paranoia. What if user entered 9999999999999
  6474. * which fits in arith_t but not int? */
  6475. if (len > INT_MAX)
  6476. len = INT_MAX;
  6477. val = to_be_freed = xstrndup(val + beg, len);
  6478. }
  6479. debug_printf_varexp("val:'%s'\n", val);
  6480. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6481. msg_and_die_if_script("malformed ${%s:...}", var);
  6482. val = NULL;
  6483. #endif
  6484. } else { /* one of "-=+?" */
  6485. /* Standard-mandated substitution ops:
  6486. * ${var?word} - indicate error if unset
  6487. * If var is unset, word (or a message indicating it is unset
  6488. * if word is null) is written to standard error
  6489. * and the shell exits with a non-zero exit status.
  6490. * Otherwise, the value of var is substituted.
  6491. * ${var-word} - use default value
  6492. * If var is unset, word is substituted.
  6493. * ${var=word} - assign and use default value
  6494. * If var is unset, word is assigned to var.
  6495. * In all cases, final value of var is substituted.
  6496. * ${var+word} - use alternative value
  6497. * If var is unset, null is substituted.
  6498. * Otherwise, word is substituted.
  6499. *
  6500. * Word is subjected to tilde expansion, parameter expansion,
  6501. * command substitution, and arithmetic expansion.
  6502. * If word is not needed, it is not expanded.
  6503. *
  6504. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6505. * but also treat null var as if it is unset.
  6506. *
  6507. * Word-splitting and single quote behavior:
  6508. *
  6509. * $ f() { for i; do echo "|$i|"; done; }
  6510. *
  6511. * $ x=; f ${x:?'x y' z}; echo $?
  6512. * bash: x: x y z # neither f nor "echo $?" executes
  6513. * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
  6514. * $ x=; f "${x:?'x y' z}"
  6515. * bash: x: x y z # dash prints: dash: x: 'x y' z
  6516. *
  6517. * $ x=; f ${x:='x y' z}
  6518. * |x|
  6519. * |y|
  6520. * |z|
  6521. * $ x=; f "${x:='x y' z}"
  6522. * |'x y' z|
  6523. *
  6524. * $ x=x; f ${x:+'x y' z}
  6525. * |x y|
  6526. * |z|
  6527. * $ x=x; f "${x:+'x y' z}"
  6528. * |'x y' z|
  6529. *
  6530. * $ x=; f ${x:-'x y' z}
  6531. * |x y|
  6532. * |z|
  6533. * $ x=; f "${x:-'x y' z}"
  6534. * |'x y' z|
  6535. */
  6536. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6537. if (exp_op == '+')
  6538. use_word = !use_word;
  6539. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6540. (exp_save == ':') ? "true" : "false", use_word);
  6541. if (use_word) {
  6542. if (exp_op == '+' || exp_op == '-') {
  6543. /* ${var+word} - use alternative value */
  6544. /* ${var-word} - use default value */
  6545. n = encode_then_append_var_plusminus(output, n, exp_word,
  6546. /*dquoted:*/ (arg0 & 0x80)
  6547. );
  6548. val = NULL;
  6549. } else {
  6550. /* ${var?word} - indicate error if unset */
  6551. /* ${var=word} - assign and use default value */
  6552. to_be_freed = encode_then_expand_vararg(exp_word,
  6553. /*handle_squotes:*/ !(arg0 & 0x80),
  6554. /*unbackslash:*/ 0
  6555. );
  6556. if (to_be_freed)
  6557. exp_word = to_be_freed;
  6558. if (exp_op == '?') {
  6559. /* mimic bash message */
  6560. msg_and_die_if_script("%s: %s",
  6561. var,
  6562. exp_word[0]
  6563. ? exp_word
  6564. : "parameter null or not set"
  6565. /* ash has more specific messages, a-la: */
  6566. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6567. );
  6568. //TODO: how interactive bash aborts expansion mid-command?
  6569. //It aborts the entire line, returns to prompt:
  6570. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6571. // bash: x: x y z
  6572. // $
  6573. // ("echo YO" is not executed, neither the f function call)
  6574. } else {
  6575. val = exp_word;
  6576. }
  6577. if (exp_op == '=') {
  6578. /* ${var=[word]} or ${var:=[word]} */
  6579. if (isdigit(var[0]) || var[0] == '#') {
  6580. /* mimic bash message */
  6581. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6582. val = NULL;
  6583. } else {
  6584. char *new_var = xasprintf("%s=%s", var, val);
  6585. set_local_var0(new_var);
  6586. }
  6587. }
  6588. }
  6589. }
  6590. } /* one of "-=+?" */
  6591. *exp_saveptr = exp_save;
  6592. } /* if (exp_op) */
  6593. arg[0] = arg0;
  6594. *pp = p;
  6595. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6596. free(to_be_freed);
  6597. return n;
  6598. }
  6599. /* Expand all variable references in given string, adding words to list[]
  6600. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6601. * to be filled). This routine is extremely tricky: has to deal with
  6602. * variables/parameters with whitespace, $* and $@, and constructs like
  6603. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6604. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6605. {
  6606. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6607. * expansion of right-hand side of assignment == 1-element expand.
  6608. */
  6609. char cant_be_null = 0; /* only bit 0x80 matters */
  6610. char *p;
  6611. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6612. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6613. debug_print_list("expand_vars_to_list[0]", output, n);
  6614. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6615. char first_ch;
  6616. #if ENABLE_FEATURE_SH_MATH
  6617. char arith_buf[sizeof(arith_t)*3 + 2];
  6618. #endif
  6619. if (output->ended_in_ifs) {
  6620. o_addchr(output, '\0');
  6621. n = o_save_ptr(output, n);
  6622. output->ended_in_ifs = 0;
  6623. }
  6624. o_addblock(output, arg, p - arg);
  6625. debug_print_list("expand_vars_to_list[1]", output, n);
  6626. arg = ++p;
  6627. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6628. /* Fetch special var name (if it is indeed one of them)
  6629. * and quote bit, force the bit on if singleword expansion -
  6630. * important for not getting v=$@ expand to many words. */
  6631. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6632. /* Is this variable quoted and thus expansion can't be null?
  6633. * "$@" is special. Even if quoted, it can still
  6634. * expand to nothing (not even an empty string),
  6635. * thus it is excluded. */
  6636. if ((first_ch & 0x7f) != '@')
  6637. cant_be_null |= first_ch;
  6638. switch (first_ch & 0x7f) {
  6639. /* Highest bit in first_ch indicates that var is double-quoted */
  6640. case '*':
  6641. case '@': {
  6642. int i;
  6643. if (!G.global_argv[1])
  6644. break;
  6645. i = 1;
  6646. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6647. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6648. while (G.global_argv[i]) {
  6649. n = expand_on_ifs(output, n, G.global_argv[i]);
  6650. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6651. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6652. /* this argv[] is not empty and not last:
  6653. * put terminating NUL, start new word */
  6654. o_addchr(output, '\0');
  6655. debug_print_list("expand_vars_to_list[2]", output, n);
  6656. n = o_save_ptr(output, n);
  6657. debug_print_list("expand_vars_to_list[3]", output, n);
  6658. }
  6659. }
  6660. } else
  6661. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6662. * and in this case should treat it like '$*' - see 'else...' below */
  6663. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6664. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6665. ) {
  6666. while (1) {
  6667. o_addQstr(output, G.global_argv[i]);
  6668. if (++i >= G.global_argc)
  6669. break;
  6670. o_addchr(output, '\0');
  6671. debug_print_list("expand_vars_to_list[4]", output, n);
  6672. n = o_save_ptr(output, n);
  6673. }
  6674. } else { /* quoted $* (or v="$@" case): add as one word */
  6675. while (1) {
  6676. o_addQstr(output, G.global_argv[i]);
  6677. if (!G.global_argv[++i])
  6678. break;
  6679. if (G.ifs[0])
  6680. o_addchr(output, G.ifs[0]);
  6681. }
  6682. output->has_quoted_part = 1;
  6683. }
  6684. break;
  6685. }
  6686. case SPECIAL_VAR_SYMBOL: {
  6687. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6688. /* "Empty variable", used to make "" etc to not disappear */
  6689. output->has_quoted_part = 1;
  6690. cant_be_null = 0x80;
  6691. arg++;
  6692. break;
  6693. }
  6694. case SPECIAL_VAR_QUOTED_SVS:
  6695. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6696. /* "^C variable", represents literal ^C char (possible in scripts) */
  6697. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6698. arg++;
  6699. break;
  6700. #if ENABLE_HUSH_TICK
  6701. case '`': {
  6702. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6703. o_string subst_result = NULL_O_STRING;
  6704. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6705. arg++;
  6706. /* Can't just stuff it into output o_string,
  6707. * expanded result may need to be globbed
  6708. * and $IFS-split */
  6709. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6710. G.last_exitcode = process_command_subs(&subst_result, arg);
  6711. G.expand_exitcode = G.last_exitcode;
  6712. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6713. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6714. o_free(&subst_result);
  6715. break;
  6716. }
  6717. #endif
  6718. #if ENABLE_FEATURE_SH_MATH
  6719. case '+': {
  6720. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6721. arith_t res;
  6722. arg++; /* skip '+' */
  6723. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6724. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6725. res = expand_and_evaluate_arith(arg, NULL);
  6726. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6727. sprintf(arith_buf, ARITH_FMT, res);
  6728. if (res < 0
  6729. && first_ch == (char)('+'|0x80)
  6730. /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
  6731. ) {
  6732. /* Quoted negative ariths, like filename[0"$((-9))"],
  6733. * should not be interpreted as glob ranges.
  6734. * Convert leading '-' to '\-':
  6735. */
  6736. o_grow_by(output, 1);
  6737. output->data[output->length++] = '\\';
  6738. }
  6739. o_addstr(output, arith_buf);
  6740. break;
  6741. }
  6742. #endif
  6743. default:
  6744. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6745. n = expand_one_var(output, n, first_ch, arg, &p);
  6746. break;
  6747. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6748. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6749. * Do the check to avoid writing to a const string. */
  6750. if (*p != SPECIAL_VAR_SYMBOL)
  6751. *p = SPECIAL_VAR_SYMBOL;
  6752. arg = ++p;
  6753. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6754. if (*arg) {
  6755. /* handle trailing string */
  6756. if (output->ended_in_ifs) {
  6757. o_addchr(output, '\0');
  6758. n = o_save_ptr(output, n);
  6759. }
  6760. debug_print_list("expand_vars_to_list[a]", output, n);
  6761. /* this part is literal, and it was already pre-quoted
  6762. * if needed (much earlier), do not use o_addQstr here!
  6763. */
  6764. o_addstr(output, arg);
  6765. debug_print_list("expand_vars_to_list[b]", output, n);
  6766. } else
  6767. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6768. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6769. && !output->has_quoted_part
  6770. ) {
  6771. n--;
  6772. /* allow to reuse list[n] later without re-growth */
  6773. output->has_empty_slot = 1;
  6774. }
  6775. return n;
  6776. }
  6777. static char **expand_variables(char **argv, unsigned expflags)
  6778. {
  6779. int n;
  6780. char **list;
  6781. o_string output = NULL_O_STRING;
  6782. output.o_expflags = expflags;
  6783. n = 0;
  6784. for (;;) {
  6785. /* go to next list[n] */
  6786. output.ended_in_ifs = 0;
  6787. n = o_save_ptr(&output, n);
  6788. if (!*argv)
  6789. break;
  6790. /* expand argv[i] */
  6791. n = expand_vars_to_list(&output, n, *argv++);
  6792. /* if (!output->has_empty_slot) -- need this?? */
  6793. o_addchr(&output, '\0');
  6794. }
  6795. debug_print_list("expand_variables", &output, n);
  6796. /* output.data (malloced in one block) gets returned in "list" */
  6797. list = o_finalize_list(&output, n);
  6798. debug_print_strings("expand_variables[1]", list);
  6799. return list;
  6800. }
  6801. static char **expand_strvec_to_strvec(char **argv)
  6802. {
  6803. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6804. }
  6805. #if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  6806. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6807. {
  6808. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6809. }
  6810. #endif
  6811. /* Used for expansion of right hand of assignments,
  6812. * $((...)), heredocs, variable expansion parts.
  6813. *
  6814. * NB: should NOT do globbing!
  6815. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6816. */
  6817. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6818. {
  6819. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6820. const int do_unbackslash = 1;
  6821. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6822. #endif
  6823. char *argv[2], **list;
  6824. debug_printf_expand("string_to_string<='%s'\n", str);
  6825. /* This is generally an optimization, but it also
  6826. * handles "", which otherwise trips over !list[0] check below.
  6827. * (is this ever happens that we actually get str="" here?)
  6828. */
  6829. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6830. //TODO: Can use on strings with \ too, just unbackslash() them?
  6831. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6832. return xstrdup(str);
  6833. }
  6834. argv[0] = (char*)str;
  6835. argv[1] = NULL;
  6836. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6837. if (!list[0]) {
  6838. /* Example where it happens:
  6839. * x=; echo ${x:-"$@"}
  6840. */
  6841. ((char*)list)[0] = '\0';
  6842. } else {
  6843. if (HUSH_DEBUG)
  6844. if (list[1])
  6845. bb_simple_error_msg_and_die("BUG in varexp2");
  6846. /* actually, just move string 2*sizeof(char*) bytes back */
  6847. overlapping_strcpy((char*)list, list[0]);
  6848. if (do_unbackslash)
  6849. unbackslash((char*)list);
  6850. }
  6851. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6852. return (char*)list;
  6853. }
  6854. #if 0
  6855. static char* expand_strvec_to_string(char **argv)
  6856. {
  6857. char **list;
  6858. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6859. /* Convert all NULs to spaces */
  6860. if (list[0]) {
  6861. int n = 1;
  6862. while (list[n]) {
  6863. if (HUSH_DEBUG)
  6864. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6865. bb_error_msg_and_die("BUG in varexp3");
  6866. /* bash uses ' ' regardless of $IFS contents */
  6867. list[n][-1] = ' ';
  6868. n++;
  6869. }
  6870. }
  6871. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6872. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6873. return (char*)list;
  6874. }
  6875. #endif
  6876. static char **expand_assignments(char **argv, int count)
  6877. {
  6878. int i;
  6879. char **p;
  6880. G.expanded_assignments = p = NULL;
  6881. /* Expand assignments into one string each */
  6882. for (i = 0; i < count; i++) {
  6883. p = add_string_to_strings(p,
  6884. expand_string_to_string(argv[i],
  6885. EXP_FLAG_ESC_GLOB_CHARS,
  6886. /*unbackslash:*/ 1
  6887. )
  6888. );
  6889. G.expanded_assignments = p;
  6890. }
  6891. G.expanded_assignments = NULL;
  6892. return p;
  6893. }
  6894. static void switch_off_special_sigs(unsigned mask)
  6895. {
  6896. unsigned sig = 0;
  6897. while ((mask >>= 1) != 0) {
  6898. sig++;
  6899. if (!(mask & 1))
  6900. continue;
  6901. #if ENABLE_HUSH_TRAP
  6902. if (G_traps) {
  6903. if (G_traps[sig] && !G_traps[sig][0])
  6904. /* trap is '', has to remain SIG_IGN */
  6905. continue;
  6906. free(G_traps[sig]);
  6907. G_traps[sig] = NULL;
  6908. }
  6909. #endif
  6910. /* We are here only if no trap or trap was not '' */
  6911. install_sighandler(sig, SIG_DFL);
  6912. }
  6913. }
  6914. #if BB_MMU
  6915. /* never called */
  6916. void re_execute_shell(char ***to_free, const char *s,
  6917. char *g_argv0, char **g_argv,
  6918. char **builtin_argv) NORETURN;
  6919. static void reset_traps_to_defaults(void)
  6920. {
  6921. /* This function is always called in a child shell
  6922. * after fork (not vfork, NOMMU doesn't use this function).
  6923. */
  6924. IF_HUSH_TRAP(unsigned sig;)
  6925. unsigned mask;
  6926. /* Child shells are not interactive.
  6927. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6928. * Testcase: (while :; do :; done) + ^Z should background.
  6929. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6930. */
  6931. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6932. if (!G_traps && !mask)
  6933. return; /* already no traps and no special sigs */
  6934. /* Switch off special sigs */
  6935. switch_off_special_sigs(mask);
  6936. # if ENABLE_HUSH_JOB
  6937. G_fatal_sig_mask = 0;
  6938. # endif
  6939. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6940. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6941. * remain set in G.special_sig_mask */
  6942. # if ENABLE_HUSH_TRAP
  6943. if (!G_traps)
  6944. return;
  6945. /* Reset all sigs to default except ones with empty traps */
  6946. for (sig = 0; sig < NSIG; sig++) {
  6947. if (!G_traps[sig])
  6948. continue; /* no trap: nothing to do */
  6949. if (!G_traps[sig][0])
  6950. continue; /* empty trap: has to remain SIG_IGN */
  6951. /* sig has non-empty trap, reset it: */
  6952. free(G_traps[sig]);
  6953. G_traps[sig] = NULL;
  6954. /* There is no signal for trap 0 (EXIT) */
  6955. if (sig == 0)
  6956. continue;
  6957. install_sighandler(sig, pick_sighandler(sig));
  6958. }
  6959. # endif
  6960. }
  6961. #else /* !BB_MMU */
  6962. static void re_execute_shell(char ***to_free, const char *s,
  6963. char *g_argv0, char **g_argv,
  6964. char **builtin_argv) NORETURN;
  6965. static void re_execute_shell(char ***to_free, const char *s,
  6966. char *g_argv0, char **g_argv,
  6967. char **builtin_argv)
  6968. {
  6969. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6970. /* delims + 2 * (number of bytes in printed hex numbers) */
  6971. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6972. char *heredoc_argv[4];
  6973. struct variable *cur;
  6974. # if ENABLE_HUSH_FUNCTIONS
  6975. struct function *funcp;
  6976. # endif
  6977. char **argv, **pp;
  6978. unsigned cnt;
  6979. unsigned long long empty_trap_mask;
  6980. if (!g_argv0) { /* heredoc */
  6981. argv = heredoc_argv;
  6982. argv[0] = (char *) G.argv0_for_re_execing;
  6983. argv[1] = (char *) "-<";
  6984. argv[2] = (char *) s;
  6985. argv[3] = NULL;
  6986. pp = &argv[3]; /* used as pointer to empty environment */
  6987. goto do_exec;
  6988. }
  6989. cnt = 0;
  6990. pp = builtin_argv;
  6991. if (pp) while (*pp++)
  6992. cnt++;
  6993. empty_trap_mask = 0;
  6994. if (G_traps) {
  6995. int sig;
  6996. for (sig = 1; sig < NSIG; sig++) {
  6997. if (G_traps[sig] && !G_traps[sig][0])
  6998. empty_trap_mask |= 1LL << sig;
  6999. }
  7000. }
  7001. sprintf(param_buf, NOMMU_HACK_FMT
  7002. , (unsigned) G.root_pid
  7003. , (unsigned) G.root_ppid
  7004. , (unsigned) G.last_bg_pid
  7005. , (unsigned) G.last_exitcode
  7006. , cnt
  7007. , empty_trap_mask
  7008. IF_HUSH_LOOPS(, G.depth_of_loop)
  7009. );
  7010. # undef NOMMU_HACK_FMT
  7011. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  7012. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  7013. */
  7014. cnt += 6;
  7015. for (cur = G.top_var; cur; cur = cur->next) {
  7016. if (!cur->flg_export || cur->flg_read_only)
  7017. cnt += 2;
  7018. }
  7019. # if ENABLE_HUSH_LINENO_VAR
  7020. cnt += 2;
  7021. # endif
  7022. # if ENABLE_HUSH_FUNCTIONS
  7023. for (funcp = G.top_func; funcp; funcp = funcp->next)
  7024. cnt += 3;
  7025. # endif
  7026. pp = g_argv;
  7027. while (*pp++)
  7028. cnt++;
  7029. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  7030. *pp++ = (char *) G.argv0_for_re_execing;
  7031. *pp++ = param_buf;
  7032. for (cur = G.top_var; cur; cur = cur->next) {
  7033. if (strcmp(cur->varstr, hush_version_str) == 0)
  7034. continue;
  7035. if (cur->flg_read_only) {
  7036. *pp++ = (char *) "-R";
  7037. *pp++ = cur->varstr;
  7038. } else if (!cur->flg_export) {
  7039. *pp++ = (char *) "-V";
  7040. *pp++ = cur->varstr;
  7041. }
  7042. }
  7043. # if ENABLE_HUSH_LINENO_VAR
  7044. *pp++ = (char *) "-L";
  7045. *pp++ = utoa(G.execute_lineno);
  7046. # endif
  7047. # if ENABLE_HUSH_FUNCTIONS
  7048. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  7049. *pp++ = (char *) "-F";
  7050. *pp++ = funcp->name;
  7051. *pp++ = funcp->body_as_string;
  7052. }
  7053. # endif
  7054. /* We can pass activated traps here. Say, -Tnn:trap_string
  7055. *
  7056. * However, POSIX says that subshells reset signals with traps
  7057. * to SIG_DFL.
  7058. * I tested bash-3.2 and it not only does that with true subshells
  7059. * of the form ( list ), but with any forked children shells.
  7060. * I set trap "echo W" WINCH; and then tried:
  7061. *
  7062. * { echo 1; sleep 20; echo 2; } &
  7063. * while true; do echo 1; sleep 20; echo 2; break; done &
  7064. * true | { echo 1; sleep 20; echo 2; } | cat
  7065. *
  7066. * In all these cases sending SIGWINCH to the child shell
  7067. * did not run the trap. If I add trap "echo V" WINCH;
  7068. * _inside_ group (just before echo 1), it works.
  7069. *
  7070. * I conclude it means we don't need to pass active traps here.
  7071. */
  7072. *pp++ = (char *) "-c";
  7073. *pp++ = (char *) s;
  7074. if (builtin_argv) {
  7075. while (*++builtin_argv)
  7076. *pp++ = *builtin_argv;
  7077. *pp++ = (char *) "";
  7078. }
  7079. *pp++ = g_argv0;
  7080. while (*g_argv)
  7081. *pp++ = *g_argv++;
  7082. /* *pp = NULL; - is already there */
  7083. pp = environ;
  7084. do_exec:
  7085. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  7086. /* Don't propagate SIG_IGN to the child */
  7087. if (SPECIAL_JOBSTOP_SIGS != 0)
  7088. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7089. execve(bb_busybox_exec_path, argv, pp);
  7090. /* Fallback. Useful for init=/bin/hush usage etc */
  7091. if (argv[0][0] == '/')
  7092. execve(argv[0], argv, pp);
  7093. xfunc_error_retval = 127;
  7094. bb_simple_error_msg_and_die("can't re-execute the shell");
  7095. }
  7096. #endif /* !BB_MMU */
  7097. static int run_and_free_list(struct pipe *pi);
  7098. /* Executing from string: eval, sh -c '...'
  7099. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  7100. * end_trigger controls how often we stop parsing
  7101. * NUL: parse all, execute, return
  7102. * ';': parse till ';' or newline, execute, repeat till EOF
  7103. */
  7104. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  7105. {
  7106. /* Why we need empty flag?
  7107. * An obscure corner case "false; ``; echo $?":
  7108. * empty command in `` should still set $? to 0.
  7109. * But we can't just set $? to 0 at the start,
  7110. * this breaks "false; echo `echo $?`" case.
  7111. */
  7112. bool empty = 1;
  7113. while (1) {
  7114. struct pipe *pipe_list;
  7115. #if ENABLE_HUSH_INTERACTIVE
  7116. if (end_trigger == ';') {
  7117. G.promptmode = 0; /* PS1 */
  7118. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  7119. }
  7120. #endif
  7121. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  7122. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  7123. /* If we are in "big" script
  7124. * (not in `cmd` or something similar)...
  7125. */
  7126. if (pipe_list == ERR_PTR && end_trigger == ';') {
  7127. /* Discard cached input (rest of line) */
  7128. int ch = inp->last_char;
  7129. while (ch != EOF && ch != '\n') {
  7130. //bb_error_msg("Discarded:'%c'", ch);
  7131. ch = i_getch(inp);
  7132. }
  7133. /* Force prompt */
  7134. inp->p = NULL;
  7135. /* Clear "peeked" EOF. Without this,
  7136. * $ { cmd }<Enter>
  7137. * > ^D
  7138. * hush: syntax error: unterminated {
  7139. * exits interactive shell:
  7140. */
  7141. if (inp->peek_buf[0] == EOF)
  7142. inp->peek_buf[0] = 0;
  7143. /* This stream isn't empty */
  7144. empty = 0;
  7145. continue;
  7146. }
  7147. if (!pipe_list && empty)
  7148. G.last_exitcode = 0;
  7149. break;
  7150. }
  7151. debug_print_tree(pipe_list, 0);
  7152. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  7153. run_and_free_list(pipe_list);
  7154. empty = 0;
  7155. if (G_flag_return_in_progress == 1)
  7156. break;
  7157. }
  7158. }
  7159. static void parse_and_run_string(const char *s)
  7160. {
  7161. struct in_str input;
  7162. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7163. setup_string_in_str(&input, s);
  7164. parse_and_run_stream(&input, '\0');
  7165. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7166. }
  7167. static void parse_and_run_file(HFILE *fp)
  7168. {
  7169. struct in_str input;
  7170. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7171. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  7172. setup_file_in_str(&input, fp);
  7173. parse_and_run_stream(&input, ';');
  7174. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7175. }
  7176. #if ENABLE_HUSH_TICK
  7177. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  7178. {
  7179. pid_t pid;
  7180. int channel[2];
  7181. # if !BB_MMU
  7182. char **to_free = NULL;
  7183. # endif
  7184. xpipe(channel);
  7185. pid = BB_MMU ? xfork() : xvfork();
  7186. if (pid == 0) { /* child */
  7187. disable_restore_tty_pgrp_on_exit();
  7188. /* Process substitution is not considered to be usual
  7189. * 'command execution'.
  7190. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  7191. */
  7192. bb_signals(0
  7193. + (1 << SIGTSTP)
  7194. + (1 << SIGTTIN)
  7195. + (1 << SIGTTOU)
  7196. , SIG_IGN);
  7197. close(channel[0]); /* NB: close _first_, then move fd! */
  7198. xmove_fd(channel[1], 1);
  7199. # if ENABLE_HUSH_TRAP
  7200. /* Awful hack for `trap` or $(trap).
  7201. *
  7202. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  7203. * contains an example where "trap" is executed in a subshell:
  7204. *
  7205. * save_traps=$(trap)
  7206. * ...
  7207. * eval "$save_traps"
  7208. *
  7209. * Standard does not say that "trap" in subshell shall print
  7210. * parent shell's traps. It only says that its output
  7211. * must have suitable form, but then, in the above example
  7212. * (which is not supposed to be normative), it implies that.
  7213. *
  7214. * bash (and probably other shell) does implement it
  7215. * (traps are reset to defaults, but "trap" still shows them),
  7216. * but as a result, "trap" logic is hopelessly messed up:
  7217. *
  7218. * # trap
  7219. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  7220. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  7221. * # true | trap <--- trap is in subshell - no output (ditto)
  7222. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  7223. * trap -- 'echo Ho' SIGWINCH
  7224. * # echo `(trap)` <--- in subshell in subshell - output
  7225. * trap -- 'echo Ho' SIGWINCH
  7226. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  7227. * trap -- 'echo Ho' SIGWINCH
  7228. *
  7229. * The rules when to forget and when to not forget traps
  7230. * get really complex and nonsensical.
  7231. *
  7232. * Our solution: ONLY bare $(trap) or `trap` is special.
  7233. */
  7234. s = skip_whitespace(s);
  7235. if (is_prefixed_with(s, "trap")
  7236. && skip_whitespace(s + 4)[0] == '\0'
  7237. ) {
  7238. static const char *const argv[] ALIGN_PTR = { NULL, NULL };
  7239. builtin_trap((char**)argv);
  7240. fflush_all(); /* important */
  7241. _exit(0);
  7242. }
  7243. # endif
  7244. # if BB_MMU
  7245. /* Prevent it from trying to handle ctrl-z etc */
  7246. IF_HUSH_JOB(G.run_list_level = 1;)
  7247. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  7248. reset_traps_to_defaults();
  7249. IF_HUSH_MODE_X(G.x_mode_depth++;)
  7250. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  7251. parse_and_run_string(s);
  7252. _exit(G.last_exitcode);
  7253. # else
  7254. /* We re-execute after vfork on NOMMU. This makes this script safe:
  7255. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  7256. * huge=`cat BIG` # was blocking here forever
  7257. * echo OK
  7258. */
  7259. re_execute_shell(&to_free,
  7260. s,
  7261. G.global_argv[0],
  7262. G.global_argv + 1,
  7263. NULL);
  7264. # endif
  7265. }
  7266. /* parent */
  7267. *pid_p = pid;
  7268. # if ENABLE_HUSH_FAST
  7269. G.count_SIGCHLD++;
  7270. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  7271. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  7272. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7273. # endif
  7274. enable_restore_tty_pgrp_on_exit();
  7275. # if !BB_MMU
  7276. free(to_free);
  7277. # endif
  7278. close(channel[1]);
  7279. return channel[0];
  7280. }
  7281. /* Return code is exit status of the process that is run. */
  7282. static int process_command_subs(o_string *dest, const char *s)
  7283. {
  7284. FILE *fp;
  7285. pid_t pid;
  7286. int status, ch, eol_cnt;
  7287. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  7288. /* Now send results of command back into original context */
  7289. eol_cnt = 0;
  7290. while ((ch = getc(fp)) != EOF) {
  7291. if (ch == '\0')
  7292. continue;
  7293. if (ch == '\n') {
  7294. eol_cnt++;
  7295. continue;
  7296. }
  7297. while (eol_cnt) {
  7298. o_addchr(dest, '\n');
  7299. eol_cnt--;
  7300. }
  7301. o_addQchr(dest, ch);
  7302. }
  7303. debug_printf("done reading from `cmd` pipe, closing it\n");
  7304. fclose(fp);
  7305. /* We need to extract exitcode. Test case
  7306. * "true; echo `sleep 1; false` $?"
  7307. * should print 1 */
  7308. safe_waitpid(pid, &status, 0);
  7309. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  7310. return WEXITSTATUS(status);
  7311. }
  7312. #endif /* ENABLE_HUSH_TICK */
  7313. static void setup_heredoc(struct redir_struct *redir)
  7314. {
  7315. struct fd_pair pair;
  7316. pid_t pid;
  7317. int len, written;
  7318. /* the _body_ of heredoc (misleading field name) */
  7319. const char *heredoc = redir->rd_filename;
  7320. char *expanded;
  7321. #if !BB_MMU
  7322. char **to_free;
  7323. #endif
  7324. expanded = NULL;
  7325. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  7326. expanded = encode_then_expand_string(heredoc);
  7327. if (expanded)
  7328. heredoc = expanded;
  7329. }
  7330. len = strlen(heredoc);
  7331. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7332. xpiped_pair(pair);
  7333. xmove_fd(pair.rd, redir->rd_fd);
  7334. /* Try writing without forking. Newer kernels have
  7335. * dynamically growing pipes. Must use non-blocking write! */
  7336. ndelay_on(pair.wr);
  7337. while (1) {
  7338. written = write(pair.wr, heredoc, len);
  7339. if (written <= 0)
  7340. break;
  7341. len -= written;
  7342. if (len == 0) {
  7343. close(pair.wr);
  7344. free(expanded);
  7345. return;
  7346. }
  7347. heredoc += written;
  7348. }
  7349. ndelay_off(pair.wr);
  7350. /* Okay, pipe buffer was not big enough */
  7351. /* Note: we must not create a stray child (bastard? :)
  7352. * for the unsuspecting parent process. Child creates a grandchild
  7353. * and exits before parent execs the process which consumes heredoc
  7354. * (that exec happens after we return from this function) */
  7355. #if !BB_MMU
  7356. to_free = NULL;
  7357. #endif
  7358. pid = xvfork();
  7359. if (pid == 0) {
  7360. /* child */
  7361. disable_restore_tty_pgrp_on_exit();
  7362. pid = BB_MMU ? xfork() : xvfork();
  7363. if (pid != 0)
  7364. _exit(0);
  7365. /* grandchild */
  7366. close(redir->rd_fd); /* read side of the pipe */
  7367. #if BB_MMU
  7368. full_write(pair.wr, heredoc, len); /* may loop or block */
  7369. _exit(0);
  7370. #else
  7371. /* Delegate blocking writes to another process */
  7372. xmove_fd(pair.wr, STDOUT_FILENO);
  7373. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7374. #endif
  7375. }
  7376. /* parent */
  7377. #if ENABLE_HUSH_FAST
  7378. G.count_SIGCHLD++;
  7379. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7380. #endif
  7381. enable_restore_tty_pgrp_on_exit();
  7382. #if !BB_MMU
  7383. free(to_free);
  7384. #endif
  7385. close(pair.wr);
  7386. free(expanded);
  7387. wait(NULL); /* wait till child has died */
  7388. }
  7389. struct squirrel {
  7390. int orig_fd;
  7391. int moved_to;
  7392. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7393. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7394. };
  7395. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7396. {
  7397. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7398. sq[i].orig_fd = orig;
  7399. sq[i].moved_to = moved;
  7400. sq[i+1].orig_fd = -1; /* end marker */
  7401. return sq;
  7402. }
  7403. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7404. {
  7405. int moved_to;
  7406. int i;
  7407. i = 0;
  7408. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7409. /* If we collide with an already moved fd... */
  7410. if (fd == sq[i].moved_to) {
  7411. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7412. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7413. if (sq[i].moved_to < 0) /* what? */
  7414. xfunc_die();
  7415. return sq;
  7416. }
  7417. if (fd == sq[i].orig_fd) {
  7418. /* Example: echo Hello >/dev/null 1>&2 */
  7419. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7420. return sq;
  7421. }
  7422. }
  7423. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7424. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7425. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7426. if (moved_to < 0 && errno != EBADF)
  7427. xfunc_die();
  7428. return append_squirrel(sq, i, fd, moved_to);
  7429. }
  7430. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7431. {
  7432. int i;
  7433. i = 0;
  7434. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7435. /* If we collide with an already moved fd... */
  7436. if (fd == sq[i].orig_fd) {
  7437. /* Examples:
  7438. * "echo 3>FILE 3>&- 3>FILE"
  7439. * "echo 3>&- 3>FILE"
  7440. * No need for last redirect to insert
  7441. * another "need to close 3" indicator.
  7442. */
  7443. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7444. return sq;
  7445. }
  7446. }
  7447. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7448. return append_squirrel(sq, i, fd, -1);
  7449. }
  7450. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7451. * Move all conflicting internally used fds,
  7452. * and remember them so that we can restore them later.
  7453. */
  7454. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7455. {
  7456. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7457. avoid_fd = 9;
  7458. #if ENABLE_HUSH_INTERACTIVE
  7459. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7460. && fd == G_interactive_fd
  7461. ) {
  7462. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7463. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7464. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7465. return 1; /* "we closed fd" */
  7466. }
  7467. #endif
  7468. /* Are we called from setup_redirects(squirrel==NULL)
  7469. * in redirect in a [v]forked child?
  7470. */
  7471. if (sqp == NULL) {
  7472. /* No need to move script fds.
  7473. * For NOMMU case, it's actively wrong: we'd change ->fd
  7474. * fields in memory for the parent, but parent's fds
  7475. * aren't moved, it would use wrong fd!
  7476. * Reproducer: "cmd 3>FILE" in script.
  7477. * If we would call move_HFILEs_on_redirect(), child would:
  7478. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7479. * close(3) = 0
  7480. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7481. */
  7482. //bb_error_msg("sqp == NULL: [v]forked child");
  7483. return 0;
  7484. }
  7485. /* If this one of script's fds? */
  7486. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7487. return 1; /* yes. "we closed fd" (actually moved it) */
  7488. /* Are we called for "exec 3>FILE"? Came through
  7489. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7490. * This case used to fail for this script:
  7491. * exec 3>FILE
  7492. * echo Ok
  7493. * ...100000 more lines...
  7494. * echo Ok
  7495. * as follows:
  7496. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7497. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7498. * dup2(4, 3) = 3
  7499. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7500. * close(4) = 0
  7501. * write(1, "Ok\n", 3) = 3
  7502. * ... = 3
  7503. * write(1, "Ok\n", 3) = 3
  7504. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7505. * ^^^^^^^^ oops, wrong fd!!!
  7506. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7507. * it now works:
  7508. */
  7509. if (sqp == ERR_PTR) {
  7510. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7511. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7512. return 0;
  7513. }
  7514. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7515. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7516. return 0; /* "we did not close fd" */
  7517. }
  7518. static void restore_redirects(struct squirrel *sq)
  7519. {
  7520. if (sq) {
  7521. int i;
  7522. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7523. if (sq[i].moved_to >= 0) {
  7524. /* We simply die on error */
  7525. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7526. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7527. } else {
  7528. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7529. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7530. close(sq[i].orig_fd);
  7531. }
  7532. }
  7533. free(sq);
  7534. }
  7535. if (G.HFILE_stdin
  7536. && G.HFILE_stdin->fd > STDIN_FILENO
  7537. /* we compare > STDIN, not == STDIN, since hfgetc()
  7538. * closes fd and sets ->fd to -1 if EOF is reached.
  7539. * Testcase: echo 'pwd' | hush
  7540. */
  7541. ) {
  7542. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7543. * Redirect moves ->fd to e.g. 10,
  7544. * and it is not restored above (we do not restore script fds
  7545. * after redirects, we just use new, "moved" fds).
  7546. * However for stdin, get_user_input() -> read_line_input(),
  7547. * and read builtin, depend on fd == STDIN_FILENO.
  7548. */
  7549. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7550. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7551. G.HFILE_stdin->fd = STDIN_FILENO;
  7552. }
  7553. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7554. }
  7555. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7556. static void close_saved_fds_and_FILE_fds(void)
  7557. {
  7558. if (G_interactive_fd)
  7559. close(G_interactive_fd);
  7560. close_all_HFILE_list();
  7561. }
  7562. #endif
  7563. static int internally_opened_fd(int fd, struct squirrel *sq)
  7564. {
  7565. int i;
  7566. #if ENABLE_HUSH_INTERACTIVE
  7567. if (fd == G_interactive_fd)
  7568. return 1;
  7569. #endif
  7570. /* If this one of script's fds? */
  7571. if (fd_in_HFILEs(fd))
  7572. return 1;
  7573. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7574. if (fd == sq[i].moved_to)
  7575. return 1;
  7576. }
  7577. return 0;
  7578. }
  7579. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7580. * and stderr if they are redirected. */
  7581. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7582. {
  7583. struct redir_struct *redir;
  7584. for (redir = prog->redirects; redir; redir = redir->next) {
  7585. int newfd;
  7586. int closed;
  7587. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7588. /* "rd_fd<<HERE" case */
  7589. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7590. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7591. * of the heredoc */
  7592. debug_printf_redir("set heredoc '%s'\n",
  7593. redir->rd_filename);
  7594. setup_heredoc(redir);
  7595. continue;
  7596. }
  7597. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7598. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7599. char *p;
  7600. int mode;
  7601. if (redir->rd_filename == NULL) {
  7602. /* Examples:
  7603. * "cmd >" (no filename)
  7604. * "cmd > <file" (2nd redirect starts too early)
  7605. */
  7606. syntax_error("invalid redirect");
  7607. continue;
  7608. }
  7609. mode = redir_table[redir->rd_type].mode;
  7610. p = expand_string_to_string(redir->rd_filename,
  7611. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7612. newfd = open_or_warn(p, mode);
  7613. free(p);
  7614. if (newfd < 0) {
  7615. /* Error message from open_or_warn can be lost
  7616. * if stderr has been redirected, but bash
  7617. * and ash both lose it as well
  7618. * (though zsh doesn't!)
  7619. */
  7620. return 1;
  7621. }
  7622. if (newfd == redir->rd_fd && sqp) {
  7623. /* open() gave us precisely the fd we wanted.
  7624. * This means that this fd was not busy
  7625. * (not opened to anywhere).
  7626. * Remember to close it on restore:
  7627. */
  7628. *sqp = add_squirrel_closed(*sqp, newfd);
  7629. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7630. }
  7631. } else {
  7632. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7633. newfd = redir->rd_dup;
  7634. }
  7635. if (newfd == redir->rd_fd)
  7636. continue;
  7637. /* if "N>FILE": move newfd to redir->rd_fd */
  7638. /* if "N>&M": dup newfd to redir->rd_fd */
  7639. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7640. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7641. if (newfd == REDIRFD_CLOSE) {
  7642. /* "N>&-" means "close me" */
  7643. if (!closed) {
  7644. /* ^^^ optimization: saving may already
  7645. * have closed it. If not... */
  7646. close(redir->rd_fd);
  7647. }
  7648. /* Sometimes we do another close on restore, getting EBADF.
  7649. * Consider "echo 3>FILE 3>&-"
  7650. * first redirect remembers "need to close 3",
  7651. * and second redirect closes 3! Restore code then closes 3 again.
  7652. */
  7653. } else {
  7654. /* if newfd is a script fd or saved fd, simulate EBADF */
  7655. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7656. //errno = EBADF;
  7657. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7658. newfd = -1; /* same effect as code above */
  7659. }
  7660. xdup2(newfd, redir->rd_fd);
  7661. if (redir->rd_dup == REDIRFD_TO_FILE)
  7662. /* "rd_fd > FILE" */
  7663. close(newfd);
  7664. /* else: "rd_fd > rd_dup" */
  7665. }
  7666. }
  7667. return 0;
  7668. }
  7669. static char *find_in_path(const char *arg)
  7670. {
  7671. char *ret = NULL;
  7672. const char *PATH = get_local_var_value("PATH");
  7673. if (!PATH)
  7674. return NULL;
  7675. while (1) {
  7676. const char *end = strchrnul(PATH, ':');
  7677. int sz = end - PATH; /* must be int! */
  7678. free(ret);
  7679. if (sz != 0) {
  7680. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7681. } else {
  7682. /* We have xxx::yyyy in $PATH,
  7683. * it means "use current dir" */
  7684. ret = xstrdup(arg);
  7685. }
  7686. if (access(ret, F_OK) == 0)
  7687. break;
  7688. if (*end == '\0') {
  7689. free(ret);
  7690. return NULL;
  7691. }
  7692. PATH = end + 1;
  7693. }
  7694. return ret;
  7695. }
  7696. static const struct built_in_command *find_builtin_helper(const char *name,
  7697. const struct built_in_command *x,
  7698. const struct built_in_command *end)
  7699. {
  7700. while (x != end) {
  7701. if (strcmp(name, x->b_cmd) != 0) {
  7702. x++;
  7703. continue;
  7704. }
  7705. debug_printf_exec("found builtin '%s'\n", name);
  7706. return x;
  7707. }
  7708. return NULL;
  7709. }
  7710. static const struct built_in_command *find_builtin1(const char *name)
  7711. {
  7712. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7713. }
  7714. static const struct built_in_command *find_builtin(const char *name)
  7715. {
  7716. const struct built_in_command *x = find_builtin1(name);
  7717. if (x)
  7718. return x;
  7719. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7720. }
  7721. #if ENABLE_HUSH_JOB && ENABLE_FEATURE_TAB_COMPLETION
  7722. static const char * FAST_FUNC hush_command_name(int i)
  7723. {
  7724. if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
  7725. return bltins1[i].b_cmd;
  7726. }
  7727. i -= ARRAY_SIZE(bltins1);
  7728. if (i < ARRAY_SIZE(bltins2)) {
  7729. return bltins2[i].b_cmd;
  7730. }
  7731. # if ENABLE_HUSH_FUNCTIONS
  7732. {
  7733. struct function *funcp;
  7734. i -= ARRAY_SIZE(bltins2);
  7735. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  7736. if (--i < 0)
  7737. return funcp->name;
  7738. }
  7739. }
  7740. # endif
  7741. return NULL;
  7742. }
  7743. #endif
  7744. static void remove_nested_vars(void)
  7745. {
  7746. struct variable *cur;
  7747. struct variable **cur_pp;
  7748. cur_pp = &G.top_var;
  7749. while ((cur = *cur_pp) != NULL) {
  7750. if (cur->var_nest_level <= G.var_nest_level) {
  7751. cur_pp = &cur->next;
  7752. continue;
  7753. }
  7754. /* Unexport */
  7755. if (cur->flg_export) {
  7756. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7757. bb_unsetenv(cur->varstr);
  7758. }
  7759. /* Remove from global list */
  7760. *cur_pp = cur->next;
  7761. /* Free */
  7762. if (!cur->max_len) {
  7763. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7764. free(cur->varstr);
  7765. }
  7766. free(cur);
  7767. }
  7768. }
  7769. static void enter_var_nest_level(void)
  7770. {
  7771. G.var_nest_level++;
  7772. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7773. /* Try: f() { echo -n .; f; }; f
  7774. * struct variable::var_nest_level is uint16_t,
  7775. * thus limiting recursion to < 2^16.
  7776. * In any case, with 8 Mbyte stack SEGV happens
  7777. * not too long after 2^16 recursions anyway.
  7778. */
  7779. if (G.var_nest_level > 0xff00)
  7780. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7781. }
  7782. static void leave_var_nest_level(void)
  7783. {
  7784. G.var_nest_level--;
  7785. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7786. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7787. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7788. remove_nested_vars();
  7789. }
  7790. #if ENABLE_HUSH_FUNCTIONS
  7791. static struct function **find_function_slot(const char *name)
  7792. {
  7793. struct function *funcp;
  7794. struct function **funcpp = &G.top_func;
  7795. while ((funcp = *funcpp) != NULL) {
  7796. if (strcmp(name, funcp->name) == 0) {
  7797. debug_printf_exec("found function '%s'\n", name);
  7798. break;
  7799. }
  7800. funcpp = &funcp->next;
  7801. }
  7802. return funcpp;
  7803. }
  7804. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7805. {
  7806. const struct function *funcp = *find_function_slot(name);
  7807. return funcp;
  7808. }
  7809. /* Note: takes ownership on name ptr */
  7810. static struct function *new_function(char *name)
  7811. {
  7812. struct function **funcpp = find_function_slot(name);
  7813. struct function *funcp = *funcpp;
  7814. if (funcp != NULL) {
  7815. struct command *cmd = funcp->parent_cmd;
  7816. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7817. if (!cmd) {
  7818. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7819. free(funcp->name);
  7820. /* Note: if !funcp->body, do not free body_as_string!
  7821. * This is a special case of "-F name body" function:
  7822. * body_as_string was not malloced! */
  7823. if (funcp->body) {
  7824. free_pipe_list(funcp->body);
  7825. # if !BB_MMU
  7826. free(funcp->body_as_string);
  7827. # endif
  7828. }
  7829. } else {
  7830. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7831. cmd->argv[0] = funcp->name;
  7832. cmd->group = funcp->body;
  7833. # if !BB_MMU
  7834. cmd->group_as_string = funcp->body_as_string;
  7835. # endif
  7836. }
  7837. } else {
  7838. debug_printf_exec("remembering new function '%s'\n", name);
  7839. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7840. /*funcp->next = NULL;*/
  7841. }
  7842. funcp->name = name;
  7843. return funcp;
  7844. }
  7845. # if ENABLE_HUSH_UNSET
  7846. static void unset_func(const char *name)
  7847. {
  7848. struct function **funcpp = find_function_slot(name);
  7849. struct function *funcp = *funcpp;
  7850. if (funcp != NULL) {
  7851. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7852. *funcpp = funcp->next;
  7853. /* funcp is unlinked now, deleting it.
  7854. * Note: if !funcp->body, the function was created by
  7855. * "-F name body", do not free ->body_as_string
  7856. * and ->name as they were not malloced. */
  7857. if (funcp->body) {
  7858. free_pipe_list(funcp->body);
  7859. free(funcp->name);
  7860. # if !BB_MMU
  7861. free(funcp->body_as_string);
  7862. # endif
  7863. }
  7864. free(funcp);
  7865. }
  7866. }
  7867. # endif
  7868. # if BB_MMU
  7869. #define exec_function(to_free, funcp, argv) \
  7870. exec_function(funcp, argv)
  7871. # endif
  7872. static void exec_function(char ***to_free,
  7873. const struct function *funcp,
  7874. char **argv) NORETURN;
  7875. static void exec_function(char ***to_free,
  7876. const struct function *funcp,
  7877. char **argv)
  7878. {
  7879. # if BB_MMU
  7880. int n;
  7881. argv[0] = G.global_argv[0];
  7882. G.global_argv = argv;
  7883. G.global_argc = n = 1 + string_array_len(argv + 1);
  7884. // Example when we are here: "cmd | func"
  7885. // func will run with saved-redirect fds open.
  7886. // $ f() { echo /proc/self/fd/*; }
  7887. // $ true | f
  7888. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7889. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7890. // Same in script:
  7891. // $ . ./SCRIPT
  7892. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7893. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7894. // They are CLOEXEC so external programs won't see them, but
  7895. // for "more correctness" we might want to close those extra fds here:
  7896. //? close_saved_fds_and_FILE_fds();
  7897. /* "we are in a function, ok to use return" */
  7898. G_flag_return_in_progress = -1;
  7899. enter_var_nest_level();
  7900. IF_HUSH_LOCAL(G.func_nest_level++;)
  7901. /* On MMU, funcp->body is always non-NULL */
  7902. n = run_list(funcp->body);
  7903. _exit(n);
  7904. # else
  7905. //? close_saved_fds_and_FILE_fds();
  7906. //TODO: check whether "true | func_with_return" works
  7907. re_execute_shell(to_free,
  7908. funcp->body_as_string,
  7909. G.global_argv[0],
  7910. argv + 1,
  7911. NULL);
  7912. # endif
  7913. }
  7914. static int run_function(const struct function *funcp, char **argv)
  7915. {
  7916. int rc;
  7917. save_arg_t sv;
  7918. smallint sv_flg;
  7919. save_and_replace_G_args(&sv, argv);
  7920. /* "We are in function, ok to use return" */
  7921. sv_flg = G_flag_return_in_progress;
  7922. G_flag_return_in_progress = -1;
  7923. /* Make "local" variables properly shadow previous ones */
  7924. IF_HUSH_LOCAL(enter_var_nest_level();)
  7925. IF_HUSH_LOCAL(G.func_nest_level++;)
  7926. /* On MMU, funcp->body is always non-NULL */
  7927. # if !BB_MMU
  7928. if (!funcp->body) {
  7929. /* Function defined by -F */
  7930. parse_and_run_string(funcp->body_as_string);
  7931. rc = G.last_exitcode;
  7932. } else
  7933. # endif
  7934. {
  7935. rc = run_list(funcp->body);
  7936. }
  7937. IF_HUSH_LOCAL(G.func_nest_level--;)
  7938. IF_HUSH_LOCAL(leave_var_nest_level();)
  7939. G_flag_return_in_progress = sv_flg;
  7940. # if ENABLE_HUSH_TRAP
  7941. debug_printf_exec("G.return_exitcode=-1\n");
  7942. G.return_exitcode = -1; /* invalidate stashed return value */
  7943. # endif
  7944. restore_G_args(&sv, argv);
  7945. return rc;
  7946. }
  7947. #endif /* ENABLE_HUSH_FUNCTIONS */
  7948. #if BB_MMU
  7949. #define exec_builtin(to_free, x, argv) \
  7950. exec_builtin(x, argv)
  7951. #else
  7952. #define exec_builtin(to_free, x, argv) \
  7953. exec_builtin(to_free, argv)
  7954. #endif
  7955. static void exec_builtin(char ***to_free,
  7956. const struct built_in_command *x,
  7957. char **argv) NORETURN;
  7958. static void exec_builtin(char ***to_free,
  7959. const struct built_in_command *x,
  7960. char **argv)
  7961. {
  7962. #if BB_MMU
  7963. int rcode;
  7964. //? close_saved_fds_and_FILE_fds();
  7965. rcode = x->b_function(argv);
  7966. fflush_all();
  7967. _exit(rcode);
  7968. #else
  7969. fflush_all();
  7970. /* On NOMMU, we must never block!
  7971. * Example: { sleep 99 | read line; } & echo Ok
  7972. */
  7973. re_execute_shell(to_free,
  7974. argv[0],
  7975. G.global_argv[0],
  7976. G.global_argv + 1,
  7977. argv);
  7978. #endif
  7979. }
  7980. static void execvp_or_die(char **argv) NORETURN;
  7981. static void execvp_or_die(char **argv)
  7982. {
  7983. int e;
  7984. debug_printf_exec("execing '%s'\n", argv[0]);
  7985. /* Don't propagate SIG_IGN to the child */
  7986. if (SPECIAL_JOBSTOP_SIGS != 0)
  7987. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7988. execvp(argv[0], argv);
  7989. e = 2;
  7990. if (errno == EACCES) e = 126;
  7991. if (errno == ENOENT) e = 127;
  7992. bb_perror_msg("can't execute '%s'", argv[0]);
  7993. _exit(e);
  7994. }
  7995. #if ENABLE_HUSH_MODE_X
  7996. static void x_mode_print_optionally_squoted(const char *str)
  7997. {
  7998. unsigned len;
  7999. const char *cp;
  8000. cp = str;
  8001. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  8002. /* test a char with: bash -c 'set -x; echo "CH"' */
  8003. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  8004. " " "\001\002\003\004\005\006\007"
  8005. "\010\011\012\013\014\015\016\017"
  8006. "\020\021\022\023\024\025\026\027"
  8007. "\030\031\032\033\034\035\036\037"
  8008. )
  8009. ] == '\0'
  8010. ) {
  8011. /* string has no special chars */
  8012. x_mode_addstr(str);
  8013. return;
  8014. }
  8015. cp = str;
  8016. for (;;) {
  8017. /* print '....' up to EOL or first squote */
  8018. len = (int)(strchrnul(cp, '\'') - cp);
  8019. if (len != 0) {
  8020. x_mode_addchr('\'');
  8021. x_mode_addblock(cp, len);
  8022. x_mode_addchr('\'');
  8023. cp += len;
  8024. }
  8025. if (*cp == '\0')
  8026. break;
  8027. /* string contains squote(s), print them as \' */
  8028. x_mode_addchr('\\');
  8029. x_mode_addchr('\'');
  8030. cp++;
  8031. }
  8032. }
  8033. static void dump_cmd_in_x_mode(char **argv)
  8034. {
  8035. if (G_x_mode && argv) {
  8036. unsigned n;
  8037. /* "+[+++...][ cmd...]\n\0" */
  8038. x_mode_prefix();
  8039. n = 0;
  8040. while (argv[n]) {
  8041. x_mode_addchr(' ');
  8042. if (argv[n][0] == '\0') {
  8043. x_mode_addchr('\'');
  8044. x_mode_addchr('\'');
  8045. } else {
  8046. x_mode_print_optionally_squoted(argv[n]);
  8047. }
  8048. n++;
  8049. }
  8050. x_mode_flush();
  8051. }
  8052. }
  8053. #else
  8054. # define dump_cmd_in_x_mode(argv) ((void)0)
  8055. #endif
  8056. #if ENABLE_HUSH_COMMAND
  8057. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  8058. {
  8059. char *to_free;
  8060. if (!opt_vV)
  8061. return;
  8062. to_free = NULL;
  8063. if (!explanation) {
  8064. char *path = getenv("PATH");
  8065. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  8066. if (!explanation)
  8067. _exit(1); /* PROG was not found */
  8068. if (opt_vV != 'V')
  8069. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  8070. }
  8071. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  8072. free(to_free);
  8073. fflush_all();
  8074. _exit(0);
  8075. }
  8076. #else
  8077. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  8078. #endif
  8079. #if BB_MMU
  8080. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  8081. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  8082. #define pseudo_exec(nommu_save, command, argv_expanded) \
  8083. pseudo_exec(command, argv_expanded)
  8084. #endif
  8085. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  8086. * Never returns.
  8087. * Don't exit() here. If you don't exec, use _exit instead.
  8088. * The at_exit handlers apparently confuse the calling process,
  8089. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  8090. */
  8091. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  8092. char **argv, int assignment_cnt,
  8093. char **argv_expanded) NORETURN;
  8094. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  8095. char **argv, int assignment_cnt,
  8096. char **argv_expanded)
  8097. {
  8098. const struct built_in_command *x;
  8099. struct variable **sv_shadowed;
  8100. char **new_env;
  8101. IF_HUSH_COMMAND(char opt_vV = 0;)
  8102. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8103. new_env = expand_assignments(argv, assignment_cnt);
  8104. dump_cmd_in_x_mode(new_env);
  8105. if (!argv[assignment_cnt]) {
  8106. /* Case when we are here: ... | var=val | ...
  8107. * (note that we do not exit early, i.e., do not optimize out
  8108. * expand_assignments(): think about ... | var=`sleep 1` | ...
  8109. */
  8110. free_strings(new_env);
  8111. _exit_SUCCESS();
  8112. }
  8113. sv_shadowed = G.shadowed_vars_pp;
  8114. #if BB_MMU
  8115. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  8116. #else
  8117. G.shadowed_vars_pp = &nommu_save->old_vars;
  8118. G.var_nest_level++;
  8119. #endif
  8120. set_vars_and_save_old(new_env);
  8121. G.shadowed_vars_pp = sv_shadowed;
  8122. if (argv_expanded) {
  8123. argv = argv_expanded;
  8124. } else {
  8125. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  8126. #if !BB_MMU
  8127. nommu_save->argv = argv;
  8128. #endif
  8129. }
  8130. dump_cmd_in_x_mode(argv);
  8131. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8132. if (strchr(argv[0], '/') != NULL)
  8133. goto skip;
  8134. #endif
  8135. #if ENABLE_HUSH_FUNCTIONS
  8136. /* Check if the command matches any functions (this goes before bltins) */
  8137. funcp = find_function(argv[0]);
  8138. if (funcp)
  8139. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  8140. #endif
  8141. #if ENABLE_HUSH_COMMAND
  8142. /* "command BAR": run BAR without looking it up among functions
  8143. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  8144. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  8145. */
  8146. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  8147. char *p;
  8148. argv++;
  8149. p = *argv;
  8150. if (p[0] != '-' || !p[1])
  8151. continue; /* bash allows "command command command [-OPT] BAR" */
  8152. for (;;) {
  8153. p++;
  8154. switch (*p) {
  8155. case '\0':
  8156. argv++;
  8157. p = *argv;
  8158. if (p[0] != '-' || !p[1])
  8159. goto after_opts;
  8160. continue; /* next arg is also -opts, process it too */
  8161. case 'v':
  8162. case 'V':
  8163. opt_vV = *p;
  8164. continue;
  8165. default:
  8166. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  8167. }
  8168. }
  8169. }
  8170. after_opts:
  8171. # if ENABLE_HUSH_FUNCTIONS
  8172. if (opt_vV && find_function(argv[0]))
  8173. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  8174. # endif
  8175. #endif
  8176. /* Check if the command matches any of the builtins.
  8177. * Depending on context, this might be redundant. But it's
  8178. * easier to waste a few CPU cycles than it is to figure out
  8179. * if this is one of those cases.
  8180. */
  8181. /* Why "BB_MMU ? :" difference in logic? -
  8182. * On NOMMU, it is more expensive to re-execute shell
  8183. * just in order to run echo or test builtin.
  8184. * It's better to skip it here and run corresponding
  8185. * non-builtin later. */
  8186. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  8187. if (x) {
  8188. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  8189. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  8190. }
  8191. #if ENABLE_FEATURE_SH_STANDALONE
  8192. /* Check if the command matches any busybox applets */
  8193. {
  8194. int a = find_applet_by_name(argv[0]);
  8195. if (a >= 0) {
  8196. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  8197. # if BB_MMU /* see above why on NOMMU it is not allowed */
  8198. if (APPLET_IS_NOEXEC(a)) {
  8199. /* Do not leak open fds from opened script files etc.
  8200. * Testcase: interactive "ls -l /proc/self/fd"
  8201. * should not show tty fd open.
  8202. */
  8203. close_saved_fds_and_FILE_fds();
  8204. //FIXME: should also close saved redir fds
  8205. //This casuses test failures in
  8206. //redir_children_should_not_see_saved_fd_2.tests
  8207. //redir_children_should_not_see_saved_fd_3.tests
  8208. //if you replace "busybox find" with just "find" in them
  8209. /* Without this, "rm -i FILE" can't be ^C'ed: */
  8210. switch_off_special_sigs(G.special_sig_mask);
  8211. debug_printf_exec("running applet '%s'\n", argv[0]);
  8212. run_noexec_applet_and_exit(a, argv[0], argv);
  8213. }
  8214. # endif
  8215. /* Re-exec ourselves */
  8216. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  8217. /* Don't propagate SIG_IGN to the child */
  8218. if (SPECIAL_JOBSTOP_SIGS != 0)
  8219. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  8220. execv(bb_busybox_exec_path, argv);
  8221. /* If they called chroot or otherwise made the binary no longer
  8222. * executable, fall through */
  8223. }
  8224. }
  8225. #endif
  8226. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8227. skip:
  8228. #endif
  8229. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  8230. execvp_or_die(argv);
  8231. }
  8232. /* Called after [v]fork() in run_pipe
  8233. */
  8234. static void pseudo_exec(nommu_save_t *nommu_save,
  8235. struct command *command,
  8236. char **argv_expanded) NORETURN;
  8237. static void pseudo_exec(nommu_save_t *nommu_save,
  8238. struct command *command,
  8239. char **argv_expanded)
  8240. {
  8241. #if ENABLE_HUSH_FUNCTIONS
  8242. if (command->cmd_type == CMD_FUNCDEF) {
  8243. /* Ignore funcdefs in pipes:
  8244. * true | f() { cmd }
  8245. */
  8246. _exit(0);
  8247. }
  8248. #endif
  8249. if (command->argv) {
  8250. pseudo_exec_argv(nommu_save, command->argv,
  8251. command->assignment_cnt, argv_expanded);
  8252. }
  8253. if (command->group) {
  8254. /* Cases when we are here:
  8255. * ( list )
  8256. * { list } &
  8257. * ... | ( list ) | ...
  8258. * ... | { list } | ...
  8259. */
  8260. #if BB_MMU
  8261. int rcode;
  8262. debug_printf_exec("pseudo_exec: run_list\n");
  8263. reset_traps_to_defaults();
  8264. rcode = run_list(command->group);
  8265. /* OK to leak memory by not calling free_pipe_list,
  8266. * since this process is about to exit */
  8267. _exit(rcode);
  8268. #else
  8269. re_execute_shell(&nommu_save->argv_from_re_execing,
  8270. command->group_as_string,
  8271. G.global_argv[0],
  8272. G.global_argv + 1,
  8273. NULL);
  8274. #endif
  8275. }
  8276. /* Case when we are here: ... | >file */
  8277. debug_printf_exec("pseudo_exec'ed null command\n");
  8278. _exit_SUCCESS();
  8279. }
  8280. #if ENABLE_HUSH_JOB
  8281. static const char *get_cmdtext(struct pipe *pi)
  8282. {
  8283. char **argv;
  8284. char *p;
  8285. int len;
  8286. /* This is subtle. ->cmdtext is created only on first backgrounding.
  8287. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  8288. * On subsequent bg argv is trashed, but we won't use it */
  8289. if (pi->cmdtext)
  8290. return pi->cmdtext;
  8291. argv = pi->cmds[0].argv;
  8292. if (!argv) {
  8293. pi->cmdtext = xzalloc(1);
  8294. return pi->cmdtext;
  8295. }
  8296. len = 0;
  8297. do {
  8298. len += strlen(*argv) + 1;
  8299. } while (*++argv);
  8300. p = xmalloc(len);
  8301. pi->cmdtext = p;
  8302. argv = pi->cmds[0].argv;
  8303. do {
  8304. p = stpcpy(p, *argv);
  8305. *p++ = ' ';
  8306. } while (*++argv);
  8307. p[-1] = '\0';
  8308. return pi->cmdtext;
  8309. }
  8310. static void remove_job_from_table(struct pipe *pi)
  8311. {
  8312. struct pipe *prev_pipe;
  8313. if (pi == G.job_list) {
  8314. G.job_list = pi->next;
  8315. } else {
  8316. prev_pipe = G.job_list;
  8317. while (prev_pipe->next != pi)
  8318. prev_pipe = prev_pipe->next;
  8319. prev_pipe->next = pi->next;
  8320. }
  8321. G.last_jobid = 0;
  8322. if (G.job_list)
  8323. G.last_jobid = G.job_list->jobid;
  8324. }
  8325. static void delete_finished_job(struct pipe *pi)
  8326. {
  8327. remove_job_from_table(pi);
  8328. free_pipe(pi);
  8329. }
  8330. static void clean_up_last_dead_job(void)
  8331. {
  8332. if (G.job_list && !G.job_list->alive_cmds)
  8333. delete_finished_job(G.job_list);
  8334. }
  8335. static void insert_job_into_table(struct pipe *pi)
  8336. {
  8337. struct pipe *job, **jobp;
  8338. int i;
  8339. clean_up_last_dead_job();
  8340. /* Find the end of the list, and find next job ID to use */
  8341. i = 0;
  8342. jobp = &G.job_list;
  8343. while ((job = *jobp) != NULL) {
  8344. if (job->jobid > i)
  8345. i = job->jobid;
  8346. jobp = &job->next;
  8347. }
  8348. pi->jobid = i + 1;
  8349. /* Create a new job struct at the end */
  8350. job = *jobp = xmemdup(pi, sizeof(*pi));
  8351. job->next = NULL;
  8352. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  8353. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  8354. for (i = 0; i < pi->num_cmds; i++) {
  8355. job->cmds[i].pid = pi->cmds[i].pid;
  8356. /* all other fields are not used and stay zero */
  8357. }
  8358. job->cmdtext = xstrdup(get_cmdtext(pi));
  8359. if (G_interactive_fd)
  8360. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8361. G.last_jobid = job->jobid;
  8362. }
  8363. #endif /* JOB */
  8364. static int job_exited_or_stopped(struct pipe *pi)
  8365. {
  8366. int rcode, i;
  8367. if (pi->alive_cmds != pi->stopped_cmds)
  8368. return -1;
  8369. /* All processes in fg pipe have exited or stopped */
  8370. rcode = 0;
  8371. i = pi->num_cmds;
  8372. while (--i >= 0) {
  8373. rcode = pi->cmds[i].cmd_exitcode;
  8374. /* usually last process gives overall exitstatus,
  8375. * but with "set -o pipefail", last *failed* process does */
  8376. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8377. break;
  8378. }
  8379. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8380. return rcode;
  8381. }
  8382. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8383. {
  8384. #if ENABLE_HUSH_JOB
  8385. struct pipe *pi;
  8386. #endif
  8387. int i, dead;
  8388. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8389. #if DEBUG_JOBS
  8390. if (WIFSTOPPED(status))
  8391. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8392. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8393. if (WIFSIGNALED(status))
  8394. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8395. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8396. if (WIFEXITED(status))
  8397. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8398. childpid, WEXITSTATUS(status));
  8399. #endif
  8400. /* Were we asked to wait for a fg pipe? */
  8401. if (fg_pipe) {
  8402. i = fg_pipe->num_cmds;
  8403. while (--i >= 0) {
  8404. int rcode;
  8405. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8406. if (fg_pipe->cmds[i].pid != childpid)
  8407. continue;
  8408. if (dead) {
  8409. int ex;
  8410. fg_pipe->cmds[i].pid = 0;
  8411. fg_pipe->alive_cmds--;
  8412. ex = WEXITSTATUS(status);
  8413. /* bash prints killer signal's name for *last*
  8414. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8415. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8416. */
  8417. if (WIFSIGNALED(status)) {
  8418. int sig = WTERMSIG(status);
  8419. #if ENABLE_HUSH_JOB
  8420. if (G.run_list_level == 1
  8421. /* ^^^^^ Do not print in nested contexts, example:
  8422. * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
  8423. */
  8424. && i == fg_pipe->num_cmds-1
  8425. ) {
  8426. /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
  8427. puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
  8428. }
  8429. #endif
  8430. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8431. /* MIPS has 128 sigs (1..128), if sig==128,
  8432. * 128 + sig would result in exitcode 256 -> 0!
  8433. */
  8434. ex = 128 | sig;
  8435. }
  8436. fg_pipe->cmds[i].cmd_exitcode = ex;
  8437. } else {
  8438. fg_pipe->stopped_cmds++;
  8439. }
  8440. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8441. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8442. rcode = job_exited_or_stopped(fg_pipe);
  8443. if (rcode >= 0) {
  8444. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8445. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8446. * and "killall -STOP cat" */
  8447. if (G_interactive_fd) {
  8448. #if ENABLE_HUSH_JOB
  8449. if (fg_pipe->alive_cmds != 0)
  8450. insert_job_into_table(fg_pipe);
  8451. #endif
  8452. return rcode;
  8453. }
  8454. if (fg_pipe->alive_cmds == 0)
  8455. return rcode;
  8456. }
  8457. /* There are still running processes in the fg_pipe */
  8458. return -1;
  8459. }
  8460. /* It wasn't in fg_pipe, look for process in bg pipes */
  8461. }
  8462. #if ENABLE_HUSH_JOB
  8463. /* We were asked to wait for bg or orphaned children */
  8464. /* No need to remember exitcode in this case */
  8465. for (pi = G.job_list; pi; pi = pi->next) {
  8466. for (i = 0; i < pi->num_cmds; i++) {
  8467. if (pi->cmds[i].pid == childpid)
  8468. goto found_pi_and_prognum;
  8469. }
  8470. }
  8471. /* Happens when shell is used as init process (init=/bin/sh) */
  8472. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8473. return -1; /* this wasn't a process from fg_pipe */
  8474. found_pi_and_prognum:
  8475. if (dead) {
  8476. /* child exited */
  8477. int rcode = WEXITSTATUS(status);
  8478. if (WIFSIGNALED(status))
  8479. /* NB: not 128 + sig, MIPS has sig 128 */
  8480. rcode = 128 | WTERMSIG(status);
  8481. pi->cmds[i].cmd_exitcode = rcode;
  8482. if (G.last_bg_pid == pi->cmds[i].pid)
  8483. G.last_bg_pid_exitcode = rcode;
  8484. pi->cmds[i].pid = 0;
  8485. pi->alive_cmds--;
  8486. if (!pi->alive_cmds) {
  8487. # if ENABLE_HUSH_BASH_COMPAT
  8488. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8489. # endif
  8490. if (G_interactive_fd) {
  8491. printf(JOB_STATUS_FORMAT, pi->jobid,
  8492. "Done", pi->cmdtext);
  8493. delete_finished_job(pi);
  8494. } else {
  8495. /*
  8496. * bash deletes finished jobs from job table only in interactive mode,
  8497. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8498. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8499. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8500. * We only retain one "dead" job, if it's the single job on the list.
  8501. * This covers most of real-world scenarios where this is useful.
  8502. */
  8503. if (pi != G.job_list)
  8504. delete_finished_job(pi);
  8505. }
  8506. }
  8507. } else {
  8508. /* child stopped */
  8509. pi->stopped_cmds++;
  8510. }
  8511. #endif
  8512. return -1; /* this wasn't a process from fg_pipe */
  8513. }
  8514. /* Check to see if any processes have exited -- if they have,
  8515. * figure out why and see if a job has completed.
  8516. *
  8517. * If non-NULL fg_pipe: wait for its completion or stop.
  8518. * Return its exitcode or zero if stopped.
  8519. *
  8520. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8521. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8522. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8523. * or 0 if no children changed status.
  8524. *
  8525. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8526. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8527. * or 0 if no children changed status.
  8528. */
  8529. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8530. {
  8531. int attributes;
  8532. int status;
  8533. int rcode = 0;
  8534. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8535. attributes = WUNTRACED;
  8536. if (fg_pipe == NULL)
  8537. attributes |= WNOHANG;
  8538. errno = 0;
  8539. #if ENABLE_HUSH_FAST
  8540. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8541. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8542. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8543. /* There was neither fork nor SIGCHLD since last waitpid */
  8544. /* Avoid doing waitpid syscall if possible */
  8545. if (!G.we_have_children) {
  8546. errno = ECHILD;
  8547. return -1;
  8548. }
  8549. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8550. /* We have children, but they did not exit
  8551. * or stop yet (we saw no SIGCHLD) */
  8552. return 0;
  8553. }
  8554. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8555. }
  8556. #endif
  8557. /* Do we do this right?
  8558. * bash-3.00# sleep 20 | false
  8559. * <ctrl-Z pressed>
  8560. * [3]+ Stopped sleep 20 | false
  8561. * bash-3.00# echo $?
  8562. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8563. * [hush 1.14.0: yes we do it right]
  8564. */
  8565. while (1) {
  8566. pid_t childpid;
  8567. #if ENABLE_HUSH_FAST
  8568. int i;
  8569. i = G.count_SIGCHLD;
  8570. #endif
  8571. childpid = waitpid(-1, &status, attributes);
  8572. if (childpid <= 0) {
  8573. if (childpid && errno != ECHILD)
  8574. bb_simple_perror_msg("waitpid");
  8575. #if ENABLE_HUSH_FAST
  8576. else { /* Until next SIGCHLD, waitpid's are useless */
  8577. G.we_have_children = (childpid == 0);
  8578. G.handled_SIGCHLD = i;
  8579. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8580. }
  8581. #endif
  8582. /* ECHILD (no children), or 0 (no change in children status) */
  8583. rcode = childpid;
  8584. break;
  8585. }
  8586. rcode = process_wait_result(fg_pipe, childpid, status);
  8587. if (rcode >= 0) {
  8588. /* fg_pipe exited or stopped */
  8589. break;
  8590. }
  8591. if (childpid == waitfor_pid) { /* "wait PID" */
  8592. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8593. rcode = WEXITSTATUS(status);
  8594. if (WIFSIGNALED(status))
  8595. rcode = 128 | WTERMSIG(status);
  8596. if (WIFSTOPPED(status))
  8597. /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
  8598. rcode = 128 | WSTOPSIG(status);
  8599. rcode++;
  8600. break; /* "wait PID" called us, give it exitcode+1 */
  8601. }
  8602. #if ENABLE_HUSH_BASH_COMPAT
  8603. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8604. && G.dead_job_exitcode >= 0 /* some job did finish */
  8605. ) {
  8606. debug_printf_exec("waitfor_pid:-1\n");
  8607. rcode = G.dead_job_exitcode + 1;
  8608. break;
  8609. }
  8610. #endif
  8611. /* This wasn't one of our processes, or */
  8612. /* fg_pipe still has running processes, do waitpid again */
  8613. } /* while (waitpid succeeds)... */
  8614. return rcode;
  8615. }
  8616. #if ENABLE_HUSH_JOB
  8617. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8618. {
  8619. pid_t p;
  8620. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8621. if (G_saved_tty_pgrp) {
  8622. /* Job finished, move the shell to the foreground */
  8623. p = getpgrp(); /* our process group id */
  8624. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8625. tcsetpgrp(G_interactive_fd, p);
  8626. }
  8627. return rcode;
  8628. }
  8629. #endif
  8630. /* Start all the jobs, but don't wait for anything to finish.
  8631. * See checkjobs().
  8632. *
  8633. * Return code is normally -1, when the caller has to wait for children
  8634. * to finish to determine the exit status of the pipe. If the pipe
  8635. * is a simple builtin command, however, the action is done by the
  8636. * time run_pipe returns, and the exit code is provided as the
  8637. * return value.
  8638. *
  8639. * Returns -1 only if started some children. IOW: we have to
  8640. * mask out retvals of builtins etc with 0xff!
  8641. *
  8642. * The only case when we do not need to [v]fork is when the pipe
  8643. * is single, non-backgrounded, non-subshell command. Examples:
  8644. * cmd ; ... { list } ; ...
  8645. * cmd && ... { list } && ...
  8646. * cmd || ... { list } || ...
  8647. * If it is, then we can run cmd as a builtin, NOFORK,
  8648. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8649. * with run_list. If it isn't one of these, we fork and exec cmd.
  8650. *
  8651. * Cases when we must fork:
  8652. * non-single: cmd | cmd
  8653. * backgrounded: cmd & { list } &
  8654. * subshell: ( list ) [&]
  8655. */
  8656. static void set_G_ifs(void)
  8657. {
  8658. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8659. * Result should be 3 lines: q w e, qwe, q w e
  8660. */
  8661. if (G.ifs_whitespace != G.ifs)
  8662. free(G.ifs_whitespace);
  8663. G.ifs = get_local_var_value("IFS");
  8664. if (G.ifs) {
  8665. char *p;
  8666. G.ifs_whitespace = (char*)G.ifs;
  8667. p = skip_whitespace(G.ifs);
  8668. if (*p) {
  8669. /* Not all $IFS is whitespace */
  8670. char *d;
  8671. int len = p - G.ifs;
  8672. p = skip_non_whitespace(p);
  8673. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8674. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8675. while (*p) {
  8676. if (isspace(*p))
  8677. *d++ = *p;
  8678. p++;
  8679. }
  8680. *d = '\0';
  8681. }
  8682. } else {
  8683. G.ifs = defifs;
  8684. G.ifs_whitespace = (char*)G.ifs;
  8685. }
  8686. }
  8687. #if !ENABLE_HUSH_MODE_X
  8688. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8689. redirect_and_varexp_helper(command, sqp)
  8690. #endif
  8691. static int redirect_and_varexp_helper(
  8692. struct command *command,
  8693. struct squirrel **sqp,
  8694. char **argv_expanded)
  8695. {
  8696. /* Assignments occur before redirects. Try:
  8697. * a=`sleep 1` sleep 2 3>/qwe/rty
  8698. */
  8699. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8700. dump_cmd_in_x_mode(new_env);
  8701. dump_cmd_in_x_mode(argv_expanded);
  8702. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8703. set_vars_and_save_old(new_env);
  8704. return setup_redirects(command, sqp);
  8705. }
  8706. static NOINLINE int run_pipe(struct pipe *pi)
  8707. {
  8708. static const char *const null_ptr = NULL;
  8709. int cmd_no;
  8710. int next_infd;
  8711. struct command *command;
  8712. char **argv_expanded;
  8713. char **argv;
  8714. struct squirrel *squirrel = NULL;
  8715. int rcode;
  8716. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8717. debug_enter();
  8718. set_G_ifs();
  8719. IF_HUSH_JOB(pi->pgrp = -1;)
  8720. pi->stopped_cmds = 0;
  8721. command = &pi->cmds[0];
  8722. argv_expanded = NULL;
  8723. if (pi->num_cmds != 1
  8724. || pi->followup == PIPE_BG
  8725. || command->cmd_type == CMD_SUBSHELL
  8726. ) {
  8727. goto must_fork;
  8728. }
  8729. pi->alive_cmds = 1;
  8730. debug_printf_exec(": group:%p argv:'%s'\n",
  8731. command->group, command->argv ? command->argv[0] : "NONE");
  8732. if (command->group) {
  8733. #if ENABLE_HUSH_FUNCTIONS
  8734. if (command->cmd_type == CMD_FUNCDEF) {
  8735. /* "executing" func () { list } */
  8736. struct function *funcp;
  8737. funcp = new_function(command->argv[0]);
  8738. /* funcp->name is already set to argv[0] */
  8739. funcp->body = command->group;
  8740. # if !BB_MMU
  8741. funcp->body_as_string = command->group_as_string;
  8742. command->group_as_string = NULL;
  8743. # endif
  8744. command->group = NULL;
  8745. command->argv[0] = NULL;
  8746. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8747. funcp->parent_cmd = command;
  8748. command->child_func = funcp;
  8749. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8750. debug_leave();
  8751. return EXIT_SUCCESS;
  8752. }
  8753. #endif
  8754. /* { list } */
  8755. debug_printf_exec("non-subshell group\n");
  8756. rcode = 1; /* exitcode if redir failed */
  8757. if (setup_redirects(command, &squirrel) == 0) {
  8758. debug_printf_exec(": run_list\n");
  8759. //FIXME: we need to pass squirrel down into run_list()
  8760. //for SH_STANDALONE case, or else this construct:
  8761. // { find /proc/self/fd; true; } >FILE; cmd2
  8762. //has no way of closing saved fd#1 for "find",
  8763. //and in SH_STANDALONE mode, "find" is not execed,
  8764. //therefore CLOEXEC on saved fd does not help.
  8765. rcode = run_list(command->group) & 0xff;
  8766. }
  8767. restore_redirects(squirrel);
  8768. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8769. debug_leave();
  8770. debug_printf_exec("run_pipe: return %d\n", rcode);
  8771. return rcode;
  8772. }
  8773. argv = command->argv ? command->argv : (char **) &null_ptr;
  8774. {
  8775. const struct built_in_command *x;
  8776. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8777. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8778. struct variable **sv_shadowed;
  8779. struct variable *old_vars;
  8780. #if ENABLE_HUSH_LINENO_VAR
  8781. G.execute_lineno = command->lineno;
  8782. #endif
  8783. if (argv[command->assignment_cnt] == NULL) {
  8784. /* Assignments, but no command.
  8785. * Ensure redirects take effect (that is, create files).
  8786. * Try "a=t >file"
  8787. */
  8788. unsigned i;
  8789. G.expand_exitcode = 0;
  8790. only_assignments:
  8791. rcode = setup_redirects(command, &squirrel);
  8792. restore_redirects(squirrel);
  8793. /* Set shell variables */
  8794. i = 0;
  8795. while (i < command->assignment_cnt) {
  8796. char *p = expand_string_to_string(argv[i],
  8797. EXP_FLAG_ESC_GLOB_CHARS,
  8798. /*unbackslash:*/ 1
  8799. );
  8800. #if ENABLE_HUSH_MODE_X
  8801. if (G_x_mode) {
  8802. char *eq;
  8803. if (i == 0)
  8804. x_mode_prefix();
  8805. x_mode_addchr(' ');
  8806. eq = strchrnul(p, '=');
  8807. if (*eq) eq++;
  8808. x_mode_addblock(p, (eq - p));
  8809. x_mode_print_optionally_squoted(eq);
  8810. x_mode_flush();
  8811. }
  8812. #endif
  8813. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8814. if (set_local_var0(p)) {
  8815. /* assignment to readonly var / putenv error? */
  8816. rcode = 1;
  8817. }
  8818. i++;
  8819. }
  8820. /* Redirect error sets $? to 1. Otherwise,
  8821. * if evaluating assignment value set $?, retain it.
  8822. * Else, clear $?:
  8823. * false; q=`exit 2`; echo $? - should print 2
  8824. * false; x=1; echo $? - should print 0
  8825. * Because of the 2nd case, we can't just use G.last_exitcode.
  8826. */
  8827. if (rcode == 0)
  8828. rcode = G.expand_exitcode;
  8829. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8830. debug_leave();
  8831. debug_printf_exec("run_pipe: return %d\n", rcode);
  8832. return rcode;
  8833. }
  8834. /* Expand the rest into (possibly) many strings each */
  8835. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  8836. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
  8837. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8838. else
  8839. #endif
  8840. #if defined(CMD_SINGLEWORD_NOGLOB)
  8841. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8842. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8843. else
  8844. #endif
  8845. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8846. /* If someone gives us an empty string: `cmd with empty output` */
  8847. if (!argv_expanded[0]) {
  8848. free(argv_expanded);
  8849. /* `false` still has to set exitcode 1 */
  8850. G.expand_exitcode = G.last_exitcode;
  8851. goto only_assignments;
  8852. }
  8853. old_vars = NULL;
  8854. sv_shadowed = G.shadowed_vars_pp;
  8855. /* Check if argv[0] matches any functions (this goes before bltins) */
  8856. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8857. IF_HUSH_FUNCTIONS(x = NULL;)
  8858. IF_HUSH_FUNCTIONS(if (!funcp))
  8859. x = find_builtin(argv_expanded[0]);
  8860. if (x || funcp) {
  8861. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8862. debug_printf("exec with redirects only\n");
  8863. /*
  8864. * Variable assignments are executed, but then "forgotten":
  8865. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8866. * sleeps, but prints nothing.
  8867. */
  8868. enter_var_nest_level();
  8869. G.shadowed_vars_pp = &old_vars;
  8870. rcode = redirect_and_varexp_helper(command,
  8871. /*squirrel:*/ ERR_PTR,
  8872. argv_expanded
  8873. );
  8874. G.shadowed_vars_pp = sv_shadowed;
  8875. /* rcode=1 can be if redir file can't be opened */
  8876. goto clean_up_and_ret1;
  8877. }
  8878. /* Bump var nesting, or this will leak exported $a:
  8879. * a=b true; env | grep ^a=
  8880. */
  8881. enter_var_nest_level();
  8882. /* Collect all variables "shadowed" by helper
  8883. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8884. * into old_vars list:
  8885. */
  8886. G.shadowed_vars_pp = &old_vars;
  8887. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8888. if (rcode == 0) {
  8889. if (!funcp) {
  8890. /* Do not collect *to old_vars list* vars shadowed
  8891. * by e.g. "local VAR" builtin (collect them
  8892. * in the previously nested list instead):
  8893. * don't want them to be restored immediately
  8894. * after "local" completes.
  8895. */
  8896. G.shadowed_vars_pp = sv_shadowed;
  8897. debug_printf_exec(": builtin '%s' '%s'...\n",
  8898. x->b_cmd, argv_expanded[1]);
  8899. fflush_all();
  8900. rcode = x->b_function(argv_expanded) & 0xff;
  8901. fflush_all();
  8902. }
  8903. #if ENABLE_HUSH_FUNCTIONS
  8904. else {
  8905. debug_printf_exec(": function '%s' '%s'...\n",
  8906. funcp->name, argv_expanded[1]);
  8907. rcode = run_function(funcp, argv_expanded) & 0xff;
  8908. /*
  8909. * But do collect *to old_vars list* vars shadowed
  8910. * within function execution. To that end, restore
  8911. * this pointer _after_ function run:
  8912. */
  8913. G.shadowed_vars_pp = sv_shadowed;
  8914. }
  8915. #endif
  8916. }
  8917. } else
  8918. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8919. int n = find_applet_by_name(argv_expanded[0]);
  8920. if (n < 0 || !APPLET_IS_NOFORK(n))
  8921. goto must_fork;
  8922. enter_var_nest_level();
  8923. /* Collect all variables "shadowed" by helper into old_vars list */
  8924. G.shadowed_vars_pp = &old_vars;
  8925. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8926. G.shadowed_vars_pp = sv_shadowed;
  8927. if (rcode == 0) {
  8928. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8929. argv_expanded[0], argv_expanded[1]);
  8930. /*
  8931. * Note: signals (^C) can't interrupt here.
  8932. * We remember them and they will be acted upon
  8933. * after applet returns.
  8934. * This makes applets which can run for a long time
  8935. * and/or wait for user input ineligible for NOFORK:
  8936. * for example, "yes" or "rm" (rm -i waits for input).
  8937. */
  8938. rcode = run_nofork_applet(n, argv_expanded);
  8939. }
  8940. } else
  8941. goto must_fork;
  8942. restore_redirects(squirrel);
  8943. clean_up_and_ret1:
  8944. leave_var_nest_level();
  8945. add_vars(old_vars);
  8946. /*
  8947. * Try "usleep 99999999" + ^C + "echo $?"
  8948. * with FEATURE_SH_NOFORK=y.
  8949. */
  8950. if (!funcp) {
  8951. /* It was builtin or nofork.
  8952. * if this would be a real fork/execed program,
  8953. * it should have died if a fatal sig was received.
  8954. * But OTOH, there was no separate process,
  8955. * the sig was sent to _shell_, not to non-existing
  8956. * child.
  8957. * Let's just handle ^C only, this one is obvious:
  8958. * we aren't ok with exitcode 0 when ^C was pressed
  8959. * during builtin/nofork.
  8960. */
  8961. if (sigismember(&G.pending_set, SIGINT))
  8962. rcode = 128 | SIGINT;
  8963. }
  8964. free(argv_expanded);
  8965. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8966. debug_leave();
  8967. debug_printf_exec("run_pipe return %d\n", rcode);
  8968. return rcode;
  8969. }
  8970. must_fork:
  8971. /* NB: argv_expanded may already be created, and that
  8972. * might include `cmd` runs! Do not rerun it! We *must*
  8973. * use argv_expanded if it's non-NULL */
  8974. /* Going to fork a child per each pipe member */
  8975. pi->alive_cmds = 0;
  8976. next_infd = 0;
  8977. cmd_no = 0;
  8978. while (cmd_no < pi->num_cmds) {
  8979. struct fd_pair pipefds;
  8980. #if !BB_MMU
  8981. int sv_var_nest_level = G.var_nest_level;
  8982. volatile nommu_save_t nommu_save;
  8983. nommu_save.old_vars = NULL;
  8984. nommu_save.argv = NULL;
  8985. nommu_save.argv_from_re_execing = NULL;
  8986. #endif
  8987. command = &pi->cmds[cmd_no];
  8988. cmd_no++;
  8989. if (command->argv) {
  8990. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8991. command->argv[0], command->argv[1]);
  8992. } else {
  8993. debug_printf_exec(": pipe member with no argv\n");
  8994. }
  8995. /* pipes are inserted between pairs of commands */
  8996. pipefds.rd = 0;
  8997. pipefds.wr = 1;
  8998. if (cmd_no < pi->num_cmds)
  8999. xpiped_pair(pipefds);
  9000. #if ENABLE_HUSH_LINENO_VAR
  9001. G.execute_lineno = command->lineno;
  9002. #endif
  9003. command->pid = BB_MMU ? fork() : vfork();
  9004. if (!command->pid) { /* child */
  9005. #if ENABLE_HUSH_JOB
  9006. disable_restore_tty_pgrp_on_exit();
  9007. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  9008. /* Every child adds itself to new process group
  9009. * with pgid == pid_of_first_child_in_pipe */
  9010. if (G.run_list_level == 1 && G_interactive_fd) {
  9011. pid_t pgrp;
  9012. pgrp = pi->pgrp;
  9013. if (pgrp < 0) /* true for 1st process only */
  9014. pgrp = getpid();
  9015. if (setpgid(0, pgrp) == 0
  9016. && pi->followup != PIPE_BG
  9017. && G_saved_tty_pgrp /* we have ctty */
  9018. ) {
  9019. /* We do it in *every* child, not just first,
  9020. * to avoid races */
  9021. tcsetpgrp(G_interactive_fd, pgrp);
  9022. }
  9023. }
  9024. #endif
  9025. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  9026. /* 1st cmd in backgrounded pipe
  9027. * should have its stdin /dev/null'ed */
  9028. close(0);
  9029. if (open(bb_dev_null, O_RDONLY))
  9030. xopen("/", O_RDONLY);
  9031. } else {
  9032. xmove_fd(next_infd, 0);
  9033. }
  9034. xmove_fd(pipefds.wr, 1);
  9035. if (pipefds.rd > 1)
  9036. close(pipefds.rd);
  9037. /* Like bash, explicit redirects override pipes,
  9038. * and the pipe fd (fd#1) is available for dup'ing:
  9039. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  9040. * of cmd1 goes into pipe.
  9041. */
  9042. if (setup_redirects(command, NULL)) {
  9043. /* Happens when redir file can't be opened:
  9044. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  9045. * FOO
  9046. * hush: can't open '/qwe/rty': No such file or directory
  9047. * BAZ
  9048. * (echo BAR is not executed, it hits _exit(1) below)
  9049. */
  9050. _exit(1);
  9051. }
  9052. /* Stores to nommu_save list of env vars putenv'ed
  9053. * (NOMMU, on MMU we don't need that) */
  9054. /* cast away volatility... */
  9055. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  9056. /* pseudo_exec() does not return */
  9057. }
  9058. /* parent or error */
  9059. #if ENABLE_HUSH_FAST
  9060. G.count_SIGCHLD++;
  9061. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  9062. #endif
  9063. enable_restore_tty_pgrp_on_exit();
  9064. #if !BB_MMU
  9065. /* Clean up after vforked child */
  9066. free(nommu_save.argv);
  9067. free(nommu_save.argv_from_re_execing);
  9068. G.var_nest_level = sv_var_nest_level;
  9069. remove_nested_vars();
  9070. add_vars(nommu_save.old_vars);
  9071. #endif
  9072. free(argv_expanded);
  9073. argv_expanded = NULL;
  9074. if (command->pid < 0) { /* [v]fork failed */
  9075. /* Clearly indicate, was it fork or vfork */
  9076. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  9077. } else {
  9078. pi->alive_cmds++;
  9079. #if ENABLE_HUSH_JOB
  9080. /* Second and next children need to know pid of first one */
  9081. if (pi->pgrp < 0)
  9082. pi->pgrp = command->pid;
  9083. #endif
  9084. }
  9085. if (cmd_no > 1)
  9086. close(next_infd);
  9087. if (cmd_no < pi->num_cmds)
  9088. close(pipefds.wr);
  9089. /* Pass read (output) pipe end to next iteration */
  9090. next_infd = pipefds.rd;
  9091. }
  9092. if (!pi->alive_cmds) {
  9093. debug_leave();
  9094. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  9095. return 1;
  9096. }
  9097. debug_leave();
  9098. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  9099. return -1;
  9100. }
  9101. /* NB: called by pseudo_exec, and therefore must not modify any
  9102. * global data until exec/_exit (we can be a child after vfork!) */
  9103. static int run_list(struct pipe *pi)
  9104. {
  9105. #if ENABLE_HUSH_CASE
  9106. char *case_word = NULL;
  9107. #endif
  9108. #if ENABLE_HUSH_LOOPS
  9109. struct pipe *loop_top = NULL;
  9110. char **for_lcur = NULL;
  9111. char **for_list = NULL;
  9112. #endif
  9113. smallint last_followup;
  9114. smalluint rcode;
  9115. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  9116. smalluint cond_code = 0;
  9117. #else
  9118. enum { cond_code = 0 };
  9119. #endif
  9120. #if HAS_KEYWORDS
  9121. smallint rword; /* RES_foo */
  9122. smallint last_rword; /* ditto */
  9123. #endif
  9124. debug_printf_exec("run_list lvl %d start\n", G.run_list_level);
  9125. debug_enter();
  9126. set_G_ifs();
  9127. #if ENABLE_HUSH_LOOPS
  9128. /* Check syntax for "for" */
  9129. {
  9130. struct pipe *cpipe;
  9131. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  9132. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  9133. continue;
  9134. /* current word is FOR or IN (BOLD in comments below) */
  9135. if (cpipe->next == NULL) {
  9136. syntax_error("malformed for");
  9137. debug_leave();
  9138. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9139. return 1;
  9140. }
  9141. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  9142. if (cpipe->next->res_word == RES_DO)
  9143. continue;
  9144. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  9145. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  9146. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  9147. ) {
  9148. syntax_error("malformed for");
  9149. debug_leave();
  9150. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9151. return 1;
  9152. }
  9153. }
  9154. }
  9155. #endif
  9156. /* Past this point, all code paths should jump to ret: label
  9157. * in order to return, no direct "return" statements please.
  9158. * This helps to ensure that no memory is leaked. */
  9159. #if ENABLE_HUSH_JOB
  9160. G.run_list_level++;
  9161. #endif
  9162. #if HAS_KEYWORDS
  9163. rword = RES_NONE;
  9164. last_rword = RES_XXXX;
  9165. #endif
  9166. last_followup = PIPE_SEQ;
  9167. rcode = G.last_exitcode;
  9168. /* Go through list of pipes, (maybe) executing them. */
  9169. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  9170. int r;
  9171. int sv_errexit_depth;
  9172. if (G.flag_SIGINT)
  9173. break;
  9174. if (G_flag_return_in_progress == 1)
  9175. break;
  9176. IF_HAS_KEYWORDS(rword = pi->res_word;)
  9177. debug_printf_exec(": rword:%d cond_code:%d last_rword:%d\n",
  9178. rword, cond_code, last_rword);
  9179. sv_errexit_depth = G.errexit_depth;
  9180. if (
  9181. #if ENABLE_HUSH_IF
  9182. rword == RES_IF || rword == RES_ELIF ||
  9183. #endif
  9184. pi->followup != PIPE_SEQ
  9185. ) {
  9186. G.errexit_depth++;
  9187. }
  9188. #if ENABLE_HUSH_LOOPS
  9189. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  9190. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  9191. ) {
  9192. /* start of a loop: remember where loop starts */
  9193. loop_top = pi;
  9194. G.depth_of_loop++;
  9195. }
  9196. #endif
  9197. /* Still in the same "if...", "then..." or "do..." branch? */
  9198. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  9199. if ((rcode == 0 && last_followup == PIPE_OR)
  9200. || (rcode != 0 && last_followup == PIPE_AND)
  9201. ) {
  9202. /* It is "<true> || CMD" or "<false> && CMD"
  9203. * and we should not execute CMD */
  9204. debug_printf_exec("skipped cmd because of || or &&\n");
  9205. last_followup = pi->followup;
  9206. goto dont_check_jobs_but_continue;
  9207. }
  9208. }
  9209. last_followup = pi->followup;
  9210. #if ENABLE_HUSH_IF
  9211. if (cond_code != 0) {
  9212. if (rword == RES_THEN) {
  9213. /* if false; then ... fi has exitcode 0! */
  9214. G.last_exitcode = rcode = EXIT_SUCCESS;
  9215. /* "if <false> THEN cmd": skip cmd */
  9216. debug_printf_exec("skipped THEN cmd because IF condition was false\n");
  9217. last_rword = rword;
  9218. continue;
  9219. }
  9220. } else {
  9221. if (rword == RES_ELSE
  9222. || (rword == RES_ELIF && last_rword != RES_ELIF)
  9223. ) {
  9224. /* "if <true> then ... ELSE/ELIF cmd":
  9225. * skip cmd and all following ones */
  9226. debug_printf_exec("skipped ELSE/ELIF branch because IF condition was true\n");
  9227. break;
  9228. }
  9229. //if (rword == RES_THEN): "if <true> THEN cmd", run cmd (fall through)
  9230. }
  9231. #endif
  9232. IF_HAS_KEYWORDS(last_rword = rword;)
  9233. #if ENABLE_HUSH_LOOPS
  9234. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  9235. if (!for_lcur) {
  9236. /* first loop through for */
  9237. static const char encoded_dollar_at[] ALIGN1 = {
  9238. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  9239. }; /* encoded representation of "$@" */
  9240. static const char *const encoded_dollar_at_argv[] ALIGN_PTR = {
  9241. encoded_dollar_at, NULL
  9242. }; /* argv list with one element: "$@" */
  9243. char **vals;
  9244. G.last_exitcode = rcode = EXIT_SUCCESS;
  9245. vals = (char**)encoded_dollar_at_argv;
  9246. if (pi->next->res_word == RES_IN) {
  9247. /* if no variable values after "in" we skip "for" */
  9248. if (!pi->next->cmds[0].argv) {
  9249. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  9250. break;
  9251. }
  9252. vals = pi->next->cmds[0].argv;
  9253. } /* else: "for var; do..." -> assume "$@" list */
  9254. /* create list of variable values */
  9255. debug_print_strings("for_list made from", vals);
  9256. for_list = expand_strvec_to_strvec(vals);
  9257. for_lcur = for_list;
  9258. debug_print_strings("for_list", for_list);
  9259. }
  9260. if (!*for_lcur) {
  9261. /* "for" loop is over, clean up */
  9262. free(for_list);
  9263. for_list = NULL;
  9264. for_lcur = NULL;
  9265. break;
  9266. }
  9267. /* Insert next value from for_lcur */
  9268. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  9269. set_local_var_from_halves(pi->cmds[0].argv[0], *for_lcur++);
  9270. continue;
  9271. }
  9272. if (rword == RES_IN) {
  9273. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  9274. }
  9275. if (rword == RES_DONE) {
  9276. continue; /* "done" has no cmds too */
  9277. }
  9278. #endif
  9279. #if ENABLE_HUSH_CASE
  9280. if (rword == RES_CASE) {
  9281. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  9282. case_word = expand_string_to_string(pi->cmds->argv[0],
  9283. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  9284. debug_printf_exec("CASE word1:'%s'\n", case_word);
  9285. //unbackslash(case_word);
  9286. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  9287. continue;
  9288. }
  9289. if (rword == RES_MATCH) {
  9290. char **argv;
  9291. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  9292. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  9293. break;
  9294. /* all prev words didn't match, does this one match? */
  9295. argv = pi->cmds->argv;
  9296. while (*argv) {
  9297. char *pattern;
  9298. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  9299. pattern = expand_string_to_string(*argv,
  9300. EXP_FLAG_ESC_GLOB_CHARS,
  9301. /*unbackslash:*/ 0
  9302. );
  9303. /* TODO: which FNM_xxx flags to use? */
  9304. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  9305. debug_printf_exec("cond_code=fnmatch(pattern:'%s',str:'%s'):%d\n",
  9306. pattern, case_word, cond_code);
  9307. free(pattern);
  9308. if (cond_code == 0) {
  9309. /* match! we will execute this branch */
  9310. free(case_word);
  9311. case_word = NULL; /* make future "word)" stop */
  9312. break;
  9313. }
  9314. argv++;
  9315. }
  9316. continue;
  9317. }
  9318. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  9319. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  9320. if (cond_code != 0)
  9321. continue; /* not matched yet, skip this pipe */
  9322. }
  9323. if (rword == RES_ESAC) {
  9324. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  9325. if (case_word) {
  9326. /* "case" did not match anything: still set $? (to 0) */
  9327. G.last_exitcode = rcode = EXIT_SUCCESS;
  9328. }
  9329. }
  9330. #endif
  9331. /* Just pressing <enter> in shell should check for jobs.
  9332. * OTOH, in non-interactive shell this is useless
  9333. * and only leads to extra job checks */
  9334. if (pi->num_cmds == 0) {
  9335. if (G_interactive_fd)
  9336. goto check_jobs_and_continue;
  9337. continue;
  9338. }
  9339. /* After analyzing all keywords and conditions, we decided
  9340. * to execute this pipe. NB: have to do checkjobs(NULL)
  9341. * after run_pipe to collect any background children,
  9342. * even if list execution is to be stopped. */
  9343. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  9344. #if ENABLE_HUSH_LOOPS
  9345. G.flag_break_continue = 0;
  9346. #endif
  9347. rcode = r = G.o_opt[OPT_O_NOEXEC] ? 0 : run_pipe(pi);
  9348. /* NB: rcode is a smalluint, r is int */
  9349. if (r != -1) {
  9350. /* We ran a builtin, function, or group.
  9351. * rcode is already known
  9352. * and we don't need to wait for anything. */
  9353. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  9354. G.last_exitcode = rcode;
  9355. check_and_run_traps();
  9356. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9357. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9358. #endif
  9359. #if ENABLE_HUSH_LOOPS
  9360. /* Was it "break" or "continue"? */
  9361. if (G.flag_break_continue) {
  9362. smallint fbc = G.flag_break_continue;
  9363. /* We might fall into outer *loop*,
  9364. * don't want to break it too */
  9365. if (loop_top) {
  9366. G.depth_break_continue--;
  9367. if (G.depth_break_continue == 0)
  9368. G.flag_break_continue = 0;
  9369. /* else: e.g. "continue 2" should *break* once, *then* continue */
  9370. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  9371. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  9372. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9373. break;
  9374. }
  9375. /* "continue": simulate end of loop */
  9376. rword = RES_DONE;
  9377. continue;
  9378. }
  9379. #endif
  9380. if (G_flag_return_in_progress == 1) {
  9381. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9382. break;
  9383. }
  9384. } else if (pi->followup == PIPE_BG) {
  9385. /* What does bash do with attempts to background builtins? */
  9386. /* even bash 3.2 doesn't do that well with nested bg:
  9387. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  9388. * I'm NOT treating inner &'s as jobs */
  9389. #if ENABLE_HUSH_JOB
  9390. if (G.run_list_level == 1)
  9391. insert_job_into_table(pi);
  9392. #endif
  9393. /* Last command's pid goes to $! */
  9394. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9395. G.last_bg_pid_exitcode = 0;
  9396. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9397. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9398. rcode = EXIT_SUCCESS;
  9399. goto check_traps;
  9400. } else {
  9401. #if ENABLE_HUSH_JOB
  9402. if (G.run_list_level == 1 && G_interactive_fd) {
  9403. /* Waits for completion, then fg's main shell */
  9404. rcode = checkjobs_and_fg_shell(pi);
  9405. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9406. goto check_traps;
  9407. }
  9408. #endif
  9409. /* This one just waits for completion */
  9410. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9411. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9412. check_traps:
  9413. G.last_exitcode = rcode;
  9414. check_and_run_traps();
  9415. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9416. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9417. #endif
  9418. }
  9419. /* Handle "set -e" */
  9420. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9421. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9422. if (G.errexit_depth == 0)
  9423. hush_exit(rcode);
  9424. }
  9425. G.errexit_depth = sv_errexit_depth;
  9426. /* Analyze how result affects subsequent commands */
  9427. #if ENABLE_HUSH_IF
  9428. if (rword == RES_IF || rword == RES_ELIF) {
  9429. debug_printf_exec("cond_code=rcode:%d\n", rcode);
  9430. cond_code = rcode;
  9431. }
  9432. #endif
  9433. check_jobs_and_continue:
  9434. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9435. dont_check_jobs_but_continue: ;
  9436. #if ENABLE_HUSH_LOOPS
  9437. /* Beware of "while false; true; do ..."! */
  9438. if (pi->next
  9439. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9440. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9441. ) {
  9442. if (rword == RES_WHILE) {
  9443. if (rcode) {
  9444. /* "while false; do...done" - exitcode 0 */
  9445. G.last_exitcode = rcode = EXIT_SUCCESS;
  9446. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9447. break;
  9448. }
  9449. }
  9450. if (rword == RES_UNTIL) {
  9451. if (!rcode) {
  9452. debug_printf_exec(": until expr is true: breaking\n");
  9453. break;
  9454. }
  9455. }
  9456. }
  9457. #endif
  9458. } /* for (pi) */
  9459. #if ENABLE_HUSH_JOB
  9460. G.run_list_level--;
  9461. #endif
  9462. #if ENABLE_HUSH_LOOPS
  9463. if (loop_top)
  9464. G.depth_of_loop--;
  9465. free(for_list);
  9466. #endif
  9467. #if ENABLE_HUSH_CASE
  9468. free(case_word);
  9469. #endif
  9470. debug_leave();
  9471. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level, rcode);
  9472. return rcode;
  9473. }
  9474. /* Select which version we will use */
  9475. static int run_and_free_list(struct pipe *pi)
  9476. {
  9477. int rcode = 0;
  9478. debug_printf_exec("run_and_free_list entered\n");
  9479. if (!G.o_opt[OPT_O_NOEXEC]) {
  9480. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9481. rcode = run_list(pi);
  9482. }
  9483. /* free_pipe_list has the side effect of clearing memory.
  9484. * In the long run that function can be merged with run_list,
  9485. * but doing that now would hobble the debugging effort. */
  9486. free_pipe_list(pi);
  9487. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9488. return rcode;
  9489. }
  9490. static void install_sighandlers(unsigned mask)
  9491. {
  9492. sighandler_t old_handler;
  9493. unsigned sig = 0;
  9494. while ((mask >>= 1) != 0) {
  9495. sig++;
  9496. if (!(mask & 1))
  9497. continue;
  9498. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9499. /* POSIX allows shell to re-enable SIGCHLD
  9500. * even if it was SIG_IGN on entry.
  9501. * Therefore we skip IGN check for it:
  9502. */
  9503. if (sig == SIGCHLD)
  9504. continue;
  9505. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  9506. * Try:
  9507. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  9508. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  9509. */
  9510. if (sig == SIGHUP && G_interactive_fd)
  9511. continue;
  9512. /* Unless one of the above signals, is it SIG_IGN? */
  9513. if (old_handler == SIG_IGN) {
  9514. /* oops... restore back to IGN, and record this fact */
  9515. install_sighandler(sig, old_handler);
  9516. #if ENABLE_HUSH_TRAP
  9517. if (!G_traps)
  9518. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9519. free(G_traps[sig]);
  9520. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9521. #endif
  9522. }
  9523. }
  9524. }
  9525. /* Called a few times only (or even once if "sh -c") */
  9526. static void install_special_sighandlers(void)
  9527. {
  9528. unsigned mask;
  9529. /* Which signals are shell-special? */
  9530. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9531. if (G_interactive_fd) {
  9532. mask |= SPECIAL_INTERACTIVE_SIGS;
  9533. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9534. mask |= SPECIAL_JOBSTOP_SIGS;
  9535. }
  9536. /* Careful, do not re-install handlers we already installed */
  9537. if (G.special_sig_mask != mask) {
  9538. unsigned diff = mask & ~G.special_sig_mask;
  9539. G.special_sig_mask = mask;
  9540. install_sighandlers(diff);
  9541. }
  9542. }
  9543. #if ENABLE_HUSH_JOB
  9544. /* helper */
  9545. /* Set handlers to restore tty pgrp and exit */
  9546. static void install_fatal_sighandlers(void)
  9547. {
  9548. unsigned mask;
  9549. /* We will restore tty pgrp on these signals */
  9550. mask = 0
  9551. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9552. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9553. + (1 << SIGBUS ) * HUSH_DEBUG
  9554. + (1 << SIGSEGV) * HUSH_DEBUG
  9555. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9556. + (1 << SIGABRT)
  9557. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9558. + (1 << SIGPIPE)
  9559. + (1 << SIGALRM)
  9560. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9561. * if we aren't interactive... but in this case
  9562. * we never want to restore pgrp on exit, and this fn is not called
  9563. */
  9564. /*+ (1 << SIGHUP )*/
  9565. /*+ (1 << SIGTERM)*/
  9566. /*+ (1 << SIGINT )*/
  9567. ;
  9568. G_fatal_sig_mask = mask;
  9569. install_sighandlers(mask);
  9570. }
  9571. #endif
  9572. static int set_mode(int state, char mode, const char *o_opt)
  9573. {
  9574. int idx;
  9575. switch (mode) {
  9576. case 'n':
  9577. /* set -n has no effect in interactive shell */
  9578. /* Try: while set -n; do echo $-; done */
  9579. if (!G_interactive_fd)
  9580. G.o_opt[OPT_O_NOEXEC] = state;
  9581. break;
  9582. case 'x':
  9583. IF_HUSH_MODE_X(G_x_mode = state;)
  9584. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9585. break;
  9586. case 'e':
  9587. G.o_opt[OPT_O_ERREXIT] = state;
  9588. break;
  9589. case 'o':
  9590. if (!o_opt) {
  9591. /* "set -o" or "set +o" without parameter.
  9592. * in bash, set -o produces this output:
  9593. * pipefail off
  9594. * and set +o:
  9595. * set +o pipefail
  9596. * We always use the second form.
  9597. */
  9598. const char *p = o_opt_strings;
  9599. idx = 0;
  9600. while (*p) {
  9601. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9602. idx++;
  9603. p += strlen(p) + 1;
  9604. }
  9605. break;
  9606. }
  9607. idx = index_in_strings(o_opt_strings, o_opt);
  9608. if (idx >= 0) {
  9609. G.o_opt[idx] = state;
  9610. break;
  9611. }
  9612. /* fall through to error */
  9613. default:
  9614. return EXIT_FAILURE;
  9615. }
  9616. return EXIT_SUCCESS;
  9617. }
  9618. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9619. int hush_main(int argc, char **argv)
  9620. {
  9621. pid_t cached_getpid;
  9622. enum {
  9623. OPT_login = (1 << 0),
  9624. };
  9625. unsigned flags;
  9626. #if !BB_MMU
  9627. unsigned builtin_argc = 0;
  9628. #endif
  9629. char **e;
  9630. struct variable *cur_var;
  9631. struct variable *shell_ver;
  9632. INIT_G();
  9633. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9634. G.last_exitcode = EXIT_SUCCESS;
  9635. #if !BB_MMU
  9636. /* "Big heredoc" support via "sh -< STRING" invocation.
  9637. * Check it first (do not bother to run the usual init code,
  9638. * it is not needed for this case).
  9639. */
  9640. if (argv[1]
  9641. && argv[1][0] == '-' && argv[1][1] == '<' /*&& !argv[1][2]*/
  9642. /*&& argv[2] && !argv[3] - we don't check some conditions */
  9643. ) {
  9644. full_write1_str(argv[2]);
  9645. _exit(0);
  9646. }
  9647. G.argv0_for_re_execing = argv[0];
  9648. #endif
  9649. #if ENABLE_HUSH_TRAP
  9650. # if ENABLE_HUSH_FUNCTIONS
  9651. G.return_exitcode = -1;
  9652. # endif
  9653. G.pre_trap_exitcode = -1;
  9654. #endif
  9655. #if ENABLE_HUSH_FAST
  9656. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9657. #endif
  9658. cached_getpid = getpid(); /* for tcsetpgrp() during init */
  9659. G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
  9660. G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
  9661. /* Deal with HUSH_VERSION */
  9662. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9663. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9664. shell_ver = xzalloc(sizeof(*shell_ver));
  9665. shell_ver->flg_export = 1;
  9666. shell_ver->flg_read_only = 1;
  9667. /* Code which handles ${var<op>...} needs writable values for all variables,
  9668. * therefore we xstrdup: */
  9669. shell_ver->varstr = xstrdup(hush_version_str);
  9670. /* Create shell local variables from the values
  9671. * currently living in the environment */
  9672. G.top_var = shell_ver;
  9673. cur_var = G.top_var;
  9674. e = environ;
  9675. if (e) while (*e) {
  9676. char *value = strchr(*e, '=');
  9677. if (value) { /* paranoia */
  9678. cur_var->next = xzalloc(sizeof(*cur_var));
  9679. cur_var = cur_var->next;
  9680. cur_var->varstr = *e;
  9681. cur_var->max_len = strlen(*e);
  9682. cur_var->flg_export = 1;
  9683. }
  9684. e++;
  9685. }
  9686. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9687. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9688. putenv(shell_ver->varstr);
  9689. /* Export PWD */
  9690. set_pwd_var(SETFLAG_EXPORT);
  9691. #if BASH_HOSTNAME_VAR
  9692. /* Set (but not export) HOSTNAME unless already set */
  9693. if (!get_local_var_value("HOSTNAME")) {
  9694. struct utsname uts;
  9695. uname(&uts);
  9696. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9697. }
  9698. #endif
  9699. /* IFS is not inherited from the parent environment */
  9700. set_local_var_from_halves("IFS", defifs);
  9701. if (!get_local_var_value("PATH"))
  9702. set_local_var_from_halves("PATH", bb_default_root_path);
  9703. /* PS1/PS2 are set later, if we determine that we are interactive */
  9704. /* bash also exports SHLVL and _,
  9705. * and sets (but doesn't export) the following variables:
  9706. * BASH=/bin/bash
  9707. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9708. * BASH_VERSION='3.2.0(1)-release'
  9709. * HOSTTYPE=i386
  9710. * MACHTYPE=i386-pc-linux-gnu
  9711. * OSTYPE=linux-gnu
  9712. * PPID=<NNNNN> - we also do it elsewhere
  9713. * EUID=<NNNNN>
  9714. * UID=<NNNNN>
  9715. * GROUPS=()
  9716. * LINES=<NNN>
  9717. * COLUMNS=<NNN>
  9718. * BASH_ARGC=()
  9719. * BASH_ARGV=()
  9720. * BASH_LINENO=()
  9721. * BASH_SOURCE=()
  9722. * DIRSTACK=()
  9723. * PIPESTATUS=([0]="0")
  9724. * HISTFILE=/<xxx>/.bash_history
  9725. * HISTFILESIZE=500
  9726. * HISTSIZE=500
  9727. * MAILCHECK=60
  9728. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9729. * SHELL=/bin/bash
  9730. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9731. * TERM=dumb
  9732. * OPTERR=1
  9733. * OPTIND=1
  9734. * PS4='+ '
  9735. */
  9736. #if NUM_SCRIPTS > 0
  9737. if (argc < 0) {
  9738. char *script = get_script_content(-argc - 1);
  9739. G.global_argv = argv;
  9740. G.global_argc = string_array_len(argv);
  9741. //install_special_sighandlers(); - needed?
  9742. parse_and_run_string(script);
  9743. goto final_return;
  9744. }
  9745. #endif
  9746. /* Initialize some more globals to non-zero values */
  9747. die_func = restore_ttypgrp_and__exit;
  9748. /* Shell is non-interactive at first. We need to call
  9749. * install_special_sighandlers() if we are going to execute "sh <script>",
  9750. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9751. * If we later decide that we are interactive, we run install_special_sighandlers()
  9752. * in order to intercept (more) signals.
  9753. */
  9754. /* Parse options */
  9755. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9756. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9757. while (1) {
  9758. int opt = getopt(argc, argv, "+" /* stop at 1st non-option */
  9759. "cexinsl"
  9760. #if !BB_MMU
  9761. "$:R:V:"
  9762. # if ENABLE_HUSH_LINENO_VAR
  9763. "L:"
  9764. # endif
  9765. # if ENABLE_HUSH_FUNCTIONS
  9766. "F:"
  9767. # endif
  9768. #endif
  9769. );
  9770. if (opt <= 0)
  9771. break;
  9772. switch (opt) {
  9773. case 'c':
  9774. /* Note: -c is not an option with param!
  9775. * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
  9776. */
  9777. G.opt_c = 1;
  9778. break;
  9779. case 'i':
  9780. /* Well, we cannot just declare interactiveness,
  9781. * we have to have some stuff (ctty, etc) */
  9782. /* G_interactive_fd++; */
  9783. //There are a few cases where bash -i -c 'SCRIPT'
  9784. //has visible effect (differs from bash -c 'SCRIPT'):
  9785. //it ignores TERM:
  9786. // bash -i -c 'kill $$; echo ALIVE'
  9787. // ALIVE
  9788. //it resets SIG_IGNed HUP to SIG_DFL:
  9789. // trap '' hup; bash -i -c 'kill -hup $$; echo ALIVE'
  9790. // Hangup [the message is not printed by bash, it's the shell which started it]
  9791. //is talkative about jobs and exiting:
  9792. // bash -i -c 'sleep 1 & exit'
  9793. // [1] 16170
  9794. // exit
  9795. //includes $ENV file (only if run as "sh"):
  9796. // echo last >/tmp/ENV; ENV=/tmp/ENV sh -i -c 'echo HERE'
  9797. // last: cannot open /var/log/wtmp: No such file or directory
  9798. // HERE
  9799. //(under "bash", it's the opposite: it runs $BASH_ENV file only *without* -i).
  9800. //
  9801. //ash -i -c 'sleep 3; sleep 3', on ^C, drops into a prompt instead of exiting
  9802. //(this may be a bug, bash does not do this).
  9803. //(ash -i -c 'sleep 3' won't show this, the last command gets auto-"exec"ed)
  9804. //
  9805. //None of the above feel like useful features people would rely on.
  9806. break;
  9807. case 's':
  9808. G.opt_s = 1;
  9809. break;
  9810. case 'l':
  9811. flags |= OPT_login;
  9812. break;
  9813. #if !BB_MMU
  9814. case '$': {
  9815. unsigned long long empty_trap_mask;
  9816. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9817. optarg++;
  9818. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9819. optarg++;
  9820. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9821. optarg++;
  9822. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9823. optarg++;
  9824. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9825. optarg++;
  9826. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9827. if (empty_trap_mask != 0) {
  9828. IF_HUSH_TRAP(int sig;)
  9829. install_special_sighandlers();
  9830. # if ENABLE_HUSH_TRAP
  9831. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9832. for (sig = 1; sig < NSIG; sig++) {
  9833. if (empty_trap_mask & (1LL << sig)) {
  9834. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9835. install_sighandler(sig, SIG_IGN);
  9836. }
  9837. }
  9838. # endif
  9839. }
  9840. # if ENABLE_HUSH_LOOPS
  9841. optarg++;
  9842. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9843. # endif
  9844. /* Suppress "killed by signal" message, -$ hack is used
  9845. * for subshells: echo `sh -c 'kill -9 $$'`
  9846. * should be silent.
  9847. */
  9848. IF_HUSH_JOB(G.run_list_level = 1;)
  9849. # if ENABLE_HUSH_FUNCTIONS
  9850. /* nommu uses re-exec trick for "... | func | ...",
  9851. * should allow "return".
  9852. * This accidentally allows returns in subshells.
  9853. */
  9854. G_flag_return_in_progress = -1;
  9855. # endif
  9856. break;
  9857. }
  9858. case 'R':
  9859. case 'V':
  9860. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9861. break;
  9862. # if ENABLE_HUSH_LINENO_VAR
  9863. case 'L':
  9864. G.parse_lineno = xatou(optarg);
  9865. break;
  9866. # endif
  9867. # if ENABLE_HUSH_FUNCTIONS
  9868. case 'F': {
  9869. struct function *funcp = new_function(optarg);
  9870. /* funcp->name is already set to optarg */
  9871. /* funcp->body is set to NULL. It's a special case. */
  9872. funcp->body_as_string = argv[optind];
  9873. optind++;
  9874. break;
  9875. }
  9876. # endif
  9877. #endif
  9878. /*case '?': invalid option encountered (set_mode('?') will fail) */
  9879. /*case 'n':*/
  9880. /*case 'x':*/
  9881. /*case 'e':*/
  9882. default:
  9883. if (set_mode(1, opt, NULL) == 0) /* no error */
  9884. break;
  9885. bb_show_usage();
  9886. }
  9887. } /* option parsing loop */
  9888. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9889. G.global_argc = argc - (optind - 1);
  9890. G.global_argv = argv + (optind - 1);
  9891. G.global_argv[0] = argv[0];
  9892. /* If we are login shell... */
  9893. if (flags & OPT_login) {
  9894. const char *hp = NULL;
  9895. HFILE *input;
  9896. debug_printf("sourcing /etc/profile\n");
  9897. input = hfopen("/etc/profile");
  9898. run_profile:
  9899. if (input != NULL) {
  9900. install_special_sighandlers();
  9901. parse_and_run_file(input);
  9902. hfclose(input);
  9903. }
  9904. /* bash: after sourcing /etc/profile,
  9905. * tries to source (in the given order):
  9906. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9907. * stopping on first found. --noprofile turns this off.
  9908. * bash also sources ~/.bash_logout on exit.
  9909. * If called as sh, skips .bash_XXX files.
  9910. */
  9911. if (!hp) { /* unless we looped on the "goto" already */
  9912. hp = get_local_var_value("HOME");
  9913. if (hp && hp[0]) {
  9914. debug_printf("sourcing ~/.profile\n");
  9915. hp = concat_path_file(hp, ".profile");
  9916. input = hfopen(hp);
  9917. free((char*)hp);
  9918. goto run_profile;
  9919. }
  9920. }
  9921. }
  9922. /* -c takes effect *after* -l */
  9923. if (G.opt_c) {
  9924. /* Possibilities:
  9925. * sh ... -c 'script'
  9926. * sh ... -c 'script' ARG0 [ARG1...]
  9927. * On NOMMU, if builtin_argc != 0,
  9928. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9929. * "" needs to be replaced with NULL
  9930. * and BARGV vector fed to builtin function.
  9931. * Note: the form without ARG0 never happens:
  9932. * sh ... -c 'builtin' BARGV... ""
  9933. */
  9934. char *script;
  9935. install_special_sighandlers();
  9936. G.global_argc--;
  9937. G.global_argv++;
  9938. #if !BB_MMU
  9939. if (builtin_argc) {
  9940. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9941. const struct built_in_command *x;
  9942. x = find_builtin(G.global_argv[0]);
  9943. if (x) { /* paranoia */
  9944. argv = G.global_argv;
  9945. G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
  9946. G.global_argv += builtin_argc + 1;
  9947. G.global_argv[-1] = NULL; /* replace "" */
  9948. G.last_exitcode = x->b_function(argv);
  9949. }
  9950. goto final_return;
  9951. }
  9952. #endif
  9953. script = G.global_argv[0];
  9954. if (!script)
  9955. bb_error_msg_and_die(bb_msg_requires_arg, "-c");
  9956. if (!G.global_argv[1]) {
  9957. /* -c 'script' (no params): prevent empty $0 */
  9958. G.global_argv[0] = argv[0];
  9959. } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9960. G.global_argc--;
  9961. G.global_argv++;
  9962. }
  9963. parse_and_run_string(script);
  9964. goto final_return;
  9965. }
  9966. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9967. if (!G.opt_s && G.global_argv[1]) {
  9968. HFILE *input;
  9969. /*
  9970. * "bash <script>" (which is never interactive (unless -i?))
  9971. * sources $BASH_ENV here (without scanning $PATH).
  9972. * If called as sh, does the same but with $ENV.
  9973. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9974. */
  9975. G.global_argc--;
  9976. G.global_argv++;
  9977. debug_printf("running script '%s'\n", G.global_argv[0]);
  9978. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9979. input = hfopen(G.global_argv[0]);
  9980. if (!input) {
  9981. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9982. }
  9983. xfunc_error_retval = 1;
  9984. install_special_sighandlers();
  9985. parse_and_run_file(input);
  9986. #if ENABLE_FEATURE_CLEAN_UP
  9987. hfclose(input);
  9988. #endif
  9989. goto final_return;
  9990. }
  9991. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9992. G.opt_s = 1;
  9993. /* Up to here, shell was non-interactive. Now it may become one.
  9994. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9995. */
  9996. /* A shell is interactive if the '-i' flag was given,
  9997. * or if all of the following conditions are met:
  9998. * no -c command
  9999. * no arguments remaining or the -s flag given
  10000. * standard input is a terminal
  10001. * standard output is a terminal
  10002. * Refer to Posix.2, the description of the 'sh' utility.
  10003. */
  10004. #if ENABLE_HUSH_JOB
  10005. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  10006. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  10007. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  10008. if (G_saved_tty_pgrp < 0)
  10009. G_saved_tty_pgrp = 0;
  10010. /* try to dup stdin to high fd#, >= 255 */
  10011. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  10012. if (G_interactive_fd < 0) {
  10013. /* try to dup to any fd */
  10014. G_interactive_fd = dup(STDIN_FILENO);
  10015. if (G_interactive_fd < 0) {
  10016. /* give up */
  10017. G_interactive_fd = 0;
  10018. G_saved_tty_pgrp = 0;
  10019. }
  10020. }
  10021. }
  10022. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  10023. if (G_interactive_fd) {
  10024. close_on_exec_on(G_interactive_fd);
  10025. if (G_saved_tty_pgrp) {
  10026. /* If we were run as 'hush &', sleep until we are
  10027. * in the foreground (tty pgrp == our pgrp).
  10028. * If we get started under a job aware app (like bash),
  10029. * make sure we are now in charge so we don't fight over
  10030. * who gets the foreground */
  10031. while (1) {
  10032. pid_t shell_pgrp = getpgrp();
  10033. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  10034. if (G_saved_tty_pgrp == shell_pgrp)
  10035. break;
  10036. /* send TTIN to ourself (should stop us) */
  10037. kill(- shell_pgrp, SIGTTIN);
  10038. }
  10039. }
  10040. /* Install more signal handlers */
  10041. install_special_sighandlers();
  10042. if (G_saved_tty_pgrp) {
  10043. /* Set other signals to restore saved_tty_pgrp */
  10044. install_fatal_sighandlers();
  10045. /* Put ourselves in our own process group
  10046. * (bash, too, does this only if ctty is available) */
  10047. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  10048. /* Grab control of the terminal */
  10049. tcsetpgrp(G_interactive_fd, cached_getpid);
  10050. }
  10051. enable_restore_tty_pgrp_on_exit();
  10052. # if ENABLE_FEATURE_EDITING
  10053. G.line_input_state = new_line_input_t(FOR_SHELL);
  10054. # if ENABLE_FEATURE_TAB_COMPLETION
  10055. G.line_input_state->get_exe_name = hush_command_name;
  10056. # endif
  10057. # if EDITING_HAS_sh_get_var
  10058. G.line_input_state->sh_get_var = get_local_var_value;
  10059. # endif
  10060. # endif
  10061. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  10062. {
  10063. const char *hp = get_local_var_value("HISTFILE");
  10064. if (!hp) {
  10065. hp = get_local_var_value("HOME");
  10066. if (hp)
  10067. hp = concat_path_file(hp, ".hush_history");
  10068. } else {
  10069. hp = xstrdup(hp);
  10070. }
  10071. if (hp) {
  10072. G.line_input_state->hist_file = hp;
  10073. //set_local_var(xasprintf("HISTFILE=%s", ...));
  10074. }
  10075. # if ENABLE_FEATURE_SH_HISTFILESIZE
  10076. hp = get_local_var_value("HISTFILESIZE");
  10077. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  10078. # endif
  10079. }
  10080. # endif
  10081. } else {
  10082. install_special_sighandlers();
  10083. }
  10084. #elif ENABLE_HUSH_INTERACTIVE
  10085. /* No job control compiled in, only prompt/line editing */
  10086. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  10087. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  10088. if (G_interactive_fd < 0) {
  10089. /* try to dup to any fd */
  10090. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  10091. if (G_interactive_fd < 0)
  10092. /* give up */
  10093. G_interactive_fd = 0;
  10094. }
  10095. }
  10096. if (G_interactive_fd) {
  10097. close_on_exec_on(G_interactive_fd);
  10098. }
  10099. install_special_sighandlers();
  10100. #else
  10101. /* We have interactiveness code disabled */
  10102. install_special_sighandlers();
  10103. #endif
  10104. /* bash:
  10105. * if interactive but not a login shell, sources ~/.bashrc
  10106. * (--norc turns this off, --rcfile <file> overrides)
  10107. */
  10108. if (G_interactive_fd) {
  10109. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  10110. /* Set (but not export) PS1/2 unless already set */
  10111. if (!get_local_var_value("PS1"))
  10112. set_local_var_from_halves("PS1", "\\w \\$ ");
  10113. if (!get_local_var_value("PS2"))
  10114. set_local_var_from_halves("PS2", "> ");
  10115. #endif
  10116. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  10117. /* note: ash and hush share this string */
  10118. printf("\n\n%s %s\n"
  10119. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  10120. "\n",
  10121. bb_banner,
  10122. "hush - the humble shell"
  10123. );
  10124. }
  10125. }
  10126. parse_and_run_file(hfopen(NULL)); /* stdin */
  10127. final_return:
  10128. hush_exit(G.last_exitcode);
  10129. }
  10130. /*
  10131. * Built-ins
  10132. */
  10133. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  10134. {
  10135. return 0;
  10136. }
  10137. static int FAST_FUNC builtin_false(char **argv UNUSED_PARAM)
  10138. {
  10139. return 1;
  10140. }
  10141. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  10142. static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  10143. {
  10144. int argc = string_array_len(argv);
  10145. return applet_main_func(argc, argv);
  10146. }
  10147. #endif
  10148. #if ENABLE_HUSH_TEST || BASH_TEST2
  10149. static int FAST_FUNC builtin_test(char **argv)
  10150. {
  10151. return run_applet_main(argv, test_main);
  10152. }
  10153. #endif
  10154. #if ENABLE_HUSH_ECHO
  10155. static int FAST_FUNC builtin_echo(char **argv)
  10156. {
  10157. return run_applet_main(argv, echo_main);
  10158. }
  10159. #endif
  10160. #if ENABLE_HUSH_PRINTF
  10161. static int FAST_FUNC builtin_printf(char **argv)
  10162. {
  10163. return run_applet_main(argv, printf_main);
  10164. }
  10165. #endif
  10166. #if ENABLE_HUSH_HELP
  10167. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  10168. {
  10169. const struct built_in_command *x;
  10170. printf(
  10171. "Built-in commands:\n"
  10172. "------------------\n");
  10173. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  10174. if (x->b_descr)
  10175. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  10176. }
  10177. return EXIT_SUCCESS;
  10178. }
  10179. #endif
  10180. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  10181. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  10182. {
  10183. show_history(G.line_input_state);
  10184. return EXIT_SUCCESS;
  10185. }
  10186. #endif
  10187. static int FAST_FUNC builtin_cd(char **argv)
  10188. {
  10189. const char *newdir;
  10190. argv = skip_dash_dash(argv);
  10191. newdir = argv[0];
  10192. if (newdir == NULL) {
  10193. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  10194. * bash says "bash: cd: HOME not set" and does nothing
  10195. * (exitcode 1)
  10196. */
  10197. const char *home = get_local_var_value("HOME");
  10198. newdir = home ? home : "/";
  10199. }
  10200. if (chdir(newdir)) {
  10201. /* Mimic bash message exactly */
  10202. bb_perror_msg("cd: %s", newdir);
  10203. return EXIT_FAILURE;
  10204. }
  10205. /* Read current dir (get_cwd(1) is inside) and set PWD.
  10206. * Note: do not enforce exporting. If PWD was unset or unexported,
  10207. * set it again, but do not export. bash does the same.
  10208. */
  10209. set_pwd_var(/*flag:*/ 0);
  10210. return EXIT_SUCCESS;
  10211. }
  10212. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  10213. {
  10214. puts(get_cwd(0));
  10215. return EXIT_SUCCESS;
  10216. }
  10217. static int FAST_FUNC builtin_eval(char **argv)
  10218. {
  10219. argv = skip_dash_dash(argv);
  10220. if (!argv[0])
  10221. return EXIT_SUCCESS;
  10222. IF_HUSH_MODE_X(G.x_mode_depth++;)
  10223. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  10224. if (!argv[1]) {
  10225. /* bash:
  10226. * eval "echo Hi; done" ("done" is syntax error):
  10227. * "echo Hi" will not execute too.
  10228. */
  10229. parse_and_run_string(argv[0]);
  10230. } else {
  10231. /* "The eval utility shall construct a command by
  10232. * concatenating arguments together, separating
  10233. * each with a <space> character."
  10234. */
  10235. char *str, *p;
  10236. unsigned len = 0;
  10237. char **pp = argv;
  10238. do
  10239. len += strlen(*pp) + 1;
  10240. while (*++pp);
  10241. str = p = xmalloc(len);
  10242. pp = argv;
  10243. for (;;) {
  10244. p = stpcpy(p, *pp);
  10245. pp++;
  10246. if (!*pp)
  10247. break;
  10248. *p++ = ' ';
  10249. }
  10250. parse_and_run_string(str);
  10251. free(str);
  10252. }
  10253. IF_HUSH_MODE_X(G.x_mode_depth--;)
  10254. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  10255. return G.last_exitcode;
  10256. }
  10257. static int FAST_FUNC builtin_exec(char **argv)
  10258. {
  10259. argv = skip_dash_dash(argv);
  10260. if (argv[0] == NULL)
  10261. return EXIT_SUCCESS; /* bash does this */
  10262. /* Careful: we can end up here after [v]fork. Do not restore
  10263. * tty pgrp then, only top-level shell process does that */
  10264. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  10265. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  10266. /* Saved-redirect fds, script fds and G_interactive_fd are still
  10267. * open here. However, they are all CLOEXEC, and execv below
  10268. * closes them. Try interactive "exec ls -l /proc/self/fd",
  10269. * it should show no extra open fds in the "ls" process.
  10270. * If we'd try to run builtins/NOEXECs, this would need improving.
  10271. */
  10272. //close_saved_fds_and_FILE_fds();
  10273. /* TODO: if exec fails, bash does NOT exit! We do.
  10274. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  10275. * and tcsetpgrp, and this is inherently racy.
  10276. */
  10277. execvp_or_die(argv);
  10278. }
  10279. static int FAST_FUNC builtin_exit(char **argv)
  10280. {
  10281. debug_printf_exec("%s()\n", __func__);
  10282. /* interactive bash:
  10283. * # trap "echo EEE" EXIT
  10284. * # exit
  10285. * exit
  10286. * There are stopped jobs.
  10287. * (if there are _stopped_ jobs, running ones don't count)
  10288. * # exit
  10289. * exit
  10290. * EEE (then bash exits)
  10291. *
  10292. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  10293. */
  10294. /* note: EXIT trap is run by hush_exit */
  10295. argv = skip_dash_dash(argv);
  10296. if (argv[0] == NULL) {
  10297. #if ENABLE_HUSH_TRAP
  10298. if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
  10299. hush_exit(G.pre_trap_exitcode);
  10300. #endif
  10301. hush_exit(G.last_exitcode);
  10302. }
  10303. /* mimic bash: exit 123abc == exit 255 + error msg */
  10304. xfunc_error_retval = 255;
  10305. /* bash: exit -2 == exit 254, no error msg */
  10306. hush_exit(xatoi(argv[0]) & 0xff);
  10307. }
  10308. #if ENABLE_HUSH_TYPE
  10309. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  10310. static int FAST_FUNC builtin_type(char **argv)
  10311. {
  10312. int ret = EXIT_SUCCESS;
  10313. while (*++argv) {
  10314. const char *type;
  10315. char *path = NULL;
  10316. if (0) {} /* make conditional compile easier below */
  10317. /*else if (find_alias(*argv))
  10318. type = "an alias";*/
  10319. # if ENABLE_HUSH_FUNCTIONS
  10320. else if (find_function(*argv))
  10321. type = "a function";
  10322. # endif
  10323. else if (find_builtin(*argv))
  10324. type = "a shell builtin";
  10325. else if ((path = find_in_path(*argv)) != NULL)
  10326. type = path;
  10327. else {
  10328. bb_error_msg("type: %s: not found", *argv);
  10329. ret = EXIT_FAILURE;
  10330. continue;
  10331. }
  10332. printf("%s is %s\n", *argv, type);
  10333. free(path);
  10334. }
  10335. return ret;
  10336. }
  10337. #endif
  10338. #if ENABLE_HUSH_READ
  10339. /* Interruptibility of read builtin in bash
  10340. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  10341. *
  10342. * Empty trap makes read ignore corresponding signal, for any signal.
  10343. *
  10344. * SIGINT:
  10345. * - terminates non-interactive shell;
  10346. * - interrupts read in interactive shell;
  10347. * if it has non-empty trap:
  10348. * - executes trap and returns to command prompt in interactive shell;
  10349. * - executes trap and returns to read in non-interactive shell;
  10350. * SIGTERM:
  10351. * - is ignored (does not interrupt) read in interactive shell;
  10352. * - terminates non-interactive shell;
  10353. * if it has non-empty trap:
  10354. * - executes trap and returns to read;
  10355. * SIGHUP:
  10356. * - terminates shell (regardless of interactivity);
  10357. * if it has non-empty trap:
  10358. * - executes trap and returns to read;
  10359. * SIGCHLD from children:
  10360. * - does not interrupt read regardless of interactivity:
  10361. * try: sleep 1 & read x; echo $x
  10362. */
  10363. static int FAST_FUNC builtin_read(char **argv)
  10364. {
  10365. const char *r;
  10366. struct builtin_read_params params;
  10367. memset(&params, 0, sizeof(params));
  10368. /* "!": do not abort on errors.
  10369. * Option string must start with "sr" to match BUILTIN_READ_xxx
  10370. */
  10371. params.read_flags = getopt32(argv,
  10372. # if BASH_READ_D
  10373. IF_NOT_HUSH_BASH_COMPAT("^")
  10374. "!srn:p:t:u:d:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10375. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  10376. # else
  10377. IF_NOT_HUSH_BASH_COMPAT("^")
  10378. "!srn:p:t:u:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10379. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  10380. # endif
  10381. //TODO: print "read: need variable name"
  10382. //for the case of !BASH "read" with no args (now it fails silently)
  10383. //(or maybe extend getopt32() to emit a message if "-1" fails)
  10384. );
  10385. if ((uint32_t)params.read_flags == (uint32_t)-1)
  10386. return EXIT_FAILURE;
  10387. argv += optind;
  10388. params.argv = argv;
  10389. params.setvar = set_local_var_from_halves;
  10390. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  10391. again:
  10392. r = shell_builtin_read(&params);
  10393. if ((uintptr_t)r == 1 && errno == EINTR) {
  10394. unsigned sig = check_and_run_traps();
  10395. if (sig != SIGINT)
  10396. goto again;
  10397. }
  10398. if ((uintptr_t)r > 1) {
  10399. bb_simple_error_msg(r);
  10400. r = (char*)(uintptr_t)1;
  10401. }
  10402. return (uintptr_t)r;
  10403. }
  10404. #endif
  10405. #if ENABLE_HUSH_UMASK
  10406. static int FAST_FUNC builtin_umask(char **argv)
  10407. {
  10408. int rc;
  10409. mode_t mask;
  10410. rc = 1;
  10411. mask = umask(0);
  10412. argv = skip_dash_dash(argv);
  10413. if (argv[0]) {
  10414. mode_t old_mask = mask;
  10415. /* numeric umasks are taken as-is */
  10416. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  10417. if (!isdigit(argv[0][0]))
  10418. mask ^= 0777;
  10419. mask = bb_parse_mode(argv[0], mask);
  10420. if (!isdigit(argv[0][0]))
  10421. mask ^= 0777;
  10422. if ((unsigned)mask > 0777) {
  10423. mask = old_mask;
  10424. /* bash messages:
  10425. * bash: umask: 'q': invalid symbolic mode operator
  10426. * bash: umask: 999: octal number out of range
  10427. */
  10428. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  10429. rc = 0;
  10430. }
  10431. } else {
  10432. /* Mimic bash */
  10433. printf("%04o\n", (unsigned) mask);
  10434. /* fall through and restore mask which we set to 0 */
  10435. }
  10436. umask(mask);
  10437. return !rc; /* rc != 0 - success */
  10438. }
  10439. #endif
  10440. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY || ENABLE_HUSH_SET || ENABLE_HUSH_TRAP
  10441. static void print_escaped(const char *s)
  10442. {
  10443. //TODO? bash "set" does not quote variables which contain only alnums and "%+,-./:=@_~",
  10444. // (but "export" quotes all variables, even with only these chars).
  10445. // I think quoting strings with %+,=~ looks better
  10446. // (example: "set" printing var== instead of var='=' looks strange)
  10447. // IOW: do not quote "-./:@_": / is used in pathnames, : in PATH, -._ often in file names, @ in emails
  10448. if (*s == '\'')
  10449. goto squote;
  10450. do {
  10451. const char *p = strchrnul(s, '\'');
  10452. /* print 'xxxx', possibly just '' */
  10453. printf("'%.*s'", (int)(p - s), s);
  10454. if (*p == '\0')
  10455. break;
  10456. s = p;
  10457. squote:
  10458. /* s points to '; print "'''...'''" */
  10459. putchar('"');
  10460. do putchar('\''); while (*++s == '\'');
  10461. putchar('"');
  10462. } while (*s);
  10463. }
  10464. #endif
  10465. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  10466. static int helper_export_local(char **argv, unsigned flags)
  10467. {
  10468. do {
  10469. char *name = *argv;
  10470. const char *name_end = endofname(name);
  10471. if (*name_end == '\0') {
  10472. struct variable *var, **vpp;
  10473. vpp = get_ptr_to_local_var(name);
  10474. var = vpp ? *vpp : NULL;
  10475. if (flags & SETFLAG_UNEXPORT) {
  10476. /* export -n NAME (without =VALUE) */
  10477. if (var) {
  10478. var->flg_export = 0;
  10479. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  10480. unsetenv(name);
  10481. } /* else: export -n NOT_EXISTING_VAR: no-op */
  10482. continue;
  10483. }
  10484. if (flags & SETFLAG_EXPORT) {
  10485. /* export NAME (without =VALUE) */
  10486. if (var) {
  10487. var->flg_export = 1;
  10488. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10489. putenv(var->varstr);
  10490. continue;
  10491. }
  10492. }
  10493. if (flags & SETFLAG_MAKE_RO) {
  10494. /* readonly NAME (without =VALUE) */
  10495. if (var) {
  10496. var->flg_read_only = 1;
  10497. continue;
  10498. }
  10499. }
  10500. # if ENABLE_HUSH_LOCAL
  10501. /* Is this "local" bltin? */
  10502. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10503. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10504. if (var && var->var_nest_level == lvl) {
  10505. /* "local x=abc; ...; local x" - ignore second local decl */
  10506. continue;
  10507. }
  10508. }
  10509. # endif
  10510. /* Exporting non-existing variable.
  10511. * bash does not put it in environment,
  10512. * but remembers that it is exported,
  10513. * and does put it in env when it is set later.
  10514. * We just set it to "" and export.
  10515. */
  10516. /* Or, it's "local NAME" (without =VALUE).
  10517. * bash sets the value to "".
  10518. */
  10519. /* Or, it's "readonly NAME" (without =VALUE).
  10520. * bash remembers NAME and disallows its creation
  10521. * in the future.
  10522. */
  10523. name = xasprintf("%s=", name);
  10524. } else {
  10525. if (*name_end != '=') {
  10526. bb_error_msg("'%s': bad variable name", name);
  10527. /* do not parse following argv[]s: */
  10528. return 1;
  10529. }
  10530. /* (Un)exporting/making local NAME=VALUE */
  10531. name = xstrdup(name);
  10532. /* Testcase: export PS1='\w \$ ' */
  10533. unbackslash(name);
  10534. }
  10535. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10536. if (set_local_var(name, flags))
  10537. return EXIT_FAILURE;
  10538. } while (*++argv);
  10539. return EXIT_SUCCESS;
  10540. }
  10541. #endif
  10542. #if ENABLE_HUSH_EXPORT
  10543. static int FAST_FUNC builtin_export(char **argv)
  10544. {
  10545. unsigned opt_unexport;
  10546. # if ENABLE_HUSH_EXPORT_N
  10547. /* "!": do not abort on errors */
  10548. opt_unexport = getopt32(argv, "!n");
  10549. if (opt_unexport == (uint32_t)-1)
  10550. return EXIT_FAILURE;
  10551. argv += optind;
  10552. # else
  10553. opt_unexport = 0;
  10554. argv++;
  10555. # endif
  10556. if (argv[0] == NULL) {
  10557. char **e = environ;
  10558. if (e) {
  10559. while (*e) {
  10560. # if 0
  10561. puts(*e++);
  10562. # else
  10563. /* ash emits: export VAR='VAL'
  10564. * bash: declare -x VAR="VAL"
  10565. * we follow ash example */
  10566. const char *s = *e++;
  10567. const char *p = strchr(s, '=');
  10568. if (!p) /* wtf? take next variable */
  10569. continue;
  10570. /* "export VAR=" */
  10571. printf("%s %.*s", "export", (int)(p - s) + 1, s);
  10572. print_escaped(p + 1);
  10573. putchar('\n');
  10574. # endif
  10575. }
  10576. /*fflush_all(); - done after each builtin anyway */
  10577. }
  10578. return EXIT_SUCCESS;
  10579. }
  10580. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10581. }
  10582. #endif
  10583. #if ENABLE_HUSH_LOCAL
  10584. static int FAST_FUNC builtin_local(char **argv)
  10585. {
  10586. if (G.func_nest_level == 0) {
  10587. bb_error_msg("%s: not in a function", argv[0]);
  10588. return EXIT_FAILURE; /* bash compat */
  10589. }
  10590. //TODO? ash and bash support "local -" special form,
  10591. //which saves/restores $- around function call (including async returns, such as ^C)
  10592. //(IOW: it makes "set +/-..." effects local)
  10593. argv++;
  10594. /* Since all builtins run in a nested variable level,
  10595. * need to use level - 1 here. Or else the variable will be removed at once
  10596. * after builtin returns.
  10597. */
  10598. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10599. }
  10600. #endif
  10601. #if ENABLE_HUSH_READONLY
  10602. static int FAST_FUNC builtin_readonly(char **argv)
  10603. {
  10604. argv++;
  10605. if (*argv == NULL) {
  10606. /* bash: readonly [-p]: list all readonly VARs
  10607. * (-p has no effect in bash)
  10608. */
  10609. struct variable *e;
  10610. for (e = G.top_var; e; e = e->next) {
  10611. if (e->flg_read_only) {
  10612. const char *s = e->varstr;
  10613. const char *p = strchr(s, '=');
  10614. if (!p) /* wtf? take next variable */
  10615. continue;
  10616. /* "readonly VAR=" */
  10617. printf("%s %.*s", "readonly", (int)(p - s) + 1, s);
  10618. print_escaped(p + 1);
  10619. putchar('\n');
  10620. }
  10621. }
  10622. return EXIT_SUCCESS;
  10623. }
  10624. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10625. }
  10626. #endif
  10627. #if ENABLE_HUSH_UNSET
  10628. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10629. static int FAST_FUNC builtin_unset(char **argv)
  10630. {
  10631. int ret;
  10632. unsigned opts;
  10633. /* "!": do not abort on errors */
  10634. /* "+": stop at 1st non-option */
  10635. opts = getopt32(argv, "!+vf");
  10636. if (opts == (unsigned)-1)
  10637. return EXIT_FAILURE;
  10638. if (opts == 3) {
  10639. bb_simple_error_msg("unset: -v and -f are exclusive");
  10640. return EXIT_FAILURE;
  10641. }
  10642. argv += optind;
  10643. ret = EXIT_SUCCESS;
  10644. while (*argv) {
  10645. if (!(opts & 2)) { /* not -f */
  10646. if (unset_local_var(*argv)) {
  10647. /* unset <nonexistent_var> doesn't fail.
  10648. * Error is when one tries to unset RO var.
  10649. * Message was printed by unset_local_var. */
  10650. ret = EXIT_FAILURE;
  10651. }
  10652. }
  10653. # if ENABLE_HUSH_FUNCTIONS
  10654. else {
  10655. unset_func(*argv);
  10656. }
  10657. # endif
  10658. argv++;
  10659. }
  10660. return ret;
  10661. }
  10662. #endif
  10663. #if ENABLE_HUSH_SET
  10664. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10665. * built-in 'set' handler
  10666. * SUSv3 says:
  10667. * set [-abCefhmnuvx] [-o option] [argument...]
  10668. * set [+abCefhmnuvx] [+o option] [argument...]
  10669. * set -- [argument...]
  10670. * set -o
  10671. * set +o
  10672. * Implementations shall support the options in both their hyphen and
  10673. * plus-sign forms. These options can also be specified as options to sh.
  10674. * Examples:
  10675. * Write out all variables and their values: set
  10676. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10677. * Turn on the -x and -v options: set -xv
  10678. * Unset all positional parameters: set --
  10679. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10680. * Set the positional parameters to the expansion of x, even if x expands
  10681. * with a leading '-' or '+': set -- $x
  10682. *
  10683. * So far, we only support "set -- [argument...]" and some of the short names.
  10684. */
  10685. static int FAST_FUNC builtin_set(char **argv)
  10686. {
  10687. int n;
  10688. char **pp, **g_argv;
  10689. char *arg = *++argv;
  10690. if (arg == NULL) {
  10691. struct variable *e;
  10692. for (e = G.top_var; e; e = e->next) {
  10693. const char *s = e->varstr;
  10694. const char *p = strchr(s, '=');
  10695. if (!p) /* wtf? take next variable */
  10696. continue;
  10697. /* var= */
  10698. printf("%.*s", (int)(p - s) + 1, s);
  10699. print_escaped(p + 1);
  10700. putchar('\n');
  10701. }
  10702. return EXIT_SUCCESS;
  10703. }
  10704. do {
  10705. if (strcmp(arg, "--") == 0) {
  10706. ++argv;
  10707. goto set_argv;
  10708. }
  10709. if (arg[0] != '+' && arg[0] != '-')
  10710. break;
  10711. for (n = 1; arg[n]; ++n) {
  10712. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10713. bb_error_msg("%s: %s: invalid option", "set", arg);
  10714. return EXIT_FAILURE;
  10715. }
  10716. if (arg[n] == 'o' && argv[1])
  10717. argv++;
  10718. }
  10719. } while ((arg = *++argv) != NULL);
  10720. /* Now argv[0] is 1st argument */
  10721. if (arg == NULL)
  10722. return EXIT_SUCCESS;
  10723. set_argv:
  10724. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10725. g_argv = G.global_argv;
  10726. if (G.global_args_malloced) {
  10727. pp = g_argv;
  10728. while (*++pp)
  10729. free(*pp);
  10730. g_argv[1] = NULL;
  10731. } else {
  10732. G.global_args_malloced = 1;
  10733. pp = xzalloc(sizeof(pp[0]) * 2);
  10734. pp[0] = g_argv[0]; /* retain $0 */
  10735. g_argv = pp;
  10736. }
  10737. /* This realloc's G.global_argv */
  10738. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10739. G.global_argc = 1 + string_array_len(pp + 1);
  10740. return EXIT_SUCCESS;
  10741. }
  10742. #endif
  10743. static int FAST_FUNC builtin_shift(char **argv)
  10744. {
  10745. int n = 1;
  10746. argv = skip_dash_dash(argv);
  10747. if (argv[0]) {
  10748. n = bb_strtou(argv[0], NULL, 10);
  10749. if (errno || n < 0) {
  10750. /* shared string with ash.c */
  10751. bb_error_msg("Illegal number: %s", argv[0]);
  10752. /*
  10753. * ash aborts in this case.
  10754. * bash prints error message and set $? to 1.
  10755. * Interestingly, for "shift 99999" bash does not
  10756. * print error message, but does set $? to 1
  10757. * (and does no shifting at all).
  10758. */
  10759. }
  10760. }
  10761. if (n >= 0 && n < G.global_argc) {
  10762. if (G_global_args_malloced) {
  10763. int m = 1;
  10764. while (m <= n)
  10765. free(G.global_argv[m++]);
  10766. }
  10767. G.global_argc -= n;
  10768. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10769. G.global_argc * sizeof(G.global_argv[0]));
  10770. return EXIT_SUCCESS;
  10771. }
  10772. return EXIT_FAILURE;
  10773. }
  10774. #if ENABLE_HUSH_GETOPTS
  10775. static int FAST_FUNC builtin_getopts(char **argv)
  10776. {
  10777. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10778. TODO:
  10779. If a required argument is not found, and getopts is not silent,
  10780. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10781. diagnostic message is printed. If getopts is silent, then a
  10782. colon (:) is placed in VAR and OPTARG is set to the option
  10783. character found.
  10784. Test that VAR is a valid variable name?
  10785. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10786. */
  10787. char cbuf[2];
  10788. const char *cp, *optstring, *var;
  10789. int c, n, exitcode, my_opterr;
  10790. unsigned count;
  10791. optstring = *++argv;
  10792. if (!optstring || !(var = *++argv)) {
  10793. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10794. return EXIT_FAILURE;
  10795. }
  10796. if (argv[1])
  10797. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10798. else
  10799. argv = G.global_argv;
  10800. cbuf[1] = '\0';
  10801. my_opterr = 0;
  10802. if (optstring[0] != ':') {
  10803. cp = get_local_var_value("OPTERR");
  10804. /* 0 if "OPTERR=0", 1 otherwise */
  10805. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10806. }
  10807. /* getopts stops on first non-option. Add "+" to force that */
  10808. /*if (optstring[0] != '+')*/ {
  10809. char *s = alloca(strlen(optstring) + 2);
  10810. sprintf(s, "+%s", optstring);
  10811. optstring = s;
  10812. }
  10813. /* Naively, now we should just
  10814. * cp = get_local_var_value("OPTIND");
  10815. * optind = cp ? atoi(cp) : 0;
  10816. * optarg = NULL;
  10817. * opterr = my_opterr;
  10818. * c = getopt(string_array_len(argv), argv, optstring);
  10819. * and be done? Not so fast...
  10820. * Unlike normal getopt() usage in C programs, here
  10821. * each successive call will (usually) have the same argv[] CONTENTS,
  10822. * but not the ADDRESSES. Worse yet, it's possible that between
  10823. * invocations of "getopts", there will be calls to shell builtins
  10824. * which use getopt() internally. Example:
  10825. * while getopts "abc" RES -a -bc -abc de; do
  10826. * unset -ff func
  10827. * done
  10828. * This would not work correctly: getopt() call inside "unset"
  10829. * modifies internal libc state which is tracking position in
  10830. * multi-option strings ("-abc"). At best, it can skip options
  10831. * or return the same option infinitely. With glibc implementation
  10832. * of getopt(), it would use outright invalid pointers and return
  10833. * garbage even _without_ "unset" mangling internal state.
  10834. *
  10835. * We resort to resetting getopt() state and calling it N times,
  10836. * until we get Nth result (or failure).
  10837. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10838. */
  10839. GETOPT_RESET();
  10840. count = 0;
  10841. n = string_array_len(argv);
  10842. do {
  10843. optarg = NULL;
  10844. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10845. c = getopt(n, argv, optstring);
  10846. if (c < 0)
  10847. break;
  10848. count++;
  10849. } while (count <= G.getopt_count);
  10850. /* Set OPTIND. Prevent resetting of the magic counter! */
  10851. set_local_var_from_halves("OPTIND", utoa(optind));
  10852. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10853. GETOPT_RESET(); /* just in case */
  10854. /* Set OPTARG */
  10855. /* Always set or unset, never left as-is, even on exit/error:
  10856. * "If no option was found, or if the option that was found
  10857. * does not have an option-argument, OPTARG shall be unset."
  10858. */
  10859. cp = optarg;
  10860. if (c == '?') {
  10861. /* If ":optstring" and unknown option is seen,
  10862. * it is stored to OPTARG.
  10863. */
  10864. if (optstring[1] == ':') {
  10865. cbuf[0] = optopt;
  10866. cp = cbuf;
  10867. }
  10868. }
  10869. if (cp)
  10870. set_local_var_from_halves("OPTARG", cp);
  10871. else
  10872. unset_local_var("OPTARG");
  10873. /* Convert -1 to "?" */
  10874. exitcode = EXIT_SUCCESS;
  10875. if (c < 0) { /* -1: end of options */
  10876. exitcode = EXIT_FAILURE;
  10877. c = '?';
  10878. }
  10879. /* Set VAR */
  10880. cbuf[0] = c;
  10881. set_local_var_from_halves(var, cbuf);
  10882. return exitcode;
  10883. }
  10884. #endif
  10885. static int FAST_FUNC builtin_source(char **argv)
  10886. {
  10887. char *arg_path, *filename;
  10888. HFILE *input;
  10889. save_arg_t sv;
  10890. char *args_need_save;
  10891. #if ENABLE_HUSH_FUNCTIONS
  10892. smallint sv_flg;
  10893. #endif
  10894. argv = skip_dash_dash(argv);
  10895. filename = argv[0];
  10896. if (!filename) {
  10897. /* bash says: "bash: .: filename argument required" */
  10898. return 2; /* bash compat */
  10899. }
  10900. arg_path = NULL;
  10901. if (!strchr(filename, '/')) {
  10902. arg_path = find_in_path(filename);
  10903. if (arg_path)
  10904. filename = arg_path;
  10905. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10906. errno = ENOENT;
  10907. bb_simple_perror_msg(filename);
  10908. return EXIT_FAILURE;
  10909. }
  10910. }
  10911. input = hfopen(filename);
  10912. free(arg_path);
  10913. if (!input) {
  10914. bb_perror_msg("%s", filename);
  10915. /* POSIX: non-interactive shell should abort here,
  10916. * not merely fail. So far no one complained :)
  10917. */
  10918. return EXIT_FAILURE;
  10919. }
  10920. #if ENABLE_HUSH_FUNCTIONS
  10921. sv_flg = G_flag_return_in_progress;
  10922. /* "we are inside sourced file, ok to use return" */
  10923. G_flag_return_in_progress = -1;
  10924. #endif
  10925. args_need_save = argv[1]; /* used as a boolean variable */
  10926. if (args_need_save)
  10927. save_and_replace_G_args(&sv, argv);
  10928. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10929. G.last_exitcode = 0;
  10930. parse_and_run_file(input);
  10931. hfclose(input);
  10932. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10933. restore_G_args(&sv, argv);
  10934. #if ENABLE_HUSH_FUNCTIONS
  10935. G_flag_return_in_progress = sv_flg;
  10936. #endif
  10937. return G.last_exitcode;
  10938. }
  10939. #if ENABLE_HUSH_TRAP
  10940. static int FAST_FUNC builtin_trap(char **argv)
  10941. {
  10942. int sig;
  10943. char *new_cmd;
  10944. if (!G_traps)
  10945. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10946. argv++;
  10947. if (!*argv) {
  10948. int i;
  10949. /* No args: print all trapped */
  10950. for (i = 0; i < NSIG; ++i) {
  10951. if (G_traps[i]) {
  10952. printf("trap -- ");
  10953. print_escaped(G_traps[i]);
  10954. /* note: bash adds "SIG", but only if invoked
  10955. * as "bash". If called as "sh", or if set -o posix,
  10956. * then it prints short signal names.
  10957. * We are printing short names: */
  10958. printf(" %s\n", get_signame(i));
  10959. }
  10960. }
  10961. /*fflush_all(); - done after each builtin anyway */
  10962. return EXIT_SUCCESS;
  10963. }
  10964. new_cmd = NULL;
  10965. /* If first arg is a number: reset all specified signals */
  10966. sig = bb_strtou(*argv, NULL, 10);
  10967. if (errno == 0) {
  10968. int ret;
  10969. process_sig_list:
  10970. ret = EXIT_SUCCESS;
  10971. while (*argv) {
  10972. sighandler_t handler;
  10973. sig = get_signum(*argv++);
  10974. if (sig < 0) {
  10975. ret = EXIT_FAILURE;
  10976. /* Mimic bash message exactly */
  10977. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10978. continue;
  10979. }
  10980. free(G_traps[sig]);
  10981. G_traps[sig] = xstrdup(new_cmd);
  10982. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10983. get_signame(sig), sig, G_traps[sig]);
  10984. /* There is no signal for 0 (EXIT) */
  10985. if (sig == 0)
  10986. continue;
  10987. if (new_cmd)
  10988. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10989. else
  10990. /* We are removing trap handler */
  10991. handler = pick_sighandler(sig);
  10992. install_sighandler(sig, handler);
  10993. }
  10994. return ret;
  10995. }
  10996. if (!argv[1]) { /* no second arg */
  10997. bb_simple_error_msg("trap: invalid arguments");
  10998. return EXIT_FAILURE;
  10999. }
  11000. /* First arg is "-": reset all specified to default */
  11001. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  11002. /* Everything else: set arg as signal handler
  11003. * (includes "" case, which ignores signal) */
  11004. if (argv[0][0] == '-') {
  11005. if (argv[0][1] == '\0') { /* "-" */
  11006. /* new_cmd remains NULL: "reset these sigs" */
  11007. goto reset_traps;
  11008. }
  11009. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  11010. argv++;
  11011. }
  11012. /* else: "-something", no special meaning */
  11013. }
  11014. new_cmd = *argv;
  11015. reset_traps:
  11016. argv++;
  11017. goto process_sig_list;
  11018. }
  11019. #endif
  11020. #if ENABLE_HUSH_JOB
  11021. static struct pipe *parse_jobspec(const char *str)
  11022. {
  11023. struct pipe *pi;
  11024. unsigned jobnum;
  11025. if (sscanf(str, "%%%u", &jobnum) != 1) {
  11026. if (str[0] != '%'
  11027. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  11028. ) {
  11029. bb_error_msg("bad argument '%s'", str);
  11030. return NULL;
  11031. }
  11032. /* It is "%%", "%+" or "%" - current job */
  11033. jobnum = G.last_jobid;
  11034. if (jobnum == 0) {
  11035. bb_simple_error_msg("no current job");
  11036. return NULL;
  11037. }
  11038. }
  11039. for (pi = G.job_list; pi; pi = pi->next) {
  11040. if (pi->jobid == jobnum) {
  11041. return pi;
  11042. }
  11043. }
  11044. bb_error_msg("%u: no such job", jobnum);
  11045. return NULL;
  11046. }
  11047. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  11048. {
  11049. struct pipe *job;
  11050. const char *status_string;
  11051. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  11052. for (job = G.job_list; job; job = job->next) {
  11053. if (job->alive_cmds == job->stopped_cmds)
  11054. status_string = "Stopped";
  11055. else
  11056. status_string = "Running";
  11057. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  11058. }
  11059. clean_up_last_dead_job();
  11060. return EXIT_SUCCESS;
  11061. }
  11062. /* built-in 'fg' and 'bg' handler */
  11063. static int FAST_FUNC builtin_fg_bg(char **argv)
  11064. {
  11065. int i;
  11066. struct pipe *pi;
  11067. if (!G_interactive_fd)
  11068. return EXIT_FAILURE;
  11069. /* If they gave us no args, assume they want the last backgrounded task */
  11070. if (!argv[1]) {
  11071. for (pi = G.job_list; pi; pi = pi->next) {
  11072. if (pi->jobid == G.last_jobid) {
  11073. goto found;
  11074. }
  11075. }
  11076. bb_error_msg("%s: no current job", argv[0]);
  11077. return EXIT_FAILURE;
  11078. }
  11079. pi = parse_jobspec(argv[1]);
  11080. if (!pi)
  11081. return EXIT_FAILURE;
  11082. found:
  11083. /* TODO: bash prints a string representation
  11084. * of job being foregrounded (like "sleep 1 | cat") */
  11085. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  11086. /* Put the job into the foreground. */
  11087. tcsetpgrp(G_interactive_fd, pi->pgrp);
  11088. }
  11089. /* Restart the processes in the job */
  11090. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  11091. for (i = 0; i < pi->num_cmds; i++) {
  11092. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  11093. }
  11094. pi->stopped_cmds = 0;
  11095. i = kill(- pi->pgrp, SIGCONT);
  11096. if (i < 0) {
  11097. if (errno == ESRCH) {
  11098. delete_finished_job(pi);
  11099. return EXIT_SUCCESS;
  11100. }
  11101. bb_simple_perror_msg("kill (SIGCONT)");
  11102. }
  11103. if (argv[0][0] == 'f') {
  11104. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  11105. return checkjobs_and_fg_shell(pi);
  11106. }
  11107. return EXIT_SUCCESS;
  11108. }
  11109. #endif
  11110. #if ENABLE_HUSH_KILL
  11111. static int FAST_FUNC builtin_kill(char **argv)
  11112. {
  11113. int ret = 0;
  11114. # if ENABLE_HUSH_JOB
  11115. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  11116. int i = 1;
  11117. do {
  11118. struct pipe *pi;
  11119. char *dst;
  11120. int j, n;
  11121. if (argv[i][0] != '%')
  11122. continue;
  11123. /*
  11124. * "kill %N" - job kill
  11125. * Converting to pgrp / pid kill
  11126. */
  11127. pi = parse_jobspec(argv[i]);
  11128. if (!pi) {
  11129. /* Eat bad jobspec */
  11130. j = i;
  11131. do {
  11132. j++;
  11133. argv[j - 1] = argv[j];
  11134. } while (argv[j]);
  11135. ret = 1;
  11136. i--;
  11137. continue;
  11138. }
  11139. /*
  11140. * In jobs started under job control, we signal
  11141. * entire process group by kill -PGRP_ID.
  11142. * This happens, f.e., in interactive shell.
  11143. *
  11144. * Otherwise, we signal each child via
  11145. * kill PID1 PID2 PID3.
  11146. * Testcases:
  11147. * sh -c 'sleep 1|sleep 1 & kill %1'
  11148. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  11149. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  11150. */
  11151. n = G_interactive_fd ? 1 : pi->num_cmds;
  11152. dst = alloca(n * sizeof(int)*4);
  11153. argv[i] = dst;
  11154. if (G_interactive_fd)
  11155. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  11156. else for (j = 0; j < n; j++) {
  11157. struct command *cmd = &pi->cmds[j];
  11158. /* Skip exited members of the job */
  11159. if (cmd->pid == 0)
  11160. continue;
  11161. /*
  11162. * kill_main has matching code to expect
  11163. * leading space. Needed to not confuse
  11164. * negative pids with "kill -SIGNAL_NO" syntax
  11165. */
  11166. dst += sprintf(dst, " %u", (int)cmd->pid);
  11167. }
  11168. *dst = '\0';
  11169. } while (argv[++i]);
  11170. }
  11171. # endif
  11172. if (argv[1] || ret == 0) {
  11173. ret = run_applet_main(argv, kill_main);
  11174. }
  11175. /* else: ret = 1, "kill %bad_jobspec" case */
  11176. return ret;
  11177. }
  11178. #endif
  11179. #if ENABLE_HUSH_WAIT
  11180. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  11181. # if !ENABLE_HUSH_JOB
  11182. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  11183. # endif
  11184. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  11185. {
  11186. int ret = 0;
  11187. for (;;) {
  11188. int sig;
  11189. sigset_t oldset;
  11190. if (!sigisemptyset(&G.pending_set))
  11191. goto check_sig;
  11192. /* waitpid is not interruptible by SA_RESTARTed
  11193. * signals which we use. Thus, this ugly dance:
  11194. */
  11195. /* Make sure possible SIGCHLD is stored in kernel's
  11196. * pending signal mask before we call waitpid.
  11197. * Or else we may race with SIGCHLD, lose it,
  11198. * and get stuck in sigsuspend...
  11199. */
  11200. sigfillset(&oldset); /* block all signals, remember old set */
  11201. sigprocmask2(SIG_SETMASK, &oldset);
  11202. if (!sigisemptyset(&G.pending_set)) {
  11203. /* Crap! we raced with some signal! */
  11204. goto restore;
  11205. }
  11206. /*errno = 0; - checkjobs does this */
  11207. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  11208. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  11209. debug_printf_exec("checkjobs:%d\n", ret);
  11210. # if ENABLE_HUSH_JOB
  11211. if (waitfor_pipe) {
  11212. int rcode = job_exited_or_stopped(waitfor_pipe);
  11213. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  11214. if (rcode >= 0) {
  11215. ret = rcode;
  11216. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11217. break;
  11218. }
  11219. }
  11220. # endif
  11221. /* if ECHILD, there are no children (ret is -1 or 0) */
  11222. /* if ret == 0, no children changed state */
  11223. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  11224. if (errno == ECHILD || ret) {
  11225. ret--;
  11226. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  11227. ret = 0;
  11228. # if ENABLE_HUSH_BASH_COMPAT
  11229. if (waitfor_pid == -1 && errno == ECHILD) {
  11230. /* exitcode of "wait -n" with no children is 127, not 0 */
  11231. ret = 127;
  11232. }
  11233. # endif
  11234. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11235. break;
  11236. }
  11237. /* Wait for SIGCHLD or any other signal */
  11238. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  11239. /* Note: sigsuspend invokes signal handler */
  11240. sigsuspend(&oldset);
  11241. /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
  11242. * to make sure SIGCHLD is not masked off?
  11243. * It was reported that this:
  11244. * fn() { : | return; }
  11245. * shopt -s lastpipe
  11246. * fn
  11247. * exec hush SCRIPT
  11248. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  11249. * making "wait" commands in SCRIPT block forever.
  11250. */
  11251. restore:
  11252. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11253. check_sig:
  11254. /* So, did we get a signal? */
  11255. sig = check_and_run_traps();
  11256. if (sig /*&& sig != SIGCHLD - always true */) {
  11257. /* Do this for any (non-ignored) signal, not only for ^C */
  11258. ret = 128 | sig;
  11259. break;
  11260. }
  11261. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  11262. }
  11263. return ret;
  11264. }
  11265. static int FAST_FUNC builtin_wait(char **argv)
  11266. {
  11267. int ret;
  11268. int status;
  11269. argv = skip_dash_dash(argv);
  11270. # if ENABLE_HUSH_BASH_COMPAT
  11271. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  11272. /* wait -n */
  11273. /* (bash accepts "wait -n PID" too and ignores PID) */
  11274. G.dead_job_exitcode = -1;
  11275. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  11276. }
  11277. # endif
  11278. if (argv[0] == NULL) {
  11279. /* Don't care about wait results */
  11280. /* Note 1: must wait until there are no more children */
  11281. /* Note 2: must be interruptible */
  11282. /* Examples:
  11283. * $ sleep 3 & sleep 6 & wait
  11284. * [1] 30934 sleep 3
  11285. * [2] 30935 sleep 6
  11286. * [1] Done sleep 3
  11287. * [2] Done sleep 6
  11288. * $ sleep 3 & sleep 6 & wait
  11289. * [1] 30936 sleep 3
  11290. * [2] 30937 sleep 6
  11291. * [1] Done sleep 3
  11292. * ^C <-- after ~4 sec from keyboard
  11293. * $
  11294. */
  11295. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  11296. }
  11297. do {
  11298. pid_t pid = bb_strtou(*argv, NULL, 10);
  11299. if (errno || pid <= 0) {
  11300. # if ENABLE_HUSH_JOB
  11301. if (argv[0][0] == '%') {
  11302. struct pipe *wait_pipe;
  11303. ret = 127; /* bash compat for bad jobspecs */
  11304. wait_pipe = parse_jobspec(*argv);
  11305. if (wait_pipe) {
  11306. ret = job_exited_or_stopped(wait_pipe);
  11307. if (ret < 0) {
  11308. ret = wait_for_child_or_signal(wait_pipe, 0);
  11309. } else {
  11310. /* waiting on "last dead job" removes it */
  11311. clean_up_last_dead_job();
  11312. }
  11313. }
  11314. /* else: parse_jobspec() already emitted error msg */
  11315. continue;
  11316. }
  11317. # endif
  11318. /* mimic bash message */
  11319. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  11320. ret = EXIT_FAILURE;
  11321. continue; /* bash checks all argv[] */
  11322. }
  11323. /* Do we have such child? */
  11324. ret = waitpid(pid, &status, WNOHANG);
  11325. if (ret < 0) {
  11326. /* No */
  11327. ret = 127;
  11328. if (errno == ECHILD) {
  11329. if (pid == G.last_bg_pid) {
  11330. /* "wait $!" but last bg task has already exited. Try:
  11331. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  11332. * In bash it prints exitcode 0, then 3.
  11333. * In dash, it is 127.
  11334. */
  11335. ret = G.last_bg_pid_exitcode;
  11336. } else {
  11337. /* Example: "wait 1". mimic bash message */
  11338. bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
  11339. }
  11340. } else {
  11341. /* ??? */
  11342. bb_perror_msg("wait %s", *argv);
  11343. }
  11344. continue; /* bash checks all argv[] */
  11345. }
  11346. if (ret == 0) {
  11347. /* Yes, and it still runs */
  11348. ret = wait_for_child_or_signal(NULL, pid);
  11349. } else {
  11350. /* Yes, and it just exited */
  11351. process_wait_result(NULL, pid, status);
  11352. ret = WEXITSTATUS(status);
  11353. if (WIFSIGNALED(status))
  11354. ret = 128 | WTERMSIG(status);
  11355. }
  11356. } while (*++argv);
  11357. return ret;
  11358. }
  11359. #endif
  11360. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  11361. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  11362. {
  11363. if (argv[1]) {
  11364. def = bb_strtou(argv[1], NULL, 10);
  11365. if (errno || def < def_min || argv[2]) {
  11366. bb_error_msg("%s: bad arguments", argv[0]);
  11367. def = UINT_MAX;
  11368. }
  11369. }
  11370. return def;
  11371. }
  11372. #endif
  11373. #if ENABLE_HUSH_LOOPS
  11374. static int FAST_FUNC builtin_break(char **argv)
  11375. {
  11376. unsigned depth;
  11377. if (G.depth_of_loop == 0) {
  11378. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  11379. /* if we came from builtin_continue(), need to undo "= 1" */
  11380. G.flag_break_continue = 0;
  11381. return EXIT_SUCCESS; /* bash compat */
  11382. }
  11383. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  11384. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  11385. if (depth == UINT_MAX)
  11386. G.flag_break_continue = BC_BREAK;
  11387. if (G.depth_of_loop < depth)
  11388. G.depth_break_continue = G.depth_of_loop;
  11389. return EXIT_SUCCESS;
  11390. }
  11391. static int FAST_FUNC builtin_continue(char **argv)
  11392. {
  11393. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  11394. return builtin_break(argv);
  11395. }
  11396. #endif
  11397. #if ENABLE_HUSH_FUNCTIONS
  11398. static int FAST_FUNC builtin_return(char **argv)
  11399. {
  11400. int rc;
  11401. if (G_flag_return_in_progress != -1) {
  11402. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  11403. return EXIT_FAILURE; /* bash compat */
  11404. }
  11405. G_flag_return_in_progress = 1;
  11406. /* bash:
  11407. * out of range: wraps around at 256, does not error out
  11408. * non-numeric param:
  11409. * f() { false; return qwe; }; f; echo $?
  11410. * bash: return: qwe: numeric argument required <== we do this
  11411. * 255 <== we also do this
  11412. */
  11413. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  11414. # if ENABLE_HUSH_TRAP
  11415. if (argv[1]) { /* "return ARG" inside a running trap sets $? */
  11416. debug_printf_exec("G.return_exitcode=%d\n", rc);
  11417. G.return_exitcode = rc;
  11418. }
  11419. # endif
  11420. return rc;
  11421. }
  11422. #endif
  11423. #if ENABLE_HUSH_TIMES
  11424. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  11425. {
  11426. static const uint8_t times_tbl[] ALIGN1 = {
  11427. ' ', offsetof(struct tms, tms_utime),
  11428. '\n', offsetof(struct tms, tms_stime),
  11429. ' ', offsetof(struct tms, tms_cutime),
  11430. '\n', offsetof(struct tms, tms_cstime),
  11431. 0
  11432. };
  11433. const uint8_t *p;
  11434. unsigned clk_tck;
  11435. struct tms buf;
  11436. clk_tck = bb_clk_tck();
  11437. times(&buf);
  11438. p = times_tbl;
  11439. do {
  11440. unsigned sec, frac;
  11441. unsigned long t;
  11442. t = *(clock_t *)(((char *) &buf) + p[1]);
  11443. sec = t / clk_tck;
  11444. frac = t % clk_tck;
  11445. printf("%um%u.%03us%c",
  11446. sec / 60, sec % 60,
  11447. (frac * 1000) / clk_tck,
  11448. p[0]);
  11449. p += 2;
  11450. } while (*p);
  11451. return EXIT_SUCCESS;
  11452. }
  11453. #endif
  11454. #if ENABLE_HUSH_MEMLEAK
  11455. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  11456. {
  11457. void *p;
  11458. unsigned long l;
  11459. # ifdef M_TRIM_THRESHOLD
  11460. /* Optional. Reduces probability of false positives */
  11461. malloc_trim(0);
  11462. # endif
  11463. /* Crude attempt to find where "free memory" starts,
  11464. * sans fragmentation. */
  11465. p = malloc(240);
  11466. l = (unsigned long)p;
  11467. free(p);
  11468. p = malloc(3400);
  11469. if (l < (unsigned long)p) l = (unsigned long)p;
  11470. free(p);
  11471. # if 0 /* debug */
  11472. {
  11473. struct mallinfo mi = mallinfo();
  11474. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  11475. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  11476. }
  11477. # endif
  11478. if (!G.memleak_value)
  11479. G.memleak_value = l;
  11480. l -= G.memleak_value;
  11481. if ((long)l < 0)
  11482. l = 0;
  11483. l /= 1024;
  11484. if (l > 127)
  11485. l = 127;
  11486. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  11487. return l;
  11488. }
  11489. #endif