hush.c 340 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329
  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. pi = ctx.list_head;
  5153. /* If we got nothing... */
  5154. /* (this makes bare "&" cmd a no-op.
  5155. * bash says: "syntax error near unexpected token '&'") */
  5156. if (pi->num_cmds == 0
  5157. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  5158. ) {
  5159. free_pipe_list(pi);
  5160. pi = NULL;
  5161. }
  5162. #if !BB_MMU
  5163. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  5164. if (pstring)
  5165. *pstring = ctx.as_string.data;
  5166. else
  5167. o_free(&ctx.as_string);
  5168. #endif
  5169. // heredoc_cnt must be 0 here anyway
  5170. //if (heredoc_cnt_ptr)
  5171. // *heredoc_cnt_ptr = heredoc_cnt;
  5172. debug_leave();
  5173. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5174. debug_printf_parse("parse_stream return %p\n", pi);
  5175. return pi;
  5176. }
  5177. /* Handle "'" and "\" first, as they won't play nice with
  5178. * i_peek_and_eat_bkslash_nl() anyway:
  5179. * echo z\\
  5180. * and
  5181. * echo '\
  5182. * '
  5183. * would break.
  5184. */
  5185. if (ch == '\\') {
  5186. ch = i_getch(input);
  5187. if (ch == '\n')
  5188. continue; /* drop \<newline>, get next char */
  5189. nommu_addchr(&ctx.as_string, '\\');
  5190. if (ch == SPECIAL_VAR_SYMBOL) {
  5191. nommu_addchr(&ctx.as_string, ch);
  5192. /* Convert \^C to corresponding special variable reference */
  5193. goto case_SPECIAL_VAR_SYMBOL;
  5194. }
  5195. o_addchr(&ctx.word, '\\');
  5196. if (ch == EOF) {
  5197. /* Testcase: eval 'echo Ok\' */
  5198. /* bash-4.3.43 was removing backslash,
  5199. * but 4.4.19 retains it, most other shells too
  5200. */
  5201. continue; /* get next char */
  5202. }
  5203. /* Example: echo Hello \2>file
  5204. * we need to know that word 2 is quoted
  5205. */
  5206. ctx.word.has_quoted_part = 1;
  5207. nommu_addchr(&ctx.as_string, ch);
  5208. o_addchr(&ctx.word, ch);
  5209. continue; /* get next char */
  5210. }
  5211. nommu_addchr(&ctx.as_string, ch);
  5212. if (ch == '\'') {
  5213. ctx.word.has_quoted_part = 1;
  5214. next = i_getch(input);
  5215. if (next == '\'' && !ctx.pending_redirect)
  5216. goto insert_empty_quoted_str_marker;
  5217. ch = next;
  5218. while (1) {
  5219. if (ch == EOF) {
  5220. syntax_error_unterm_ch('\'');
  5221. goto parse_error_exitcode1;
  5222. }
  5223. nommu_addchr(&ctx.as_string, ch);
  5224. if (ch == '\'')
  5225. break;
  5226. if (ch == SPECIAL_VAR_SYMBOL) {
  5227. /* Convert raw ^C to corresponding special variable reference */
  5228. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5229. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5230. }
  5231. o_addqchr(&ctx.word, ch);
  5232. ch = i_getch(input);
  5233. }
  5234. continue; /* get next char */
  5235. }
  5236. next = '\0';
  5237. if (ch != '\n')
  5238. next = i_peek_and_eat_bkslash_nl(input);
  5239. is_special = "{}<>&|();#" /* special outside of "str" */
  5240. "$\"" IF_HUSH_TICK("`") /* always special */
  5241. SPECIAL_VAR_SYMBOL_STR;
  5242. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  5243. if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
  5244. /* In [[ ]], {}<>&|() are not special */
  5245. is_special += 8;
  5246. } else
  5247. #endif
  5248. /* Are { and } special here? */
  5249. if (ctx.command->argv /* word [word]{... - non-special */
  5250. || ctx.word.length /* word{... - non-special */
  5251. || ctx.word.has_quoted_part /* ""{... - non-special */
  5252. || (next != ';' /* }; - special */
  5253. && next != ')' /* }) - special */
  5254. && next != '(' /* {( - special */
  5255. && next != '&' /* }& and }&& ... - special */
  5256. && next != '|' /* }|| ... - special */
  5257. && !strchr(defifs, next) /* {word - non-special */
  5258. )
  5259. ) {
  5260. /* They are not special, skip "{}" */
  5261. is_special += 2;
  5262. }
  5263. is_special = strchr(is_special, ch);
  5264. is_blank = strchr(defifs, ch);
  5265. if (!is_special && !is_blank) { /* ordinary char */
  5266. ordinary_char:
  5267. o_addQchr(&ctx.word, ch);
  5268. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5269. || ctx.is_assignment == WORD_IS_KEYWORD)
  5270. && ch == '='
  5271. && endofname(ctx.word.data)[0] == '='
  5272. ) {
  5273. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5274. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5275. }
  5276. continue;
  5277. }
  5278. if (is_blank) {
  5279. #if ENABLE_HUSH_LINENO_VAR
  5280. /* Case:
  5281. * "while ...; do<whitespace><newline>
  5282. * cmd ..."
  5283. * would think that "cmd" starts in <whitespace> -
  5284. * i.e., at the previous line.
  5285. * We need to skip all whitespace before newlines.
  5286. */
  5287. while (ch != '\n') {
  5288. next = i_peek(input);
  5289. if (next != ' ' && next != '\t' && next != '\n')
  5290. break; /* next char is not ws */
  5291. ch = i_getch(input);
  5292. }
  5293. /* ch == last eaten whitespace char */
  5294. #endif
  5295. if (done_word(&ctx)) {
  5296. goto parse_error_exitcode1;
  5297. }
  5298. if (ch == '\n') {
  5299. /* Is this a case when newline is simply ignored?
  5300. * Some examples:
  5301. * "cmd | <newline> cmd ..."
  5302. * "case ... in <newline> word) ..."
  5303. */
  5304. if (IS_NULL_CMD(ctx.command)
  5305. && ctx.word.length == 0
  5306. && !ctx.word.has_quoted_part
  5307. && heredoc_cnt == 0
  5308. ) {
  5309. /* This newline can be ignored. But...
  5310. * Without check #1, interactive shell
  5311. * ignores even bare <newline>,
  5312. * and shows the continuation prompt:
  5313. * ps1_prompt$ <enter>
  5314. * ps2> _ <=== wrong, should be ps1
  5315. * Without check #2, "cmd & <newline>"
  5316. * is similarly mistreated.
  5317. * (BTW, this makes "cmd & cmd"
  5318. * and "cmd && cmd" non-orthogonal.
  5319. * Really, ask yourself, why
  5320. * "cmd && <newline>" doesn't start
  5321. * cmd but waits for more input?
  5322. * The only reason is that it might be
  5323. * a "cmd1 && <nl> cmd2 &" construct,
  5324. * cmd1 may need to run in BG).
  5325. */
  5326. struct pipe *pi = ctx.list_head;
  5327. if (pi->num_cmds != 0 /* check #1 */
  5328. && pi->followup != PIPE_BG /* check #2 */
  5329. ) {
  5330. continue;
  5331. }
  5332. }
  5333. /* Treat newline as a command separator. */
  5334. done_pipe(&ctx, PIPE_SEQ);
  5335. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5336. if (heredoc_cnt) {
  5337. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5338. if (heredoc_cnt != 0)
  5339. goto parse_error_exitcode1;
  5340. }
  5341. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5342. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5343. ch = ';';
  5344. /* note: if (is_blank) continue;
  5345. * will still trigger for us */
  5346. }
  5347. }
  5348. /* "cmd}" or "cmd }..." without semicolon or &:
  5349. * } is an ordinary char in this case, even inside { cmd; }
  5350. * Pathological example: { ""}; } should exec "}" cmd
  5351. */
  5352. if (ch == '}') {
  5353. if (ctx.word.length != 0 /* word} */
  5354. || ctx.word.has_quoted_part /* ""} */
  5355. ) {
  5356. goto ordinary_char;
  5357. }
  5358. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5359. /* Generally, there should be semicolon: "cmd; }"
  5360. * However, bash allows to omit it if "cmd" is
  5361. * a group. Examples:
  5362. * { { echo 1; } }
  5363. * {(echo 1)}
  5364. * { echo 0 >&2 | { echo 1; } }
  5365. * { while false; do :; done }
  5366. * { case a in b) ;; esac }
  5367. */
  5368. if (ctx.command->group)
  5369. goto term_group;
  5370. goto ordinary_char;
  5371. }
  5372. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5373. /* Can't be an end of {cmd}, skip the check */
  5374. goto skip_end_trigger;
  5375. /* else: } does terminate a group */
  5376. }
  5377. term_group:
  5378. if (end_trigger && end_trigger == ch
  5379. && (ch != ';' || heredoc_cnt == 0)
  5380. #if ENABLE_HUSH_CASE
  5381. && (ch != ')'
  5382. || ctx.ctx_res_w != RES_MATCH
  5383. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5384. )
  5385. #endif
  5386. ) {
  5387. if (done_word(&ctx)) {
  5388. goto parse_error_exitcode1;
  5389. }
  5390. done_pipe(&ctx, PIPE_SEQ);
  5391. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5392. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5393. /* Do we sit outside of any if's, loops or case's? */
  5394. if (!HAS_KEYWORDS
  5395. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5396. ) {
  5397. o_free_and_set_NULL(&ctx.word);
  5398. #if !BB_MMU
  5399. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5400. if (pstring)
  5401. *pstring = ctx.as_string.data;
  5402. else
  5403. o_free(&ctx.as_string);
  5404. #endif
  5405. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5406. /* Example: bare "{ }", "()" */
  5407. G.last_exitcode = 2; /* bash compat */
  5408. syntax_error_unexpected_ch(ch);
  5409. goto parse_error;
  5410. }
  5411. if (heredoc_cnt_ptr)
  5412. *heredoc_cnt_ptr = heredoc_cnt;
  5413. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5414. debug_printf_parse("parse_stream return %p: "
  5415. "end_trigger char found\n",
  5416. ctx.list_head);
  5417. debug_leave();
  5418. return ctx.list_head;
  5419. }
  5420. }
  5421. if (is_blank)
  5422. continue;
  5423. /* Catch <, > before deciding whether this word is
  5424. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5425. switch (ch) {
  5426. case '>':
  5427. redir_fd = redirect_opt_num(&ctx.word);
  5428. if (done_word(&ctx)) {
  5429. goto parse_error_exitcode1;
  5430. }
  5431. redir_style = REDIRECT_OVERWRITE;
  5432. if (next == '>') {
  5433. redir_style = REDIRECT_APPEND;
  5434. ch = i_getch(input);
  5435. nommu_addchr(&ctx.as_string, ch);
  5436. }
  5437. #if 0
  5438. else if (next == '(') {
  5439. syntax_error(">(process) not supported");
  5440. goto parse_error_exitcode1;
  5441. }
  5442. #endif
  5443. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5444. goto parse_error_exitcode1;
  5445. continue; /* get next char */
  5446. case '<':
  5447. redir_fd = redirect_opt_num(&ctx.word);
  5448. if (done_word(&ctx)) {
  5449. goto parse_error_exitcode1;
  5450. }
  5451. redir_style = REDIRECT_INPUT;
  5452. if (next == '<') {
  5453. redir_style = REDIRECT_HEREDOC;
  5454. heredoc_cnt++;
  5455. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5456. ch = i_getch(input);
  5457. nommu_addchr(&ctx.as_string, ch);
  5458. } else if (next == '>') {
  5459. redir_style = REDIRECT_IO;
  5460. ch = i_getch(input);
  5461. nommu_addchr(&ctx.as_string, ch);
  5462. }
  5463. #if 0
  5464. else if (next == '(') {
  5465. syntax_error("<(process) not supported");
  5466. goto parse_error_exitcode1;
  5467. }
  5468. #endif
  5469. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5470. goto parse_error_exitcode1;
  5471. continue; /* get next char */
  5472. case '#':
  5473. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5474. /* skip "#comment" */
  5475. /* note: we do not add it to &ctx.as_string */
  5476. /* TODO: in bash:
  5477. * comment inside $() goes to the next \n, even inside quoted string (!):
  5478. * cmd "$(cmd2 #comment)" - syntax error
  5479. * cmd "`cmd2 #comment`" - ok
  5480. * We accept both (comment ends where command subst ends, in both cases).
  5481. */
  5482. while (1) {
  5483. ch = i_peek(input);
  5484. if (ch == '\n') {
  5485. nommu_addchr(&ctx.as_string, '\n');
  5486. break;
  5487. }
  5488. ch = i_getch(input);
  5489. if (ch == EOF)
  5490. break;
  5491. }
  5492. continue; /* get next char */
  5493. }
  5494. break;
  5495. }
  5496. skip_end_trigger:
  5497. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5498. /* check that we are not in word in "a=1 2>word b=1": */
  5499. && !ctx.pending_redirect
  5500. ) {
  5501. /* ch is a special char and thus this word
  5502. * cannot be an assignment */
  5503. ctx.is_assignment = NOT_ASSIGNMENT;
  5504. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5505. }
  5506. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5507. switch (ch) {
  5508. case_SPECIAL_VAR_SYMBOL:
  5509. case SPECIAL_VAR_SYMBOL:
  5510. /* Convert raw ^C to corresponding special variable reference */
  5511. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5512. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5513. /* fall through */
  5514. case '#':
  5515. /* non-comment #: "echo a#b" etc */
  5516. o_addchr(&ctx.word, ch);
  5517. continue; /* get next char */
  5518. case '$':
  5519. if (parse_dollar_squote(&ctx.as_string, &ctx.word, input))
  5520. continue; /* get next char */
  5521. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5522. debug_printf_parse("parse_stream parse error: "
  5523. "parse_dollar returned 0 (error)\n");
  5524. goto parse_error_exitcode1;
  5525. }
  5526. continue; /* get next char */
  5527. case '"':
  5528. ctx.word.has_quoted_part = 1;
  5529. if (next == '"' && !ctx.pending_redirect) {
  5530. i_getch(input); /* eat second " */
  5531. insert_empty_quoted_str_marker:
  5532. nommu_addchr(&ctx.as_string, next);
  5533. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5534. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5535. continue; /* get next char */
  5536. }
  5537. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5538. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5539. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5540. goto parse_error_exitcode1;
  5541. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5542. continue; /* get next char */
  5543. #if ENABLE_HUSH_TICK
  5544. case '`': {
  5545. USE_FOR_NOMMU(unsigned pos;)
  5546. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5547. o_addchr(&ctx.word, '`');
  5548. USE_FOR_NOMMU(pos = ctx.word.length;)
  5549. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5550. goto parse_error_exitcode1;
  5551. # if !BB_MMU
  5552. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5553. o_addchr(&ctx.as_string, '`');
  5554. # endif
  5555. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5556. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5557. continue; /* get next char */
  5558. }
  5559. #endif
  5560. case ';':
  5561. #if ENABLE_HUSH_CASE
  5562. case_semi:
  5563. #endif
  5564. if (done_word(&ctx)) {
  5565. goto parse_error_exitcode1;
  5566. }
  5567. done_pipe(&ctx, PIPE_SEQ);
  5568. #if ENABLE_HUSH_CASE
  5569. /* Eat multiple semicolons, detect
  5570. * whether it means something special */
  5571. while (1) {
  5572. ch = i_peek_and_eat_bkslash_nl(input);
  5573. if (ch != ';')
  5574. break;
  5575. ch = i_getch(input);
  5576. nommu_addchr(&ctx.as_string, ch);
  5577. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5578. ctx.ctx_dsemicolon = 1;
  5579. ctx.ctx_res_w = RES_MATCH;
  5580. break;
  5581. }
  5582. }
  5583. #endif
  5584. new_cmd:
  5585. /* We just finished a cmd. New one may start
  5586. * with an assignment */
  5587. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5588. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5589. continue; /* get next char */
  5590. case '&':
  5591. if (done_word(&ctx)) {
  5592. goto parse_error_exitcode1;
  5593. }
  5594. if (next == '&') {
  5595. ch = i_getch(input);
  5596. nommu_addchr(&ctx.as_string, ch);
  5597. done_pipe(&ctx, PIPE_AND);
  5598. } else {
  5599. done_pipe(&ctx, PIPE_BG);
  5600. }
  5601. goto new_cmd;
  5602. case '|':
  5603. if (done_word(&ctx)) {
  5604. goto parse_error_exitcode1;
  5605. }
  5606. #if ENABLE_HUSH_CASE
  5607. if (ctx.ctx_res_w == RES_MATCH)
  5608. break; /* we are in case's "word | word)" */
  5609. #endif
  5610. if (next == '|') { /* || */
  5611. ch = i_getch(input);
  5612. nommu_addchr(&ctx.as_string, ch);
  5613. done_pipe(&ctx, PIPE_OR);
  5614. } else {
  5615. /* we could pick up a file descriptor choice here
  5616. * with redirect_opt_num(), but bash doesn't do it.
  5617. * "echo foo 2| cat" yields "foo 2". */
  5618. done_command(&ctx);
  5619. }
  5620. goto new_cmd;
  5621. case '(':
  5622. #if ENABLE_HUSH_CASE
  5623. /* "case... in [(]word)..." - skip '(' */
  5624. if (ctx.ctx_res_w == RES_MATCH
  5625. && ctx.command->argv == NULL /* not (word|(... */
  5626. && ctx.word.length == 0 /* not word(... */
  5627. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5628. ) {
  5629. continue; /* get next char */
  5630. }
  5631. #endif
  5632. /* fall through */
  5633. case '{': {
  5634. int n = parse_group(&ctx, input, ch);
  5635. if (n < 0) {
  5636. goto parse_error_exitcode1;
  5637. }
  5638. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5639. heredoc_cnt += n;
  5640. goto new_cmd;
  5641. }
  5642. case ')':
  5643. #if ENABLE_HUSH_CASE
  5644. if (ctx.ctx_res_w == RES_MATCH)
  5645. goto case_semi;
  5646. #endif
  5647. case '}':
  5648. /* proper use of this character is caught by end_trigger:
  5649. * if we see {, we call parse_group(..., end_trigger='}')
  5650. * and it will match } earlier (not here). */
  5651. G.last_exitcode = 2;
  5652. syntax_error_unexpected_ch(ch);
  5653. goto parse_error;
  5654. default:
  5655. if (HUSH_DEBUG)
  5656. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5657. }
  5658. } /* while (1) */
  5659. parse_error_exitcode1:
  5660. G.last_exitcode = 1;
  5661. parse_error:
  5662. {
  5663. struct parse_context *pctx;
  5664. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5665. /* Clean up allocated tree.
  5666. * Sample for finding leaks on syntax error recovery path.
  5667. * Run it from interactive shell, watch pmap `pidof hush`.
  5668. * while if false; then false; fi; do break; fi
  5669. * Samples to catch leaks at execution:
  5670. * while if (true | { true;}); then echo ok; fi; do break; done
  5671. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5672. */
  5673. pctx = &ctx;
  5674. do {
  5675. /* Update pipe/command counts,
  5676. * otherwise freeing may miss some */
  5677. done_pipe(pctx, PIPE_SEQ);
  5678. debug_printf_clean("freeing list %p from ctx %p\n",
  5679. pctx->list_head, pctx);
  5680. debug_print_tree(pctx->list_head, 0);
  5681. free_pipe_list(pctx->list_head);
  5682. debug_printf_clean("freed list %p\n", pctx->list_head);
  5683. #if !BB_MMU
  5684. o_free(&pctx->as_string);
  5685. #endif
  5686. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5687. if (pctx != &ctx) {
  5688. free(pctx);
  5689. }
  5690. IF_HAS_KEYWORDS(pctx = p2;)
  5691. } while (HAS_KEYWORDS && pctx);
  5692. o_free(&ctx.word);
  5693. #if !BB_MMU
  5694. if (pstring)
  5695. *pstring = NULL;
  5696. #endif
  5697. debug_leave();
  5698. return ERR_PTR;
  5699. }
  5700. }
  5701. /*** Execution routines ***/
  5702. /* Expansion can recurse, need forward decls: */
  5703. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5704. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5705. expand_string_to_string(str)
  5706. #endif
  5707. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5708. #if ENABLE_HUSH_TICK
  5709. static int process_command_subs(o_string *dest, const char *s);
  5710. #endif
  5711. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5712. /* expand_strvec_to_strvec() takes a list of strings, expands
  5713. * all variable references within and returns a pointer to
  5714. * a list of expanded strings, possibly with larger number
  5715. * of strings. (Think VAR="a b"; echo $VAR).
  5716. * This new list is allocated as a single malloc block.
  5717. * NULL-terminated list of char* pointers is at the beginning of it,
  5718. * followed by strings themselves.
  5719. * Caller can deallocate entire list by single free(list). */
  5720. /* A horde of its helpers come first: */
  5721. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5722. {
  5723. while (--len >= 0) {
  5724. char c = *str++;
  5725. #if ENABLE_HUSH_BRACE_EXPANSION
  5726. if (c == '{' || c == '}') {
  5727. /* { -> \{, } -> \} */
  5728. o_addchr(o, '\\');
  5729. /* And now we want to add { or } and continue:
  5730. * o_addchr(o, c);
  5731. * continue;
  5732. * luckily, just falling through achieves this.
  5733. */
  5734. }
  5735. #endif
  5736. o_addchr(o, c);
  5737. if (c == '\\') {
  5738. /* \z -> \\\z; \<eol> -> \\<eol> */
  5739. o_addchr(o, '\\');
  5740. if (len) {
  5741. len--;
  5742. o_addchr(o, '\\');
  5743. o_addchr(o, *str++);
  5744. }
  5745. }
  5746. }
  5747. }
  5748. /* Store given string, finalizing the word and starting new one whenever
  5749. * we encounter IFS char(s). This is used for expanding variable values.
  5750. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5751. * Return in output->ended_in_ifs:
  5752. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5753. */
  5754. static int expand_on_ifs(o_string *output, int n, const char *str)
  5755. {
  5756. int last_is_ifs = 0;
  5757. while (1) {
  5758. int word_len;
  5759. if (!*str) /* EOL - do not finalize word */
  5760. break;
  5761. word_len = strcspn(str, G.ifs);
  5762. if (word_len) {
  5763. /* We have WORD_LEN leading non-IFS chars */
  5764. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5765. o_addblock(output, str, word_len);
  5766. } else {
  5767. /* Protect backslashes against globbing up :)
  5768. * Example: "v='\*'; echo b$v" prints "b\*"
  5769. * (and does not try to glob on "*")
  5770. */
  5771. o_addblock_duplicate_backslash(output, str, word_len);
  5772. /*/ Why can't we do it easier? */
  5773. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5774. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5775. }
  5776. last_is_ifs = 0;
  5777. str += word_len;
  5778. if (!*str) /* EOL - do not finalize word */
  5779. break;
  5780. }
  5781. /* We know str here points to at least one IFS char */
  5782. last_is_ifs = 1;
  5783. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5784. if (!*str) /* EOL - do not finalize word */
  5785. break;
  5786. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5787. && strchr(G.ifs, *str) /* the second check would fail */
  5788. ) {
  5789. /* This is a non-whitespace $IFS char */
  5790. /* Skip it and IFS whitespace chars, start new word */
  5791. str++;
  5792. str += strspn(str, G.ifs_whitespace);
  5793. goto new_word;
  5794. }
  5795. /* Start new word... but not always! */
  5796. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5797. if (output->has_quoted_part
  5798. /*
  5799. * Case "v=' a'; echo $v":
  5800. * here nothing precedes the space in $v expansion,
  5801. * therefore we should not finish the word
  5802. * (IOW: if there *is* word to finalize, only then do it):
  5803. * It's okay if this accesses the byte before first argv[]:
  5804. * past call to o_save_ptr() cleared it to zero byte
  5805. * (grep for -prev-ifs-check-).
  5806. */
  5807. || output->data[output->length - 1]
  5808. ) {
  5809. new_word:
  5810. o_addchr(output, '\0');
  5811. debug_print_list("expand_on_ifs", output, n);
  5812. n = o_save_ptr(output, n);
  5813. }
  5814. }
  5815. output->ended_in_ifs = last_is_ifs;
  5816. debug_print_list("expand_on_ifs[1]", output, n);
  5817. return n;
  5818. }
  5819. /* Helper to expand $((...)) and heredoc body. These act as if
  5820. * they are in double quotes, with the exception that they are not :).
  5821. * Just the rules are similar: "expand only $var and `cmd`"
  5822. *
  5823. * Returns malloced string.
  5824. * As an optimization, we return NULL if expansion is not needed.
  5825. */
  5826. static char *encode_then_expand_string(const char *str)
  5827. {
  5828. char *exp_str;
  5829. struct in_str input;
  5830. o_string dest = NULL_O_STRING;
  5831. const char *cp;
  5832. cp = str;
  5833. for (;;) {
  5834. if (!*cp) return NULL; /* string has no special chars */
  5835. if (*cp == '$') break;
  5836. if (*cp == '\\') break;
  5837. #if ENABLE_HUSH_TICK
  5838. if (*cp == '`') break;
  5839. #endif
  5840. cp++;
  5841. }
  5842. /* We need to expand. Example:
  5843. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5844. */
  5845. setup_string_in_str(&input, str);
  5846. encode_string(NULL, &dest, &input, EOF);
  5847. //TODO: error check (encode_string returns 0 on error)?
  5848. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5849. exp_str = expand_string_to_string(dest.data,
  5850. EXP_FLAG_ESC_GLOB_CHARS,
  5851. /*unbackslash:*/ 1
  5852. );
  5853. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5854. o_free(&dest);
  5855. return exp_str;
  5856. }
  5857. static const char *first_special_char_in_vararg(const char *cp)
  5858. {
  5859. for (;;) {
  5860. if (!*cp) return NULL; /* string has no special chars */
  5861. if (*cp == '$') return cp;
  5862. if (*cp == '\\') return cp;
  5863. if (*cp == '\'') return cp;
  5864. if (*cp == '"') return cp;
  5865. #if ENABLE_HUSH_TICK
  5866. if (*cp == '`') return cp;
  5867. #endif
  5868. /* dquoted "${x:+ARG}" should not glob, therefore
  5869. * '*' et al require some non-literal processing: */
  5870. if (*cp == '*') return cp;
  5871. if (*cp == '?') return cp;
  5872. if (*cp == '[') return cp;
  5873. cp++;
  5874. }
  5875. }
  5876. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5877. * These can contain single- and double-quoted strings,
  5878. * and treated as if the ARG string is initially unquoted. IOW:
  5879. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5880. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5881. * (word splitting and globbing of the ${var...} result).
  5882. */
  5883. #if !BASH_PATTERN_SUBST
  5884. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5885. encode_then_expand_vararg(str, handle_squotes)
  5886. #endif
  5887. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5888. {
  5889. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5890. const int do_unbackslash = 0;
  5891. #endif
  5892. char *exp_str;
  5893. struct in_str input;
  5894. o_string dest = NULL_O_STRING;
  5895. if (!first_special_char_in_vararg(str)) {
  5896. /* string has no special chars */
  5897. return NULL;
  5898. }
  5899. setup_string_in_str(&input, str);
  5900. dest.data = xzalloc(1); /* start as "", not as NULL */
  5901. exp_str = NULL;
  5902. for (;;) {
  5903. int ch;
  5904. ch = i_getch(&input);
  5905. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5906. __func__, ch, ch, !!dest.o_expflags);
  5907. if (!dest.o_expflags) {
  5908. if (ch == EOF)
  5909. break;
  5910. if (handle_squotes && ch == '\'') {
  5911. if (!add_till_single_quote_dquoted(&dest, &input))
  5912. goto ret; /* error */
  5913. continue;
  5914. }
  5915. }
  5916. if (ch == EOF) {
  5917. syntax_error_unterm_ch('"');
  5918. goto ret; /* error */
  5919. }
  5920. if (ch == '"') {
  5921. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5922. continue;
  5923. }
  5924. if (ch == '\\') {
  5925. ch = i_getch(&input);
  5926. if (ch == EOF) {
  5927. //example? error message? syntax_error_unterm_ch('"');
  5928. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5929. goto ret;
  5930. }
  5931. o_addqchr(&dest, ch);
  5932. continue;
  5933. }
  5934. if (ch == '$') {
  5935. if (parse_dollar_squote(NULL, &dest, &input))
  5936. continue;
  5937. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5938. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5939. goto ret;
  5940. }
  5941. continue;
  5942. }
  5943. #if ENABLE_HUSH_TICK
  5944. if (ch == '`') {
  5945. //unsigned pos = dest->length;
  5946. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5947. o_addchr(&dest, 0x80 | '`');
  5948. if (!add_till_backquote(&dest, &input,
  5949. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5950. )
  5951. ) {
  5952. goto ret; /* error */
  5953. }
  5954. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5955. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5956. continue;
  5957. }
  5958. #endif
  5959. o_addQchr(&dest, ch);
  5960. } /* for (;;) */
  5961. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5962. exp_str = expand_string_to_string(dest.data,
  5963. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5964. do_unbackslash
  5965. );
  5966. ret:
  5967. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5968. o_free(&dest);
  5969. return exp_str;
  5970. }
  5971. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5972. */
  5973. static NOINLINE int encode_then_append_var_plusminus(o_string *output, int n,
  5974. char *str, int dquoted)
  5975. {
  5976. struct in_str input;
  5977. o_string dest = NULL_O_STRING;
  5978. if (!first_special_char_in_vararg(str)
  5979. && '\0' == str[strcspn(str, G.ifs)]
  5980. ) {
  5981. /* string has no special chars
  5982. * && string has no $IFS chars
  5983. */
  5984. if (dquoted) {
  5985. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5986. * set -- "${notexist-}"; echo $#
  5987. */
  5988. output->has_quoted_part = 1;
  5989. }
  5990. return expand_vars_to_list(output, n, str);
  5991. }
  5992. setup_string_in_str(&input, str);
  5993. for (;;) {
  5994. int ch;
  5995. ch = i_getch(&input);
  5996. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5997. __func__, ch, ch, dest.o_expflags);
  5998. if (!dest.o_expflags) {
  5999. if (ch == EOF)
  6000. break;
  6001. if (!dquoted && !(output->o_expflags & EXP_FLAG_SINGLEWORD) && strchr(G.ifs, ch)) {
  6002. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  6003. * do not assume we are at the start of the word (PREFIX above).
  6004. */
  6005. if (dest.data) {
  6006. n = expand_vars_to_list(output, n, dest.data);
  6007. o_free_and_set_NULL(&dest);
  6008. o_addchr(output, '\0');
  6009. n = o_save_ptr(output, n); /* create next word */
  6010. } else
  6011. if (output->length != o_get_last_ptr(output, n)
  6012. || output->has_quoted_part
  6013. ) {
  6014. /* For these cases:
  6015. * f() { for i; do echo "|$i|"; done; }; x=x
  6016. * f a${x:+ }b # 1st condition
  6017. * |a|
  6018. * |b|
  6019. * f ""${x:+ }b # 2nd condition
  6020. * ||
  6021. * |b|
  6022. */
  6023. o_addchr(output, '\0');
  6024. n = o_save_ptr(output, n); /* create next word */
  6025. }
  6026. continue;
  6027. }
  6028. if (!dquoted && ch == '\'') {
  6029. if (!add_till_single_quote_dquoted(&dest, &input))
  6030. goto ret; /* error */
  6031. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6032. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6033. continue;
  6034. }
  6035. }
  6036. if (ch == EOF) {
  6037. syntax_error_unterm_ch('"');
  6038. goto ret; /* error */
  6039. }
  6040. if (ch == '"') {
  6041. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  6042. if (dest.o_expflags) {
  6043. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6044. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6045. }
  6046. continue;
  6047. }
  6048. if (ch == '\\') {
  6049. ch = i_getch(&input);
  6050. if (ch == EOF) {
  6051. //example? error message? syntax_error_unterm_ch('"');
  6052. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  6053. goto ret;
  6054. }
  6055. o_addqchr(&dest, ch);
  6056. continue;
  6057. }
  6058. if (ch == '$') {
  6059. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  6060. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  6061. goto ret;
  6062. }
  6063. continue;
  6064. }
  6065. #if ENABLE_HUSH_TICK
  6066. if (ch == '`') {
  6067. //unsigned pos = dest->length;
  6068. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6069. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  6070. if (!add_till_backquote(&dest, &input,
  6071. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  6072. )
  6073. ) {
  6074. goto ret; /* error */
  6075. }
  6076. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6077. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  6078. continue;
  6079. }
  6080. #endif
  6081. if (dquoted) {
  6082. /* Always glob-protect if in dquotes:
  6083. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  6084. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  6085. */
  6086. o_addqchr(&dest, ch);
  6087. } else {
  6088. /* Glob-protect only if char is quoted:
  6089. * x=x; echo ${x:+/bin/c*} - prints many filenames
  6090. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  6091. */
  6092. o_addQchr(&dest, ch);
  6093. }
  6094. } /* for (;;) */
  6095. if (dest.data) {
  6096. n = expand_vars_to_list(output, n, dest.data);
  6097. }
  6098. ret:
  6099. o_free(&dest);
  6100. return n;
  6101. }
  6102. #if ENABLE_FEATURE_SH_MATH
  6103. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  6104. {
  6105. arith_state_t math_state;
  6106. arith_t res;
  6107. char *exp_str;
  6108. math_state.lookupvar = get_local_var_value;
  6109. math_state.setvar = set_local_var_from_halves;
  6110. //math_state.endofname = endofname;
  6111. exp_str = encode_then_expand_string(arg);
  6112. res = arith(&math_state, exp_str ? exp_str : arg);
  6113. free(exp_str);
  6114. if (errmsg_p)
  6115. *errmsg_p = math_state.errmsg;
  6116. if (math_state.errmsg)
  6117. msg_and_die_if_script(math_state.errmsg);
  6118. return res;
  6119. }
  6120. #endif
  6121. #if BASH_PATTERN_SUBST
  6122. /* ${var/[/]pattern[/repl]} helpers */
  6123. static char *strstr_pattern(char *val, const char *pattern, int *size)
  6124. {
  6125. int first_escaped = (pattern[0] == '\\' && pattern[1]);
  6126. /* "first_escaped" trick allows to treat e.g. "\*no_glob_chars"
  6127. * as literal too (as it is semi-common, and easy to accomodate
  6128. * by just using str + 1).
  6129. */
  6130. int sz = strcspn(pattern + first_escaped * 2, "*?[\\");
  6131. if ((pattern + first_escaped * 2)[sz] == '\0') {
  6132. /* Optimization for trivial patterns.
  6133. * Testcase for very slow replace (performs about 22k replaces):
  6134. * x=::::::::::::::::::::::
  6135. * 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}
  6136. * echo "${x//:/|}"
  6137. */
  6138. *size = sz + first_escaped;
  6139. return strstr(val, pattern + first_escaped);
  6140. }
  6141. while (1) {
  6142. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  6143. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  6144. if (end) {
  6145. *size = end - val;
  6146. return val;
  6147. }
  6148. if (*val == '\0')
  6149. return NULL;
  6150. /* Optimization: if "*pat" did not match the start of "string",
  6151. * we know that "tring", "ring" etc will not match too:
  6152. */
  6153. if (pattern[0] == '*')
  6154. return NULL;
  6155. val++;
  6156. }
  6157. }
  6158. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  6159. {
  6160. char *result = NULL;
  6161. unsigned res_len = 0;
  6162. unsigned repl_len = strlen(repl);
  6163. /* Null pattern never matches, including if "var" is empty */
  6164. if (!pattern[0])
  6165. return result; /* NULL, no replaces happened */
  6166. while (1) {
  6167. int size;
  6168. char *s = strstr_pattern(val, pattern, &size);
  6169. if (!s)
  6170. break;
  6171. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  6172. strcpy(mempcpy(result + res_len, val, s - val), repl);
  6173. res_len += (s - val) + repl_len;
  6174. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  6175. val = s + size;
  6176. if (exp_op == '/')
  6177. break;
  6178. }
  6179. if (*val && result) {
  6180. result = xrealloc(result, res_len + strlen(val) + 1);
  6181. strcpy(result + res_len, val);
  6182. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  6183. }
  6184. debug_printf_varexp("result:'%s'\n", result);
  6185. return result;
  6186. }
  6187. #endif /* BASH_PATTERN_SUBST */
  6188. static int append_str_maybe_ifs_split(o_string *output, int n,
  6189. int first_ch, const char *val)
  6190. {
  6191. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  6192. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  6193. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6194. if (val && val[0])
  6195. n = expand_on_ifs(output, n, val);
  6196. } else { /* quoted "$VAR" */
  6197. output->has_quoted_part = 1;
  6198. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  6199. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6200. if (val && val[0])
  6201. o_addQstr(output, val);
  6202. }
  6203. return n;
  6204. }
  6205. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  6206. */
  6207. static NOINLINE int expand_one_var(o_string *output, int n,
  6208. int first_ch, char *arg, char **pp)
  6209. {
  6210. const char *val;
  6211. char *to_be_freed;
  6212. char *p;
  6213. char *var;
  6214. char exp_op;
  6215. char exp_save = exp_save; /* for compiler */
  6216. char *exp_saveptr; /* points to expansion operator */
  6217. char *exp_word = exp_word; /* for compiler */
  6218. char arg0;
  6219. val = NULL;
  6220. to_be_freed = NULL;
  6221. p = *pp;
  6222. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  6223. var = arg;
  6224. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  6225. arg0 = arg[0];
  6226. arg[0] = (arg0 & 0x7f);
  6227. exp_op = 0;
  6228. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  6229. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  6230. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  6231. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  6232. ) {
  6233. /* It must be length operator: ${#var} */
  6234. var++;
  6235. exp_op = 'L';
  6236. } else {
  6237. /* Maybe handle parameter expansion */
  6238. if (exp_saveptr /* if 2nd char is one of expansion operators */
  6239. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  6240. ) {
  6241. /* ${?:0}, ${#[:]%0} etc */
  6242. exp_saveptr = var + 1;
  6243. } else {
  6244. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  6245. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  6246. }
  6247. exp_op = exp_save = *exp_saveptr;
  6248. if (exp_op) {
  6249. exp_word = exp_saveptr + 1;
  6250. if (exp_op == ':') {
  6251. exp_op = *exp_word++;
  6252. //TODO: try ${var:} and ${var:bogus} in non-bash config
  6253. if (BASH_SUBSTR
  6254. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  6255. ) {
  6256. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  6257. exp_op = ':';
  6258. exp_word--;
  6259. }
  6260. }
  6261. *exp_saveptr = '\0';
  6262. } /* else: it's not an expansion op, but bare ${var} */
  6263. }
  6264. /* Look up the variable in question */
  6265. if (isdigit(var[0])) {
  6266. /* parse_dollar should have vetted var for us */
  6267. int nn = xatoi_positive(var);
  6268. if (nn < G.global_argc)
  6269. val = G.global_argv[nn];
  6270. /* else val remains NULL: $N with too big N */
  6271. } else {
  6272. switch (var[0]) {
  6273. case '$': /* pid */
  6274. val = utoa(G.root_pid);
  6275. break;
  6276. case '!': /* bg pid */
  6277. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6278. break;
  6279. case '?': /* exitcode */
  6280. val = utoa(G.last_exitcode);
  6281. break;
  6282. case '#': /* argc */
  6283. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6284. break;
  6285. case '-': { /* active options */
  6286. /* Check set_mode() to see what option chars we support */
  6287. char *cp;
  6288. val = cp = G.optstring_buf;
  6289. if (G.o_opt[OPT_O_ERREXIT])
  6290. *cp++ = 'e';
  6291. if (G_interactive_fd)
  6292. *cp++ = 'i';
  6293. if (G_x_mode)
  6294. *cp++ = 'x';
  6295. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6296. * commands read but are not executed,
  6297. * so $- can not execute too, 'n' is never seen in $-.
  6298. */
  6299. if (G.opt_c)
  6300. *cp++ = 'c';
  6301. if (G.opt_s)
  6302. *cp++ = 's';
  6303. *cp = '\0';
  6304. break;
  6305. }
  6306. default:
  6307. val = get_local_var_value(var);
  6308. }
  6309. }
  6310. /* Handle any expansions */
  6311. if (exp_op == 'L') {
  6312. reinit_unicode_for_hush();
  6313. debug_printf_expand("expand: length(%s)=", val);
  6314. val = utoa(val ? unicode_strlen(val) : 0);
  6315. debug_printf_expand("%s\n", val);
  6316. } else if (exp_op) {
  6317. if (exp_op == '%' || exp_op == '#') {
  6318. /* Standard-mandated substring removal ops:
  6319. * ${parameter%word} - remove smallest suffix pattern
  6320. * ${parameter%%word} - remove largest suffix pattern
  6321. * ${parameter#word} - remove smallest prefix pattern
  6322. * ${parameter##word} - remove largest prefix pattern
  6323. *
  6324. * Word is expanded to produce a glob pattern.
  6325. * Then var's value is matched to it and matching part removed.
  6326. */
  6327. /* bash compat: if x is "" and no shrinking of it is possible,
  6328. * inner ${...} is not evaluated. Example:
  6329. * unset b; : ${a%${b=B}}; echo $b
  6330. * assignment b=B only happens if $a is not "".
  6331. */
  6332. if (val && val[0]) {
  6333. char *t;
  6334. char *exp_exp_word;
  6335. char *loc;
  6336. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6337. if (exp_op == *exp_word) /* ## or %% */
  6338. exp_word++;
  6339. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6340. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6341. if (exp_exp_word)
  6342. exp_word = exp_exp_word;
  6343. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6344. /*
  6345. * HACK ALERT. We depend here on the fact that
  6346. * G.global_argv and results of utoa and get_local_var_value
  6347. * are actually in writable memory:
  6348. * scan_and_match momentarily stores NULs there.
  6349. */
  6350. t = (char*)val;
  6351. loc = scan_and_match(t, exp_word, scan_flags);
  6352. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6353. free(exp_exp_word);
  6354. if (loc) { /* match was found */
  6355. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6356. val = loc; /* take right part */
  6357. else /* %[%] */
  6358. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6359. }
  6360. }
  6361. }
  6362. #if BASH_PATTERN_SUBST
  6363. else if (exp_op == '/' || exp_op == '\\') {
  6364. /* It's ${var/[/]pattern[/repl]} thing.
  6365. * Note that in encoded form it has TWO parts:
  6366. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6367. * and if // is used, it is encoded as \:
  6368. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6369. */
  6370. /* bash compat: if var is "", both pattern and repl
  6371. * are still evaluated, if it is unset, then not:
  6372. * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
  6373. * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
  6374. */
  6375. if (val /*&& val[0]*/) {
  6376. /* pattern uses non-standard expansion.
  6377. * repl should be unbackslashed and globbed
  6378. * by the usual expansion rules:
  6379. * >az >bz
  6380. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6381. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6382. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6383. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6384. * (note that a*z _pattern_ is never globbed!)
  6385. */
  6386. char *pattern, *repl, *t;
  6387. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6388. if (!pattern)
  6389. pattern = xstrdup(exp_word);
  6390. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6391. *p++ = SPECIAL_VAR_SYMBOL;
  6392. exp_word = p;
  6393. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6394. *p = '\0';
  6395. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6396. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6397. /* HACK ALERT. We depend here on the fact that
  6398. * G.global_argv and results of utoa and get_local_var_value
  6399. * are actually in writable memory:
  6400. * replace_pattern momentarily stores NULs there. */
  6401. t = (char*)val;
  6402. to_be_freed = replace_pattern(t,
  6403. pattern,
  6404. (repl ? repl : exp_word),
  6405. exp_op);
  6406. if (to_be_freed) /* at least one replace happened */
  6407. val = to_be_freed;
  6408. free(pattern);
  6409. free(repl);
  6410. } else {
  6411. /* Unset variable always gives nothing */
  6412. // a=; echo ${a/*/w} # "w"
  6413. // unset a; echo ${a/*/w} # ""
  6414. /* Just skip "replace" part */
  6415. *p++ = SPECIAL_VAR_SYMBOL;
  6416. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6417. *p = '\0';
  6418. }
  6419. }
  6420. #endif /* BASH_PATTERN_SUBST */
  6421. else if (exp_op == ':') {
  6422. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6423. /* It's ${var:N[:M]} bashism.
  6424. * Note that in encoded form it has TWO parts:
  6425. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6426. */
  6427. arith_t beg, len;
  6428. unsigned vallen;
  6429. const char *errmsg;
  6430. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6431. if (errmsg)
  6432. goto empty_result;
  6433. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6434. *p++ = SPECIAL_VAR_SYMBOL;
  6435. exp_word = p;
  6436. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6437. *p = '\0';
  6438. vallen = val ? strlen(val) : 0;
  6439. if (beg < 0) {
  6440. /* negative beg counts from the end */
  6441. beg = (arith_t)vallen + beg;
  6442. }
  6443. /* If expansion will be empty, do not even evaluate len */
  6444. if (!val || beg < 0 || beg > vallen) {
  6445. /* Why > vallen, not >=? bash:
  6446. * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
  6447. * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
  6448. */
  6449. goto empty_result;
  6450. }
  6451. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6452. if (errmsg)
  6453. goto empty_result;
  6454. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6455. debug_printf_varexp("from val:'%s'\n", val);
  6456. if (len < 0) {
  6457. /* in bash, len=-n means strlen()-n */
  6458. len = (arith_t)vallen - beg + len;
  6459. if (len < 0) /* bash compat */
  6460. msg_and_die_if_script("%s: substring expression < 0", var);
  6461. }
  6462. if (len <= 0 || !val /*|| beg >= vallen*/) {
  6463. empty_result:
  6464. val = NULL;
  6465. } else {
  6466. /* Paranoia. What if user entered 9999999999999
  6467. * which fits in arith_t but not int? */
  6468. if (len > INT_MAX)
  6469. len = INT_MAX;
  6470. val = to_be_freed = xstrndup(val + beg, len);
  6471. }
  6472. debug_printf_varexp("val:'%s'\n", val);
  6473. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6474. msg_and_die_if_script("malformed ${%s:...}", var);
  6475. val = NULL;
  6476. #endif
  6477. } else { /* one of "-=+?" */
  6478. /* Standard-mandated substitution ops:
  6479. * ${var?word} - indicate error if unset
  6480. * If var is unset, word (or a message indicating it is unset
  6481. * if word is null) is written to standard error
  6482. * and the shell exits with a non-zero exit status.
  6483. * Otherwise, the value of var is substituted.
  6484. * ${var-word} - use default value
  6485. * If var is unset, word is substituted.
  6486. * ${var=word} - assign and use default value
  6487. * If var is unset, word is assigned to var.
  6488. * In all cases, final value of var is substituted.
  6489. * ${var+word} - use alternative value
  6490. * If var is unset, null is substituted.
  6491. * Otherwise, word is substituted.
  6492. *
  6493. * Word is subjected to tilde expansion, parameter expansion,
  6494. * command substitution, and arithmetic expansion.
  6495. * If word is not needed, it is not expanded.
  6496. *
  6497. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6498. * but also treat null var as if it is unset.
  6499. *
  6500. * Word-splitting and single quote behavior:
  6501. *
  6502. * $ f() { for i; do echo "|$i|"; done; }
  6503. *
  6504. * $ x=; f ${x:?'x y' z}; echo $?
  6505. * bash: x: x y z # neither f nor "echo $?" executes
  6506. * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
  6507. * $ x=; f "${x:?'x y' z}"
  6508. * bash: x: x y z # dash prints: dash: x: 'x y' z
  6509. *
  6510. * $ x=; f ${x:='x y' z}
  6511. * |x|
  6512. * |y|
  6513. * |z|
  6514. * $ x=; f "${x:='x y' z}"
  6515. * |'x y' z|
  6516. *
  6517. * $ x=x; f ${x:+'x y' z}
  6518. * |x y|
  6519. * |z|
  6520. * $ x=x; f "${x:+'x y' z}"
  6521. * |'x y' z|
  6522. *
  6523. * $ x=; f ${x:-'x y' z}
  6524. * |x y|
  6525. * |z|
  6526. * $ x=; f "${x:-'x y' z}"
  6527. * |'x y' z|
  6528. */
  6529. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6530. if (exp_op == '+')
  6531. use_word = !use_word;
  6532. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6533. (exp_save == ':') ? "true" : "false", use_word);
  6534. if (use_word) {
  6535. if (exp_op == '+' || exp_op == '-') {
  6536. /* ${var+word} - use alternative value */
  6537. /* ${var-word} - use default value */
  6538. n = encode_then_append_var_plusminus(output, n, exp_word,
  6539. /*dquoted:*/ (arg0 & 0x80)
  6540. );
  6541. val = NULL;
  6542. } else {
  6543. /* ${var?word} - indicate error if unset */
  6544. /* ${var=word} - assign and use default value */
  6545. to_be_freed = encode_then_expand_vararg(exp_word,
  6546. /*handle_squotes:*/ !(arg0 & 0x80),
  6547. /*unbackslash:*/ 0
  6548. );
  6549. if (to_be_freed)
  6550. exp_word = to_be_freed;
  6551. if (exp_op == '?') {
  6552. /* mimic bash message */
  6553. msg_and_die_if_script("%s: %s",
  6554. var,
  6555. exp_word[0]
  6556. ? exp_word
  6557. : "parameter null or not set"
  6558. /* ash has more specific messages, a-la: */
  6559. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6560. );
  6561. //TODO: how interactive bash aborts expansion mid-command?
  6562. //It aborts the entire line, returns to prompt:
  6563. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6564. // bash: x: x y z
  6565. // $
  6566. // ("echo YO" is not executed, neither the f function call)
  6567. } else {
  6568. val = exp_word;
  6569. }
  6570. if (exp_op == '=') {
  6571. /* ${var=[word]} or ${var:=[word]} */
  6572. if (isdigit(var[0]) || var[0] == '#') {
  6573. /* mimic bash message */
  6574. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6575. val = NULL;
  6576. } else {
  6577. char *new_var = xasprintf("%s=%s", var, val);
  6578. set_local_var0(new_var);
  6579. }
  6580. }
  6581. }
  6582. }
  6583. } /* one of "-=+?" */
  6584. *exp_saveptr = exp_save;
  6585. } /* if (exp_op) */
  6586. arg[0] = arg0;
  6587. *pp = p;
  6588. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6589. free(to_be_freed);
  6590. return n;
  6591. }
  6592. /* Expand all variable references in given string, adding words to list[]
  6593. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6594. * to be filled). This routine is extremely tricky: has to deal with
  6595. * variables/parameters with whitespace, $* and $@, and constructs like
  6596. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6597. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6598. {
  6599. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6600. * expansion of right-hand side of assignment == 1-element expand.
  6601. */
  6602. char cant_be_null = 0; /* only bit 0x80 matters */
  6603. char *p;
  6604. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6605. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6606. debug_print_list("expand_vars_to_list[0]", output, n);
  6607. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6608. char first_ch;
  6609. #if ENABLE_FEATURE_SH_MATH
  6610. char arith_buf[sizeof(arith_t)*3 + 2];
  6611. #endif
  6612. if (output->ended_in_ifs) {
  6613. o_addchr(output, '\0');
  6614. n = o_save_ptr(output, n);
  6615. output->ended_in_ifs = 0;
  6616. }
  6617. o_addblock(output, arg, p - arg);
  6618. debug_print_list("expand_vars_to_list[1]", output, n);
  6619. arg = ++p;
  6620. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6621. /* Fetch special var name (if it is indeed one of them)
  6622. * and quote bit, force the bit on if singleword expansion -
  6623. * important for not getting v=$@ expand to many words. */
  6624. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6625. /* Is this variable quoted and thus expansion can't be null?
  6626. * "$@" is special. Even if quoted, it can still
  6627. * expand to nothing (not even an empty string),
  6628. * thus it is excluded. */
  6629. if ((first_ch & 0x7f) != '@')
  6630. cant_be_null |= first_ch;
  6631. switch (first_ch & 0x7f) {
  6632. /* Highest bit in first_ch indicates that var is double-quoted */
  6633. case '*':
  6634. case '@': {
  6635. int i;
  6636. if (!G.global_argv[1])
  6637. break;
  6638. i = 1;
  6639. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6640. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6641. while (G.global_argv[i]) {
  6642. n = expand_on_ifs(output, n, G.global_argv[i]);
  6643. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6644. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6645. /* this argv[] is not empty and not last:
  6646. * put terminating NUL, start new word */
  6647. o_addchr(output, '\0');
  6648. debug_print_list("expand_vars_to_list[2]", output, n);
  6649. n = o_save_ptr(output, n);
  6650. debug_print_list("expand_vars_to_list[3]", output, n);
  6651. }
  6652. }
  6653. } else
  6654. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6655. * and in this case should treat it like '$*' - see 'else...' below */
  6656. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6657. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6658. ) {
  6659. while (1) {
  6660. o_addQstr(output, G.global_argv[i]);
  6661. if (++i >= G.global_argc)
  6662. break;
  6663. o_addchr(output, '\0');
  6664. debug_print_list("expand_vars_to_list[4]", output, n);
  6665. n = o_save_ptr(output, n);
  6666. }
  6667. } else { /* quoted $* (or v="$@" case): add as one word */
  6668. while (1) {
  6669. o_addQstr(output, G.global_argv[i]);
  6670. if (!G.global_argv[++i])
  6671. break;
  6672. if (G.ifs[0])
  6673. o_addchr(output, G.ifs[0]);
  6674. }
  6675. output->has_quoted_part = 1;
  6676. }
  6677. break;
  6678. }
  6679. case SPECIAL_VAR_SYMBOL: {
  6680. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6681. /* "Empty variable", used to make "" etc to not disappear */
  6682. output->has_quoted_part = 1;
  6683. cant_be_null = 0x80;
  6684. arg++;
  6685. break;
  6686. }
  6687. case SPECIAL_VAR_QUOTED_SVS:
  6688. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6689. /* "^C variable", represents literal ^C char (possible in scripts) */
  6690. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6691. arg++;
  6692. break;
  6693. #if ENABLE_HUSH_TICK
  6694. case '`': {
  6695. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6696. o_string subst_result = NULL_O_STRING;
  6697. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6698. arg++;
  6699. /* Can't just stuff it into output o_string,
  6700. * expanded result may need to be globbed
  6701. * and $IFS-split */
  6702. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6703. G.last_exitcode = process_command_subs(&subst_result, arg);
  6704. G.expand_exitcode = G.last_exitcode;
  6705. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6706. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6707. o_free(&subst_result);
  6708. break;
  6709. }
  6710. #endif
  6711. #if ENABLE_FEATURE_SH_MATH
  6712. case '+': {
  6713. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6714. arith_t res;
  6715. arg++; /* skip '+' */
  6716. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6717. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6718. res = expand_and_evaluate_arith(arg, NULL);
  6719. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6720. sprintf(arith_buf, ARITH_FMT, res);
  6721. if (res < 0
  6722. && first_ch == (char)('+'|0x80)
  6723. /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
  6724. ) {
  6725. /* Quoted negative ariths, like filename[0"$((-9))"],
  6726. * should not be interpreted as glob ranges.
  6727. * Convert leading '-' to '\-':
  6728. */
  6729. o_grow_by(output, 1);
  6730. output->data[output->length++] = '\\';
  6731. }
  6732. o_addstr(output, arith_buf);
  6733. break;
  6734. }
  6735. #endif
  6736. default:
  6737. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6738. n = expand_one_var(output, n, first_ch, arg, &p);
  6739. break;
  6740. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6741. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6742. * Do the check to avoid writing to a const string. */
  6743. if (*p != SPECIAL_VAR_SYMBOL)
  6744. *p = SPECIAL_VAR_SYMBOL;
  6745. arg = ++p;
  6746. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6747. if (*arg) {
  6748. /* handle trailing string */
  6749. if (output->ended_in_ifs) {
  6750. o_addchr(output, '\0');
  6751. n = o_save_ptr(output, n);
  6752. }
  6753. debug_print_list("expand_vars_to_list[a]", output, n);
  6754. /* this part is literal, and it was already pre-quoted
  6755. * if needed (much earlier), do not use o_addQstr here!
  6756. */
  6757. o_addstr(output, arg);
  6758. debug_print_list("expand_vars_to_list[b]", output, n);
  6759. } else
  6760. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6761. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6762. && !output->has_quoted_part
  6763. ) {
  6764. n--;
  6765. /* allow to reuse list[n] later without re-growth */
  6766. output->has_empty_slot = 1;
  6767. }
  6768. return n;
  6769. }
  6770. static char **expand_variables(char **argv, unsigned expflags)
  6771. {
  6772. int n;
  6773. char **list;
  6774. o_string output = NULL_O_STRING;
  6775. output.o_expflags = expflags;
  6776. n = 0;
  6777. for (;;) {
  6778. /* go to next list[n] */
  6779. output.ended_in_ifs = 0;
  6780. n = o_save_ptr(&output, n);
  6781. if (!*argv)
  6782. break;
  6783. /* expand argv[i] */
  6784. n = expand_vars_to_list(&output, n, *argv++);
  6785. /* if (!output->has_empty_slot) -- need this?? */
  6786. o_addchr(&output, '\0');
  6787. }
  6788. debug_print_list("expand_variables", &output, n);
  6789. /* output.data (malloced in one block) gets returned in "list" */
  6790. list = o_finalize_list(&output, n);
  6791. debug_print_strings("expand_variables[1]", list);
  6792. return list;
  6793. }
  6794. static char **expand_strvec_to_strvec(char **argv)
  6795. {
  6796. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6797. }
  6798. #if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  6799. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6800. {
  6801. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6802. }
  6803. #endif
  6804. /* Used for expansion of right hand of assignments,
  6805. * $((...)), heredocs, variable expansion parts.
  6806. *
  6807. * NB: should NOT do globbing!
  6808. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6809. */
  6810. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6811. {
  6812. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6813. const int do_unbackslash = 1;
  6814. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6815. #endif
  6816. char *argv[2], **list;
  6817. debug_printf_expand("string_to_string<='%s'\n", str);
  6818. /* This is generally an optimization, but it also
  6819. * handles "", which otherwise trips over !list[0] check below.
  6820. * (is this ever happens that we actually get str="" here?)
  6821. */
  6822. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6823. //TODO: Can use on strings with \ too, just unbackslash() them?
  6824. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6825. return xstrdup(str);
  6826. }
  6827. argv[0] = (char*)str;
  6828. argv[1] = NULL;
  6829. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6830. if (!list[0]) {
  6831. /* Example where it happens:
  6832. * x=; echo ${x:-"$@"}
  6833. */
  6834. ((char*)list)[0] = '\0';
  6835. } else {
  6836. if (HUSH_DEBUG)
  6837. if (list[1])
  6838. bb_simple_error_msg_and_die("BUG in varexp2");
  6839. /* actually, just move string 2*sizeof(char*) bytes back */
  6840. overlapping_strcpy((char*)list, list[0]);
  6841. if (do_unbackslash)
  6842. unbackslash((char*)list);
  6843. }
  6844. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6845. return (char*)list;
  6846. }
  6847. #if 0
  6848. static char* expand_strvec_to_string(char **argv)
  6849. {
  6850. char **list;
  6851. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6852. /* Convert all NULs to spaces */
  6853. if (list[0]) {
  6854. int n = 1;
  6855. while (list[n]) {
  6856. if (HUSH_DEBUG)
  6857. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6858. bb_error_msg_and_die("BUG in varexp3");
  6859. /* bash uses ' ' regardless of $IFS contents */
  6860. list[n][-1] = ' ';
  6861. n++;
  6862. }
  6863. }
  6864. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6865. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6866. return (char*)list;
  6867. }
  6868. #endif
  6869. static char **expand_assignments(char **argv, int count)
  6870. {
  6871. int i;
  6872. char **p;
  6873. G.expanded_assignments = p = NULL;
  6874. /* Expand assignments into one string each */
  6875. for (i = 0; i < count; i++) {
  6876. p = add_string_to_strings(p,
  6877. expand_string_to_string(argv[i],
  6878. EXP_FLAG_ESC_GLOB_CHARS,
  6879. /*unbackslash:*/ 1
  6880. )
  6881. );
  6882. G.expanded_assignments = p;
  6883. }
  6884. G.expanded_assignments = NULL;
  6885. return p;
  6886. }
  6887. static void switch_off_special_sigs(unsigned mask)
  6888. {
  6889. unsigned sig = 0;
  6890. while ((mask >>= 1) != 0) {
  6891. sig++;
  6892. if (!(mask & 1))
  6893. continue;
  6894. #if ENABLE_HUSH_TRAP
  6895. if (G_traps) {
  6896. if (G_traps[sig] && !G_traps[sig][0])
  6897. /* trap is '', has to remain SIG_IGN */
  6898. continue;
  6899. free(G_traps[sig]);
  6900. G_traps[sig] = NULL;
  6901. }
  6902. #endif
  6903. /* We are here only if no trap or trap was not '' */
  6904. install_sighandler(sig, SIG_DFL);
  6905. }
  6906. }
  6907. #if BB_MMU
  6908. /* never called */
  6909. void re_execute_shell(char ***to_free, const char *s,
  6910. char *g_argv0, char **g_argv,
  6911. char **builtin_argv) NORETURN;
  6912. static void reset_traps_to_defaults(void)
  6913. {
  6914. /* This function is always called in a child shell
  6915. * after fork (not vfork, NOMMU doesn't use this function).
  6916. */
  6917. IF_HUSH_TRAP(unsigned sig;)
  6918. unsigned mask;
  6919. /* Child shells are not interactive.
  6920. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6921. * Testcase: (while :; do :; done) + ^Z should background.
  6922. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6923. */
  6924. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6925. if (!G_traps && !mask)
  6926. return; /* already no traps and no special sigs */
  6927. /* Switch off special sigs */
  6928. switch_off_special_sigs(mask);
  6929. # if ENABLE_HUSH_JOB
  6930. G_fatal_sig_mask = 0;
  6931. # endif
  6932. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6933. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6934. * remain set in G.special_sig_mask */
  6935. # if ENABLE_HUSH_TRAP
  6936. if (!G_traps)
  6937. return;
  6938. /* Reset all sigs to default except ones with empty traps */
  6939. for (sig = 0; sig < NSIG; sig++) {
  6940. if (!G_traps[sig])
  6941. continue; /* no trap: nothing to do */
  6942. if (!G_traps[sig][0])
  6943. continue; /* empty trap: has to remain SIG_IGN */
  6944. /* sig has non-empty trap, reset it: */
  6945. free(G_traps[sig]);
  6946. G_traps[sig] = NULL;
  6947. /* There is no signal for trap 0 (EXIT) */
  6948. if (sig == 0)
  6949. continue;
  6950. install_sighandler(sig, pick_sighandler(sig));
  6951. }
  6952. # endif
  6953. }
  6954. #else /* !BB_MMU */
  6955. static void re_execute_shell(char ***to_free, const char *s,
  6956. char *g_argv0, char **g_argv,
  6957. char **builtin_argv) NORETURN;
  6958. static void re_execute_shell(char ***to_free, const char *s,
  6959. char *g_argv0, char **g_argv,
  6960. char **builtin_argv)
  6961. {
  6962. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6963. /* delims + 2 * (number of bytes in printed hex numbers) */
  6964. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6965. char *heredoc_argv[4];
  6966. struct variable *cur;
  6967. # if ENABLE_HUSH_FUNCTIONS
  6968. struct function *funcp;
  6969. # endif
  6970. char **argv, **pp;
  6971. unsigned cnt;
  6972. unsigned long long empty_trap_mask;
  6973. if (!g_argv0) { /* heredoc */
  6974. argv = heredoc_argv;
  6975. argv[0] = (char *) G.argv0_for_re_execing;
  6976. argv[1] = (char *) "-<";
  6977. argv[2] = (char *) s;
  6978. argv[3] = NULL;
  6979. pp = &argv[3]; /* used as pointer to empty environment */
  6980. goto do_exec;
  6981. }
  6982. cnt = 0;
  6983. pp = builtin_argv;
  6984. if (pp) while (*pp++)
  6985. cnt++;
  6986. empty_trap_mask = 0;
  6987. if (G_traps) {
  6988. int sig;
  6989. for (sig = 1; sig < NSIG; sig++) {
  6990. if (G_traps[sig] && !G_traps[sig][0])
  6991. empty_trap_mask |= 1LL << sig;
  6992. }
  6993. }
  6994. sprintf(param_buf, NOMMU_HACK_FMT
  6995. , (unsigned) G.root_pid
  6996. , (unsigned) G.root_ppid
  6997. , (unsigned) G.last_bg_pid
  6998. , (unsigned) G.last_exitcode
  6999. , cnt
  7000. , empty_trap_mask
  7001. IF_HUSH_LOOPS(, G.depth_of_loop)
  7002. );
  7003. # undef NOMMU_HACK_FMT
  7004. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  7005. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  7006. */
  7007. cnt += 6;
  7008. for (cur = G.top_var; cur; cur = cur->next) {
  7009. if (!cur->flg_export || cur->flg_read_only)
  7010. cnt += 2;
  7011. }
  7012. # if ENABLE_HUSH_LINENO_VAR
  7013. cnt += 2;
  7014. # endif
  7015. # if ENABLE_HUSH_FUNCTIONS
  7016. for (funcp = G.top_func; funcp; funcp = funcp->next)
  7017. cnt += 3;
  7018. # endif
  7019. pp = g_argv;
  7020. while (*pp++)
  7021. cnt++;
  7022. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  7023. *pp++ = (char *) G.argv0_for_re_execing;
  7024. *pp++ = param_buf;
  7025. for (cur = G.top_var; cur; cur = cur->next) {
  7026. if (strcmp(cur->varstr, hush_version_str) == 0)
  7027. continue;
  7028. if (cur->flg_read_only) {
  7029. *pp++ = (char *) "-R";
  7030. *pp++ = cur->varstr;
  7031. } else if (!cur->flg_export) {
  7032. *pp++ = (char *) "-V";
  7033. *pp++ = cur->varstr;
  7034. }
  7035. }
  7036. # if ENABLE_HUSH_LINENO_VAR
  7037. *pp++ = (char *) "-L";
  7038. *pp++ = utoa(G.execute_lineno);
  7039. # endif
  7040. # if ENABLE_HUSH_FUNCTIONS
  7041. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  7042. *pp++ = (char *) "-F";
  7043. *pp++ = funcp->name;
  7044. *pp++ = funcp->body_as_string;
  7045. }
  7046. # endif
  7047. /* We can pass activated traps here. Say, -Tnn:trap_string
  7048. *
  7049. * However, POSIX says that subshells reset signals with traps
  7050. * to SIG_DFL.
  7051. * I tested bash-3.2 and it not only does that with true subshells
  7052. * of the form ( list ), but with any forked children shells.
  7053. * I set trap "echo W" WINCH; and then tried:
  7054. *
  7055. * { echo 1; sleep 20; echo 2; } &
  7056. * while true; do echo 1; sleep 20; echo 2; break; done &
  7057. * true | { echo 1; sleep 20; echo 2; } | cat
  7058. *
  7059. * In all these cases sending SIGWINCH to the child shell
  7060. * did not run the trap. If I add trap "echo V" WINCH;
  7061. * _inside_ group (just before echo 1), it works.
  7062. *
  7063. * I conclude it means we don't need to pass active traps here.
  7064. */
  7065. *pp++ = (char *) "-c";
  7066. *pp++ = (char *) s;
  7067. if (builtin_argv) {
  7068. while (*++builtin_argv)
  7069. *pp++ = *builtin_argv;
  7070. *pp++ = (char *) "";
  7071. }
  7072. *pp++ = g_argv0;
  7073. while (*g_argv)
  7074. *pp++ = *g_argv++;
  7075. /* *pp = NULL; - is already there */
  7076. pp = environ;
  7077. do_exec:
  7078. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  7079. /* Don't propagate SIG_IGN to the child */
  7080. if (SPECIAL_JOBSTOP_SIGS != 0)
  7081. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7082. execve(bb_busybox_exec_path, argv, pp);
  7083. /* Fallback. Useful for init=/bin/hush usage etc */
  7084. if (argv[0][0] == '/')
  7085. execve(argv[0], argv, pp);
  7086. xfunc_error_retval = 127;
  7087. bb_simple_error_msg_and_die("can't re-execute the shell");
  7088. }
  7089. #endif /* !BB_MMU */
  7090. static int run_and_free_list(struct pipe *pi);
  7091. /* Executing from string: eval, sh -c '...'
  7092. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  7093. * end_trigger controls how often we stop parsing
  7094. * NUL: parse all, execute, return
  7095. * ';': parse till ';' or newline, execute, repeat till EOF
  7096. */
  7097. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  7098. {
  7099. /* Why we need empty flag?
  7100. * An obscure corner case "false; ``; echo $?":
  7101. * empty command in `` should still set $? to 0.
  7102. * But we can't just set $? to 0 at the start,
  7103. * this breaks "false; echo `echo $?`" case.
  7104. */
  7105. bool empty = 1;
  7106. while (1) {
  7107. struct pipe *pipe_list;
  7108. #if ENABLE_HUSH_INTERACTIVE
  7109. if (end_trigger == ';') {
  7110. G.promptmode = 0; /* PS1 */
  7111. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  7112. }
  7113. #endif
  7114. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  7115. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  7116. /* If we are in "big" script
  7117. * (not in `cmd` or something similar)...
  7118. */
  7119. if (pipe_list == ERR_PTR && end_trigger == ';') {
  7120. /* Discard cached input (rest of line) */
  7121. int ch = inp->last_char;
  7122. while (ch != EOF && ch != '\n') {
  7123. //bb_error_msg("Discarded:'%c'", ch);
  7124. ch = i_getch(inp);
  7125. }
  7126. /* Force prompt */
  7127. inp->p = NULL;
  7128. /* Clear "peeked" EOF. Without this,
  7129. * $ { cmd }<Enter>
  7130. * > ^D
  7131. * hush: syntax error: unterminated {
  7132. * exits interactive shell:
  7133. */
  7134. if (inp->peek_buf[0] == EOF)
  7135. inp->peek_buf[0] = 0;
  7136. /* This stream isn't empty */
  7137. empty = 0;
  7138. continue;
  7139. }
  7140. if (!pipe_list && empty)
  7141. G.last_exitcode = 0;
  7142. break;
  7143. }
  7144. debug_print_tree(pipe_list, 0);
  7145. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  7146. run_and_free_list(pipe_list);
  7147. empty = 0;
  7148. if (G_flag_return_in_progress == 1)
  7149. break;
  7150. }
  7151. }
  7152. static void parse_and_run_string(const char *s)
  7153. {
  7154. struct in_str input;
  7155. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7156. setup_string_in_str(&input, s);
  7157. parse_and_run_stream(&input, '\0');
  7158. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7159. }
  7160. static void parse_and_run_file(HFILE *fp)
  7161. {
  7162. struct in_str input;
  7163. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7164. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  7165. setup_file_in_str(&input, fp);
  7166. parse_and_run_stream(&input, ';');
  7167. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7168. }
  7169. #if ENABLE_HUSH_TICK
  7170. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  7171. {
  7172. pid_t pid;
  7173. int channel[2];
  7174. # if !BB_MMU
  7175. char **to_free = NULL;
  7176. # endif
  7177. xpipe(channel);
  7178. pid = BB_MMU ? xfork() : xvfork();
  7179. if (pid == 0) { /* child */
  7180. disable_restore_tty_pgrp_on_exit();
  7181. /* Process substitution is not considered to be usual
  7182. * 'command execution'.
  7183. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  7184. */
  7185. bb_signals(0
  7186. + (1 << SIGTSTP)
  7187. + (1 << SIGTTIN)
  7188. + (1 << SIGTTOU)
  7189. , SIG_IGN);
  7190. close(channel[0]); /* NB: close _first_, then move fd! */
  7191. xmove_fd(channel[1], 1);
  7192. # if ENABLE_HUSH_TRAP
  7193. /* Awful hack for `trap` or $(trap).
  7194. *
  7195. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  7196. * contains an example where "trap" is executed in a subshell:
  7197. *
  7198. * save_traps=$(trap)
  7199. * ...
  7200. * eval "$save_traps"
  7201. *
  7202. * Standard does not say that "trap" in subshell shall print
  7203. * parent shell's traps. It only says that its output
  7204. * must have suitable form, but then, in the above example
  7205. * (which is not supposed to be normative), it implies that.
  7206. *
  7207. * bash (and probably other shell) does implement it
  7208. * (traps are reset to defaults, but "trap" still shows them),
  7209. * but as a result, "trap" logic is hopelessly messed up:
  7210. *
  7211. * # trap
  7212. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  7213. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  7214. * # true | trap <--- trap is in subshell - no output (ditto)
  7215. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  7216. * trap -- 'echo Ho' SIGWINCH
  7217. * # echo `(trap)` <--- in subshell in subshell - output
  7218. * trap -- 'echo Ho' SIGWINCH
  7219. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  7220. * trap -- 'echo Ho' SIGWINCH
  7221. *
  7222. * The rules when to forget and when to not forget traps
  7223. * get really complex and nonsensical.
  7224. *
  7225. * Our solution: ONLY bare $(trap) or `trap` is special.
  7226. */
  7227. s = skip_whitespace(s);
  7228. if (is_prefixed_with(s, "trap")
  7229. && skip_whitespace(s + 4)[0] == '\0'
  7230. ) {
  7231. static const char *const argv[] ALIGN_PTR = { NULL, NULL };
  7232. builtin_trap((char**)argv);
  7233. fflush_all(); /* important */
  7234. _exit(0);
  7235. }
  7236. # endif
  7237. # if BB_MMU
  7238. /* Prevent it from trying to handle ctrl-z etc */
  7239. IF_HUSH_JOB(G.run_list_level = 1;)
  7240. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  7241. reset_traps_to_defaults();
  7242. IF_HUSH_MODE_X(G.x_mode_depth++;)
  7243. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  7244. parse_and_run_string(s);
  7245. _exit(G.last_exitcode);
  7246. # else
  7247. /* We re-execute after vfork on NOMMU. This makes this script safe:
  7248. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  7249. * huge=`cat BIG` # was blocking here forever
  7250. * echo OK
  7251. */
  7252. re_execute_shell(&to_free,
  7253. s,
  7254. G.global_argv[0],
  7255. G.global_argv + 1,
  7256. NULL);
  7257. # endif
  7258. }
  7259. /* parent */
  7260. *pid_p = pid;
  7261. # if ENABLE_HUSH_FAST
  7262. G.count_SIGCHLD++;
  7263. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  7264. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  7265. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7266. # endif
  7267. enable_restore_tty_pgrp_on_exit();
  7268. # if !BB_MMU
  7269. free(to_free);
  7270. # endif
  7271. close(channel[1]);
  7272. return channel[0];
  7273. }
  7274. /* Return code is exit status of the process that is run. */
  7275. static int process_command_subs(o_string *dest, const char *s)
  7276. {
  7277. FILE *fp;
  7278. pid_t pid;
  7279. int status, ch, eol_cnt;
  7280. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  7281. /* Now send results of command back into original context */
  7282. eol_cnt = 0;
  7283. while ((ch = getc(fp)) != EOF) {
  7284. if (ch == '\0')
  7285. continue;
  7286. if (ch == '\n') {
  7287. eol_cnt++;
  7288. continue;
  7289. }
  7290. while (eol_cnt) {
  7291. o_addchr(dest, '\n');
  7292. eol_cnt--;
  7293. }
  7294. o_addQchr(dest, ch);
  7295. }
  7296. debug_printf("done reading from `cmd` pipe, closing it\n");
  7297. fclose(fp);
  7298. /* We need to extract exitcode. Test case
  7299. * "true; echo `sleep 1; false` $?"
  7300. * should print 1 */
  7301. safe_waitpid(pid, &status, 0);
  7302. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  7303. return WEXITSTATUS(status);
  7304. }
  7305. #endif /* ENABLE_HUSH_TICK */
  7306. static void setup_heredoc(struct redir_struct *redir)
  7307. {
  7308. struct fd_pair pair;
  7309. pid_t pid;
  7310. int len, written;
  7311. /* the _body_ of heredoc (misleading field name) */
  7312. const char *heredoc = redir->rd_filename;
  7313. char *expanded;
  7314. #if !BB_MMU
  7315. char **to_free;
  7316. #endif
  7317. expanded = NULL;
  7318. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  7319. expanded = encode_then_expand_string(heredoc);
  7320. if (expanded)
  7321. heredoc = expanded;
  7322. }
  7323. len = strlen(heredoc);
  7324. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7325. xpiped_pair(pair);
  7326. xmove_fd(pair.rd, redir->rd_fd);
  7327. /* Try writing without forking. Newer kernels have
  7328. * dynamically growing pipes. Must use non-blocking write! */
  7329. ndelay_on(pair.wr);
  7330. while (1) {
  7331. written = write(pair.wr, heredoc, len);
  7332. if (written <= 0)
  7333. break;
  7334. len -= written;
  7335. if (len == 0) {
  7336. close(pair.wr);
  7337. free(expanded);
  7338. return;
  7339. }
  7340. heredoc += written;
  7341. }
  7342. ndelay_off(pair.wr);
  7343. /* Okay, pipe buffer was not big enough */
  7344. /* Note: we must not create a stray child (bastard? :)
  7345. * for the unsuspecting parent process. Child creates a grandchild
  7346. * and exits before parent execs the process which consumes heredoc
  7347. * (that exec happens after we return from this function) */
  7348. #if !BB_MMU
  7349. to_free = NULL;
  7350. #endif
  7351. pid = xvfork();
  7352. if (pid == 0) {
  7353. /* child */
  7354. disable_restore_tty_pgrp_on_exit();
  7355. pid = BB_MMU ? xfork() : xvfork();
  7356. if (pid != 0)
  7357. _exit(0);
  7358. /* grandchild */
  7359. close(redir->rd_fd); /* read side of the pipe */
  7360. #if BB_MMU
  7361. full_write(pair.wr, heredoc, len); /* may loop or block */
  7362. _exit(0);
  7363. #else
  7364. /* Delegate blocking writes to another process */
  7365. xmove_fd(pair.wr, STDOUT_FILENO);
  7366. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7367. #endif
  7368. }
  7369. /* parent */
  7370. #if ENABLE_HUSH_FAST
  7371. G.count_SIGCHLD++;
  7372. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7373. #endif
  7374. enable_restore_tty_pgrp_on_exit();
  7375. #if !BB_MMU
  7376. free(to_free);
  7377. #endif
  7378. close(pair.wr);
  7379. free(expanded);
  7380. wait(NULL); /* wait till child has died */
  7381. }
  7382. struct squirrel {
  7383. int orig_fd;
  7384. int moved_to;
  7385. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7386. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7387. };
  7388. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7389. {
  7390. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7391. sq[i].orig_fd = orig;
  7392. sq[i].moved_to = moved;
  7393. sq[i+1].orig_fd = -1; /* end marker */
  7394. return sq;
  7395. }
  7396. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7397. {
  7398. int moved_to;
  7399. int i;
  7400. i = 0;
  7401. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7402. /* If we collide with an already moved fd... */
  7403. if (fd == sq[i].moved_to) {
  7404. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7405. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7406. if (sq[i].moved_to < 0) /* what? */
  7407. xfunc_die();
  7408. return sq;
  7409. }
  7410. if (fd == sq[i].orig_fd) {
  7411. /* Example: echo Hello >/dev/null 1>&2 */
  7412. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7413. return sq;
  7414. }
  7415. }
  7416. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7417. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7418. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7419. if (moved_to < 0 && errno != EBADF)
  7420. xfunc_die();
  7421. return append_squirrel(sq, i, fd, moved_to);
  7422. }
  7423. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7424. {
  7425. int i;
  7426. i = 0;
  7427. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7428. /* If we collide with an already moved fd... */
  7429. if (fd == sq[i].orig_fd) {
  7430. /* Examples:
  7431. * "echo 3>FILE 3>&- 3>FILE"
  7432. * "echo 3>&- 3>FILE"
  7433. * No need for last redirect to insert
  7434. * another "need to close 3" indicator.
  7435. */
  7436. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7437. return sq;
  7438. }
  7439. }
  7440. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7441. return append_squirrel(sq, i, fd, -1);
  7442. }
  7443. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7444. * Move all conflicting internally used fds,
  7445. * and remember them so that we can restore them later.
  7446. */
  7447. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7448. {
  7449. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7450. avoid_fd = 9;
  7451. #if ENABLE_HUSH_INTERACTIVE
  7452. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7453. && fd == G_interactive_fd
  7454. ) {
  7455. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7456. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7457. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7458. return 1; /* "we closed fd" */
  7459. }
  7460. #endif
  7461. /* Are we called from setup_redirects(squirrel==NULL)
  7462. * in redirect in a [v]forked child?
  7463. */
  7464. if (sqp == NULL) {
  7465. /* No need to move script fds.
  7466. * For NOMMU case, it's actively wrong: we'd change ->fd
  7467. * fields in memory for the parent, but parent's fds
  7468. * aren't moved, it would use wrong fd!
  7469. * Reproducer: "cmd 3>FILE" in script.
  7470. * If we would call move_HFILEs_on_redirect(), child would:
  7471. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7472. * close(3) = 0
  7473. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7474. */
  7475. //bb_error_msg("sqp == NULL: [v]forked child");
  7476. return 0;
  7477. }
  7478. /* If this one of script's fds? */
  7479. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7480. return 1; /* yes. "we closed fd" (actually moved it) */
  7481. /* Are we called for "exec 3>FILE"? Came through
  7482. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7483. * This case used to fail for this script:
  7484. * exec 3>FILE
  7485. * echo Ok
  7486. * ...100000 more lines...
  7487. * echo Ok
  7488. * as follows:
  7489. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7490. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7491. * dup2(4, 3) = 3
  7492. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7493. * close(4) = 0
  7494. * write(1, "Ok\n", 3) = 3
  7495. * ... = 3
  7496. * write(1, "Ok\n", 3) = 3
  7497. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7498. * ^^^^^^^^ oops, wrong fd!!!
  7499. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7500. * it now works:
  7501. */
  7502. if (sqp == ERR_PTR) {
  7503. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7504. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7505. return 0;
  7506. }
  7507. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7508. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7509. return 0; /* "we did not close fd" */
  7510. }
  7511. static void restore_redirects(struct squirrel *sq)
  7512. {
  7513. if (sq) {
  7514. int i;
  7515. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7516. if (sq[i].moved_to >= 0) {
  7517. /* We simply die on error */
  7518. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7519. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7520. } else {
  7521. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7522. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7523. close(sq[i].orig_fd);
  7524. }
  7525. }
  7526. free(sq);
  7527. }
  7528. if (G.HFILE_stdin
  7529. && G.HFILE_stdin->fd > STDIN_FILENO
  7530. /* we compare > STDIN, not == STDIN, since hfgetc()
  7531. * closes fd and sets ->fd to -1 if EOF is reached.
  7532. * Testcase: echo 'pwd' | hush
  7533. */
  7534. ) {
  7535. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7536. * Redirect moves ->fd to e.g. 10,
  7537. * and it is not restored above (we do not restore script fds
  7538. * after redirects, we just use new, "moved" fds).
  7539. * However for stdin, get_user_input() -> read_line_input(),
  7540. * and read builtin, depend on fd == STDIN_FILENO.
  7541. */
  7542. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7543. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7544. G.HFILE_stdin->fd = STDIN_FILENO;
  7545. }
  7546. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7547. }
  7548. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7549. static void close_saved_fds_and_FILE_fds(void)
  7550. {
  7551. if (G_interactive_fd)
  7552. close(G_interactive_fd);
  7553. close_all_HFILE_list();
  7554. }
  7555. #endif
  7556. static int internally_opened_fd(int fd, struct squirrel *sq)
  7557. {
  7558. int i;
  7559. #if ENABLE_HUSH_INTERACTIVE
  7560. if (fd == G_interactive_fd)
  7561. return 1;
  7562. #endif
  7563. /* If this one of script's fds? */
  7564. if (fd_in_HFILEs(fd))
  7565. return 1;
  7566. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7567. if (fd == sq[i].moved_to)
  7568. return 1;
  7569. }
  7570. return 0;
  7571. }
  7572. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7573. * and stderr if they are redirected. */
  7574. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7575. {
  7576. struct redir_struct *redir;
  7577. for (redir = prog->redirects; redir; redir = redir->next) {
  7578. int newfd;
  7579. int closed;
  7580. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7581. /* "rd_fd<<HERE" case */
  7582. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7583. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7584. * of the heredoc */
  7585. debug_printf_redir("set heredoc '%s'\n",
  7586. redir->rd_filename);
  7587. setup_heredoc(redir);
  7588. continue;
  7589. }
  7590. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7591. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7592. char *p;
  7593. int mode;
  7594. if (redir->rd_filename == NULL) {
  7595. /* Examples:
  7596. * "cmd >" (no filename)
  7597. * "cmd > <file" (2nd redirect starts too early)
  7598. */
  7599. syntax_error("invalid redirect");
  7600. continue;
  7601. }
  7602. mode = redir_table[redir->rd_type].mode;
  7603. p = expand_string_to_string(redir->rd_filename,
  7604. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7605. newfd = open_or_warn(p, mode);
  7606. free(p);
  7607. if (newfd < 0) {
  7608. /* Error message from open_or_warn can be lost
  7609. * if stderr has been redirected, but bash
  7610. * and ash both lose it as well
  7611. * (though zsh doesn't!)
  7612. */
  7613. return 1;
  7614. }
  7615. if (newfd == redir->rd_fd && sqp) {
  7616. /* open() gave us precisely the fd we wanted.
  7617. * This means that this fd was not busy
  7618. * (not opened to anywhere).
  7619. * Remember to close it on restore:
  7620. */
  7621. *sqp = add_squirrel_closed(*sqp, newfd);
  7622. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7623. }
  7624. } else {
  7625. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7626. newfd = redir->rd_dup;
  7627. }
  7628. if (newfd == redir->rd_fd)
  7629. continue;
  7630. /* if "N>FILE": move newfd to redir->rd_fd */
  7631. /* if "N>&M": dup newfd to redir->rd_fd */
  7632. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7633. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7634. if (newfd == REDIRFD_CLOSE) {
  7635. /* "N>&-" means "close me" */
  7636. if (!closed) {
  7637. /* ^^^ optimization: saving may already
  7638. * have closed it. If not... */
  7639. close(redir->rd_fd);
  7640. }
  7641. /* Sometimes we do another close on restore, getting EBADF.
  7642. * Consider "echo 3>FILE 3>&-"
  7643. * first redirect remembers "need to close 3",
  7644. * and second redirect closes 3! Restore code then closes 3 again.
  7645. */
  7646. } else {
  7647. /* if newfd is a script fd or saved fd, simulate EBADF */
  7648. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7649. //errno = EBADF;
  7650. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7651. newfd = -1; /* same effect as code above */
  7652. }
  7653. xdup2(newfd, redir->rd_fd);
  7654. if (redir->rd_dup == REDIRFD_TO_FILE)
  7655. /* "rd_fd > FILE" */
  7656. close(newfd);
  7657. /* else: "rd_fd > rd_dup" */
  7658. }
  7659. }
  7660. return 0;
  7661. }
  7662. static char *find_in_path(const char *arg)
  7663. {
  7664. char *ret = NULL;
  7665. const char *PATH = get_local_var_value("PATH");
  7666. if (!PATH)
  7667. return NULL;
  7668. while (1) {
  7669. const char *end = strchrnul(PATH, ':');
  7670. int sz = end - PATH; /* must be int! */
  7671. free(ret);
  7672. if (sz != 0) {
  7673. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7674. } else {
  7675. /* We have xxx::yyyy in $PATH,
  7676. * it means "use current dir" */
  7677. ret = xstrdup(arg);
  7678. }
  7679. if (access(ret, F_OK) == 0)
  7680. break;
  7681. if (*end == '\0') {
  7682. free(ret);
  7683. return NULL;
  7684. }
  7685. PATH = end + 1;
  7686. }
  7687. return ret;
  7688. }
  7689. static const struct built_in_command *find_builtin_helper(const char *name,
  7690. const struct built_in_command *x,
  7691. const struct built_in_command *end)
  7692. {
  7693. while (x != end) {
  7694. if (strcmp(name, x->b_cmd) != 0) {
  7695. x++;
  7696. continue;
  7697. }
  7698. debug_printf_exec("found builtin '%s'\n", name);
  7699. return x;
  7700. }
  7701. return NULL;
  7702. }
  7703. static const struct built_in_command *find_builtin1(const char *name)
  7704. {
  7705. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7706. }
  7707. static const struct built_in_command *find_builtin(const char *name)
  7708. {
  7709. const struct built_in_command *x = find_builtin1(name);
  7710. if (x)
  7711. return x;
  7712. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7713. }
  7714. #if ENABLE_HUSH_JOB && ENABLE_FEATURE_TAB_COMPLETION
  7715. static const char * FAST_FUNC hush_command_name(int i)
  7716. {
  7717. if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
  7718. return bltins1[i].b_cmd;
  7719. }
  7720. i -= ARRAY_SIZE(bltins1);
  7721. if (i < ARRAY_SIZE(bltins2)) {
  7722. return bltins2[i].b_cmd;
  7723. }
  7724. # if ENABLE_HUSH_FUNCTIONS
  7725. {
  7726. struct function *funcp;
  7727. i -= ARRAY_SIZE(bltins2);
  7728. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  7729. if (--i < 0)
  7730. return funcp->name;
  7731. }
  7732. }
  7733. # endif
  7734. return NULL;
  7735. }
  7736. #endif
  7737. static void remove_nested_vars(void)
  7738. {
  7739. struct variable *cur;
  7740. struct variable **cur_pp;
  7741. cur_pp = &G.top_var;
  7742. while ((cur = *cur_pp) != NULL) {
  7743. if (cur->var_nest_level <= G.var_nest_level) {
  7744. cur_pp = &cur->next;
  7745. continue;
  7746. }
  7747. /* Unexport */
  7748. if (cur->flg_export) {
  7749. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7750. bb_unsetenv(cur->varstr);
  7751. }
  7752. /* Remove from global list */
  7753. *cur_pp = cur->next;
  7754. /* Free */
  7755. if (!cur->max_len) {
  7756. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7757. free(cur->varstr);
  7758. }
  7759. free(cur);
  7760. }
  7761. }
  7762. static void enter_var_nest_level(void)
  7763. {
  7764. G.var_nest_level++;
  7765. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7766. /* Try: f() { echo -n .; f; }; f
  7767. * struct variable::var_nest_level is uint16_t,
  7768. * thus limiting recursion to < 2^16.
  7769. * In any case, with 8 Mbyte stack SEGV happens
  7770. * not too long after 2^16 recursions anyway.
  7771. */
  7772. if (G.var_nest_level > 0xff00)
  7773. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7774. }
  7775. static void leave_var_nest_level(void)
  7776. {
  7777. G.var_nest_level--;
  7778. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7779. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7780. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7781. remove_nested_vars();
  7782. }
  7783. #if ENABLE_HUSH_FUNCTIONS
  7784. static struct function **find_function_slot(const char *name)
  7785. {
  7786. struct function *funcp;
  7787. struct function **funcpp = &G.top_func;
  7788. while ((funcp = *funcpp) != NULL) {
  7789. if (strcmp(name, funcp->name) == 0) {
  7790. debug_printf_exec("found function '%s'\n", name);
  7791. break;
  7792. }
  7793. funcpp = &funcp->next;
  7794. }
  7795. return funcpp;
  7796. }
  7797. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7798. {
  7799. const struct function *funcp = *find_function_slot(name);
  7800. return funcp;
  7801. }
  7802. /* Note: takes ownership on name ptr */
  7803. static struct function *new_function(char *name)
  7804. {
  7805. struct function **funcpp = find_function_slot(name);
  7806. struct function *funcp = *funcpp;
  7807. if (funcp != NULL) {
  7808. struct command *cmd = funcp->parent_cmd;
  7809. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7810. if (!cmd) {
  7811. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7812. free(funcp->name);
  7813. /* Note: if !funcp->body, do not free body_as_string!
  7814. * This is a special case of "-F name body" function:
  7815. * body_as_string was not malloced! */
  7816. if (funcp->body) {
  7817. free_pipe_list(funcp->body);
  7818. # if !BB_MMU
  7819. free(funcp->body_as_string);
  7820. # endif
  7821. }
  7822. } else {
  7823. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7824. cmd->argv[0] = funcp->name;
  7825. cmd->group = funcp->body;
  7826. # if !BB_MMU
  7827. cmd->group_as_string = funcp->body_as_string;
  7828. # endif
  7829. }
  7830. } else {
  7831. debug_printf_exec("remembering new function '%s'\n", name);
  7832. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7833. /*funcp->next = NULL;*/
  7834. }
  7835. funcp->name = name;
  7836. return funcp;
  7837. }
  7838. # if ENABLE_HUSH_UNSET
  7839. static void unset_func(const char *name)
  7840. {
  7841. struct function **funcpp = find_function_slot(name);
  7842. struct function *funcp = *funcpp;
  7843. if (funcp != NULL) {
  7844. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7845. *funcpp = funcp->next;
  7846. /* funcp is unlinked now, deleting it.
  7847. * Note: if !funcp->body, the function was created by
  7848. * "-F name body", do not free ->body_as_string
  7849. * and ->name as they were not malloced. */
  7850. if (funcp->body) {
  7851. free_pipe_list(funcp->body);
  7852. free(funcp->name);
  7853. # if !BB_MMU
  7854. free(funcp->body_as_string);
  7855. # endif
  7856. }
  7857. free(funcp);
  7858. }
  7859. }
  7860. # endif
  7861. # if BB_MMU
  7862. #define exec_function(to_free, funcp, argv) \
  7863. exec_function(funcp, argv)
  7864. # endif
  7865. static void exec_function(char ***to_free,
  7866. const struct function *funcp,
  7867. char **argv) NORETURN;
  7868. static void exec_function(char ***to_free,
  7869. const struct function *funcp,
  7870. char **argv)
  7871. {
  7872. # if BB_MMU
  7873. int n;
  7874. argv[0] = G.global_argv[0];
  7875. G.global_argv = argv;
  7876. G.global_argc = n = 1 + string_array_len(argv + 1);
  7877. // Example when we are here: "cmd | func"
  7878. // func will run with saved-redirect fds open.
  7879. // $ f() { echo /proc/self/fd/*; }
  7880. // $ true | f
  7881. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7882. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7883. // Same in script:
  7884. // $ . ./SCRIPT
  7885. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7886. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7887. // They are CLOEXEC so external programs won't see them, but
  7888. // for "more correctness" we might want to close those extra fds here:
  7889. //? close_saved_fds_and_FILE_fds();
  7890. /* "we are in a function, ok to use return" */
  7891. G_flag_return_in_progress = -1;
  7892. enter_var_nest_level();
  7893. IF_HUSH_LOCAL(G.func_nest_level++;)
  7894. /* On MMU, funcp->body is always non-NULL */
  7895. n = run_list(funcp->body);
  7896. _exit(n);
  7897. # else
  7898. //? close_saved_fds_and_FILE_fds();
  7899. //TODO: check whether "true | func_with_return" works
  7900. re_execute_shell(to_free,
  7901. funcp->body_as_string,
  7902. G.global_argv[0],
  7903. argv + 1,
  7904. NULL);
  7905. # endif
  7906. }
  7907. static int run_function(const struct function *funcp, char **argv)
  7908. {
  7909. int rc;
  7910. save_arg_t sv;
  7911. smallint sv_flg;
  7912. save_and_replace_G_args(&sv, argv);
  7913. /* "We are in function, ok to use return" */
  7914. sv_flg = G_flag_return_in_progress;
  7915. G_flag_return_in_progress = -1;
  7916. /* Make "local" variables properly shadow previous ones */
  7917. IF_HUSH_LOCAL(enter_var_nest_level();)
  7918. IF_HUSH_LOCAL(G.func_nest_level++;)
  7919. /* On MMU, funcp->body is always non-NULL */
  7920. # if !BB_MMU
  7921. if (!funcp->body) {
  7922. /* Function defined by -F */
  7923. parse_and_run_string(funcp->body_as_string);
  7924. rc = G.last_exitcode;
  7925. } else
  7926. # endif
  7927. {
  7928. rc = run_list(funcp->body);
  7929. }
  7930. IF_HUSH_LOCAL(G.func_nest_level--;)
  7931. IF_HUSH_LOCAL(leave_var_nest_level();)
  7932. G_flag_return_in_progress = sv_flg;
  7933. # if ENABLE_HUSH_TRAP
  7934. debug_printf_exec("G.return_exitcode=-1\n");
  7935. G.return_exitcode = -1; /* invalidate stashed return value */
  7936. # endif
  7937. restore_G_args(&sv, argv);
  7938. return rc;
  7939. }
  7940. #endif /* ENABLE_HUSH_FUNCTIONS */
  7941. #if BB_MMU
  7942. #define exec_builtin(to_free, x, argv) \
  7943. exec_builtin(x, argv)
  7944. #else
  7945. #define exec_builtin(to_free, x, argv) \
  7946. exec_builtin(to_free, argv)
  7947. #endif
  7948. static void exec_builtin(char ***to_free,
  7949. const struct built_in_command *x,
  7950. char **argv) NORETURN;
  7951. static void exec_builtin(char ***to_free,
  7952. const struct built_in_command *x,
  7953. char **argv)
  7954. {
  7955. #if BB_MMU
  7956. int rcode;
  7957. //? close_saved_fds_and_FILE_fds();
  7958. rcode = x->b_function(argv);
  7959. fflush_all();
  7960. _exit(rcode);
  7961. #else
  7962. fflush_all();
  7963. /* On NOMMU, we must never block!
  7964. * Example: { sleep 99 | read line; } & echo Ok
  7965. */
  7966. re_execute_shell(to_free,
  7967. argv[0],
  7968. G.global_argv[0],
  7969. G.global_argv + 1,
  7970. argv);
  7971. #endif
  7972. }
  7973. static void execvp_or_die(char **argv) NORETURN;
  7974. static void execvp_or_die(char **argv)
  7975. {
  7976. int e;
  7977. debug_printf_exec("execing '%s'\n", argv[0]);
  7978. /* Don't propagate SIG_IGN to the child */
  7979. if (SPECIAL_JOBSTOP_SIGS != 0)
  7980. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7981. execvp(argv[0], argv);
  7982. e = 2;
  7983. if (errno == EACCES) e = 126;
  7984. if (errno == ENOENT) e = 127;
  7985. bb_perror_msg("can't execute '%s'", argv[0]);
  7986. _exit(e);
  7987. }
  7988. #if ENABLE_HUSH_MODE_X
  7989. static void x_mode_print_optionally_squoted(const char *str)
  7990. {
  7991. unsigned len;
  7992. const char *cp;
  7993. cp = str;
  7994. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7995. /* test a char with: bash -c 'set -x; echo "CH"' */
  7996. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7997. " " "\001\002\003\004\005\006\007"
  7998. "\010\011\012\013\014\015\016\017"
  7999. "\020\021\022\023\024\025\026\027"
  8000. "\030\031\032\033\034\035\036\037"
  8001. )
  8002. ] == '\0'
  8003. ) {
  8004. /* string has no special chars */
  8005. x_mode_addstr(str);
  8006. return;
  8007. }
  8008. cp = str;
  8009. for (;;) {
  8010. /* print '....' up to EOL or first squote */
  8011. len = (int)(strchrnul(cp, '\'') - cp);
  8012. if (len != 0) {
  8013. x_mode_addchr('\'');
  8014. x_mode_addblock(cp, len);
  8015. x_mode_addchr('\'');
  8016. cp += len;
  8017. }
  8018. if (*cp == '\0')
  8019. break;
  8020. /* string contains squote(s), print them as \' */
  8021. x_mode_addchr('\\');
  8022. x_mode_addchr('\'');
  8023. cp++;
  8024. }
  8025. }
  8026. static void dump_cmd_in_x_mode(char **argv)
  8027. {
  8028. if (G_x_mode && argv) {
  8029. unsigned n;
  8030. /* "+[+++...][ cmd...]\n\0" */
  8031. x_mode_prefix();
  8032. n = 0;
  8033. while (argv[n]) {
  8034. x_mode_addchr(' ');
  8035. if (argv[n][0] == '\0') {
  8036. x_mode_addchr('\'');
  8037. x_mode_addchr('\'');
  8038. } else {
  8039. x_mode_print_optionally_squoted(argv[n]);
  8040. }
  8041. n++;
  8042. }
  8043. x_mode_flush();
  8044. }
  8045. }
  8046. #else
  8047. # define dump_cmd_in_x_mode(argv) ((void)0)
  8048. #endif
  8049. #if ENABLE_HUSH_COMMAND
  8050. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  8051. {
  8052. char *to_free;
  8053. if (!opt_vV)
  8054. return;
  8055. to_free = NULL;
  8056. if (!explanation) {
  8057. char *path = getenv("PATH");
  8058. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  8059. if (!explanation)
  8060. _exit(1); /* PROG was not found */
  8061. if (opt_vV != 'V')
  8062. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  8063. }
  8064. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  8065. free(to_free);
  8066. fflush_all();
  8067. _exit(0);
  8068. }
  8069. #else
  8070. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  8071. #endif
  8072. #if BB_MMU
  8073. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  8074. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  8075. #define pseudo_exec(nommu_save, command, argv_expanded) \
  8076. pseudo_exec(command, argv_expanded)
  8077. #endif
  8078. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  8079. * Never returns.
  8080. * Don't exit() here. If you don't exec, use _exit instead.
  8081. * The at_exit handlers apparently confuse the calling process,
  8082. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  8083. */
  8084. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  8085. char **argv, int assignment_cnt,
  8086. char **argv_expanded) NORETURN;
  8087. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  8088. char **argv, int assignment_cnt,
  8089. char **argv_expanded)
  8090. {
  8091. const struct built_in_command *x;
  8092. struct variable **sv_shadowed;
  8093. char **new_env;
  8094. IF_HUSH_COMMAND(char opt_vV = 0;)
  8095. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8096. new_env = expand_assignments(argv, assignment_cnt);
  8097. dump_cmd_in_x_mode(new_env);
  8098. if (!argv[assignment_cnt]) {
  8099. /* Case when we are here: ... | var=val | ...
  8100. * (note that we do not exit early, i.e., do not optimize out
  8101. * expand_assignments(): think about ... | var=`sleep 1` | ...
  8102. */
  8103. free_strings(new_env);
  8104. _exit_SUCCESS();
  8105. }
  8106. sv_shadowed = G.shadowed_vars_pp;
  8107. #if BB_MMU
  8108. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  8109. #else
  8110. G.shadowed_vars_pp = &nommu_save->old_vars;
  8111. G.var_nest_level++;
  8112. #endif
  8113. set_vars_and_save_old(new_env);
  8114. G.shadowed_vars_pp = sv_shadowed;
  8115. if (argv_expanded) {
  8116. argv = argv_expanded;
  8117. } else {
  8118. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  8119. #if !BB_MMU
  8120. nommu_save->argv = argv;
  8121. #endif
  8122. }
  8123. dump_cmd_in_x_mode(argv);
  8124. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8125. if (strchr(argv[0], '/') != NULL)
  8126. goto skip;
  8127. #endif
  8128. #if ENABLE_HUSH_FUNCTIONS
  8129. /* Check if the command matches any functions (this goes before bltins) */
  8130. funcp = find_function(argv[0]);
  8131. if (funcp)
  8132. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  8133. #endif
  8134. #if ENABLE_HUSH_COMMAND
  8135. /* "command BAR": run BAR without looking it up among functions
  8136. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  8137. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  8138. */
  8139. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  8140. char *p;
  8141. argv++;
  8142. p = *argv;
  8143. if (p[0] != '-' || !p[1])
  8144. continue; /* bash allows "command command command [-OPT] BAR" */
  8145. for (;;) {
  8146. p++;
  8147. switch (*p) {
  8148. case '\0':
  8149. argv++;
  8150. p = *argv;
  8151. if (p[0] != '-' || !p[1])
  8152. goto after_opts;
  8153. continue; /* next arg is also -opts, process it too */
  8154. case 'v':
  8155. case 'V':
  8156. opt_vV = *p;
  8157. continue;
  8158. default:
  8159. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  8160. }
  8161. }
  8162. }
  8163. after_opts:
  8164. # if ENABLE_HUSH_FUNCTIONS
  8165. if (opt_vV && find_function(argv[0]))
  8166. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  8167. # endif
  8168. #endif
  8169. /* Check if the command matches any of the builtins.
  8170. * Depending on context, this might be redundant. But it's
  8171. * easier to waste a few CPU cycles than it is to figure out
  8172. * if this is one of those cases.
  8173. */
  8174. /* Why "BB_MMU ? :" difference in logic? -
  8175. * On NOMMU, it is more expensive to re-execute shell
  8176. * just in order to run echo or test builtin.
  8177. * It's better to skip it here and run corresponding
  8178. * non-builtin later. */
  8179. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  8180. if (x) {
  8181. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  8182. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  8183. }
  8184. #if ENABLE_FEATURE_SH_STANDALONE
  8185. /* Check if the command matches any busybox applets */
  8186. {
  8187. int a = find_applet_by_name(argv[0]);
  8188. if (a >= 0) {
  8189. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  8190. # if BB_MMU /* see above why on NOMMU it is not allowed */
  8191. if (APPLET_IS_NOEXEC(a)) {
  8192. /* Do not leak open fds from opened script files etc.
  8193. * Testcase: interactive "ls -l /proc/self/fd"
  8194. * should not show tty fd open.
  8195. */
  8196. close_saved_fds_and_FILE_fds();
  8197. //FIXME: should also close saved redir fds
  8198. //This casuses test failures in
  8199. //redir_children_should_not_see_saved_fd_2.tests
  8200. //redir_children_should_not_see_saved_fd_3.tests
  8201. //if you replace "busybox find" with just "find" in them
  8202. /* Without this, "rm -i FILE" can't be ^C'ed: */
  8203. switch_off_special_sigs(G.special_sig_mask);
  8204. debug_printf_exec("running applet '%s'\n", argv[0]);
  8205. run_noexec_applet_and_exit(a, argv[0], argv);
  8206. }
  8207. # endif
  8208. /* Re-exec ourselves */
  8209. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  8210. /* Don't propagate SIG_IGN to the child */
  8211. if (SPECIAL_JOBSTOP_SIGS != 0)
  8212. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  8213. execv(bb_busybox_exec_path, argv);
  8214. /* If they called chroot or otherwise made the binary no longer
  8215. * executable, fall through */
  8216. }
  8217. }
  8218. #endif
  8219. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8220. skip:
  8221. #endif
  8222. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  8223. execvp_or_die(argv);
  8224. }
  8225. /* Called after [v]fork() in run_pipe
  8226. */
  8227. static void pseudo_exec(nommu_save_t *nommu_save,
  8228. struct command *command,
  8229. char **argv_expanded) NORETURN;
  8230. static void pseudo_exec(nommu_save_t *nommu_save,
  8231. struct command *command,
  8232. char **argv_expanded)
  8233. {
  8234. #if ENABLE_HUSH_FUNCTIONS
  8235. if (command->cmd_type == CMD_FUNCDEF) {
  8236. /* Ignore funcdefs in pipes:
  8237. * true | f() { cmd }
  8238. */
  8239. _exit(0);
  8240. }
  8241. #endif
  8242. if (command->argv) {
  8243. pseudo_exec_argv(nommu_save, command->argv,
  8244. command->assignment_cnt, argv_expanded);
  8245. }
  8246. if (command->group) {
  8247. /* Cases when we are here:
  8248. * ( list )
  8249. * { list } &
  8250. * ... | ( list ) | ...
  8251. * ... | { list } | ...
  8252. */
  8253. #if BB_MMU
  8254. int rcode;
  8255. debug_printf_exec("pseudo_exec: run_list\n");
  8256. reset_traps_to_defaults();
  8257. rcode = run_list(command->group);
  8258. /* OK to leak memory by not calling free_pipe_list,
  8259. * since this process is about to exit */
  8260. _exit(rcode);
  8261. #else
  8262. re_execute_shell(&nommu_save->argv_from_re_execing,
  8263. command->group_as_string,
  8264. G.global_argv[0],
  8265. G.global_argv + 1,
  8266. NULL);
  8267. #endif
  8268. }
  8269. /* Case when we are here: ... | >file */
  8270. debug_printf_exec("pseudo_exec'ed null command\n");
  8271. _exit_SUCCESS();
  8272. }
  8273. #if ENABLE_HUSH_JOB
  8274. static const char *get_cmdtext(struct pipe *pi)
  8275. {
  8276. char **argv;
  8277. char *p;
  8278. int len;
  8279. /* This is subtle. ->cmdtext is created only on first backgrounding.
  8280. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  8281. * On subsequent bg argv is trashed, but we won't use it */
  8282. if (pi->cmdtext)
  8283. return pi->cmdtext;
  8284. argv = pi->cmds[0].argv;
  8285. if (!argv) {
  8286. pi->cmdtext = xzalloc(1);
  8287. return pi->cmdtext;
  8288. }
  8289. len = 0;
  8290. do {
  8291. len += strlen(*argv) + 1;
  8292. } while (*++argv);
  8293. p = xmalloc(len);
  8294. pi->cmdtext = p;
  8295. argv = pi->cmds[0].argv;
  8296. do {
  8297. p = stpcpy(p, *argv);
  8298. *p++ = ' ';
  8299. } while (*++argv);
  8300. p[-1] = '\0';
  8301. return pi->cmdtext;
  8302. }
  8303. static void remove_job_from_table(struct pipe *pi)
  8304. {
  8305. struct pipe *prev_pipe;
  8306. if (pi == G.job_list) {
  8307. G.job_list = pi->next;
  8308. } else {
  8309. prev_pipe = G.job_list;
  8310. while (prev_pipe->next != pi)
  8311. prev_pipe = prev_pipe->next;
  8312. prev_pipe->next = pi->next;
  8313. }
  8314. G.last_jobid = 0;
  8315. if (G.job_list)
  8316. G.last_jobid = G.job_list->jobid;
  8317. }
  8318. static void delete_finished_job(struct pipe *pi)
  8319. {
  8320. remove_job_from_table(pi);
  8321. free_pipe(pi);
  8322. }
  8323. static void clean_up_last_dead_job(void)
  8324. {
  8325. if (G.job_list && !G.job_list->alive_cmds)
  8326. delete_finished_job(G.job_list);
  8327. }
  8328. static void insert_job_into_table(struct pipe *pi)
  8329. {
  8330. struct pipe *job, **jobp;
  8331. int i;
  8332. clean_up_last_dead_job();
  8333. /* Find the end of the list, and find next job ID to use */
  8334. i = 0;
  8335. jobp = &G.job_list;
  8336. while ((job = *jobp) != NULL) {
  8337. if (job->jobid > i)
  8338. i = job->jobid;
  8339. jobp = &job->next;
  8340. }
  8341. pi->jobid = i + 1;
  8342. /* Create a new job struct at the end */
  8343. job = *jobp = xmemdup(pi, sizeof(*pi));
  8344. job->next = NULL;
  8345. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  8346. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  8347. for (i = 0; i < pi->num_cmds; i++) {
  8348. job->cmds[i].pid = pi->cmds[i].pid;
  8349. /* all other fields are not used and stay zero */
  8350. }
  8351. job->cmdtext = xstrdup(get_cmdtext(pi));
  8352. if (G_interactive_fd)
  8353. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8354. G.last_jobid = job->jobid;
  8355. }
  8356. #endif /* JOB */
  8357. static int job_exited_or_stopped(struct pipe *pi)
  8358. {
  8359. int rcode, i;
  8360. if (pi->alive_cmds != pi->stopped_cmds)
  8361. return -1;
  8362. /* All processes in fg pipe have exited or stopped */
  8363. rcode = 0;
  8364. i = pi->num_cmds;
  8365. while (--i >= 0) {
  8366. rcode = pi->cmds[i].cmd_exitcode;
  8367. /* usually last process gives overall exitstatus,
  8368. * but with "set -o pipefail", last *failed* process does */
  8369. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8370. break;
  8371. }
  8372. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8373. return rcode;
  8374. }
  8375. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8376. {
  8377. #if ENABLE_HUSH_JOB
  8378. struct pipe *pi;
  8379. #endif
  8380. int i, dead;
  8381. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8382. #if DEBUG_JOBS
  8383. if (WIFSTOPPED(status))
  8384. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8385. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8386. if (WIFSIGNALED(status))
  8387. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8388. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8389. if (WIFEXITED(status))
  8390. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8391. childpid, WEXITSTATUS(status));
  8392. #endif
  8393. /* Were we asked to wait for a fg pipe? */
  8394. if (fg_pipe) {
  8395. i = fg_pipe->num_cmds;
  8396. while (--i >= 0) {
  8397. int rcode;
  8398. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8399. if (fg_pipe->cmds[i].pid != childpid)
  8400. continue;
  8401. if (dead) {
  8402. int ex;
  8403. fg_pipe->cmds[i].pid = 0;
  8404. fg_pipe->alive_cmds--;
  8405. ex = WEXITSTATUS(status);
  8406. /* bash prints killer signal's name for *last*
  8407. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8408. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8409. */
  8410. if (WIFSIGNALED(status)) {
  8411. int sig = WTERMSIG(status);
  8412. #if ENABLE_HUSH_JOB
  8413. if (G.run_list_level == 1
  8414. /* ^^^^^ Do not print in nested contexts, example:
  8415. * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
  8416. */
  8417. && i == fg_pipe->num_cmds-1
  8418. ) {
  8419. /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
  8420. puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
  8421. }
  8422. #endif
  8423. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8424. /* MIPS has 128 sigs (1..128), if sig==128,
  8425. * 128 + sig would result in exitcode 256 -> 0!
  8426. */
  8427. ex = 128 | sig;
  8428. }
  8429. fg_pipe->cmds[i].cmd_exitcode = ex;
  8430. } else {
  8431. fg_pipe->stopped_cmds++;
  8432. }
  8433. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8434. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8435. rcode = job_exited_or_stopped(fg_pipe);
  8436. if (rcode >= 0) {
  8437. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8438. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8439. * and "killall -STOP cat" */
  8440. if (G_interactive_fd) {
  8441. #if ENABLE_HUSH_JOB
  8442. if (fg_pipe->alive_cmds != 0)
  8443. insert_job_into_table(fg_pipe);
  8444. #endif
  8445. return rcode;
  8446. }
  8447. if (fg_pipe->alive_cmds == 0)
  8448. return rcode;
  8449. }
  8450. /* There are still running processes in the fg_pipe */
  8451. return -1;
  8452. }
  8453. /* It wasn't in fg_pipe, look for process in bg pipes */
  8454. }
  8455. #if ENABLE_HUSH_JOB
  8456. /* We were asked to wait for bg or orphaned children */
  8457. /* No need to remember exitcode in this case */
  8458. for (pi = G.job_list; pi; pi = pi->next) {
  8459. for (i = 0; i < pi->num_cmds; i++) {
  8460. if (pi->cmds[i].pid == childpid)
  8461. goto found_pi_and_prognum;
  8462. }
  8463. }
  8464. /* Happens when shell is used as init process (init=/bin/sh) */
  8465. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8466. return -1; /* this wasn't a process from fg_pipe */
  8467. found_pi_and_prognum:
  8468. if (dead) {
  8469. /* child exited */
  8470. int rcode = WEXITSTATUS(status);
  8471. if (WIFSIGNALED(status))
  8472. /* NB: not 128 + sig, MIPS has sig 128 */
  8473. rcode = 128 | WTERMSIG(status);
  8474. pi->cmds[i].cmd_exitcode = rcode;
  8475. if (G.last_bg_pid == pi->cmds[i].pid)
  8476. G.last_bg_pid_exitcode = rcode;
  8477. pi->cmds[i].pid = 0;
  8478. pi->alive_cmds--;
  8479. if (!pi->alive_cmds) {
  8480. # if ENABLE_HUSH_BASH_COMPAT
  8481. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8482. # endif
  8483. if (G_interactive_fd) {
  8484. printf(JOB_STATUS_FORMAT, pi->jobid,
  8485. "Done", pi->cmdtext);
  8486. delete_finished_job(pi);
  8487. } else {
  8488. /*
  8489. * bash deletes finished jobs from job table only in interactive mode,
  8490. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8491. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8492. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8493. * We only retain one "dead" job, if it's the single job on the list.
  8494. * This covers most of real-world scenarios where this is useful.
  8495. */
  8496. if (pi != G.job_list)
  8497. delete_finished_job(pi);
  8498. }
  8499. }
  8500. } else {
  8501. /* child stopped */
  8502. pi->stopped_cmds++;
  8503. }
  8504. #endif
  8505. return -1; /* this wasn't a process from fg_pipe */
  8506. }
  8507. /* Check to see if any processes have exited -- if they have,
  8508. * figure out why and see if a job has completed.
  8509. *
  8510. * If non-NULL fg_pipe: wait for its completion or stop.
  8511. * Return its exitcode or zero if stopped.
  8512. *
  8513. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8514. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8515. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8516. * or 0 if no children changed status.
  8517. *
  8518. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8519. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8520. * or 0 if no children changed status.
  8521. */
  8522. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8523. {
  8524. int attributes;
  8525. int status;
  8526. int rcode = 0;
  8527. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8528. attributes = WUNTRACED;
  8529. if (fg_pipe == NULL)
  8530. attributes |= WNOHANG;
  8531. errno = 0;
  8532. #if ENABLE_HUSH_FAST
  8533. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8534. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8535. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8536. /* There was neither fork nor SIGCHLD since last waitpid */
  8537. /* Avoid doing waitpid syscall if possible */
  8538. if (!G.we_have_children) {
  8539. errno = ECHILD;
  8540. return -1;
  8541. }
  8542. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8543. /* We have children, but they did not exit
  8544. * or stop yet (we saw no SIGCHLD) */
  8545. return 0;
  8546. }
  8547. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8548. }
  8549. #endif
  8550. /* Do we do this right?
  8551. * bash-3.00# sleep 20 | false
  8552. * <ctrl-Z pressed>
  8553. * [3]+ Stopped sleep 20 | false
  8554. * bash-3.00# echo $?
  8555. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8556. * [hush 1.14.0: yes we do it right]
  8557. */
  8558. while (1) {
  8559. pid_t childpid;
  8560. #if ENABLE_HUSH_FAST
  8561. int i;
  8562. i = G.count_SIGCHLD;
  8563. #endif
  8564. childpid = waitpid(-1, &status, attributes);
  8565. if (childpid <= 0) {
  8566. if (childpid && errno != ECHILD)
  8567. bb_simple_perror_msg("waitpid");
  8568. #if ENABLE_HUSH_FAST
  8569. else { /* Until next SIGCHLD, waitpid's are useless */
  8570. G.we_have_children = (childpid == 0);
  8571. G.handled_SIGCHLD = i;
  8572. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8573. }
  8574. #endif
  8575. /* ECHILD (no children), or 0 (no change in children status) */
  8576. rcode = childpid;
  8577. break;
  8578. }
  8579. rcode = process_wait_result(fg_pipe, childpid, status);
  8580. if (rcode >= 0) {
  8581. /* fg_pipe exited or stopped */
  8582. break;
  8583. }
  8584. if (childpid == waitfor_pid) { /* "wait PID" */
  8585. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8586. rcode = WEXITSTATUS(status);
  8587. if (WIFSIGNALED(status))
  8588. rcode = 128 | WTERMSIG(status);
  8589. if (WIFSTOPPED(status))
  8590. /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
  8591. rcode = 128 | WSTOPSIG(status);
  8592. rcode++;
  8593. break; /* "wait PID" called us, give it exitcode+1 */
  8594. }
  8595. #if ENABLE_HUSH_BASH_COMPAT
  8596. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8597. && G.dead_job_exitcode >= 0 /* some job did finish */
  8598. ) {
  8599. debug_printf_exec("waitfor_pid:-1\n");
  8600. rcode = G.dead_job_exitcode + 1;
  8601. break;
  8602. }
  8603. #endif
  8604. /* This wasn't one of our processes, or */
  8605. /* fg_pipe still has running processes, do waitpid again */
  8606. } /* while (waitpid succeeds)... */
  8607. return rcode;
  8608. }
  8609. #if ENABLE_HUSH_JOB
  8610. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8611. {
  8612. pid_t p;
  8613. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8614. if (G_saved_tty_pgrp) {
  8615. /* Job finished, move the shell to the foreground */
  8616. p = getpgrp(); /* our process group id */
  8617. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8618. tcsetpgrp(G_interactive_fd, p);
  8619. }
  8620. return rcode;
  8621. }
  8622. #endif
  8623. /* Start all the jobs, but don't wait for anything to finish.
  8624. * See checkjobs().
  8625. *
  8626. * Return code is normally -1, when the caller has to wait for children
  8627. * to finish to determine the exit status of the pipe. If the pipe
  8628. * is a simple builtin command, however, the action is done by the
  8629. * time run_pipe returns, and the exit code is provided as the
  8630. * return value.
  8631. *
  8632. * Returns -1 only if started some children. IOW: we have to
  8633. * mask out retvals of builtins etc with 0xff!
  8634. *
  8635. * The only case when we do not need to [v]fork is when the pipe
  8636. * is single, non-backgrounded, non-subshell command. Examples:
  8637. * cmd ; ... { list } ; ...
  8638. * cmd && ... { list } && ...
  8639. * cmd || ... { list } || ...
  8640. * If it is, then we can run cmd as a builtin, NOFORK,
  8641. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8642. * with run_list. If it isn't one of these, we fork and exec cmd.
  8643. *
  8644. * Cases when we must fork:
  8645. * non-single: cmd | cmd
  8646. * backgrounded: cmd & { list } &
  8647. * subshell: ( list ) [&]
  8648. */
  8649. static void set_G_ifs(void)
  8650. {
  8651. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8652. * Result should be 3 lines: q w e, qwe, q w e
  8653. */
  8654. if (G.ifs_whitespace != G.ifs)
  8655. free(G.ifs_whitespace);
  8656. G.ifs = get_local_var_value("IFS");
  8657. if (G.ifs) {
  8658. char *p;
  8659. G.ifs_whitespace = (char*)G.ifs;
  8660. p = skip_whitespace(G.ifs);
  8661. if (*p) {
  8662. /* Not all $IFS is whitespace */
  8663. char *d;
  8664. int len = p - G.ifs;
  8665. p = skip_non_whitespace(p);
  8666. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8667. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8668. while (*p) {
  8669. if (isspace(*p))
  8670. *d++ = *p;
  8671. p++;
  8672. }
  8673. *d = '\0';
  8674. }
  8675. } else {
  8676. G.ifs = defifs;
  8677. G.ifs_whitespace = (char*)G.ifs;
  8678. }
  8679. }
  8680. #if !ENABLE_HUSH_MODE_X
  8681. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8682. redirect_and_varexp_helper(command, sqp)
  8683. #endif
  8684. static int redirect_and_varexp_helper(
  8685. struct command *command,
  8686. struct squirrel **sqp,
  8687. char **argv_expanded)
  8688. {
  8689. /* Assignments occur before redirects. Try:
  8690. * a=`sleep 1` sleep 2 3>/qwe/rty
  8691. */
  8692. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8693. dump_cmd_in_x_mode(new_env);
  8694. dump_cmd_in_x_mode(argv_expanded);
  8695. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8696. set_vars_and_save_old(new_env);
  8697. return setup_redirects(command, sqp);
  8698. }
  8699. static NOINLINE int run_pipe(struct pipe *pi)
  8700. {
  8701. static const char *const null_ptr = NULL;
  8702. int cmd_no;
  8703. int next_infd;
  8704. struct command *command;
  8705. char **argv_expanded;
  8706. char **argv;
  8707. struct squirrel *squirrel = NULL;
  8708. int rcode;
  8709. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8710. debug_enter();
  8711. set_G_ifs();
  8712. IF_HUSH_JOB(pi->pgrp = -1;)
  8713. pi->stopped_cmds = 0;
  8714. command = &pi->cmds[0];
  8715. argv_expanded = NULL;
  8716. if (pi->num_cmds != 1
  8717. || pi->followup == PIPE_BG
  8718. || command->cmd_type == CMD_SUBSHELL
  8719. ) {
  8720. goto must_fork;
  8721. }
  8722. pi->alive_cmds = 1;
  8723. debug_printf_exec(": group:%p argv:'%s'\n",
  8724. command->group, command->argv ? command->argv[0] : "NONE");
  8725. if (command->group) {
  8726. #if ENABLE_HUSH_FUNCTIONS
  8727. if (command->cmd_type == CMD_FUNCDEF) {
  8728. /* "executing" func () { list } */
  8729. struct function *funcp;
  8730. funcp = new_function(command->argv[0]);
  8731. /* funcp->name is already set to argv[0] */
  8732. funcp->body = command->group;
  8733. # if !BB_MMU
  8734. funcp->body_as_string = command->group_as_string;
  8735. command->group_as_string = NULL;
  8736. # endif
  8737. command->group = NULL;
  8738. command->argv[0] = NULL;
  8739. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8740. funcp->parent_cmd = command;
  8741. command->child_func = funcp;
  8742. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8743. debug_leave();
  8744. return EXIT_SUCCESS;
  8745. }
  8746. #endif
  8747. /* { list } */
  8748. debug_printf_exec("non-subshell group\n");
  8749. rcode = 1; /* exitcode if redir failed */
  8750. if (setup_redirects(command, &squirrel) == 0) {
  8751. debug_printf_exec(": run_list\n");
  8752. //FIXME: we need to pass squirrel down into run_list()
  8753. //for SH_STANDALONE case, or else this construct:
  8754. // { find /proc/self/fd; true; } >FILE; cmd2
  8755. //has no way of closing saved fd#1 for "find",
  8756. //and in SH_STANDALONE mode, "find" is not execed,
  8757. //therefore CLOEXEC on saved fd does not help.
  8758. rcode = run_list(command->group) & 0xff;
  8759. }
  8760. restore_redirects(squirrel);
  8761. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8762. debug_leave();
  8763. debug_printf_exec("run_pipe: return %d\n", rcode);
  8764. return rcode;
  8765. }
  8766. argv = command->argv ? command->argv : (char **) &null_ptr;
  8767. {
  8768. const struct built_in_command *x;
  8769. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8770. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8771. struct variable **sv_shadowed;
  8772. struct variable *old_vars;
  8773. #if ENABLE_HUSH_LINENO_VAR
  8774. G.execute_lineno = command->lineno;
  8775. #endif
  8776. if (argv[command->assignment_cnt] == NULL) {
  8777. /* Assignments, but no command.
  8778. * Ensure redirects take effect (that is, create files).
  8779. * Try "a=t >file"
  8780. */
  8781. unsigned i;
  8782. G.expand_exitcode = 0;
  8783. only_assignments:
  8784. rcode = setup_redirects(command, &squirrel);
  8785. restore_redirects(squirrel);
  8786. /* Set shell variables */
  8787. i = 0;
  8788. while (i < command->assignment_cnt) {
  8789. char *p = expand_string_to_string(argv[i],
  8790. EXP_FLAG_ESC_GLOB_CHARS,
  8791. /*unbackslash:*/ 1
  8792. );
  8793. #if ENABLE_HUSH_MODE_X
  8794. if (G_x_mode) {
  8795. char *eq;
  8796. if (i == 0)
  8797. x_mode_prefix();
  8798. x_mode_addchr(' ');
  8799. eq = strchrnul(p, '=');
  8800. if (*eq) eq++;
  8801. x_mode_addblock(p, (eq - p));
  8802. x_mode_print_optionally_squoted(eq);
  8803. x_mode_flush();
  8804. }
  8805. #endif
  8806. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8807. if (set_local_var0(p)) {
  8808. /* assignment to readonly var / putenv error? */
  8809. rcode = 1;
  8810. }
  8811. i++;
  8812. }
  8813. /* Redirect error sets $? to 1. Otherwise,
  8814. * if evaluating assignment value set $?, retain it.
  8815. * Else, clear $?:
  8816. * false; q=`exit 2`; echo $? - should print 2
  8817. * false; x=1; echo $? - should print 0
  8818. * Because of the 2nd case, we can't just use G.last_exitcode.
  8819. */
  8820. if (rcode == 0)
  8821. rcode = G.expand_exitcode;
  8822. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8823. debug_leave();
  8824. debug_printf_exec("run_pipe: return %d\n", rcode);
  8825. return rcode;
  8826. }
  8827. /* Expand the rest into (possibly) many strings each */
  8828. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  8829. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
  8830. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8831. else
  8832. #endif
  8833. #if defined(CMD_SINGLEWORD_NOGLOB)
  8834. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8835. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8836. else
  8837. #endif
  8838. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8839. /* If someone gives us an empty string: `cmd with empty output` */
  8840. if (!argv_expanded[0]) {
  8841. free(argv_expanded);
  8842. /* `false` still has to set exitcode 1 */
  8843. G.expand_exitcode = G.last_exitcode;
  8844. goto only_assignments;
  8845. }
  8846. old_vars = NULL;
  8847. sv_shadowed = G.shadowed_vars_pp;
  8848. /* Check if argv[0] matches any functions (this goes before bltins) */
  8849. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8850. IF_HUSH_FUNCTIONS(x = NULL;)
  8851. IF_HUSH_FUNCTIONS(if (!funcp))
  8852. x = find_builtin(argv_expanded[0]);
  8853. if (x || funcp) {
  8854. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8855. debug_printf("exec with redirects only\n");
  8856. /*
  8857. * Variable assignments are executed, but then "forgotten":
  8858. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8859. * sleeps, but prints nothing.
  8860. */
  8861. enter_var_nest_level();
  8862. G.shadowed_vars_pp = &old_vars;
  8863. rcode = redirect_and_varexp_helper(command,
  8864. /*squirrel:*/ ERR_PTR,
  8865. argv_expanded
  8866. );
  8867. G.shadowed_vars_pp = sv_shadowed;
  8868. /* rcode=1 can be if redir file can't be opened */
  8869. goto clean_up_and_ret1;
  8870. }
  8871. /* Bump var nesting, or this will leak exported $a:
  8872. * a=b true; env | grep ^a=
  8873. */
  8874. enter_var_nest_level();
  8875. /* Collect all variables "shadowed" by helper
  8876. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8877. * into old_vars list:
  8878. */
  8879. G.shadowed_vars_pp = &old_vars;
  8880. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8881. if (rcode == 0) {
  8882. if (!funcp) {
  8883. /* Do not collect *to old_vars list* vars shadowed
  8884. * by e.g. "local VAR" builtin (collect them
  8885. * in the previously nested list instead):
  8886. * don't want them to be restored immediately
  8887. * after "local" completes.
  8888. */
  8889. G.shadowed_vars_pp = sv_shadowed;
  8890. debug_printf_exec(": builtin '%s' '%s'...\n",
  8891. x->b_cmd, argv_expanded[1]);
  8892. fflush_all();
  8893. rcode = x->b_function(argv_expanded) & 0xff;
  8894. fflush_all();
  8895. }
  8896. #if ENABLE_HUSH_FUNCTIONS
  8897. else {
  8898. debug_printf_exec(": function '%s' '%s'...\n",
  8899. funcp->name, argv_expanded[1]);
  8900. rcode = run_function(funcp, argv_expanded) & 0xff;
  8901. /*
  8902. * But do collect *to old_vars list* vars shadowed
  8903. * within function execution. To that end, restore
  8904. * this pointer _after_ function run:
  8905. */
  8906. G.shadowed_vars_pp = sv_shadowed;
  8907. }
  8908. #endif
  8909. }
  8910. } else
  8911. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8912. int n = find_applet_by_name(argv_expanded[0]);
  8913. if (n < 0 || !APPLET_IS_NOFORK(n))
  8914. goto must_fork;
  8915. enter_var_nest_level();
  8916. /* Collect all variables "shadowed" by helper into old_vars list */
  8917. G.shadowed_vars_pp = &old_vars;
  8918. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8919. G.shadowed_vars_pp = sv_shadowed;
  8920. if (rcode == 0) {
  8921. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8922. argv_expanded[0], argv_expanded[1]);
  8923. /*
  8924. * Note: signals (^C) can't interrupt here.
  8925. * We remember them and they will be acted upon
  8926. * after applet returns.
  8927. * This makes applets which can run for a long time
  8928. * and/or wait for user input ineligible for NOFORK:
  8929. * for example, "yes" or "rm" (rm -i waits for input).
  8930. */
  8931. rcode = run_nofork_applet(n, argv_expanded);
  8932. }
  8933. } else
  8934. goto must_fork;
  8935. restore_redirects(squirrel);
  8936. clean_up_and_ret1:
  8937. leave_var_nest_level();
  8938. add_vars(old_vars);
  8939. /*
  8940. * Try "usleep 99999999" + ^C + "echo $?"
  8941. * with FEATURE_SH_NOFORK=y.
  8942. */
  8943. if (!funcp) {
  8944. /* It was builtin or nofork.
  8945. * if this would be a real fork/execed program,
  8946. * it should have died if a fatal sig was received.
  8947. * But OTOH, there was no separate process,
  8948. * the sig was sent to _shell_, not to non-existing
  8949. * child.
  8950. * Let's just handle ^C only, this one is obvious:
  8951. * we aren't ok with exitcode 0 when ^C was pressed
  8952. * during builtin/nofork.
  8953. */
  8954. if (sigismember(&G.pending_set, SIGINT))
  8955. rcode = 128 | SIGINT;
  8956. }
  8957. free(argv_expanded);
  8958. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8959. debug_leave();
  8960. debug_printf_exec("run_pipe return %d\n", rcode);
  8961. return rcode;
  8962. }
  8963. must_fork:
  8964. /* NB: argv_expanded may already be created, and that
  8965. * might include `cmd` runs! Do not rerun it! We *must*
  8966. * use argv_expanded if it's non-NULL */
  8967. /* Going to fork a child per each pipe member */
  8968. pi->alive_cmds = 0;
  8969. next_infd = 0;
  8970. cmd_no = 0;
  8971. while (cmd_no < pi->num_cmds) {
  8972. struct fd_pair pipefds;
  8973. #if !BB_MMU
  8974. int sv_var_nest_level = G.var_nest_level;
  8975. volatile nommu_save_t nommu_save;
  8976. nommu_save.old_vars = NULL;
  8977. nommu_save.argv = NULL;
  8978. nommu_save.argv_from_re_execing = NULL;
  8979. #endif
  8980. command = &pi->cmds[cmd_no];
  8981. cmd_no++;
  8982. if (command->argv) {
  8983. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8984. command->argv[0], command->argv[1]);
  8985. } else {
  8986. debug_printf_exec(": pipe member with no argv\n");
  8987. }
  8988. /* pipes are inserted between pairs of commands */
  8989. pipefds.rd = 0;
  8990. pipefds.wr = 1;
  8991. if (cmd_no < pi->num_cmds)
  8992. xpiped_pair(pipefds);
  8993. #if ENABLE_HUSH_LINENO_VAR
  8994. G.execute_lineno = command->lineno;
  8995. #endif
  8996. command->pid = BB_MMU ? fork() : vfork();
  8997. if (!command->pid) { /* child */
  8998. #if ENABLE_HUSH_JOB
  8999. disable_restore_tty_pgrp_on_exit();
  9000. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  9001. /* Every child adds itself to new process group
  9002. * with pgid == pid_of_first_child_in_pipe */
  9003. if (G.run_list_level == 1 && G_interactive_fd) {
  9004. pid_t pgrp;
  9005. pgrp = pi->pgrp;
  9006. if (pgrp < 0) /* true for 1st process only */
  9007. pgrp = getpid();
  9008. if (setpgid(0, pgrp) == 0
  9009. && pi->followup != PIPE_BG
  9010. && G_saved_tty_pgrp /* we have ctty */
  9011. ) {
  9012. /* We do it in *every* child, not just first,
  9013. * to avoid races */
  9014. tcsetpgrp(G_interactive_fd, pgrp);
  9015. }
  9016. }
  9017. #endif
  9018. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  9019. /* 1st cmd in backgrounded pipe
  9020. * should have its stdin /dev/null'ed */
  9021. close(0);
  9022. if (open(bb_dev_null, O_RDONLY))
  9023. xopen("/", O_RDONLY);
  9024. } else {
  9025. xmove_fd(next_infd, 0);
  9026. }
  9027. xmove_fd(pipefds.wr, 1);
  9028. if (pipefds.rd > 1)
  9029. close(pipefds.rd);
  9030. /* Like bash, explicit redirects override pipes,
  9031. * and the pipe fd (fd#1) is available for dup'ing:
  9032. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  9033. * of cmd1 goes into pipe.
  9034. */
  9035. if (setup_redirects(command, NULL)) {
  9036. /* Happens when redir file can't be opened:
  9037. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  9038. * FOO
  9039. * hush: can't open '/qwe/rty': No such file or directory
  9040. * BAZ
  9041. * (echo BAR is not executed, it hits _exit(1) below)
  9042. */
  9043. _exit(1);
  9044. }
  9045. /* Stores to nommu_save list of env vars putenv'ed
  9046. * (NOMMU, on MMU we don't need that) */
  9047. /* cast away volatility... */
  9048. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  9049. /* pseudo_exec() does not return */
  9050. }
  9051. /* parent or error */
  9052. #if ENABLE_HUSH_FAST
  9053. G.count_SIGCHLD++;
  9054. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  9055. #endif
  9056. enable_restore_tty_pgrp_on_exit();
  9057. #if !BB_MMU
  9058. /* Clean up after vforked child */
  9059. free(nommu_save.argv);
  9060. free(nommu_save.argv_from_re_execing);
  9061. G.var_nest_level = sv_var_nest_level;
  9062. remove_nested_vars();
  9063. add_vars(nommu_save.old_vars);
  9064. #endif
  9065. free(argv_expanded);
  9066. argv_expanded = NULL;
  9067. if (command->pid < 0) { /* [v]fork failed */
  9068. /* Clearly indicate, was it fork or vfork */
  9069. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  9070. } else {
  9071. pi->alive_cmds++;
  9072. #if ENABLE_HUSH_JOB
  9073. /* Second and next children need to know pid of first one */
  9074. if (pi->pgrp < 0)
  9075. pi->pgrp = command->pid;
  9076. #endif
  9077. }
  9078. if (cmd_no > 1)
  9079. close(next_infd);
  9080. if (cmd_no < pi->num_cmds)
  9081. close(pipefds.wr);
  9082. /* Pass read (output) pipe end to next iteration */
  9083. next_infd = pipefds.rd;
  9084. }
  9085. if (!pi->alive_cmds) {
  9086. debug_leave();
  9087. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  9088. return 1;
  9089. }
  9090. debug_leave();
  9091. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  9092. return -1;
  9093. }
  9094. /* NB: called by pseudo_exec, and therefore must not modify any
  9095. * global data until exec/_exit (we can be a child after vfork!) */
  9096. static int run_list(struct pipe *pi)
  9097. {
  9098. #if ENABLE_HUSH_CASE
  9099. char *case_word = NULL;
  9100. #endif
  9101. #if ENABLE_HUSH_LOOPS
  9102. struct pipe *loop_top = NULL;
  9103. char **for_lcur = NULL;
  9104. char **for_list = NULL;
  9105. #endif
  9106. smallint last_followup;
  9107. smalluint rcode;
  9108. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  9109. smalluint cond_code = 0;
  9110. #else
  9111. enum { cond_code = 0 };
  9112. #endif
  9113. #if HAS_KEYWORDS
  9114. smallint rword; /* RES_foo */
  9115. smallint last_rword; /* ditto */
  9116. #endif
  9117. debug_printf_exec("run_list lvl %d start\n", G.run_list_level);
  9118. debug_enter();
  9119. set_G_ifs();
  9120. #if ENABLE_HUSH_LOOPS
  9121. /* Check syntax for "for" */
  9122. {
  9123. struct pipe *cpipe;
  9124. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  9125. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  9126. continue;
  9127. /* current word is FOR or IN (BOLD in comments below) */
  9128. if (cpipe->next == NULL) {
  9129. syntax_error("malformed for");
  9130. debug_leave();
  9131. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9132. return 1;
  9133. }
  9134. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  9135. if (cpipe->next->res_word == RES_DO)
  9136. continue;
  9137. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  9138. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  9139. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  9140. ) {
  9141. syntax_error("malformed for");
  9142. debug_leave();
  9143. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9144. return 1;
  9145. }
  9146. }
  9147. }
  9148. #endif
  9149. /* Past this point, all code paths should jump to ret: label
  9150. * in order to return, no direct "return" statements please.
  9151. * This helps to ensure that no memory is leaked. */
  9152. #if ENABLE_HUSH_JOB
  9153. G.run_list_level++;
  9154. #endif
  9155. #if HAS_KEYWORDS
  9156. rword = RES_NONE;
  9157. last_rword = RES_XXXX;
  9158. #endif
  9159. last_followup = PIPE_SEQ;
  9160. rcode = G.last_exitcode;
  9161. /* Go through list of pipes, (maybe) executing them. */
  9162. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  9163. int r;
  9164. int sv_errexit_depth;
  9165. if (G.flag_SIGINT)
  9166. break;
  9167. if (G_flag_return_in_progress == 1)
  9168. break;
  9169. IF_HAS_KEYWORDS(rword = pi->res_word;)
  9170. debug_printf_exec(": rword:%d cond_code:%d last_rword:%d\n",
  9171. rword, cond_code, last_rword);
  9172. sv_errexit_depth = G.errexit_depth;
  9173. if (
  9174. #if ENABLE_HUSH_IF
  9175. rword == RES_IF || rword == RES_ELIF ||
  9176. #endif
  9177. pi->followup != PIPE_SEQ
  9178. ) {
  9179. G.errexit_depth++;
  9180. }
  9181. #if ENABLE_HUSH_LOOPS
  9182. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  9183. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  9184. ) {
  9185. /* start of a loop: remember where loop starts */
  9186. loop_top = pi;
  9187. G.depth_of_loop++;
  9188. }
  9189. #endif
  9190. /* Still in the same "if...", "then..." or "do..." branch? */
  9191. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  9192. if ((rcode == 0 && last_followup == PIPE_OR)
  9193. || (rcode != 0 && last_followup == PIPE_AND)
  9194. ) {
  9195. /* It is "<true> || CMD" or "<false> && CMD"
  9196. * and we should not execute CMD */
  9197. debug_printf_exec("skipped cmd because of || or &&\n");
  9198. last_followup = pi->followup;
  9199. goto dont_check_jobs_but_continue;
  9200. }
  9201. }
  9202. last_followup = pi->followup;
  9203. #if ENABLE_HUSH_IF
  9204. if (cond_code != 0) {
  9205. if (rword == RES_THEN) {
  9206. /* if false; then ... fi has exitcode 0! */
  9207. G.last_exitcode = rcode = EXIT_SUCCESS;
  9208. /* "if <false> THEN cmd": skip cmd */
  9209. debug_printf_exec("skipped THEN cmd because IF condition was false\n");
  9210. last_rword = rword;
  9211. continue;
  9212. }
  9213. } else {
  9214. if (rword == RES_ELSE
  9215. || (rword == RES_ELIF && last_rword != RES_ELIF)
  9216. ) {
  9217. /* "if <true> then ... ELSE/ELIF cmd":
  9218. * skip cmd and all following ones */
  9219. debug_printf_exec("skipped ELSE/ELIF branch because IF condition was true\n");
  9220. break;
  9221. }
  9222. //if (rword == RES_THEN): "if <true> THEN cmd", run cmd (fall through)
  9223. }
  9224. #endif
  9225. IF_HAS_KEYWORDS(last_rword = rword;)
  9226. #if ENABLE_HUSH_LOOPS
  9227. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  9228. if (!for_lcur) {
  9229. /* first loop through for */
  9230. static const char encoded_dollar_at[] ALIGN1 = {
  9231. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  9232. }; /* encoded representation of "$@" */
  9233. static const char *const encoded_dollar_at_argv[] ALIGN_PTR = {
  9234. encoded_dollar_at, NULL
  9235. }; /* argv list with one element: "$@" */
  9236. char **vals;
  9237. G.last_exitcode = rcode = EXIT_SUCCESS;
  9238. vals = (char**)encoded_dollar_at_argv;
  9239. if (pi->next->res_word == RES_IN) {
  9240. /* if no variable values after "in" we skip "for" */
  9241. if (!pi->next->cmds[0].argv) {
  9242. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  9243. break;
  9244. }
  9245. vals = pi->next->cmds[0].argv;
  9246. } /* else: "for var; do..." -> assume "$@" list */
  9247. /* create list of variable values */
  9248. debug_print_strings("for_list made from", vals);
  9249. for_list = expand_strvec_to_strvec(vals);
  9250. for_lcur = for_list;
  9251. debug_print_strings("for_list", for_list);
  9252. }
  9253. if (!*for_lcur) {
  9254. /* "for" loop is over, clean up */
  9255. free(for_list);
  9256. for_list = NULL;
  9257. for_lcur = NULL;
  9258. break;
  9259. }
  9260. /* Insert next value from for_lcur */
  9261. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  9262. set_local_var_from_halves(pi->cmds[0].argv[0], *for_lcur++);
  9263. continue;
  9264. }
  9265. if (rword == RES_IN) {
  9266. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  9267. }
  9268. if (rword == RES_DONE) {
  9269. continue; /* "done" has no cmds too */
  9270. }
  9271. #endif
  9272. #if ENABLE_HUSH_CASE
  9273. if (rword == RES_CASE) {
  9274. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  9275. case_word = expand_string_to_string(pi->cmds->argv[0],
  9276. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  9277. debug_printf_exec("CASE word1:'%s'\n", case_word);
  9278. //unbackslash(case_word);
  9279. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  9280. continue;
  9281. }
  9282. if (rword == RES_MATCH) {
  9283. char **argv;
  9284. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  9285. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  9286. break;
  9287. /* all prev words didn't match, does this one match? */
  9288. argv = pi->cmds->argv;
  9289. while (*argv) {
  9290. char *pattern;
  9291. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  9292. pattern = expand_string_to_string(*argv,
  9293. EXP_FLAG_ESC_GLOB_CHARS,
  9294. /*unbackslash:*/ 0
  9295. );
  9296. /* TODO: which FNM_xxx flags to use? */
  9297. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  9298. debug_printf_exec("cond_code=fnmatch(pattern:'%s',str:'%s'):%d\n",
  9299. pattern, case_word, cond_code);
  9300. free(pattern);
  9301. if (cond_code == 0) {
  9302. /* match! we will execute this branch */
  9303. free(case_word);
  9304. case_word = NULL; /* make future "word)" stop */
  9305. break;
  9306. }
  9307. argv++;
  9308. }
  9309. continue;
  9310. }
  9311. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  9312. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  9313. if (cond_code != 0)
  9314. continue; /* not matched yet, skip this pipe */
  9315. }
  9316. if (rword == RES_ESAC) {
  9317. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  9318. if (case_word) {
  9319. /* "case" did not match anything: still set $? (to 0) */
  9320. G.last_exitcode = rcode = EXIT_SUCCESS;
  9321. }
  9322. }
  9323. #endif
  9324. /* Just pressing <enter> in shell should check for jobs.
  9325. * OTOH, in non-interactive shell this is useless
  9326. * and only leads to extra job checks */
  9327. if (pi->num_cmds == 0) {
  9328. if (G_interactive_fd)
  9329. goto check_jobs_and_continue;
  9330. continue;
  9331. }
  9332. /* After analyzing all keywords and conditions, we decided
  9333. * to execute this pipe. NB: have to do checkjobs(NULL)
  9334. * after run_pipe to collect any background children,
  9335. * even if list execution is to be stopped. */
  9336. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  9337. #if ENABLE_HUSH_LOOPS
  9338. G.flag_break_continue = 0;
  9339. #endif
  9340. rcode = r = G.o_opt[OPT_O_NOEXEC] ? 0 : run_pipe(pi);
  9341. /* NB: rcode is a smalluint, r is int */
  9342. if (r != -1) {
  9343. /* We ran a builtin, function, or group.
  9344. * rcode is already known
  9345. * and we don't need to wait for anything. */
  9346. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  9347. G.last_exitcode = rcode;
  9348. check_and_run_traps();
  9349. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9350. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9351. #endif
  9352. #if ENABLE_HUSH_LOOPS
  9353. /* Was it "break" or "continue"? */
  9354. if (G.flag_break_continue) {
  9355. smallint fbc = G.flag_break_continue;
  9356. /* We might fall into outer *loop*,
  9357. * don't want to break it too */
  9358. if (loop_top) {
  9359. G.depth_break_continue--;
  9360. if (G.depth_break_continue == 0)
  9361. G.flag_break_continue = 0;
  9362. /* else: e.g. "continue 2" should *break* once, *then* continue */
  9363. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  9364. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  9365. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9366. break;
  9367. }
  9368. /* "continue": simulate end of loop */
  9369. rword = RES_DONE;
  9370. continue;
  9371. }
  9372. #endif
  9373. if (G_flag_return_in_progress == 1) {
  9374. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9375. break;
  9376. }
  9377. } else if (pi->followup == PIPE_BG) {
  9378. /* What does bash do with attempts to background builtins? */
  9379. /* even bash 3.2 doesn't do that well with nested bg:
  9380. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  9381. * I'm NOT treating inner &'s as jobs */
  9382. #if ENABLE_HUSH_JOB
  9383. if (G.run_list_level == 1)
  9384. insert_job_into_table(pi);
  9385. #endif
  9386. /* Last command's pid goes to $! */
  9387. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9388. G.last_bg_pid_exitcode = 0;
  9389. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9390. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9391. rcode = EXIT_SUCCESS;
  9392. goto check_traps;
  9393. } else {
  9394. #if ENABLE_HUSH_JOB
  9395. if (G.run_list_level == 1 && G_interactive_fd) {
  9396. /* Waits for completion, then fg's main shell */
  9397. rcode = checkjobs_and_fg_shell(pi);
  9398. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9399. goto check_traps;
  9400. }
  9401. #endif
  9402. /* This one just waits for completion */
  9403. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9404. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9405. check_traps:
  9406. G.last_exitcode = rcode;
  9407. check_and_run_traps();
  9408. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9409. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9410. #endif
  9411. }
  9412. /* Handle "set -e" */
  9413. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9414. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9415. if (G.errexit_depth == 0)
  9416. hush_exit(rcode);
  9417. }
  9418. G.errexit_depth = sv_errexit_depth;
  9419. /* Analyze how result affects subsequent commands */
  9420. #if ENABLE_HUSH_IF
  9421. if (rword == RES_IF || rword == RES_ELIF) {
  9422. debug_printf_exec("cond_code=rcode:%d\n", rcode);
  9423. cond_code = rcode;
  9424. }
  9425. #endif
  9426. check_jobs_and_continue:
  9427. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9428. dont_check_jobs_but_continue: ;
  9429. #if ENABLE_HUSH_LOOPS
  9430. /* Beware of "while false; true; do ..."! */
  9431. if (pi->next
  9432. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9433. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9434. ) {
  9435. if (rword == RES_WHILE) {
  9436. if (rcode) {
  9437. /* "while false; do...done" - exitcode 0 */
  9438. G.last_exitcode = rcode = EXIT_SUCCESS;
  9439. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9440. break;
  9441. }
  9442. }
  9443. if (rword == RES_UNTIL) {
  9444. if (!rcode) {
  9445. debug_printf_exec(": until expr is true: breaking\n");
  9446. break;
  9447. }
  9448. }
  9449. }
  9450. #endif
  9451. } /* for (pi) */
  9452. #if ENABLE_HUSH_JOB
  9453. G.run_list_level--;
  9454. #endif
  9455. #if ENABLE_HUSH_LOOPS
  9456. if (loop_top)
  9457. G.depth_of_loop--;
  9458. free(for_list);
  9459. #endif
  9460. #if ENABLE_HUSH_CASE
  9461. free(case_word);
  9462. #endif
  9463. debug_leave();
  9464. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level, rcode);
  9465. return rcode;
  9466. }
  9467. /* Select which version we will use */
  9468. static int run_and_free_list(struct pipe *pi)
  9469. {
  9470. int rcode = 0;
  9471. debug_printf_exec("run_and_free_list entered\n");
  9472. if (!G.o_opt[OPT_O_NOEXEC]) {
  9473. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9474. rcode = run_list(pi);
  9475. }
  9476. /* free_pipe_list has the side effect of clearing memory.
  9477. * In the long run that function can be merged with run_list,
  9478. * but doing that now would hobble the debugging effort. */
  9479. free_pipe_list(pi);
  9480. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9481. return rcode;
  9482. }
  9483. static void install_sighandlers(unsigned mask)
  9484. {
  9485. sighandler_t old_handler;
  9486. unsigned sig = 0;
  9487. while ((mask >>= 1) != 0) {
  9488. sig++;
  9489. if (!(mask & 1))
  9490. continue;
  9491. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9492. /* POSIX allows shell to re-enable SIGCHLD
  9493. * even if it was SIG_IGN on entry.
  9494. * Therefore we skip IGN check for it:
  9495. */
  9496. if (sig == SIGCHLD)
  9497. continue;
  9498. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  9499. * Try:
  9500. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  9501. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  9502. */
  9503. if (sig == SIGHUP && G_interactive_fd)
  9504. continue;
  9505. /* Unless one of the above signals, is it SIG_IGN? */
  9506. if (old_handler == SIG_IGN) {
  9507. /* oops... restore back to IGN, and record this fact */
  9508. install_sighandler(sig, old_handler);
  9509. #if ENABLE_HUSH_TRAP
  9510. if (!G_traps)
  9511. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9512. free(G_traps[sig]);
  9513. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9514. #endif
  9515. }
  9516. }
  9517. }
  9518. /* Called a few times only (or even once if "sh -c") */
  9519. static void install_special_sighandlers(void)
  9520. {
  9521. unsigned mask;
  9522. /* Which signals are shell-special? */
  9523. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9524. if (G_interactive_fd) {
  9525. mask |= SPECIAL_INTERACTIVE_SIGS;
  9526. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9527. mask |= SPECIAL_JOBSTOP_SIGS;
  9528. }
  9529. /* Careful, do not re-install handlers we already installed */
  9530. if (G.special_sig_mask != mask) {
  9531. unsigned diff = mask & ~G.special_sig_mask;
  9532. G.special_sig_mask = mask;
  9533. install_sighandlers(diff);
  9534. }
  9535. }
  9536. #if ENABLE_HUSH_JOB
  9537. /* helper */
  9538. /* Set handlers to restore tty pgrp and exit */
  9539. static void install_fatal_sighandlers(void)
  9540. {
  9541. unsigned mask;
  9542. /* We will restore tty pgrp on these signals */
  9543. mask = 0
  9544. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9545. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9546. + (1 << SIGBUS ) * HUSH_DEBUG
  9547. + (1 << SIGSEGV) * HUSH_DEBUG
  9548. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9549. + (1 << SIGABRT)
  9550. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9551. + (1 << SIGPIPE)
  9552. + (1 << SIGALRM)
  9553. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9554. * if we aren't interactive... but in this case
  9555. * we never want to restore pgrp on exit, and this fn is not called
  9556. */
  9557. /*+ (1 << SIGHUP )*/
  9558. /*+ (1 << SIGTERM)*/
  9559. /*+ (1 << SIGINT )*/
  9560. ;
  9561. G_fatal_sig_mask = mask;
  9562. install_sighandlers(mask);
  9563. }
  9564. #endif
  9565. static int set_mode(int state, char mode, const char *o_opt)
  9566. {
  9567. int idx;
  9568. switch (mode) {
  9569. case 'n':
  9570. /* set -n has no effect in interactive shell */
  9571. /* Try: while set -n; do echo $-; done */
  9572. if (!G_interactive_fd)
  9573. G.o_opt[OPT_O_NOEXEC] = state;
  9574. break;
  9575. case 'x':
  9576. IF_HUSH_MODE_X(G_x_mode = state;)
  9577. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9578. break;
  9579. case 'e':
  9580. G.o_opt[OPT_O_ERREXIT] = state;
  9581. break;
  9582. case 'o':
  9583. if (!o_opt) {
  9584. /* "set -o" or "set +o" without parameter.
  9585. * in bash, set -o produces this output:
  9586. * pipefail off
  9587. * and set +o:
  9588. * set +o pipefail
  9589. * We always use the second form.
  9590. */
  9591. const char *p = o_opt_strings;
  9592. idx = 0;
  9593. while (*p) {
  9594. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9595. idx++;
  9596. p += strlen(p) + 1;
  9597. }
  9598. break;
  9599. }
  9600. idx = index_in_strings(o_opt_strings, o_opt);
  9601. if (idx >= 0) {
  9602. G.o_opt[idx] = state;
  9603. break;
  9604. }
  9605. /* fall through to error */
  9606. default:
  9607. return EXIT_FAILURE;
  9608. }
  9609. return EXIT_SUCCESS;
  9610. }
  9611. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9612. int hush_main(int argc, char **argv)
  9613. {
  9614. pid_t cached_getpid;
  9615. enum {
  9616. OPT_login = (1 << 0),
  9617. };
  9618. unsigned flags;
  9619. #if !BB_MMU
  9620. unsigned builtin_argc = 0;
  9621. #endif
  9622. char **e;
  9623. struct variable *cur_var;
  9624. struct variable *shell_ver;
  9625. INIT_G();
  9626. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9627. G.last_exitcode = EXIT_SUCCESS;
  9628. #if !BB_MMU
  9629. /* "Big heredoc" support via "sh -< STRING" invocation.
  9630. * Check it first (do not bother to run the usual init code,
  9631. * it is not needed for this case).
  9632. */
  9633. if (argv[1]
  9634. && argv[1][0] == '-' && argv[1][1] == '<' /*&& !argv[1][2]*/
  9635. /*&& argv[2] && !argv[3] - we don't check some conditions */
  9636. ) {
  9637. full_write1_str(argv[2]);
  9638. _exit(0);
  9639. }
  9640. G.argv0_for_re_execing = argv[0];
  9641. #endif
  9642. #if ENABLE_HUSH_TRAP
  9643. # if ENABLE_HUSH_FUNCTIONS
  9644. G.return_exitcode = -1;
  9645. # endif
  9646. G.pre_trap_exitcode = -1;
  9647. #endif
  9648. #if ENABLE_HUSH_FAST
  9649. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9650. #endif
  9651. cached_getpid = getpid(); /* for tcsetpgrp() during init */
  9652. G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
  9653. G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
  9654. /* Deal with HUSH_VERSION */
  9655. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9656. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9657. shell_ver = xzalloc(sizeof(*shell_ver));
  9658. shell_ver->flg_export = 1;
  9659. shell_ver->flg_read_only = 1;
  9660. /* Code which handles ${var<op>...} needs writable values for all variables,
  9661. * therefore we xstrdup: */
  9662. shell_ver->varstr = xstrdup(hush_version_str);
  9663. /* Create shell local variables from the values
  9664. * currently living in the environment */
  9665. G.top_var = shell_ver;
  9666. cur_var = G.top_var;
  9667. e = environ;
  9668. if (e) while (*e) {
  9669. char *value = strchr(*e, '=');
  9670. if (value) { /* paranoia */
  9671. cur_var->next = xzalloc(sizeof(*cur_var));
  9672. cur_var = cur_var->next;
  9673. cur_var->varstr = *e;
  9674. cur_var->max_len = strlen(*e);
  9675. cur_var->flg_export = 1;
  9676. }
  9677. e++;
  9678. }
  9679. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9680. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9681. putenv(shell_ver->varstr);
  9682. /* Export PWD */
  9683. set_pwd_var(SETFLAG_EXPORT);
  9684. #if BASH_HOSTNAME_VAR
  9685. /* Set (but not export) HOSTNAME unless already set */
  9686. if (!get_local_var_value("HOSTNAME")) {
  9687. struct utsname uts;
  9688. uname(&uts);
  9689. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9690. }
  9691. #endif
  9692. /* IFS is not inherited from the parent environment */
  9693. set_local_var_from_halves("IFS", defifs);
  9694. if (!get_local_var_value("PATH"))
  9695. set_local_var_from_halves("PATH", bb_default_root_path);
  9696. /* PS1/PS2 are set later, if we determine that we are interactive */
  9697. /* bash also exports SHLVL and _,
  9698. * and sets (but doesn't export) the following variables:
  9699. * BASH=/bin/bash
  9700. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9701. * BASH_VERSION='3.2.0(1)-release'
  9702. * HOSTTYPE=i386
  9703. * MACHTYPE=i386-pc-linux-gnu
  9704. * OSTYPE=linux-gnu
  9705. * PPID=<NNNNN> - we also do it elsewhere
  9706. * EUID=<NNNNN>
  9707. * UID=<NNNNN>
  9708. * GROUPS=()
  9709. * LINES=<NNN>
  9710. * COLUMNS=<NNN>
  9711. * BASH_ARGC=()
  9712. * BASH_ARGV=()
  9713. * BASH_LINENO=()
  9714. * BASH_SOURCE=()
  9715. * DIRSTACK=()
  9716. * PIPESTATUS=([0]="0")
  9717. * HISTFILE=/<xxx>/.bash_history
  9718. * HISTFILESIZE=500
  9719. * HISTSIZE=500
  9720. * MAILCHECK=60
  9721. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9722. * SHELL=/bin/bash
  9723. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9724. * TERM=dumb
  9725. * OPTERR=1
  9726. * OPTIND=1
  9727. * PS4='+ '
  9728. */
  9729. #if NUM_SCRIPTS > 0
  9730. if (argc < 0) {
  9731. char *script = get_script_content(-argc - 1);
  9732. G.global_argv = argv;
  9733. G.global_argc = string_array_len(argv);
  9734. //install_special_sighandlers(); - needed?
  9735. parse_and_run_string(script);
  9736. goto final_return;
  9737. }
  9738. #endif
  9739. /* Initialize some more globals to non-zero values */
  9740. die_func = restore_ttypgrp_and__exit;
  9741. /* Shell is non-interactive at first. We need to call
  9742. * install_special_sighandlers() if we are going to execute "sh <script>",
  9743. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9744. * If we later decide that we are interactive, we run install_special_sighandlers()
  9745. * in order to intercept (more) signals.
  9746. */
  9747. /* Parse options */
  9748. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9749. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9750. while (1) {
  9751. int opt = getopt(argc, argv, "+" /* stop at 1st non-option */
  9752. "cexinsl"
  9753. #if !BB_MMU
  9754. "$:R:V:"
  9755. # if ENABLE_HUSH_LINENO_VAR
  9756. "L:"
  9757. # endif
  9758. # if ENABLE_HUSH_FUNCTIONS
  9759. "F:"
  9760. # endif
  9761. #endif
  9762. );
  9763. if (opt <= 0)
  9764. break;
  9765. switch (opt) {
  9766. case 'c':
  9767. /* Note: -c is not an option with param!
  9768. * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
  9769. */
  9770. G.opt_c = 1;
  9771. break;
  9772. case 'i':
  9773. /* Well, we cannot just declare interactiveness,
  9774. * we have to have some stuff (ctty, etc) */
  9775. /* G_interactive_fd++; */
  9776. //There are a few cases where bash -i -c 'SCRIPT'
  9777. //has visible effect (differs from bash -c 'SCRIPT'):
  9778. //it ignores TERM:
  9779. // bash -i -c 'kill $$; echo ALIVE'
  9780. // ALIVE
  9781. //it resets SIG_IGNed HUP to SIG_DFL:
  9782. // trap '' hup; bash -i -c 'kill -hup $$; echo ALIVE'
  9783. // Hangup [the message is not printed by bash, it's the shell which started it]
  9784. //is talkative about jobs and exiting:
  9785. // bash -i -c 'sleep 1 & exit'
  9786. // [1] 16170
  9787. // exit
  9788. //includes $ENV file (only if run as "sh"):
  9789. // echo last >/tmp/ENV; ENV=/tmp/ENV sh -i -c 'echo HERE'
  9790. // last: cannot open /var/log/wtmp: No such file or directory
  9791. // HERE
  9792. //(under "bash", it's the opposite: it runs $BASH_ENV file only *without* -i).
  9793. //
  9794. //ash -i -c 'sleep 3; sleep 3', on ^C, drops into a prompt instead of exiting
  9795. //(this may be a bug, bash does not do this).
  9796. //(ash -i -c 'sleep 3' won't show this, the last command gets auto-"exec"ed)
  9797. //
  9798. //None of the above feel like useful features people would rely on.
  9799. break;
  9800. case 's':
  9801. G.opt_s = 1;
  9802. break;
  9803. case 'l':
  9804. flags |= OPT_login;
  9805. break;
  9806. #if !BB_MMU
  9807. case '$': {
  9808. unsigned long long empty_trap_mask;
  9809. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9810. optarg++;
  9811. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9812. optarg++;
  9813. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9814. optarg++;
  9815. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9816. optarg++;
  9817. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9818. optarg++;
  9819. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9820. if (empty_trap_mask != 0) {
  9821. IF_HUSH_TRAP(int sig;)
  9822. install_special_sighandlers();
  9823. # if ENABLE_HUSH_TRAP
  9824. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9825. for (sig = 1; sig < NSIG; sig++) {
  9826. if (empty_trap_mask & (1LL << sig)) {
  9827. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9828. install_sighandler(sig, SIG_IGN);
  9829. }
  9830. }
  9831. # endif
  9832. }
  9833. # if ENABLE_HUSH_LOOPS
  9834. optarg++;
  9835. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9836. # endif
  9837. /* Suppress "killed by signal" message, -$ hack is used
  9838. * for subshells: echo `sh -c 'kill -9 $$'`
  9839. * should be silent.
  9840. */
  9841. IF_HUSH_JOB(G.run_list_level = 1;)
  9842. # if ENABLE_HUSH_FUNCTIONS
  9843. /* nommu uses re-exec trick for "... | func | ...",
  9844. * should allow "return".
  9845. * This accidentally allows returns in subshells.
  9846. */
  9847. G_flag_return_in_progress = -1;
  9848. # endif
  9849. break;
  9850. }
  9851. case 'R':
  9852. case 'V':
  9853. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9854. break;
  9855. # if ENABLE_HUSH_LINENO_VAR
  9856. case 'L':
  9857. G.parse_lineno = xatou(optarg);
  9858. break;
  9859. # endif
  9860. # if ENABLE_HUSH_FUNCTIONS
  9861. case 'F': {
  9862. struct function *funcp = new_function(optarg);
  9863. /* funcp->name is already set to optarg */
  9864. /* funcp->body is set to NULL. It's a special case. */
  9865. funcp->body_as_string = argv[optind];
  9866. optind++;
  9867. break;
  9868. }
  9869. # endif
  9870. #endif
  9871. /*case '?': invalid option encountered (set_mode('?') will fail) */
  9872. /*case 'n':*/
  9873. /*case 'x':*/
  9874. /*case 'e':*/
  9875. default:
  9876. if (set_mode(1, opt, NULL) == 0) /* no error */
  9877. break;
  9878. bb_show_usage();
  9879. }
  9880. } /* option parsing loop */
  9881. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9882. G.global_argc = argc - (optind - 1);
  9883. G.global_argv = argv + (optind - 1);
  9884. G.global_argv[0] = argv[0];
  9885. /* If we are login shell... */
  9886. if (flags & OPT_login) {
  9887. const char *hp = NULL;
  9888. HFILE *input;
  9889. debug_printf("sourcing /etc/profile\n");
  9890. input = hfopen("/etc/profile");
  9891. run_profile:
  9892. if (input != NULL) {
  9893. install_special_sighandlers();
  9894. parse_and_run_file(input);
  9895. hfclose(input);
  9896. }
  9897. /* bash: after sourcing /etc/profile,
  9898. * tries to source (in the given order):
  9899. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9900. * stopping on first found. --noprofile turns this off.
  9901. * bash also sources ~/.bash_logout on exit.
  9902. * If called as sh, skips .bash_XXX files.
  9903. */
  9904. if (!hp) { /* unless we looped on the "goto" already */
  9905. hp = get_local_var_value("HOME");
  9906. if (hp && hp[0]) {
  9907. debug_printf("sourcing ~/.profile\n");
  9908. hp = concat_path_file(hp, ".profile");
  9909. input = hfopen(hp);
  9910. free((char*)hp);
  9911. goto run_profile;
  9912. }
  9913. }
  9914. }
  9915. /* -c takes effect *after* -l */
  9916. if (G.opt_c) {
  9917. /* Possibilities:
  9918. * sh ... -c 'script'
  9919. * sh ... -c 'script' ARG0 [ARG1...]
  9920. * On NOMMU, if builtin_argc != 0,
  9921. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9922. * "" needs to be replaced with NULL
  9923. * and BARGV vector fed to builtin function.
  9924. * Note: the form without ARG0 never happens:
  9925. * sh ... -c 'builtin' BARGV... ""
  9926. */
  9927. char *script;
  9928. install_special_sighandlers();
  9929. G.global_argc--;
  9930. G.global_argv++;
  9931. #if !BB_MMU
  9932. if (builtin_argc) {
  9933. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9934. const struct built_in_command *x;
  9935. x = find_builtin(G.global_argv[0]);
  9936. if (x) { /* paranoia */
  9937. argv = G.global_argv;
  9938. G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
  9939. G.global_argv += builtin_argc + 1;
  9940. G.global_argv[-1] = NULL; /* replace "" */
  9941. G.last_exitcode = x->b_function(argv);
  9942. }
  9943. goto final_return;
  9944. }
  9945. #endif
  9946. script = G.global_argv[0];
  9947. if (!script)
  9948. bb_error_msg_and_die(bb_msg_requires_arg, "-c");
  9949. if (!G.global_argv[1]) {
  9950. /* -c 'script' (no params): prevent empty $0 */
  9951. G.global_argv[0] = argv[0];
  9952. } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9953. G.global_argc--;
  9954. G.global_argv++;
  9955. }
  9956. parse_and_run_string(script);
  9957. goto final_return;
  9958. }
  9959. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9960. if (!G.opt_s && G.global_argv[1]) {
  9961. HFILE *input;
  9962. /*
  9963. * "bash <script>" (which is never interactive (unless -i?))
  9964. * sources $BASH_ENV here (without scanning $PATH).
  9965. * If called as sh, does the same but with $ENV.
  9966. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9967. */
  9968. G.global_argc--;
  9969. G.global_argv++;
  9970. debug_printf("running script '%s'\n", G.global_argv[0]);
  9971. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9972. input = hfopen(G.global_argv[0]);
  9973. if (!input) {
  9974. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9975. }
  9976. xfunc_error_retval = 1;
  9977. install_special_sighandlers();
  9978. parse_and_run_file(input);
  9979. #if ENABLE_FEATURE_CLEAN_UP
  9980. hfclose(input);
  9981. #endif
  9982. goto final_return;
  9983. }
  9984. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9985. G.opt_s = 1;
  9986. /* Up to here, shell was non-interactive. Now it may become one.
  9987. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9988. */
  9989. /* A shell is interactive if the '-i' flag was given,
  9990. * or if all of the following conditions are met:
  9991. * no -c command
  9992. * no arguments remaining or the -s flag given
  9993. * standard input is a terminal
  9994. * standard output is a terminal
  9995. * Refer to Posix.2, the description of the 'sh' utility.
  9996. */
  9997. #if ENABLE_HUSH_JOB
  9998. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9999. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  10000. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  10001. if (G_saved_tty_pgrp < 0)
  10002. G_saved_tty_pgrp = 0;
  10003. /* try to dup stdin to high fd#, >= 255 */
  10004. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  10005. if (G_interactive_fd < 0) {
  10006. /* try to dup to any fd */
  10007. G_interactive_fd = dup(STDIN_FILENO);
  10008. if (G_interactive_fd < 0) {
  10009. /* give up */
  10010. G_interactive_fd = 0;
  10011. G_saved_tty_pgrp = 0;
  10012. }
  10013. }
  10014. }
  10015. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  10016. if (G_interactive_fd) {
  10017. close_on_exec_on(G_interactive_fd);
  10018. if (G_saved_tty_pgrp) {
  10019. /* If we were run as 'hush &', sleep until we are
  10020. * in the foreground (tty pgrp == our pgrp).
  10021. * If we get started under a job aware app (like bash),
  10022. * make sure we are now in charge so we don't fight over
  10023. * who gets the foreground */
  10024. while (1) {
  10025. pid_t shell_pgrp = getpgrp();
  10026. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  10027. if (G_saved_tty_pgrp == shell_pgrp)
  10028. break;
  10029. /* send TTIN to ourself (should stop us) */
  10030. kill(- shell_pgrp, SIGTTIN);
  10031. }
  10032. }
  10033. /* Install more signal handlers */
  10034. install_special_sighandlers();
  10035. if (G_saved_tty_pgrp) {
  10036. /* Set other signals to restore saved_tty_pgrp */
  10037. install_fatal_sighandlers();
  10038. /* Put ourselves in our own process group
  10039. * (bash, too, does this only if ctty is available) */
  10040. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  10041. /* Grab control of the terminal */
  10042. tcsetpgrp(G_interactive_fd, cached_getpid);
  10043. }
  10044. enable_restore_tty_pgrp_on_exit();
  10045. # if ENABLE_FEATURE_EDITING
  10046. G.line_input_state = new_line_input_t(FOR_SHELL);
  10047. # if ENABLE_FEATURE_TAB_COMPLETION
  10048. G.line_input_state->get_exe_name = hush_command_name;
  10049. # endif
  10050. # if EDITING_HAS_sh_get_var
  10051. G.line_input_state->sh_get_var = get_local_var_value;
  10052. # endif
  10053. # endif
  10054. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  10055. {
  10056. const char *hp = get_local_var_value("HISTFILE");
  10057. if (!hp) {
  10058. hp = get_local_var_value("HOME");
  10059. if (hp)
  10060. hp = concat_path_file(hp, ".hush_history");
  10061. } else {
  10062. hp = xstrdup(hp);
  10063. }
  10064. if (hp) {
  10065. G.line_input_state->hist_file = hp;
  10066. //set_local_var(xasprintf("HISTFILE=%s", ...));
  10067. }
  10068. # if ENABLE_FEATURE_SH_HISTFILESIZE
  10069. hp = get_local_var_value("HISTFILESIZE");
  10070. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  10071. # endif
  10072. }
  10073. # endif
  10074. } else {
  10075. install_special_sighandlers();
  10076. }
  10077. #elif ENABLE_HUSH_INTERACTIVE
  10078. /* No job control compiled in, only prompt/line editing */
  10079. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  10080. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  10081. if (G_interactive_fd < 0) {
  10082. /* try to dup to any fd */
  10083. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  10084. if (G_interactive_fd < 0)
  10085. /* give up */
  10086. G_interactive_fd = 0;
  10087. }
  10088. }
  10089. if (G_interactive_fd) {
  10090. close_on_exec_on(G_interactive_fd);
  10091. }
  10092. install_special_sighandlers();
  10093. #else
  10094. /* We have interactiveness code disabled */
  10095. install_special_sighandlers();
  10096. #endif
  10097. /* bash:
  10098. * if interactive but not a login shell, sources ~/.bashrc
  10099. * (--norc turns this off, --rcfile <file> overrides)
  10100. */
  10101. if (G_interactive_fd) {
  10102. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  10103. /* Set (but not export) PS1/2 unless already set */
  10104. if (!get_local_var_value("PS1"))
  10105. set_local_var_from_halves("PS1", "\\w \\$ ");
  10106. if (!get_local_var_value("PS2"))
  10107. set_local_var_from_halves("PS2", "> ");
  10108. #endif
  10109. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  10110. /* note: ash and hush share this string */
  10111. printf("\n\n%s %s\n"
  10112. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  10113. "\n",
  10114. bb_banner,
  10115. "hush - the humble shell"
  10116. );
  10117. }
  10118. }
  10119. parse_and_run_file(hfopen(NULL)); /* stdin */
  10120. final_return:
  10121. hush_exit(G.last_exitcode);
  10122. }
  10123. /*
  10124. * Built-ins
  10125. */
  10126. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  10127. {
  10128. return 0;
  10129. }
  10130. static int FAST_FUNC builtin_false(char **argv UNUSED_PARAM)
  10131. {
  10132. return 1;
  10133. }
  10134. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  10135. static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  10136. {
  10137. int argc = string_array_len(argv);
  10138. return applet_main_func(argc, argv);
  10139. }
  10140. #endif
  10141. #if ENABLE_HUSH_TEST || BASH_TEST2
  10142. static int FAST_FUNC builtin_test(char **argv)
  10143. {
  10144. return run_applet_main(argv, test_main);
  10145. }
  10146. #endif
  10147. #if ENABLE_HUSH_ECHO
  10148. static int FAST_FUNC builtin_echo(char **argv)
  10149. {
  10150. return run_applet_main(argv, echo_main);
  10151. }
  10152. #endif
  10153. #if ENABLE_HUSH_PRINTF
  10154. static int FAST_FUNC builtin_printf(char **argv)
  10155. {
  10156. return run_applet_main(argv, printf_main);
  10157. }
  10158. #endif
  10159. #if ENABLE_HUSH_HELP
  10160. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  10161. {
  10162. const struct built_in_command *x;
  10163. printf(
  10164. "Built-in commands:\n"
  10165. "------------------\n");
  10166. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  10167. if (x->b_descr)
  10168. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  10169. }
  10170. return EXIT_SUCCESS;
  10171. }
  10172. #endif
  10173. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  10174. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  10175. {
  10176. show_history(G.line_input_state);
  10177. return EXIT_SUCCESS;
  10178. }
  10179. #endif
  10180. static int FAST_FUNC builtin_cd(char **argv)
  10181. {
  10182. const char *newdir;
  10183. argv = skip_dash_dash(argv);
  10184. newdir = argv[0];
  10185. if (newdir == NULL) {
  10186. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  10187. * bash says "bash: cd: HOME not set" and does nothing
  10188. * (exitcode 1)
  10189. */
  10190. const char *home = get_local_var_value("HOME");
  10191. newdir = home ? home : "/";
  10192. }
  10193. if (chdir(newdir)) {
  10194. /* Mimic bash message exactly */
  10195. bb_perror_msg("cd: %s", newdir);
  10196. return EXIT_FAILURE;
  10197. }
  10198. /* Read current dir (get_cwd(1) is inside) and set PWD.
  10199. * Note: do not enforce exporting. If PWD was unset or unexported,
  10200. * set it again, but do not export. bash does the same.
  10201. */
  10202. set_pwd_var(/*flag:*/ 0);
  10203. return EXIT_SUCCESS;
  10204. }
  10205. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  10206. {
  10207. puts(get_cwd(0));
  10208. return EXIT_SUCCESS;
  10209. }
  10210. static int FAST_FUNC builtin_eval(char **argv)
  10211. {
  10212. argv = skip_dash_dash(argv);
  10213. if (!argv[0])
  10214. return EXIT_SUCCESS;
  10215. IF_HUSH_MODE_X(G.x_mode_depth++;)
  10216. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  10217. if (!argv[1]) {
  10218. /* bash:
  10219. * eval "echo Hi; done" ("done" is syntax error):
  10220. * "echo Hi" will not execute too.
  10221. */
  10222. parse_and_run_string(argv[0]);
  10223. } else {
  10224. /* "The eval utility shall construct a command by
  10225. * concatenating arguments together, separating
  10226. * each with a <space> character."
  10227. */
  10228. char *str, *p;
  10229. unsigned len = 0;
  10230. char **pp = argv;
  10231. do
  10232. len += strlen(*pp) + 1;
  10233. while (*++pp);
  10234. str = p = xmalloc(len);
  10235. pp = argv;
  10236. for (;;) {
  10237. p = stpcpy(p, *pp);
  10238. pp++;
  10239. if (!*pp)
  10240. break;
  10241. *p++ = ' ';
  10242. }
  10243. parse_and_run_string(str);
  10244. free(str);
  10245. }
  10246. IF_HUSH_MODE_X(G.x_mode_depth--;)
  10247. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  10248. return G.last_exitcode;
  10249. }
  10250. static int FAST_FUNC builtin_exec(char **argv)
  10251. {
  10252. argv = skip_dash_dash(argv);
  10253. if (argv[0] == NULL)
  10254. return EXIT_SUCCESS; /* bash does this */
  10255. /* Careful: we can end up here after [v]fork. Do not restore
  10256. * tty pgrp then, only top-level shell process does that */
  10257. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  10258. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  10259. /* Saved-redirect fds, script fds and G_interactive_fd are still
  10260. * open here. However, they are all CLOEXEC, and execv below
  10261. * closes them. Try interactive "exec ls -l /proc/self/fd",
  10262. * it should show no extra open fds in the "ls" process.
  10263. * If we'd try to run builtins/NOEXECs, this would need improving.
  10264. */
  10265. //close_saved_fds_and_FILE_fds();
  10266. /* TODO: if exec fails, bash does NOT exit! We do.
  10267. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  10268. * and tcsetpgrp, and this is inherently racy.
  10269. */
  10270. execvp_or_die(argv);
  10271. }
  10272. static int FAST_FUNC builtin_exit(char **argv)
  10273. {
  10274. debug_printf_exec("%s()\n", __func__);
  10275. /* interactive bash:
  10276. * # trap "echo EEE" EXIT
  10277. * # exit
  10278. * exit
  10279. * There are stopped jobs.
  10280. * (if there are _stopped_ jobs, running ones don't count)
  10281. * # exit
  10282. * exit
  10283. * EEE (then bash exits)
  10284. *
  10285. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  10286. */
  10287. /* note: EXIT trap is run by hush_exit */
  10288. argv = skip_dash_dash(argv);
  10289. if (argv[0] == NULL) {
  10290. #if ENABLE_HUSH_TRAP
  10291. if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
  10292. hush_exit(G.pre_trap_exitcode);
  10293. #endif
  10294. hush_exit(G.last_exitcode);
  10295. }
  10296. /* mimic bash: exit 123abc == exit 255 + error msg */
  10297. xfunc_error_retval = 255;
  10298. /* bash: exit -2 == exit 254, no error msg */
  10299. hush_exit(xatoi(argv[0]) & 0xff);
  10300. }
  10301. #if ENABLE_HUSH_TYPE
  10302. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  10303. static int FAST_FUNC builtin_type(char **argv)
  10304. {
  10305. int ret = EXIT_SUCCESS;
  10306. while (*++argv) {
  10307. const char *type;
  10308. char *path = NULL;
  10309. if (0) {} /* make conditional compile easier below */
  10310. /*else if (find_alias(*argv))
  10311. type = "an alias";*/
  10312. # if ENABLE_HUSH_FUNCTIONS
  10313. else if (find_function(*argv))
  10314. type = "a function";
  10315. # endif
  10316. else if (find_builtin(*argv))
  10317. type = "a shell builtin";
  10318. else if ((path = find_in_path(*argv)) != NULL)
  10319. type = path;
  10320. else {
  10321. bb_error_msg("type: %s: not found", *argv);
  10322. ret = EXIT_FAILURE;
  10323. continue;
  10324. }
  10325. printf("%s is %s\n", *argv, type);
  10326. free(path);
  10327. }
  10328. return ret;
  10329. }
  10330. #endif
  10331. #if ENABLE_HUSH_READ
  10332. /* Interruptibility of read builtin in bash
  10333. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  10334. *
  10335. * Empty trap makes read ignore corresponding signal, for any signal.
  10336. *
  10337. * SIGINT:
  10338. * - terminates non-interactive shell;
  10339. * - interrupts read in interactive shell;
  10340. * if it has non-empty trap:
  10341. * - executes trap and returns to command prompt in interactive shell;
  10342. * - executes trap and returns to read in non-interactive shell;
  10343. * SIGTERM:
  10344. * - is ignored (does not interrupt) read in interactive shell;
  10345. * - terminates non-interactive shell;
  10346. * if it has non-empty trap:
  10347. * - executes trap and returns to read;
  10348. * SIGHUP:
  10349. * - terminates shell (regardless of interactivity);
  10350. * if it has non-empty trap:
  10351. * - executes trap and returns to read;
  10352. * SIGCHLD from children:
  10353. * - does not interrupt read regardless of interactivity:
  10354. * try: sleep 1 & read x; echo $x
  10355. */
  10356. static int FAST_FUNC builtin_read(char **argv)
  10357. {
  10358. const char *r;
  10359. struct builtin_read_params params;
  10360. memset(&params, 0, sizeof(params));
  10361. /* "!": do not abort on errors.
  10362. * Option string must start with "sr" to match BUILTIN_READ_xxx
  10363. */
  10364. params.read_flags = getopt32(argv,
  10365. # if BASH_READ_D
  10366. IF_NOT_HUSH_BASH_COMPAT("^")
  10367. "!srn:p:t:u:d:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10368. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  10369. # else
  10370. IF_NOT_HUSH_BASH_COMPAT("^")
  10371. "!srn:p:t:u:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10372. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  10373. # endif
  10374. //TODO: print "read: need variable name"
  10375. //for the case of !BASH "read" with no args (now it fails silently)
  10376. //(or maybe extend getopt32() to emit a message if "-1" fails)
  10377. );
  10378. if ((uint32_t)params.read_flags == (uint32_t)-1)
  10379. return EXIT_FAILURE;
  10380. argv += optind;
  10381. params.argv = argv;
  10382. params.setvar = set_local_var_from_halves;
  10383. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  10384. again:
  10385. r = shell_builtin_read(&params);
  10386. if ((uintptr_t)r == 1 && errno == EINTR) {
  10387. unsigned sig = check_and_run_traps();
  10388. if (sig != SIGINT)
  10389. goto again;
  10390. }
  10391. if ((uintptr_t)r > 1) {
  10392. bb_simple_error_msg(r);
  10393. r = (char*)(uintptr_t)1;
  10394. }
  10395. return (uintptr_t)r;
  10396. }
  10397. #endif
  10398. #if ENABLE_HUSH_UMASK
  10399. static int FAST_FUNC builtin_umask(char **argv)
  10400. {
  10401. int rc;
  10402. mode_t mask;
  10403. rc = 1;
  10404. mask = umask(0);
  10405. argv = skip_dash_dash(argv);
  10406. if (argv[0]) {
  10407. mode_t old_mask = mask;
  10408. /* numeric umasks are taken as-is */
  10409. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  10410. if (!isdigit(argv[0][0]))
  10411. mask ^= 0777;
  10412. mask = bb_parse_mode(argv[0], mask);
  10413. if (!isdigit(argv[0][0]))
  10414. mask ^= 0777;
  10415. if ((unsigned)mask > 0777) {
  10416. mask = old_mask;
  10417. /* bash messages:
  10418. * bash: umask: 'q': invalid symbolic mode operator
  10419. * bash: umask: 999: octal number out of range
  10420. */
  10421. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  10422. rc = 0;
  10423. }
  10424. } else {
  10425. /* Mimic bash */
  10426. printf("%04o\n", (unsigned) mask);
  10427. /* fall through and restore mask which we set to 0 */
  10428. }
  10429. umask(mask);
  10430. return !rc; /* rc != 0 - success */
  10431. }
  10432. #endif
  10433. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY || ENABLE_HUSH_SET || ENABLE_HUSH_TRAP
  10434. static void print_escaped(const char *s)
  10435. {
  10436. //TODO? bash "set" does not quote variables which contain only alnums and "%+,-./:=@_~",
  10437. // (but "export" quotes all variables, even with only these chars).
  10438. // I think quoting strings with %+,=~ looks better
  10439. // (example: "set" printing var== instead of var='=' looks strange)
  10440. // IOW: do not quote "-./:@_": / is used in pathnames, : in PATH, -._ often in file names, @ in emails
  10441. if (*s == '\'')
  10442. goto squote;
  10443. do {
  10444. const char *p = strchrnul(s, '\'');
  10445. /* print 'xxxx', possibly just '' */
  10446. printf("'%.*s'", (int)(p - s), s);
  10447. if (*p == '\0')
  10448. break;
  10449. s = p;
  10450. squote:
  10451. /* s points to '; print "'''...'''" */
  10452. putchar('"');
  10453. do putchar('\''); while (*++s == '\'');
  10454. putchar('"');
  10455. } while (*s);
  10456. }
  10457. #endif
  10458. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  10459. static int helper_export_local(char **argv, unsigned flags)
  10460. {
  10461. do {
  10462. char *name = *argv;
  10463. const char *name_end = endofname(name);
  10464. if (*name_end == '\0') {
  10465. struct variable *var, **vpp;
  10466. vpp = get_ptr_to_local_var(name);
  10467. var = vpp ? *vpp : NULL;
  10468. if (flags & SETFLAG_UNEXPORT) {
  10469. /* export -n NAME (without =VALUE) */
  10470. if (var) {
  10471. var->flg_export = 0;
  10472. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  10473. unsetenv(name);
  10474. } /* else: export -n NOT_EXISTING_VAR: no-op */
  10475. continue;
  10476. }
  10477. if (flags & SETFLAG_EXPORT) {
  10478. /* export NAME (without =VALUE) */
  10479. if (var) {
  10480. var->flg_export = 1;
  10481. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10482. putenv(var->varstr);
  10483. continue;
  10484. }
  10485. }
  10486. if (flags & SETFLAG_MAKE_RO) {
  10487. /* readonly NAME (without =VALUE) */
  10488. if (var) {
  10489. var->flg_read_only = 1;
  10490. continue;
  10491. }
  10492. }
  10493. # if ENABLE_HUSH_LOCAL
  10494. /* Is this "local" bltin? */
  10495. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10496. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10497. if (var && var->var_nest_level == lvl) {
  10498. /* "local x=abc; ...; local x" - ignore second local decl */
  10499. continue;
  10500. }
  10501. }
  10502. # endif
  10503. /* Exporting non-existing variable.
  10504. * bash does not put it in environment,
  10505. * but remembers that it is exported,
  10506. * and does put it in env when it is set later.
  10507. * We just set it to "" and export.
  10508. */
  10509. /* Or, it's "local NAME" (without =VALUE).
  10510. * bash sets the value to "".
  10511. */
  10512. /* Or, it's "readonly NAME" (without =VALUE).
  10513. * bash remembers NAME and disallows its creation
  10514. * in the future.
  10515. */
  10516. name = xasprintf("%s=", name);
  10517. } else {
  10518. if (*name_end != '=') {
  10519. bb_error_msg("'%s': bad variable name", name);
  10520. /* do not parse following argv[]s: */
  10521. return 1;
  10522. }
  10523. /* (Un)exporting/making local NAME=VALUE */
  10524. name = xstrdup(name);
  10525. /* Testcase: export PS1='\w \$ ' */
  10526. unbackslash(name);
  10527. }
  10528. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10529. if (set_local_var(name, flags))
  10530. return EXIT_FAILURE;
  10531. } while (*++argv);
  10532. return EXIT_SUCCESS;
  10533. }
  10534. #endif
  10535. #if ENABLE_HUSH_EXPORT
  10536. static int FAST_FUNC builtin_export(char **argv)
  10537. {
  10538. unsigned opt_unexport;
  10539. # if ENABLE_HUSH_EXPORT_N
  10540. /* "!": do not abort on errors */
  10541. opt_unexport = getopt32(argv, "!n");
  10542. if (opt_unexport == (uint32_t)-1)
  10543. return EXIT_FAILURE;
  10544. argv += optind;
  10545. # else
  10546. opt_unexport = 0;
  10547. argv++;
  10548. # endif
  10549. if (argv[0] == NULL) {
  10550. char **e = environ;
  10551. if (e) {
  10552. while (*e) {
  10553. # if 0
  10554. puts(*e++);
  10555. # else
  10556. /* ash emits: export VAR='VAL'
  10557. * bash: declare -x VAR="VAL"
  10558. * we follow ash example */
  10559. const char *s = *e++;
  10560. const char *p = strchr(s, '=');
  10561. if (!p) /* wtf? take next variable */
  10562. continue;
  10563. /* "export VAR=" */
  10564. printf("%s %.*s", "export", (int)(p - s) + 1, s);
  10565. print_escaped(p + 1);
  10566. putchar('\n');
  10567. # endif
  10568. }
  10569. /*fflush_all(); - done after each builtin anyway */
  10570. }
  10571. return EXIT_SUCCESS;
  10572. }
  10573. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10574. }
  10575. #endif
  10576. #if ENABLE_HUSH_LOCAL
  10577. static int FAST_FUNC builtin_local(char **argv)
  10578. {
  10579. if (G.func_nest_level == 0) {
  10580. bb_error_msg("%s: not in a function", argv[0]);
  10581. return EXIT_FAILURE; /* bash compat */
  10582. }
  10583. //TODO? ash and bash support "local -" special form,
  10584. //which saves/restores $- around function call (including async returns, such as ^C)
  10585. //(IOW: it makes "set +/-..." effects local)
  10586. argv++;
  10587. /* Since all builtins run in a nested variable level,
  10588. * need to use level - 1 here. Or else the variable will be removed at once
  10589. * after builtin returns.
  10590. */
  10591. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10592. }
  10593. #endif
  10594. #if ENABLE_HUSH_READONLY
  10595. static int FAST_FUNC builtin_readonly(char **argv)
  10596. {
  10597. argv++;
  10598. if (*argv == NULL) {
  10599. /* bash: readonly [-p]: list all readonly VARs
  10600. * (-p has no effect in bash)
  10601. */
  10602. struct variable *e;
  10603. for (e = G.top_var; e; e = e->next) {
  10604. if (e->flg_read_only) {
  10605. const char *s = e->varstr;
  10606. const char *p = strchr(s, '=');
  10607. if (!p) /* wtf? take next variable */
  10608. continue;
  10609. /* "readonly VAR=" */
  10610. printf("%s %.*s", "readonly", (int)(p - s) + 1, s);
  10611. print_escaped(p + 1);
  10612. putchar('\n');
  10613. }
  10614. }
  10615. return EXIT_SUCCESS;
  10616. }
  10617. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10618. }
  10619. #endif
  10620. #if ENABLE_HUSH_UNSET
  10621. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10622. static int FAST_FUNC builtin_unset(char **argv)
  10623. {
  10624. int ret;
  10625. unsigned opts;
  10626. /* "!": do not abort on errors */
  10627. /* "+": stop at 1st non-option */
  10628. opts = getopt32(argv, "!+vf");
  10629. if (opts == (unsigned)-1)
  10630. return EXIT_FAILURE;
  10631. if (opts == 3) {
  10632. bb_simple_error_msg("unset: -v and -f are exclusive");
  10633. return EXIT_FAILURE;
  10634. }
  10635. argv += optind;
  10636. ret = EXIT_SUCCESS;
  10637. while (*argv) {
  10638. if (!(opts & 2)) { /* not -f */
  10639. if (unset_local_var(*argv)) {
  10640. /* unset <nonexistent_var> doesn't fail.
  10641. * Error is when one tries to unset RO var.
  10642. * Message was printed by unset_local_var. */
  10643. ret = EXIT_FAILURE;
  10644. }
  10645. }
  10646. # if ENABLE_HUSH_FUNCTIONS
  10647. else {
  10648. unset_func(*argv);
  10649. }
  10650. # endif
  10651. argv++;
  10652. }
  10653. return ret;
  10654. }
  10655. #endif
  10656. #if ENABLE_HUSH_SET
  10657. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10658. * built-in 'set' handler
  10659. * SUSv3 says:
  10660. * set [-abCefhmnuvx] [-o option] [argument...]
  10661. * set [+abCefhmnuvx] [+o option] [argument...]
  10662. * set -- [argument...]
  10663. * set -o
  10664. * set +o
  10665. * Implementations shall support the options in both their hyphen and
  10666. * plus-sign forms. These options can also be specified as options to sh.
  10667. * Examples:
  10668. * Write out all variables and their values: set
  10669. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10670. * Turn on the -x and -v options: set -xv
  10671. * Unset all positional parameters: set --
  10672. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10673. * Set the positional parameters to the expansion of x, even if x expands
  10674. * with a leading '-' or '+': set -- $x
  10675. *
  10676. * So far, we only support "set -- [argument...]" and some of the short names.
  10677. */
  10678. static int FAST_FUNC builtin_set(char **argv)
  10679. {
  10680. int n;
  10681. char **pp, **g_argv;
  10682. char *arg = *++argv;
  10683. if (arg == NULL) {
  10684. struct variable *e;
  10685. for (e = G.top_var; e; e = e->next) {
  10686. const char *s = e->varstr;
  10687. const char *p = strchr(s, '=');
  10688. if (!p) /* wtf? take next variable */
  10689. continue;
  10690. /* var= */
  10691. printf("%.*s", (int)(p - s) + 1, s);
  10692. print_escaped(p + 1);
  10693. putchar('\n');
  10694. }
  10695. return EXIT_SUCCESS;
  10696. }
  10697. do {
  10698. if (strcmp(arg, "--") == 0) {
  10699. ++argv;
  10700. goto set_argv;
  10701. }
  10702. if (arg[0] != '+' && arg[0] != '-')
  10703. break;
  10704. for (n = 1; arg[n]; ++n) {
  10705. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10706. bb_error_msg("%s: %s: invalid option", "set", arg);
  10707. return EXIT_FAILURE;
  10708. }
  10709. if (arg[n] == 'o' && argv[1])
  10710. argv++;
  10711. }
  10712. } while ((arg = *++argv) != NULL);
  10713. /* Now argv[0] is 1st argument */
  10714. if (arg == NULL)
  10715. return EXIT_SUCCESS;
  10716. set_argv:
  10717. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10718. g_argv = G.global_argv;
  10719. if (G.global_args_malloced) {
  10720. pp = g_argv;
  10721. while (*++pp)
  10722. free(*pp);
  10723. g_argv[1] = NULL;
  10724. } else {
  10725. G.global_args_malloced = 1;
  10726. pp = xzalloc(sizeof(pp[0]) * 2);
  10727. pp[0] = g_argv[0]; /* retain $0 */
  10728. g_argv = pp;
  10729. }
  10730. /* This realloc's G.global_argv */
  10731. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10732. G.global_argc = 1 + string_array_len(pp + 1);
  10733. return EXIT_SUCCESS;
  10734. }
  10735. #endif
  10736. static int FAST_FUNC builtin_shift(char **argv)
  10737. {
  10738. int n = 1;
  10739. argv = skip_dash_dash(argv);
  10740. if (argv[0]) {
  10741. n = bb_strtou(argv[0], NULL, 10);
  10742. if (errno || n < 0) {
  10743. /* shared string with ash.c */
  10744. bb_error_msg("Illegal number: %s", argv[0]);
  10745. /*
  10746. * ash aborts in this case.
  10747. * bash prints error message and set $? to 1.
  10748. * Interestingly, for "shift 99999" bash does not
  10749. * print error message, but does set $? to 1
  10750. * (and does no shifting at all).
  10751. */
  10752. }
  10753. }
  10754. if (n >= 0 && n < G.global_argc) {
  10755. if (G_global_args_malloced) {
  10756. int m = 1;
  10757. while (m <= n)
  10758. free(G.global_argv[m++]);
  10759. }
  10760. G.global_argc -= n;
  10761. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10762. G.global_argc * sizeof(G.global_argv[0]));
  10763. return EXIT_SUCCESS;
  10764. }
  10765. return EXIT_FAILURE;
  10766. }
  10767. #if ENABLE_HUSH_GETOPTS
  10768. static int FAST_FUNC builtin_getopts(char **argv)
  10769. {
  10770. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10771. TODO:
  10772. If a required argument is not found, and getopts is not silent,
  10773. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10774. diagnostic message is printed. If getopts is silent, then a
  10775. colon (:) is placed in VAR and OPTARG is set to the option
  10776. character found.
  10777. Test that VAR is a valid variable name?
  10778. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10779. */
  10780. char cbuf[2];
  10781. const char *cp, *optstring, *var;
  10782. int c, n, exitcode, my_opterr;
  10783. unsigned count;
  10784. optstring = *++argv;
  10785. if (!optstring || !(var = *++argv)) {
  10786. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10787. return EXIT_FAILURE;
  10788. }
  10789. if (argv[1])
  10790. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10791. else
  10792. argv = G.global_argv;
  10793. cbuf[1] = '\0';
  10794. my_opterr = 0;
  10795. if (optstring[0] != ':') {
  10796. cp = get_local_var_value("OPTERR");
  10797. /* 0 if "OPTERR=0", 1 otherwise */
  10798. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10799. }
  10800. /* getopts stops on first non-option. Add "+" to force that */
  10801. /*if (optstring[0] != '+')*/ {
  10802. char *s = alloca(strlen(optstring) + 2);
  10803. sprintf(s, "+%s", optstring);
  10804. optstring = s;
  10805. }
  10806. /* Naively, now we should just
  10807. * cp = get_local_var_value("OPTIND");
  10808. * optind = cp ? atoi(cp) : 0;
  10809. * optarg = NULL;
  10810. * opterr = my_opterr;
  10811. * c = getopt(string_array_len(argv), argv, optstring);
  10812. * and be done? Not so fast...
  10813. * Unlike normal getopt() usage in C programs, here
  10814. * each successive call will (usually) have the same argv[] CONTENTS,
  10815. * but not the ADDRESSES. Worse yet, it's possible that between
  10816. * invocations of "getopts", there will be calls to shell builtins
  10817. * which use getopt() internally. Example:
  10818. * while getopts "abc" RES -a -bc -abc de; do
  10819. * unset -ff func
  10820. * done
  10821. * This would not work correctly: getopt() call inside "unset"
  10822. * modifies internal libc state which is tracking position in
  10823. * multi-option strings ("-abc"). At best, it can skip options
  10824. * or return the same option infinitely. With glibc implementation
  10825. * of getopt(), it would use outright invalid pointers and return
  10826. * garbage even _without_ "unset" mangling internal state.
  10827. *
  10828. * We resort to resetting getopt() state and calling it N times,
  10829. * until we get Nth result (or failure).
  10830. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10831. */
  10832. GETOPT_RESET();
  10833. count = 0;
  10834. n = string_array_len(argv);
  10835. do {
  10836. optarg = NULL;
  10837. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10838. c = getopt(n, argv, optstring);
  10839. if (c < 0)
  10840. break;
  10841. count++;
  10842. } while (count <= G.getopt_count);
  10843. /* Set OPTIND. Prevent resetting of the magic counter! */
  10844. set_local_var_from_halves("OPTIND", utoa(optind));
  10845. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10846. GETOPT_RESET(); /* just in case */
  10847. /* Set OPTARG */
  10848. /* Always set or unset, never left as-is, even on exit/error:
  10849. * "If no option was found, or if the option that was found
  10850. * does not have an option-argument, OPTARG shall be unset."
  10851. */
  10852. cp = optarg;
  10853. if (c == '?') {
  10854. /* If ":optstring" and unknown option is seen,
  10855. * it is stored to OPTARG.
  10856. */
  10857. if (optstring[1] == ':') {
  10858. cbuf[0] = optopt;
  10859. cp = cbuf;
  10860. }
  10861. }
  10862. if (cp)
  10863. set_local_var_from_halves("OPTARG", cp);
  10864. else
  10865. unset_local_var("OPTARG");
  10866. /* Convert -1 to "?" */
  10867. exitcode = EXIT_SUCCESS;
  10868. if (c < 0) { /* -1: end of options */
  10869. exitcode = EXIT_FAILURE;
  10870. c = '?';
  10871. }
  10872. /* Set VAR */
  10873. cbuf[0] = c;
  10874. set_local_var_from_halves(var, cbuf);
  10875. return exitcode;
  10876. }
  10877. #endif
  10878. static int FAST_FUNC builtin_source(char **argv)
  10879. {
  10880. char *arg_path, *filename;
  10881. HFILE *input;
  10882. save_arg_t sv;
  10883. char *args_need_save;
  10884. #if ENABLE_HUSH_FUNCTIONS
  10885. smallint sv_flg;
  10886. #endif
  10887. argv = skip_dash_dash(argv);
  10888. filename = argv[0];
  10889. if (!filename) {
  10890. /* bash says: "bash: .: filename argument required" */
  10891. return 2; /* bash compat */
  10892. }
  10893. arg_path = NULL;
  10894. if (!strchr(filename, '/')) {
  10895. arg_path = find_in_path(filename);
  10896. if (arg_path)
  10897. filename = arg_path;
  10898. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10899. errno = ENOENT;
  10900. bb_simple_perror_msg(filename);
  10901. return EXIT_FAILURE;
  10902. }
  10903. }
  10904. input = hfopen(filename);
  10905. free(arg_path);
  10906. if (!input) {
  10907. bb_perror_msg("%s", filename);
  10908. /* POSIX: non-interactive shell should abort here,
  10909. * not merely fail. So far no one complained :)
  10910. */
  10911. return EXIT_FAILURE;
  10912. }
  10913. #if ENABLE_HUSH_FUNCTIONS
  10914. sv_flg = G_flag_return_in_progress;
  10915. /* "we are inside sourced file, ok to use return" */
  10916. G_flag_return_in_progress = -1;
  10917. #endif
  10918. args_need_save = argv[1]; /* used as a boolean variable */
  10919. if (args_need_save)
  10920. save_and_replace_G_args(&sv, argv);
  10921. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10922. G.last_exitcode = 0;
  10923. parse_and_run_file(input);
  10924. hfclose(input);
  10925. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10926. restore_G_args(&sv, argv);
  10927. #if ENABLE_HUSH_FUNCTIONS
  10928. G_flag_return_in_progress = sv_flg;
  10929. #endif
  10930. return G.last_exitcode;
  10931. }
  10932. #if ENABLE_HUSH_TRAP
  10933. static int FAST_FUNC builtin_trap(char **argv)
  10934. {
  10935. int sig;
  10936. char *new_cmd;
  10937. if (!G_traps)
  10938. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10939. argv++;
  10940. if (!*argv) {
  10941. int i;
  10942. /* No args: print all trapped */
  10943. for (i = 0; i < NSIG; ++i) {
  10944. if (G_traps[i]) {
  10945. printf("trap -- ");
  10946. print_escaped(G_traps[i]);
  10947. /* note: bash adds "SIG", but only if invoked
  10948. * as "bash". If called as "sh", or if set -o posix,
  10949. * then it prints short signal names.
  10950. * We are printing short names: */
  10951. printf(" %s\n", get_signame(i));
  10952. }
  10953. }
  10954. /*fflush_all(); - done after each builtin anyway */
  10955. return EXIT_SUCCESS;
  10956. }
  10957. new_cmd = NULL;
  10958. /* If first arg is a number: reset all specified signals */
  10959. sig = bb_strtou(*argv, NULL, 10);
  10960. if (errno == 0) {
  10961. int ret;
  10962. process_sig_list:
  10963. ret = EXIT_SUCCESS;
  10964. while (*argv) {
  10965. sighandler_t handler;
  10966. sig = get_signum(*argv++);
  10967. if (sig < 0) {
  10968. ret = EXIT_FAILURE;
  10969. /* Mimic bash message exactly */
  10970. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10971. continue;
  10972. }
  10973. free(G_traps[sig]);
  10974. G_traps[sig] = xstrdup(new_cmd);
  10975. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10976. get_signame(sig), sig, G_traps[sig]);
  10977. /* There is no signal for 0 (EXIT) */
  10978. if (sig == 0)
  10979. continue;
  10980. if (new_cmd)
  10981. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10982. else
  10983. /* We are removing trap handler */
  10984. handler = pick_sighandler(sig);
  10985. install_sighandler(sig, handler);
  10986. }
  10987. return ret;
  10988. }
  10989. if (!argv[1]) { /* no second arg */
  10990. bb_simple_error_msg("trap: invalid arguments");
  10991. return EXIT_FAILURE;
  10992. }
  10993. /* First arg is "-": reset all specified to default */
  10994. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10995. /* Everything else: set arg as signal handler
  10996. * (includes "" case, which ignores signal) */
  10997. if (argv[0][0] == '-') {
  10998. if (argv[0][1] == '\0') { /* "-" */
  10999. /* new_cmd remains NULL: "reset these sigs" */
  11000. goto reset_traps;
  11001. }
  11002. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  11003. argv++;
  11004. }
  11005. /* else: "-something", no special meaning */
  11006. }
  11007. new_cmd = *argv;
  11008. reset_traps:
  11009. argv++;
  11010. goto process_sig_list;
  11011. }
  11012. #endif
  11013. #if ENABLE_HUSH_JOB
  11014. static struct pipe *parse_jobspec(const char *str)
  11015. {
  11016. struct pipe *pi;
  11017. unsigned jobnum;
  11018. if (sscanf(str, "%%%u", &jobnum) != 1) {
  11019. if (str[0] != '%'
  11020. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  11021. ) {
  11022. bb_error_msg("bad argument '%s'", str);
  11023. return NULL;
  11024. }
  11025. /* It is "%%", "%+" or "%" - current job */
  11026. jobnum = G.last_jobid;
  11027. if (jobnum == 0) {
  11028. bb_simple_error_msg("no current job");
  11029. return NULL;
  11030. }
  11031. }
  11032. for (pi = G.job_list; pi; pi = pi->next) {
  11033. if (pi->jobid == jobnum) {
  11034. return pi;
  11035. }
  11036. }
  11037. bb_error_msg("%u: no such job", jobnum);
  11038. return NULL;
  11039. }
  11040. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  11041. {
  11042. struct pipe *job;
  11043. const char *status_string;
  11044. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  11045. for (job = G.job_list; job; job = job->next) {
  11046. if (job->alive_cmds == job->stopped_cmds)
  11047. status_string = "Stopped";
  11048. else
  11049. status_string = "Running";
  11050. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  11051. }
  11052. clean_up_last_dead_job();
  11053. return EXIT_SUCCESS;
  11054. }
  11055. /* built-in 'fg' and 'bg' handler */
  11056. static int FAST_FUNC builtin_fg_bg(char **argv)
  11057. {
  11058. int i;
  11059. struct pipe *pi;
  11060. if (!G_interactive_fd)
  11061. return EXIT_FAILURE;
  11062. /* If they gave us no args, assume they want the last backgrounded task */
  11063. if (!argv[1]) {
  11064. for (pi = G.job_list; pi; pi = pi->next) {
  11065. if (pi->jobid == G.last_jobid) {
  11066. goto found;
  11067. }
  11068. }
  11069. bb_error_msg("%s: no current job", argv[0]);
  11070. return EXIT_FAILURE;
  11071. }
  11072. pi = parse_jobspec(argv[1]);
  11073. if (!pi)
  11074. return EXIT_FAILURE;
  11075. found:
  11076. /* TODO: bash prints a string representation
  11077. * of job being foregrounded (like "sleep 1 | cat") */
  11078. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  11079. /* Put the job into the foreground. */
  11080. tcsetpgrp(G_interactive_fd, pi->pgrp);
  11081. }
  11082. /* Restart the processes in the job */
  11083. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  11084. for (i = 0; i < pi->num_cmds; i++) {
  11085. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  11086. }
  11087. pi->stopped_cmds = 0;
  11088. i = kill(- pi->pgrp, SIGCONT);
  11089. if (i < 0) {
  11090. if (errno == ESRCH) {
  11091. delete_finished_job(pi);
  11092. return EXIT_SUCCESS;
  11093. }
  11094. bb_simple_perror_msg("kill (SIGCONT)");
  11095. }
  11096. if (argv[0][0] == 'f') {
  11097. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  11098. return checkjobs_and_fg_shell(pi);
  11099. }
  11100. return EXIT_SUCCESS;
  11101. }
  11102. #endif
  11103. #if ENABLE_HUSH_KILL
  11104. static int FAST_FUNC builtin_kill(char **argv)
  11105. {
  11106. int ret = 0;
  11107. # if ENABLE_HUSH_JOB
  11108. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  11109. int i = 1;
  11110. do {
  11111. struct pipe *pi;
  11112. char *dst;
  11113. int j, n;
  11114. if (argv[i][0] != '%')
  11115. continue;
  11116. /*
  11117. * "kill %N" - job kill
  11118. * Converting to pgrp / pid kill
  11119. */
  11120. pi = parse_jobspec(argv[i]);
  11121. if (!pi) {
  11122. /* Eat bad jobspec */
  11123. j = i;
  11124. do {
  11125. j++;
  11126. argv[j - 1] = argv[j];
  11127. } while (argv[j]);
  11128. ret = 1;
  11129. i--;
  11130. continue;
  11131. }
  11132. /*
  11133. * In jobs started under job control, we signal
  11134. * entire process group by kill -PGRP_ID.
  11135. * This happens, f.e., in interactive shell.
  11136. *
  11137. * Otherwise, we signal each child via
  11138. * kill PID1 PID2 PID3.
  11139. * Testcases:
  11140. * sh -c 'sleep 1|sleep 1 & kill %1'
  11141. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  11142. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  11143. */
  11144. n = G_interactive_fd ? 1 : pi->num_cmds;
  11145. dst = alloca(n * sizeof(int)*4);
  11146. argv[i] = dst;
  11147. if (G_interactive_fd)
  11148. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  11149. else for (j = 0; j < n; j++) {
  11150. struct command *cmd = &pi->cmds[j];
  11151. /* Skip exited members of the job */
  11152. if (cmd->pid == 0)
  11153. continue;
  11154. /*
  11155. * kill_main has matching code to expect
  11156. * leading space. Needed to not confuse
  11157. * negative pids with "kill -SIGNAL_NO" syntax
  11158. */
  11159. dst += sprintf(dst, " %u", (int)cmd->pid);
  11160. }
  11161. *dst = '\0';
  11162. } while (argv[++i]);
  11163. }
  11164. # endif
  11165. if (argv[1] || ret == 0) {
  11166. ret = run_applet_main(argv, kill_main);
  11167. }
  11168. /* else: ret = 1, "kill %bad_jobspec" case */
  11169. return ret;
  11170. }
  11171. #endif
  11172. #if ENABLE_HUSH_WAIT
  11173. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  11174. # if !ENABLE_HUSH_JOB
  11175. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  11176. # endif
  11177. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  11178. {
  11179. int ret = 0;
  11180. for (;;) {
  11181. int sig;
  11182. sigset_t oldset;
  11183. if (!sigisemptyset(&G.pending_set))
  11184. goto check_sig;
  11185. /* waitpid is not interruptible by SA_RESTARTed
  11186. * signals which we use. Thus, this ugly dance:
  11187. */
  11188. /* Make sure possible SIGCHLD is stored in kernel's
  11189. * pending signal mask before we call waitpid.
  11190. * Or else we may race with SIGCHLD, lose it,
  11191. * and get stuck in sigsuspend...
  11192. */
  11193. sigfillset(&oldset); /* block all signals, remember old set */
  11194. sigprocmask2(SIG_SETMASK, &oldset);
  11195. if (!sigisemptyset(&G.pending_set)) {
  11196. /* Crap! we raced with some signal! */
  11197. goto restore;
  11198. }
  11199. /*errno = 0; - checkjobs does this */
  11200. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  11201. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  11202. debug_printf_exec("checkjobs:%d\n", ret);
  11203. # if ENABLE_HUSH_JOB
  11204. if (waitfor_pipe) {
  11205. int rcode = job_exited_or_stopped(waitfor_pipe);
  11206. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  11207. if (rcode >= 0) {
  11208. ret = rcode;
  11209. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11210. break;
  11211. }
  11212. }
  11213. # endif
  11214. /* if ECHILD, there are no children (ret is -1 or 0) */
  11215. /* if ret == 0, no children changed state */
  11216. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  11217. if (errno == ECHILD || ret) {
  11218. ret--;
  11219. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  11220. ret = 0;
  11221. # if ENABLE_HUSH_BASH_COMPAT
  11222. if (waitfor_pid == -1 && errno == ECHILD) {
  11223. /* exitcode of "wait -n" with no children is 127, not 0 */
  11224. ret = 127;
  11225. }
  11226. # endif
  11227. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11228. break;
  11229. }
  11230. /* Wait for SIGCHLD or any other signal */
  11231. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  11232. /* Note: sigsuspend invokes signal handler */
  11233. sigsuspend(&oldset);
  11234. /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
  11235. * to make sure SIGCHLD is not masked off?
  11236. * It was reported that this:
  11237. * fn() { : | return; }
  11238. * shopt -s lastpipe
  11239. * fn
  11240. * exec hush SCRIPT
  11241. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  11242. * making "wait" commands in SCRIPT block forever.
  11243. */
  11244. restore:
  11245. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11246. check_sig:
  11247. /* So, did we get a signal? */
  11248. sig = check_and_run_traps();
  11249. if (sig /*&& sig != SIGCHLD - always true */) {
  11250. /* Do this for any (non-ignored) signal, not only for ^C */
  11251. ret = 128 | sig;
  11252. break;
  11253. }
  11254. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  11255. }
  11256. return ret;
  11257. }
  11258. static int FAST_FUNC builtin_wait(char **argv)
  11259. {
  11260. int ret;
  11261. int status;
  11262. argv = skip_dash_dash(argv);
  11263. # if ENABLE_HUSH_BASH_COMPAT
  11264. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  11265. /* wait -n */
  11266. /* (bash accepts "wait -n PID" too and ignores PID) */
  11267. G.dead_job_exitcode = -1;
  11268. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  11269. }
  11270. # endif
  11271. if (argv[0] == NULL) {
  11272. /* Don't care about wait results */
  11273. /* Note 1: must wait until there are no more children */
  11274. /* Note 2: must be interruptible */
  11275. /* Examples:
  11276. * $ sleep 3 & sleep 6 & wait
  11277. * [1] 30934 sleep 3
  11278. * [2] 30935 sleep 6
  11279. * [1] Done sleep 3
  11280. * [2] Done sleep 6
  11281. * $ sleep 3 & sleep 6 & wait
  11282. * [1] 30936 sleep 3
  11283. * [2] 30937 sleep 6
  11284. * [1] Done sleep 3
  11285. * ^C <-- after ~4 sec from keyboard
  11286. * $
  11287. */
  11288. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  11289. }
  11290. do {
  11291. pid_t pid = bb_strtou(*argv, NULL, 10);
  11292. if (errno || pid <= 0) {
  11293. # if ENABLE_HUSH_JOB
  11294. if (argv[0][0] == '%') {
  11295. struct pipe *wait_pipe;
  11296. ret = 127; /* bash compat for bad jobspecs */
  11297. wait_pipe = parse_jobspec(*argv);
  11298. if (wait_pipe) {
  11299. ret = job_exited_or_stopped(wait_pipe);
  11300. if (ret < 0) {
  11301. ret = wait_for_child_or_signal(wait_pipe, 0);
  11302. } else {
  11303. /* waiting on "last dead job" removes it */
  11304. clean_up_last_dead_job();
  11305. }
  11306. }
  11307. /* else: parse_jobspec() already emitted error msg */
  11308. continue;
  11309. }
  11310. # endif
  11311. /* mimic bash message */
  11312. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  11313. ret = EXIT_FAILURE;
  11314. continue; /* bash checks all argv[] */
  11315. }
  11316. /* Do we have such child? */
  11317. ret = waitpid(pid, &status, WNOHANG);
  11318. if (ret < 0) {
  11319. /* No */
  11320. ret = 127;
  11321. if (errno == ECHILD) {
  11322. if (pid == G.last_bg_pid) {
  11323. /* "wait $!" but last bg task has already exited. Try:
  11324. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  11325. * In bash it prints exitcode 0, then 3.
  11326. * In dash, it is 127.
  11327. */
  11328. ret = G.last_bg_pid_exitcode;
  11329. } else {
  11330. /* Example: "wait 1". mimic bash message */
  11331. bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
  11332. }
  11333. } else {
  11334. /* ??? */
  11335. bb_perror_msg("wait %s", *argv);
  11336. }
  11337. continue; /* bash checks all argv[] */
  11338. }
  11339. if (ret == 0) {
  11340. /* Yes, and it still runs */
  11341. ret = wait_for_child_or_signal(NULL, pid);
  11342. } else {
  11343. /* Yes, and it just exited */
  11344. process_wait_result(NULL, pid, status);
  11345. ret = WEXITSTATUS(status);
  11346. if (WIFSIGNALED(status))
  11347. ret = 128 | WTERMSIG(status);
  11348. }
  11349. } while (*++argv);
  11350. return ret;
  11351. }
  11352. #endif
  11353. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  11354. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  11355. {
  11356. if (argv[1]) {
  11357. def = bb_strtou(argv[1], NULL, 10);
  11358. if (errno || def < def_min || argv[2]) {
  11359. bb_error_msg("%s: bad arguments", argv[0]);
  11360. def = UINT_MAX;
  11361. }
  11362. }
  11363. return def;
  11364. }
  11365. #endif
  11366. #if ENABLE_HUSH_LOOPS
  11367. static int FAST_FUNC builtin_break(char **argv)
  11368. {
  11369. unsigned depth;
  11370. if (G.depth_of_loop == 0) {
  11371. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  11372. /* if we came from builtin_continue(), need to undo "= 1" */
  11373. G.flag_break_continue = 0;
  11374. return EXIT_SUCCESS; /* bash compat */
  11375. }
  11376. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  11377. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  11378. if (depth == UINT_MAX)
  11379. G.flag_break_continue = BC_BREAK;
  11380. if (G.depth_of_loop < depth)
  11381. G.depth_break_continue = G.depth_of_loop;
  11382. return EXIT_SUCCESS;
  11383. }
  11384. static int FAST_FUNC builtin_continue(char **argv)
  11385. {
  11386. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  11387. return builtin_break(argv);
  11388. }
  11389. #endif
  11390. #if ENABLE_HUSH_FUNCTIONS
  11391. static int FAST_FUNC builtin_return(char **argv)
  11392. {
  11393. int rc;
  11394. if (G_flag_return_in_progress != -1) {
  11395. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  11396. return EXIT_FAILURE; /* bash compat */
  11397. }
  11398. G_flag_return_in_progress = 1;
  11399. /* bash:
  11400. * out of range: wraps around at 256, does not error out
  11401. * non-numeric param:
  11402. * f() { false; return qwe; }; f; echo $?
  11403. * bash: return: qwe: numeric argument required <== we do this
  11404. * 255 <== we also do this
  11405. */
  11406. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  11407. # if ENABLE_HUSH_TRAP
  11408. if (argv[1]) { /* "return ARG" inside a running trap sets $? */
  11409. debug_printf_exec("G.return_exitcode=%d\n", rc);
  11410. G.return_exitcode = rc;
  11411. }
  11412. # endif
  11413. return rc;
  11414. }
  11415. #endif
  11416. #if ENABLE_HUSH_TIMES
  11417. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  11418. {
  11419. static const uint8_t times_tbl[] ALIGN1 = {
  11420. ' ', offsetof(struct tms, tms_utime),
  11421. '\n', offsetof(struct tms, tms_stime),
  11422. ' ', offsetof(struct tms, tms_cutime),
  11423. '\n', offsetof(struct tms, tms_cstime),
  11424. 0
  11425. };
  11426. const uint8_t *p;
  11427. unsigned clk_tck;
  11428. struct tms buf;
  11429. clk_tck = bb_clk_tck();
  11430. times(&buf);
  11431. p = times_tbl;
  11432. do {
  11433. unsigned sec, frac;
  11434. unsigned long t;
  11435. t = *(clock_t *)(((char *) &buf) + p[1]);
  11436. sec = t / clk_tck;
  11437. frac = t % clk_tck;
  11438. printf("%um%u.%03us%c",
  11439. sec / 60, sec % 60,
  11440. (frac * 1000) / clk_tck,
  11441. p[0]);
  11442. p += 2;
  11443. } while (*p);
  11444. return EXIT_SUCCESS;
  11445. }
  11446. #endif
  11447. #if ENABLE_HUSH_MEMLEAK
  11448. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  11449. {
  11450. void *p;
  11451. unsigned long l;
  11452. # ifdef M_TRIM_THRESHOLD
  11453. /* Optional. Reduces probability of false positives */
  11454. malloc_trim(0);
  11455. # endif
  11456. /* Crude attempt to find where "free memory" starts,
  11457. * sans fragmentation. */
  11458. p = malloc(240);
  11459. l = (unsigned long)p;
  11460. free(p);
  11461. p = malloc(3400);
  11462. if (l < (unsigned long)p) l = (unsigned long)p;
  11463. free(p);
  11464. # if 0 /* debug */
  11465. {
  11466. struct mallinfo mi = mallinfo();
  11467. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  11468. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  11469. }
  11470. # endif
  11471. if (!G.memleak_value)
  11472. G.memleak_value = l;
  11473. l -= G.memleak_value;
  11474. if ((long)l < 0)
  11475. l = 0;
  11476. l /= 1024;
  11477. if (l > 127)
  11478. l = 127;
  11479. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  11480. return l;
  11481. }
  11482. #endif