1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380 |
- #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
- || defined(__APPLE__) \
- )
- # include <malloc.h> /* for malloc_trim */
- #endif
- #include <glob.h>
- #if ENABLE_HUSH_CASE
- # include <fnmatch.h>
- #endif
- #include <sys/times.h>
- #include <sys/utsname.h> /* for setting $HOSTNAME */
- #include "busybox.h"
- #include "unicode.h"
- #include "shell_common.h"
- #include "math.h"
- #include "match.h"
- #if ENABLE_HUSH_RANDOM_SUPPORT
- # include "random.h"
- #else
- # define CLEAR_RANDOM_T(rnd) ((void)0)
- #endif
- #ifndef O_CLOEXEC
- # define O_CLOEXEC 0
- #endif
- #ifndef F_DUPFD_CLOEXEC
- # define F_DUPFD_CLOEXEC F_DUPFD
- #endif
- #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !ENABLE_SHELL_ASH
- # include "embedded_scripts.h"
- #else
- # define NUM_SCRIPTS 0
- #endif
- #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
- #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
- #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
- #define BASH_DOLLAR_SQUOTE ENABLE_HUSH_BASH_COMPAT
- #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
- #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
- #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
- #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
- #define LEAK_HUNTING 0
- #define BUILD_AS_NOMMU 0
- #define HUSH_DEBUG 1
- #define ENABLE_HUSH_FAST 0
- #define ENABLE_HUSH_DOLLAR_OPS 1
- #if BUILD_AS_NOMMU
- # undef BB_MMU
- # undef USE_FOR_NOMMU
- # undef USE_FOR_MMU
- # define BB_MMU 0
- # define USE_FOR_NOMMU(...) __VA_ARGS__
- # define USE_FOR_MMU(...)
- #endif
- #include "NUM_APPLETS.h"
- #if NUM_APPLETS == 1
- # undef CONFIG_FEATURE_SH_STANDALONE
- # undef ENABLE_FEATURE_SH_STANDALONE
- # undef IF_FEATURE_SH_STANDALONE
- # undef IF_NOT_FEATURE_SH_STANDALONE
- # define ENABLE_FEATURE_SH_STANDALONE 0
- # define IF_FEATURE_SH_STANDALONE(...)
- # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
- #endif
- #if !ENABLE_HUSH_INTERACTIVE
- # undef ENABLE_FEATURE_EDITING
- # define ENABLE_FEATURE_EDITING 0
- # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
- # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
- # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
- # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
- #endif
- #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
- # define HAS_KEYWORDS 1
- # define IF_HAS_KEYWORDS(...) __VA_ARGS__
- # define IF_HAS_NO_KEYWORDS(...)
- #else
- # define HAS_KEYWORDS 0
- # define IF_HAS_KEYWORDS(...)
- # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
- #endif
- #define debug_printf(...) do {} while (0)
- #define debug_printf_parse(...) do {} while (0)
- #define debug_printf_heredoc(...) do {} while (0)
- #define debug_print_tree(a, b) do {} while (0)
- #define debug_printf_exec(...) do {} while (0)
- #define debug_printf_env(...) do {} while (0)
- #define debug_printf_jobs(...) do {} while (0)
- #define debug_printf_expand(...) do {} while (0)
- #define debug_printf_varexp(...) do {} while (0)
- #define debug_printf_glob(...) do {} while (0)
- #define debug_printf_redir(...) do {} while (0)
- #define debug_printf_list(...) do {} while (0)
- #define debug_printf_subst(...) do {} while (0)
- #define debug_printf_prompt(...) do {} while (0)
- #define debug_printf_clean(...) do {} while (0)
- #define ERR_PTR ((void*)(long)1)
- #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
- #define _SPECIAL_VARS_STR "_*@$!?#-"
- #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
- #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
- #if BASH_PATTERN_SUBST
- # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
- # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
- # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
- #else
- # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
- # define VAR_SUBST_OPS "%#:-=+?"
- # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
- #endif
- #define SPECIAL_VAR_SYMBOL_STR "\3"
- #define SPECIAL_VAR_SYMBOL 3
- #define SPECIAL_VAR_QUOTED_SVS 1
- struct variable;
- static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
- #if !BB_MMU
- typedef struct nommu_save_t {
- struct variable *old_vars;
- char **argv;
- char **argv_from_re_execing;
- } nommu_save_t;
- #endif
- enum {
- RES_NONE = 0,
- #if ENABLE_HUSH_IF
- RES_IF ,
- RES_THEN ,
- RES_ELIF ,
- RES_ELSE ,
- RES_FI ,
- #endif
- #if ENABLE_HUSH_LOOPS
- RES_FOR ,
- RES_WHILE ,
- RES_UNTIL ,
- RES_DO ,
- RES_DONE ,
- #endif
- #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
- RES_IN ,
- #endif
- #if ENABLE_HUSH_CASE
- RES_CASE ,
-
- RES_CASE_IN,
- RES_MATCH ,
- RES_CASE_BODY,
- RES_ESAC ,
- #endif
- RES_XXXX ,
- RES_SNTX
- };
- typedef struct o_string {
- char *data;
- int length;
- int maxlen;
- int o_expflags;
-
- smallint has_quoted_part;
- smallint has_empty_slot;
- smallint ended_in_ifs;
- } o_string;
- enum {
- EXP_FLAG_SINGLEWORD = 0x80,
- EXP_FLAG_GLOB = 0x2,
-
- EXP_FLAG_ESC_GLOB_CHARS = 0x1,
- };
- #define NULL_O_STRING { NULL }
- #ifndef debug_printf_parse
- static const char *const assignment_flag[] ALIGN_PTR = {
- "MAYBE_ASSIGNMENT",
- "DEFINITELY_ASSIGNMENT",
- "NOT_ASSIGNMENT",
- "WORD_IS_KEYWORD",
- };
- #endif
- typedef struct HFILE {
- char *cur;
- char *end;
- struct HFILE *next_hfile;
- int fd;
- char buf[1024];
- } HFILE;
- typedef struct in_str {
- const char *p;
- int peek_buf[2];
- int last_char;
- HFILE *file;
- } in_str;
- static const struct {
- int32_t mode;
- signed char default_fd;
- char descrip[3];
- } redir_table[] ALIGN4 = {
- { O_RDONLY, 0, "<" },
- { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
- { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
- { O_CREAT|O_RDWR, 1, "<>" },
- { O_RDONLY, 0, "<<" },
- };
- struct redir_struct {
- struct redir_struct *next;
- char *rd_filename;
- int rd_fd;
-
- int rd_dup;
- smallint rd_type;
-
- };
- typedef enum redir_type {
- REDIRECT_INPUT = 0,
- REDIRECT_OVERWRITE = 1,
- REDIRECT_APPEND = 2,
- REDIRECT_IO = 3,
- REDIRECT_HEREDOC = 4,
- REDIRECT_HEREDOC2 = 5,
- REDIRFD_CLOSE = -3,
- REDIRFD_SYNTAX_ERR = -2,
- REDIRFD_TO_FILE = -1,
-
- HEREDOC_SKIPTABS = 1,
- HEREDOC_QUOTED = 2,
- } redir_type;
- struct command {
- pid_t pid;
- unsigned assignment_cnt;
- #if ENABLE_HUSH_LINENO_VAR
- unsigned lineno;
- #endif
- smallint cmd_type;
- #define CMD_NORMAL 0
- #define CMD_SUBSHELL 1
- #if BASH_TEST2
- # define CMD_TEST2_SINGLEWORD_NOGLOB 2
- #endif
- #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
- # define CMD_SINGLEWORD_NOGLOB 3
- #endif
- #if ENABLE_HUSH_FUNCTIONS
- # define CMD_FUNCDEF 4
- #endif
- smalluint cmd_exitcode;
-
- struct pipe *group;
- #if !BB_MMU
- char *group_as_string;
- #endif
- #if ENABLE_HUSH_FUNCTIONS
- struct function *child_func;
- #endif
- char **argv;
- struct redir_struct *redirects;
- };
- #define IS_NULL_CMD(cmd) \
- (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
- struct pipe {
- struct pipe *next;
- int num_cmds;
- int alive_cmds;
- int stopped_cmds;
- #if ENABLE_HUSH_JOB
- unsigned jobid;
- pid_t pgrp;
- char *cmdtext;
- #endif
- struct command *cmds;
- smallint followup;
- IF_HAS_KEYWORDS(smallint pi_inverted;)
- IF_HAS_KEYWORDS(smallint res_word;)
- };
- typedef enum pipe_style {
- PIPE_SEQ = 0,
- PIPE_AND = 1,
- PIPE_OR = 2,
- PIPE_BG = 3,
- } pipe_style;
- #define IS_NULL_PIPE(pi) \
- ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
- struct parse_context {
-
- struct pipe *list_head;
-
- struct pipe *pipe;
-
- struct command *command;
-
- struct redir_struct *pending_redirect;
- o_string word;
- #if !BB_MMU
- o_string as_string;
- #endif
- smallint is_assignment;
- #if HAS_KEYWORDS
- smallint ctx_res_w;
- smallint ctx_inverted;
- #if ENABLE_HUSH_CASE
- smallint ctx_dsemicolon;
- #endif
-
- int old_flag;
-
- struct parse_context *stack;
- #endif
- };
- enum {
- MAYBE_ASSIGNMENT = 0,
- DEFINITELY_ASSIGNMENT = 1,
- NOT_ASSIGNMENT = 2,
-
- WORD_IS_KEYWORD = 3,
- };
- #define setenv(...) setenv_is_leaky_dont_use()
- struct variable {
- struct variable *next;
- char *varstr;
- int max_len;
- uint16_t var_nest_level;
- smallint flg_export;
- smallint flg_read_only;
- };
- enum {
- BC_BREAK = 1,
- BC_CONTINUE = 2,
- };
- #if ENABLE_HUSH_FUNCTIONS
- struct function {
- struct function *next;
- char *name;
- struct command *parent_cmd;
- struct pipe *body;
- # if !BB_MMU
- char *body_as_string;
- # endif
- };
- #endif
- static const char o_opt_strings[] ALIGN1 =
- "pipefail\0"
- "noexec\0"
- "errexit\0"
- #if ENABLE_HUSH_MODE_X
- "xtrace\0"
- #endif
- ;
- enum {
- OPT_O_PIPEFAIL,
- OPT_O_NOEXEC,
- OPT_O_ERREXIT,
- #if ENABLE_HUSH_MODE_X
- OPT_O_XTRACE,
- #endif
- NUM_OPT_O
- };
- struct globals {
-
- #if ENABLE_HUSH_INTERACTIVE
-
- int interactive_fd;
- IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
- # define G_interactive_fd (G.interactive_fd)
- #else
- # define G_interactive_fd 0
- #endif
- #if ENABLE_FEATURE_EDITING
- line_input_t *line_input_state;
- #endif
- pid_t root_pid;
- pid_t root_ppid;
- pid_t last_bg_pid;
- #if ENABLE_HUSH_RANDOM_SUPPORT
- random_t random_gen;
- #endif
- #if ENABLE_HUSH_JOB
- int run_list_level;
- unsigned last_jobid;
- pid_t saved_tty_pgrp;
- struct pipe *job_list;
- # define G_saved_tty_pgrp (G.saved_tty_pgrp)
- #else
- # define G_saved_tty_pgrp 0
- #endif
-
- int errexit_depth;
-
- char o_opt[NUM_OPT_O];
- #if ENABLE_HUSH_MODE_X
- # define G_x_mode (G.o_opt[OPT_O_XTRACE])
- #else
- # define G_x_mode 0
- #endif
- char opt_s;
- char opt_c;
- #if ENABLE_HUSH_INTERACTIVE
- smallint promptmode;
- #endif
-
- smallint flag_SIGINT;
- #if ENABLE_HUSH_LOOPS
- smallint flag_break_continue;
- #endif
- #if ENABLE_HUSH_FUNCTIONS
-
- smallint flag_return_in_progress;
- # define G_flag_return_in_progress (G.flag_return_in_progress)
- #else
- # define G_flag_return_in_progress 0
- #endif
- smallint exiting;
-
- smalluint last_exitcode;
- smalluint expand_exitcode;
- smalluint last_bg_pid_exitcode;
- #if ENABLE_HUSH_SET
-
- smalluint global_args_malloced;
- # define G_global_args_malloced (G.global_args_malloced)
- #else
- # define G_global_args_malloced 0
- #endif
- #if ENABLE_HUSH_BASH_COMPAT
- int dead_job_exitcode;
- #endif
-
- int global_argc;
- char **global_argv;
- #if !BB_MMU
- char *argv0_for_re_execing;
- #endif
- #if ENABLE_HUSH_LOOPS
- unsigned depth_break_continue;
- unsigned depth_of_loop;
- #endif
- #if ENABLE_HUSH_GETOPTS
- unsigned getopt_count;
- #endif
- const char *ifs;
- char *ifs_whitespace;
- const char *cwd;
- struct variable *top_var;
- char **expanded_assignments;
- struct variable **shadowed_vars_pp;
- unsigned var_nest_level;
- #if ENABLE_HUSH_FUNCTIONS
- # if ENABLE_HUSH_LOCAL
- unsigned func_nest_level;
- # endif
- struct function *top_func;
- #endif
-
- #if ENABLE_HUSH_FAST
- unsigned count_SIGCHLD;
- unsigned handled_SIGCHLD;
- smallint we_have_children;
- #endif
- #if ENABLE_HUSH_LINENO_VAR
- unsigned parse_lineno;
- unsigned execute_lineno;
- #endif
- HFILE *HFILE_list;
- HFILE *HFILE_stdin;
-
- unsigned special_sig_mask;
- #if ENABLE_HUSH_JOB
- unsigned fatal_sig_mask;
- # define G_fatal_sig_mask (G.fatal_sig_mask)
- #else
- # define G_fatal_sig_mask 0
- #endif
- #if ENABLE_HUSH_TRAP
- int pre_trap_exitcode;
- # if ENABLE_HUSH_FUNCTIONS
- int return_exitcode;
- # endif
- char **traps;
- # define G_traps G.traps
- #else
- # define G_traps ((char**)NULL)
- #endif
- sigset_t pending_set;
- #if ENABLE_HUSH_MEMLEAK
- unsigned long memleak_value;
- #endif
- #if ENABLE_HUSH_MODE_X
- unsigned x_mode_depth;
-
- int x_mode_fd;
- o_string x_mode_buf;
- #endif
- #if HUSH_DEBUG >= 2
- int debug_indent;
- #endif
- #if ENABLE_HUSH_TEST || BASH_TEST2
-
- struct cached_groupinfo groupinfo;
- # define GROUPINFO_INIT { G.groupinfo.euid = -1; G.groupinfo.egid = -1; }
- #else
- # define GROUPINFO_INIT
- #endif
- struct sigaction sa;
- char optstring_buf[sizeof("eixcs")];
- #if BASH_EPOCH_VARS
- char epoch_buf[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
- #endif
- #if ENABLE_FEATURE_EDITING
- char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
- #endif
- };
- #define G (*ptr_to_globals)
- #define INIT_G() do { \
- SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
- \
- sigfillset(&G.sa.sa_mask); \
- G.sa.sa_flags = SA_RESTART; \
- GROUPINFO_INIT; \
- } while (0)
- static int builtin_cd(char **argv) FAST_FUNC;
- #if ENABLE_HUSH_ECHO
- static int builtin_echo(char **argv) FAST_FUNC;
- #endif
- static int builtin_eval(char **argv) FAST_FUNC;
- static int builtin_exec(char **argv) FAST_FUNC;
- static int builtin_exit(char **argv) FAST_FUNC;
- #if ENABLE_HUSH_EXPORT
- static int builtin_export(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_READONLY
- static int builtin_readonly(char **argv) FAST_FUNC;
- #endif
- static int builtin_false(char **argv) FAST_FUNC;
- #if ENABLE_HUSH_JOB
- static int builtin_fg_bg(char **argv) FAST_FUNC;
- static int builtin_jobs(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_GETOPTS
- static int builtin_getopts(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_HELP
- static int builtin_help(char **argv) FAST_FUNC;
- #endif
- #if MAX_HISTORY && ENABLE_FEATURE_EDITING
- static int builtin_history(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_LOCAL
- static int builtin_local(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_MEMLEAK
- static int builtin_memleak(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_PRINTF
- static int builtin_printf(char **argv) FAST_FUNC;
- #endif
- static int builtin_pwd(char **argv) FAST_FUNC;
- #if ENABLE_HUSH_READ
- static int builtin_read(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_SET
- static int builtin_set(char **argv) FAST_FUNC;
- #endif
- static int builtin_shift(char **argv) FAST_FUNC;
- static int builtin_source(char **argv) FAST_FUNC;
- #if ENABLE_HUSH_TEST || BASH_TEST2
- static int builtin_test(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_TRAP
- static int builtin_trap(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_TYPE
- static int builtin_type(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_TIMES
- static int builtin_times(char **argv) FAST_FUNC;
- #endif
- static int builtin_true(char **argv) FAST_FUNC;
- #if ENABLE_HUSH_UMASK
- static int builtin_umask(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_UNSET
- static int builtin_unset(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_KILL
- static int builtin_kill(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_WAIT
- static int builtin_wait(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_LOOPS
- static int builtin_break(char **argv) FAST_FUNC;
- static int builtin_continue(char **argv) FAST_FUNC;
- #endif
- #if ENABLE_HUSH_FUNCTIONS
- static int builtin_return(char **argv) FAST_FUNC;
- #endif
- struct built_in_command {
- const char *b_cmd;
- int (*b_function)(char **argv) FAST_FUNC;
- #if ENABLE_HUSH_HELP
- const char *b_descr;
- # define BLTIN(cmd, func, help) { cmd, func, help }
- #else
- # define BLTIN(cmd, func, help) { cmd, func }
- #endif
- };
- static const struct built_in_command bltins1[] ALIGN_PTR = {
- BLTIN("." , builtin_source , "Run commands in file"),
- BLTIN(":" , builtin_true , NULL),
- #if ENABLE_HUSH_JOB
- BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
- #endif
- #if ENABLE_HUSH_LOOPS
- BLTIN("break" , builtin_break , "Exit loop"),
- #endif
- BLTIN("cd" , builtin_cd , "Change directory"),
- #if ENABLE_HUSH_LOOPS
- BLTIN("continue" , builtin_continue, "Start new loop iteration"),
- #endif
- BLTIN("eval" , builtin_eval , "Construct and run shell command"),
- BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
- BLTIN("exit" , builtin_exit , NULL),
- #if ENABLE_HUSH_EXPORT
- BLTIN("export" , builtin_export , "Set environment variables"),
- #endif
- BLTIN("false" , builtin_false , NULL),
- #if ENABLE_HUSH_JOB
- BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
- #endif
- #if ENABLE_HUSH_GETOPTS
- BLTIN("getopts" , builtin_getopts , NULL),
- #endif
- #if ENABLE_HUSH_HELP
- BLTIN("help" , builtin_help , NULL),
- #endif
- #if MAX_HISTORY && ENABLE_FEATURE_EDITING
- BLTIN("history" , builtin_history , "Show history"),
- #endif
- #if ENABLE_HUSH_JOB
- BLTIN("jobs" , builtin_jobs , "List jobs"),
- #endif
- #if ENABLE_HUSH_KILL
- BLTIN("kill" , builtin_kill , "Send signals to processes"),
- #endif
- #if ENABLE_HUSH_LOCAL
- BLTIN("local" , builtin_local , "Set local variables"),
- #endif
- #if ENABLE_HUSH_MEMLEAK
- BLTIN("memleak" , builtin_memleak , NULL),
- #endif
- #if ENABLE_HUSH_READ
- BLTIN("read" , builtin_read , "Input into variable"),
- #endif
- #if ENABLE_HUSH_READONLY
- BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
- #endif
- #if ENABLE_HUSH_FUNCTIONS
- BLTIN("return" , builtin_return , "Return from function"),
- #endif
- #if ENABLE_HUSH_SET
- BLTIN("set" , builtin_set , "Set positional parameters"),
- #endif
- BLTIN("shift" , builtin_shift , "Shift positional parameters"),
- #if BASH_SOURCE
- BLTIN("source" , builtin_source , NULL),
- #endif
- #if ENABLE_HUSH_TIMES
- BLTIN("times" , builtin_times , NULL),
- #endif
- #if ENABLE_HUSH_TRAP
- BLTIN("trap" , builtin_trap , "Trap signals"),
- #endif
- BLTIN("true" , builtin_true , NULL),
- #if ENABLE_HUSH_TYPE
- BLTIN("type" , builtin_type , "Show command type"),
- #endif
- #if ENABLE_HUSH_ULIMIT
- BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
- #endif
- #if ENABLE_HUSH_UMASK
- BLTIN("umask" , builtin_umask , "Set file creation mask"),
- #endif
- #if ENABLE_HUSH_UNSET
- BLTIN("unset" , builtin_unset , "Unset variables"),
- #endif
- #if ENABLE_HUSH_WAIT
- BLTIN("wait" , builtin_wait , "Wait for process to finish"),
- #endif
- };
- static const struct built_in_command bltins2[] ALIGN_PTR = {
- #if ENABLE_HUSH_TEST
- BLTIN("[" , builtin_test , NULL),
- #endif
- #if BASH_TEST2
- BLTIN("[[" , builtin_test , NULL),
- #endif
- #if ENABLE_HUSH_ECHO
- BLTIN("echo" , builtin_echo , NULL),
- #endif
- #if ENABLE_HUSH_PRINTF
- BLTIN("printf" , builtin_printf , NULL),
- #endif
- BLTIN("pwd" , builtin_pwd , NULL),
- #if ENABLE_HUSH_TEST
- BLTIN("test" , builtin_test , NULL),
- #endif
- };
- #if HUSH_DEBUG >= 2
- # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
- # define debug_enter() (G.debug_indent++)
- # define debug_leave() (G.debug_indent--)
- #else
- # define indent() ((void)0)
- # define debug_enter() ((void)0)
- # define debug_leave() ((void)0)
- #endif
- #ifndef debug_printf
- # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
- #endif
- #ifndef debug_printf_parse
- # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
- #endif
- #ifndef debug_printf_heredoc
- # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
- #endif
- #ifndef debug_printf_exec
- #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
- #endif
- #ifndef debug_printf_env
- # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
- #endif
- #ifndef debug_printf_jobs
- # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
- # define DEBUG_JOBS 1
- #else
- # define DEBUG_JOBS 0
- #endif
- #ifndef debug_printf_expand
- # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
- # define DEBUG_EXPAND 1
- #else
- # define DEBUG_EXPAND 0
- #endif
- #ifndef debug_printf_varexp
- # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
- #endif
- #ifndef debug_printf_glob
- # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
- # define DEBUG_GLOB 1
- #else
- # define DEBUG_GLOB 0
- #endif
- #ifndef debug_printf_redir
- # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
- #endif
- #ifndef debug_printf_list
- # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
- #endif
- #ifndef debug_printf_subst
- # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
- #endif
- #ifndef debug_printf_prompt
- # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
- #endif
- #ifndef debug_printf_clean
- # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
- # define DEBUG_CLEAN 1
- #else
- # define DEBUG_CLEAN 0
- #endif
- #if DEBUG_EXPAND
- static void debug_print_strings(const char *prefix, char **vv)
- {
- indent();
- fdprintf(2, "%s:\n", prefix);
- while (*vv)
- fdprintf(2, " '%s'\n", *vv++);
- }
- #else
- # define debug_print_strings(prefix, vv) ((void)0)
- #endif
- #if LEAK_HUNTING
- static void *xxmalloc(int lineno, size_t size)
- {
- void *ptr = xmalloc((size + 0xff) & ~0xff);
- fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
- return ptr;
- }
- static void *xxrealloc(int lineno, void *ptr, size_t size)
- {
- ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
- fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
- return ptr;
- }
- static char *xxstrdup(int lineno, const char *str)
- {
- char *ptr = xstrdup(str);
- fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
- return ptr;
- }
- static void xxfree(void *ptr)
- {
- fdprintf(2, "free %p\n", ptr);
- free(ptr);
- }
- # define xmalloc(s) xxmalloc(__LINE__, s)
- # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
- # define xstrdup(s) xxstrdup(__LINE__, s)
- # define free(p) xxfree(p)
- #endif
- #if HUSH_DEBUG < 2
- # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
- # define syntax_error(lineno, msg) syntax_error(msg)
- # define syntax_error_at(lineno, msg) syntax_error_at(msg)
- # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
- # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
- # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
- #endif
- static void die_if_script(void)
- {
- if (!G_interactive_fd) {
- if (G.last_exitcode)
- xfunc_error_retval = G.last_exitcode;
- xfunc_die();
- }
- }
- static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
- {
- va_list p;
- #if HUSH_DEBUG >= 2
- bb_error_msg("hush.c:%u", lineno);
- #endif
- va_start(p, fmt);
- bb_verror_msg(fmt, p, NULL);
- va_end(p);
- die_if_script();
- }
- static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
- {
- if (msg)
- bb_error_msg("syntax error: %s", msg);
- else
- bb_simple_error_msg("syntax error");
- die_if_script();
- }
- static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
- {
- bb_error_msg("syntax error at '%s'", msg);
- die_if_script();
- }
- static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
- {
- bb_error_msg("syntax error: unterminated %s", s);
- }
- static void syntax_error_unterm_ch(unsigned lineno, char ch)
- {
- char msg[2] = { ch, '\0' };
- syntax_error_unterm_str(lineno, msg);
- }
- static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
- {
- char msg[2];
- msg[0] = ch;
- msg[1] = '\0';
- #if HUSH_DEBUG >= 2
- bb_error_msg("hush.c:%u", lineno);
- #endif
- bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
- die_if_script();
- }
- #if HUSH_DEBUG < 2
- # undef msg_and_die_if_script
- # undef syntax_error
- # undef syntax_error_at
- # undef syntax_error_unterm_ch
- # undef syntax_error_unterm_str
- # undef syntax_error_unexpected_ch
- #else
- # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
- # define syntax_error(msg) syntax_error(__LINE__, msg)
- # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
- # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
- # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
- # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
- #endif
- static char *unbackslash(char *src)
- {
- char *dst = src = strchrnul(src, '\\');
- while (1) {
- if (*src == '\\') {
- src++;
- if (*src != '\0') {
-
- *dst++ = *src++;
- continue;
- }
-
- *dst++ = '\\';
-
- }
- if ((*dst++ = *src++) == '\0')
- break;
- }
- return dst;
- }
- static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
- {
- int i;
- unsigned count1;
- unsigned count2;
- char **v;
- v = strings;
- count1 = 0;
- if (v) {
- while (*v) {
- count1++;
- v++;
- }
- }
- count2 = 0;
- v = add;
- while (*v) {
- count2++;
- v++;
- }
- v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
- v[count1 + count2] = NULL;
- i = count2;
- while (--i >= 0)
- v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
- return v;
- }
- #if LEAK_HUNTING
- static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
- {
- char **ptr = add_strings_to_strings(strings, add, need_to_dup);
- fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
- return ptr;
- }
- #define add_strings_to_strings(strings, add, need_to_dup) \
- xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
- #endif
- static char **add_string_to_strings(char **strings, char *add)
- {
- char *v[2];
- v[0] = add;
- v[1] = NULL;
- return add_strings_to_strings(strings, v, 0);
- }
- #if LEAK_HUNTING
- static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
- {
- char **ptr = add_string_to_strings(strings, add);
- fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
- return ptr;
- }
- #define add_string_to_strings(strings, add) \
- xx_add_string_to_strings(__LINE__, strings, add)
- #endif
- static void free_strings(char **strings)
- {
- char **v;
- if (!strings)
- return;
- v = strings;
- while (*v) {
- free(*v);
- v++;
- }
- free(strings);
- }
- static int dup_CLOEXEC(int fd, int avoid_fd)
- {
- int newfd;
- repeat:
- newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
- if (newfd >= 0) {
- if (F_DUPFD_CLOEXEC == F_DUPFD)
- close_on_exec_on(newfd);
- } else {
- if (errno == EBUSY)
- goto repeat;
- if (errno == EINTR)
- goto repeat;
- if (errno != EBADF) {
-
- bb_perror_msg("fcntl(%d,F_DUPFD,%d)", fd, avoid_fd + 1);
- }
- }
- return newfd;
- }
- static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
- {
- int newfd;
- repeat:
- newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
- if (newfd < 0) {
- if (errno == EBUSY)
- goto repeat;
- if (errno == EINTR)
- goto repeat;
-
- if (errno == EBADF)
- return fd;
- xfunc_die();
- }
- if (F_DUPFD_CLOEXEC == F_DUPFD)
- close_on_exec_on(newfd);
- close(fd);
- return newfd;
- }
- static HFILE *hfopen(const char *name)
- {
- HFILE *fp;
- int fd;
- fd = STDIN_FILENO;
- if (name) {
- fd = open(name, O_RDONLY | O_CLOEXEC);
- if (fd < 0)
- return NULL;
- if (O_CLOEXEC == 0)
- close_on_exec_on(fd);
- }
- fp = xmalloc(sizeof(*fp));
- if (name == NULL)
- G.HFILE_stdin = fp;
- fp->fd = fd;
- fp->cur = fp->end = fp->buf;
- fp->next_hfile = G.HFILE_list;
- G.HFILE_list = fp;
- return fp;
- }
- static void hfclose(HFILE *fp)
- {
- HFILE **pp = &G.HFILE_list;
- while (*pp) {
- HFILE *cur = *pp;
- if (cur == fp) {
- *pp = cur->next_hfile;
- break;
- }
- pp = &cur->next_hfile;
- }
- if (fp->fd >= 0)
- close(fp->fd);
- free(fp);
- }
- static int refill_HFILE_and_getc(HFILE *fp)
- {
- int n;
- if (fp->fd < 0) {
-
- return EOF;
- }
- #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
-
- if (fp == G.HFILE_stdin) {
- struct pollfd pfd[1];
- pfd[0].fd = fp->fd;
- pfd[0].events = POLLIN;
- n = poll(pfd, 1, -1);
- if (n < 0
-
- && sigismember(&G.pending_set, SIGINT)
- ) {
- return '\0';
- }
- }
- #else
- #endif
-
- n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
- if (n < 0) {
- bb_simple_perror_msg("read error");
- n = 0;
- }
- fp->cur = fp->buf;
- fp->end = fp->buf + n;
- if (n == 0) {
-
- close(fp->fd);
- fp->fd = -1;
- return EOF;
- }
- return (unsigned char)(*fp->cur++);
- }
- static ALWAYS_INLINE int hfgetc(HFILE *fp)
- {
- if (fp->cur < fp->end)
- return (unsigned char)(*fp->cur++);
-
- return refill_HFILE_and_getc(fp);
- }
- static int move_HFILEs_on_redirect(int fd, int avoid_fd)
- {
- HFILE *fl = G.HFILE_list;
- while (fl) {
- if (fd == fl->fd) {
-
- fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
- debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
- return 1;
- }
- fl = fl->next_hfile;
- }
- #if ENABLE_HUSH_MODE_X
- if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
- G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
- return 1;
- }
- #endif
- return 0;
- }
- #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
- static void close_all_HFILE_list(void)
- {
- HFILE *fl = G.HFILE_list;
- while (fl) {
-
- if (fl->fd > 0)
-
- close(fl->fd);
- fl = fl->next_hfile;
- }
- }
- #endif
- static int fd_in_HFILEs(int fd)
- {
- HFILE *fl = G.HFILE_list;
- while (fl) {
- if (fl->fd == fd)
- return 1;
- fl = fl->next_hfile;
- }
- return 0;
- }
- typedef struct save_arg_t {
- char *sv_argv0;
- char **sv_g_argv;
- int sv_g_argc;
- IF_HUSH_SET(smallint sv_g_malloced;)
- } save_arg_t;
- static void save_and_replace_G_args(save_arg_t *sv, char **argv)
- {
- sv->sv_argv0 = argv[0];
- sv->sv_g_argv = G.global_argv;
- sv->sv_g_argc = G.global_argc;
- IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
- argv[0] = G.global_argv[0];
- G.global_argv = argv;
- IF_HUSH_SET(G.global_args_malloced = 0;)
- G.global_argc = 1 + string_array_len(argv + 1);
- }
- static void restore_G_args(save_arg_t *sv, char **argv)
- {
- #if ENABLE_HUSH_SET
- if (G.global_args_malloced) {
-
- char **pp = G.global_argv;
- while (*++pp)
- free(*pp);
- free(G.global_argv);
- }
- #endif
- argv[0] = sv->sv_argv0;
- G.global_argv = sv->sv_g_argv;
- G.global_argc = sv->sv_g_argc;
- IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
- }
- enum {
- SPECIAL_INTERACTIVE_SIGS = 0
- | (1 << SIGTERM)
- | (1 << SIGINT)
- | (1 << SIGHUP)
- ,
- SPECIAL_JOBSTOP_SIGS = 0
- #if ENABLE_HUSH_JOB
- | (1 << SIGTTIN)
- | (1 << SIGTTOU)
- | (1 << SIGTSTP)
- #endif
- ,
- };
- static void record_pending_signo(int sig)
- {
- sigaddset(&G.pending_set, sig);
- #if ENABLE_FEATURE_EDITING
- if (sig != SIGCHLD
- || (G_traps && G_traps[SIGCHLD] && G_traps[SIGCHLD][0])
-
- ) {
- bb_got_signal = sig;
- }
- #endif
- #if ENABLE_HUSH_FAST
- if (sig == SIGCHLD) {
- G.count_SIGCHLD++;
- }
- #endif
- }
- static sighandler_t install_sighandler(int sig, sighandler_t handler)
- {
- struct sigaction old_sa;
-
-
-
-
- G.sa.sa_handler = handler;
- sigaction(sig, &G.sa, &old_sa);
- return old_sa.sa_handler;
- }
- static void hush_exit(int exitcode) NORETURN;
- static void restore_ttypgrp_and__exit(void) NORETURN;
- static void restore_ttypgrp_and__exit(void)
- {
-
-
- G.exiting = 1;
- hush_exit(xfunc_error_retval);
- }
- #if ENABLE_HUSH_JOB
- static void fflush_and__exit(void) NORETURN;
- static void fflush_and__exit(void)
- {
- fflush_all();
- _exit(xfunc_error_retval);
- }
- # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
- # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
- static void sigexit(int sig) NORETURN;
- static void sigexit(int sig)
- {
-
- if (G_saved_tty_pgrp && getpid() == G.root_pid) {
-
- sigprocmask_allsigs(SIG_BLOCK);
- tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
- }
-
- if (sig <= 0)
- _exit(- sig);
- kill_myself_with_sig(sig);
- }
- #else
- # define disable_restore_tty_pgrp_on_exit() ((void)0)
- # define enable_restore_tty_pgrp_on_exit() ((void)0)
- #endif
- static sighandler_t pick_sighandler(unsigned sig)
- {
- sighandler_t handler = SIG_DFL;
- if (sig < sizeof(unsigned)*8) {
- unsigned sigmask = (1 << sig);
- #if ENABLE_HUSH_JOB
-
- if (G_fatal_sig_mask & sigmask)
- handler = sigexit;
- else
- #endif
-
- if (G.special_sig_mask & sigmask) {
- handler = record_pending_signo;
-
- if (SPECIAL_JOBSTOP_SIGS & sigmask)
- handler = SIG_IGN;
- }
- }
- return handler;
- }
- static void hush_exit(int exitcode)
- {
- #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
- save_history(G.line_input_state);
- #endif
- fflush_all();
- if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
- char *argv[3];
-
- argv[1] = xstrdup(G_traps[0]);
- argv[2] = NULL;
- G.exiting = 1;
-
- builtin_eval(argv);
- }
- #if ENABLE_FEATURE_CLEAN_UP
- {
- struct variable *cur_var;
- if (G.cwd != bb_msg_unknown)
- free((char*)G.cwd);
- cur_var = G.top_var;
- while (cur_var) {
- struct variable *tmp = cur_var;
- if (!cur_var->max_len)
- free(cur_var->varstr);
- cur_var = cur_var->next;
- free(tmp);
- }
- }
- #endif
- fflush_all();
- #if ENABLE_HUSH_JOB
- sigexit(- (exitcode & 0xff));
- #else
- _exit(exitcode);
- #endif
- }
- static int check_and_run_traps(void)
- {
- int last_sig = 0;
- while (1) {
- int sig;
- if (sigisemptyset(&G.pending_set))
- break;
- sig = 0;
- do {
- sig++;
- if (sigismember(&G.pending_set, sig)) {
- sigdelset(&G.pending_set, sig);
- goto got_sig;
- }
- } while (sig < NSIG);
- break;
- got_sig:
- #if ENABLE_HUSH_TRAP
- if (G_traps && G_traps[sig]) {
- debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
- if (G_traps[sig][0]) {
-
- smalluint save_rcode;
- int save_pre;
- char *argv[3];
-
- argv[1] = xstrdup(G_traps[sig]);
-
- argv[2] = NULL;
- save_pre = G.pre_trap_exitcode;
- G.pre_trap_exitcode = save_rcode = G.last_exitcode;
- builtin_eval(argv);
- free(argv[1]);
- G.pre_trap_exitcode = save_pre;
- G.last_exitcode = save_rcode;
- # if ENABLE_HUSH_FUNCTIONS
- if (G.return_exitcode >= 0) {
- debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
- G.last_exitcode = G.return_exitcode;
- }
- # endif
- last_sig = sig;
- }
- continue;
- }
- #endif
-
- switch (sig) {
- case SIGINT:
- debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
- G.flag_SIGINT = 1;
- last_sig = sig;
- break;
- #if ENABLE_HUSH_JOB
- case SIGHUP: {
-
- {
-
- struct pipe *job;
- debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
-
- for (job = G.job_list; job; job = job->next) {
- if (job->pgrp <= 0)
- continue;
- debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
- if (kill(- job->pgrp, SIGHUP) == 0)
- kill(- job->pgrp, SIGCONT);
- }
- }
-
- sigexit(SIGHUP);
- }
- #endif
- #if ENABLE_HUSH_FAST
- case SIGCHLD:
- debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
- G.count_SIGCHLD++;
-
- break;
- #endif
- default:
- debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
-
-
- break;
- }
- }
- return last_sig;
- }
- static const char *get_cwd(int force)
- {
- if (force || G.cwd == NULL) {
-
- if (G.cwd == bb_msg_unknown)
- G.cwd = NULL;
- G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
- if (!G.cwd)
- G.cwd = bb_msg_unknown;
- }
- return G.cwd;
- }
- static struct variable **get_ptr_to_local_var(const char *name)
- {
- struct variable **pp;
- struct variable *cur;
- pp = &G.top_var;
- while ((cur = *pp) != NULL) {
- if (varcmp(cur->varstr, name) == 0)
- return pp;
- pp = &cur->next;
- }
- return NULL;
- }
- static const char* FAST_FUNC get_local_var_value(const char *name)
- {
- struct variable **vpp;
- if (G.expanded_assignments) {
- char **cpp = G.expanded_assignments;
- while (*cpp) {
- char *cp = *cpp;
- if (varcmp(cp, name) == 0)
- return strchr(cp, '=') + 1;
- cpp++;
- }
- }
- vpp = get_ptr_to_local_var(name);
- if (vpp)
- return strchr((*vpp)->varstr, '=') + 1;
- if (strcmp(name, "PPID") == 0)
- return utoa(G.root_ppid);
-
- #if ENABLE_HUSH_RANDOM_SUPPORT
- if (strcmp(name, "RANDOM") == 0)
- return utoa(next_random(&G.random_gen));
- #endif
- #if ENABLE_HUSH_LINENO_VAR
- if (strcmp(name, "LINENO") == 0)
- return utoa(G.execute_lineno);
- #endif
- #if BASH_EPOCH_VARS
- {
- const char *fmt = NULL;
- if (strcmp(name, "EPOCHSECONDS") == 0)
- fmt = "%llu";
- else if (strcmp(name, "EPOCHREALTIME") == 0)
- fmt = "%llu.%06u";
- if (fmt) {
- struct timeval tv;
- xgettimeofday(&tv);
- sprintf(G.epoch_buf, fmt, (unsigned long long)tv.tv_sec,
- (unsigned)tv.tv_usec);
- return G.epoch_buf;
- }
- }
- #endif
- return NULL;
- }
- #if ENABLE_HUSH_GETOPTS
- static void handle_changed_special_names(const char *name)
- {
- if (varcmp(name, "OPTIND") == 0) {
- G.getopt_count = 0;
- return;
- }
- }
- #else
- # define handle_changed_special_names(...) ((void)0)
- #endif
- #define SETFLAG_EXPORT (1 << 0)
- #define SETFLAG_UNEXPORT (1 << 1)
- #define SETFLAG_MAKE_RO (1 << 2)
- #define SETFLAG_VARLVL_SHIFT 3
- static int set_local_var(char *str, unsigned flags)
- {
- struct variable **cur_pp;
- struct variable *cur;
- char *free_me = NULL;
- char *eq_sign;
- int name_len;
- int retval;
- unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
- eq_sign = strchr(str, '=');
- if (HUSH_DEBUG && !eq_sign)
- bb_simple_error_msg_and_die("BUG in setvar");
- name_len = eq_sign - str + 1;
- cur_pp = &G.top_var;
- while ((cur = *cur_pp) != NULL) {
- if (strncmp(cur->varstr, str, name_len) != 0) {
- cur_pp = &cur->next;
- continue;
- }
-
- if (cur->flg_read_only) {
- bb_error_msg("%s: readonly variable", str);
- free(str);
- return -1;
- }
- if (flags & SETFLAG_UNEXPORT) {
- debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
- *eq_sign = '\0';
- unsetenv(str);
- *eq_sign = '=';
- }
- if (cur->var_nest_level < local_lvl) {
-
- if (cur->flg_export)
- flags |= SETFLAG_EXPORT;
-
- *cur_pp = cur->next;
- if (G.shadowed_vars_pp) {
-
- debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
- cur->flg_export ? "exported " : "",
- cur->varstr, cur->var_nest_level, str, local_lvl
- );
- cur->next = *G.shadowed_vars_pp;
- *G.shadowed_vars_pp = cur;
- } else {
-
- debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
- cur->flg_export ? "exported " : "",
- cur->varstr, cur->var_nest_level, str, local_lvl
- );
- if (cur->max_len == 0)
- free_me = cur->varstr;
- free(cur);
- }
- break;
- }
- if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
- debug_printf_env("assignement '%s' does not change anything\n", str);
- free_and_exp:
- free(str);
- goto exp;
- }
-
- if (cur->max_len != 0) {
- if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
-
- debug_printf_env("reusing startup env for '%s'\n", str);
- strcpy(cur->varstr, str);
- goto free_and_exp;
- }
-
- cur->max_len = 0;
- goto set_str_and_exp;
- }
-
- free_me = cur->varstr;
- goto set_str_and_exp;
- }
-
- debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
- cur = xzalloc(sizeof(*cur));
- cur->var_nest_level = local_lvl;
- cur->next = *cur_pp;
- *cur_pp = cur;
- set_str_and_exp:
- cur->varstr = str;
- exp:
- #if !BB_MMU || ENABLE_HUSH_READONLY
- if (flags & SETFLAG_MAKE_RO) {
- cur->flg_read_only = 1;
- }
- #endif
- if (flags & SETFLAG_EXPORT)
- cur->flg_export = 1;
- retval = 0;
- if (cur->flg_export) {
- if (flags & SETFLAG_UNEXPORT) {
- cur->flg_export = 0;
-
- } else {
- debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
- retval = putenv(cur->varstr);
-
- }
- }
- free(free_me);
- handle_changed_special_names(cur->varstr);
- return retval;
- }
- static int set_local_var0(char *str)
- {
- return set_local_var(str, 0);
- }
- static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
- {
- char *var = xasprintf("%s=%s", name, val);
- set_local_var0(var);
- }
- static void set_pwd_var(unsigned flag)
- {
- set_local_var(xasprintf("PWD=%s", get_cwd( 1)), flag);
- }
- #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
- static int unset_local_var(const char *name)
- {
- struct variable *cur;
- struct variable **cur_pp;
- cur_pp = &G.top_var;
- while ((cur = *cur_pp) != NULL) {
- if (varcmp(cur->varstr, name) == 0) {
- if (cur->flg_read_only) {
- bb_error_msg("%s: readonly variable", name);
- return EXIT_FAILURE;
- }
- *cur_pp = cur->next;
- debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
- bb_unsetenv(cur->varstr);
- if (!cur->max_len)
- free(cur->varstr);
- free(cur);
- break;
- }
- cur_pp = &cur->next;
- }
-
- handle_changed_special_names(name);
- return EXIT_SUCCESS;
- }
- #endif
- static void add_vars(struct variable *var)
- {
- struct variable *next;
- while (var) {
- next = var->next;
- var->next = G.top_var;
- G.top_var = var;
- if (var->flg_export) {
- debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
- putenv(var->varstr);
- } else {
- debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
- }
- var = next;
- }
- }
- static void set_vars_and_save_old(char **strings)
- {
- char **s;
- if (!strings)
- return;
- s = strings;
- while (*s) {
- struct variable *var_p;
- struct variable **var_pp;
- char *eq;
- eq = strchr(*s, '=');
- if (HUSH_DEBUG && !eq)
- bb_simple_error_msg_and_die("BUG in varexp4");
- var_pp = get_ptr_to_local_var(*s);
- if (var_pp) {
- var_p = *var_pp;
- if (var_p->flg_read_only) {
- char **p;
- bb_error_msg("%s: readonly variable", *s);
-
- debug_printf_env("removing/freeing '%s' element\n", *s);
- free(*s);
- p = s;
- do { *p = p[1]; p++; } while (*p);
- goto next;
- }
-
- }
- debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
- set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
- s++;
- next: ;
- }
- free(strings);
- }
- static void reinit_unicode_for_hush(void)
- {
-
- if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
- || ENABLE_UNICODE_USING_LOCALE
- ) {
- const char *s = get_local_var_value("LC_ALL");
- if (!s) s = get_local_var_value("LC_CTYPE");
- if (!s) s = get_local_var_value("LANG");
- reinit_unicode(s);
- }
- }
- #if ENABLE_HUSH_INTERACTIVE
- static const char *setup_prompt_string(void)
- {
- const char *prompt_str;
- debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
- # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
- prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
- if (!prompt_str)
- prompt_str = "";
- # else
- prompt_str = "> ";
- if (G.promptmode == 0) {
-
- free(G.PS1);
-
- prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
- }
- # endif
- debug_printf("prompt_str '%s'\n", prompt_str);
- return prompt_str;
- }
- static int get_user_input(struct in_str *i)
- {
- # if ENABLE_FEATURE_EDITING
-
- int r;
- const char *prompt_str;
- prompt_str = setup_prompt_string();
- for (;;) {
- reinit_unicode_for_hush();
- G.flag_SIGINT = 0;
- bb_got_signal = 0;
- if (!sigisemptyset(&G.pending_set)) {
-
- bb_got_signal = r = -1;
- } else {
-
- r = read_line_input(G.line_input_state, prompt_str,
- G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
- );
-
- if (r == 0)
- raise(SIGINT);
- }
-
- if (sigismember(&G.pending_set, SIGINT)) {
- write(STDOUT_FILENO, "^C\n", 3);
- G.last_exitcode = 128 | SIGINT;
- }
- check_and_run_traps();
- if (r == 0)
- continue;
- if (r > 0)
- break;
- if (!bb_got_signal) {
-
-
- write(STDOUT_FILENO, "\n", 1);
- i->p = NULL;
- i->peek_buf[0] = r = EOF;
- return r;
- }
-
- }
- i->p = G.user_input_buf;
- return (unsigned char)*i->p++;
- # else
-
- int r;
- for (;;) {
- G.flag_SIGINT = 0;
- if (i->last_char == '\0' || i->last_char == '\n') {
- const char *prompt_str = setup_prompt_string();
-
- check_and_run_traps();
- fputs_stdout(prompt_str);
- fflush_all();
- }
- r = hfgetc(i->file);
-
- check_and_run_traps();
- if (r != '\0' && !G.flag_SIGINT)
- break;
- if (G.flag_SIGINT) {
-
-
-
- write(STDOUT_FILENO, "\n", 1);
- G.last_exitcode = 128 | SIGINT;
- }
- }
- return r;
- # endif
- }
- static int fgetc_interactive(struct in_str *i)
- {
- int ch;
-
- if (G_interactive_fd && i->file == G.HFILE_stdin) {
-
- ch = get_user_input(i);
- G.promptmode = 1;
- debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
- } else {
-
- do ch = hfgetc(i->file); while (ch == '\0');
- }
- return ch;
- }
- #else
- static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
- {
- int ch;
- do ch = hfgetc(i->file); while (ch == '\0');
- return ch;
- }
- #endif
- static int i_getch(struct in_str *i)
- {
- int ch;
- if (!i->file) {
-
- ch = (unsigned char)*i->p;
- if (ch != '\0') {
- i->p++;
- i->last_char = ch;
- #if ENABLE_HUSH_LINENO_VAR
- if (ch == '\n') {
- G.parse_lineno++;
- debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
- }
- #endif
- return ch;
- }
- return EOF;
- }
-
- #if ENABLE_FEATURE_EDITING
-
- if (i->p && *i->p != '\0') {
- ch = (unsigned char)*i->p++;
- goto out;
- }
- #endif
-
- ch = i->peek_buf[0];
- if (ch != 0) {
- int ch2 = i->peek_buf[1];
- i->peek_buf[0] = ch2;
- if (ch2 == 0)
- goto out;
- i->peek_buf[1] = 0;
- goto out;
- }
- ch = fgetc_interactive(i);
- out:
- debug_printf("file_get: got '%c' %d\n", ch, ch);
- i->last_char = ch;
- #if ENABLE_HUSH_LINENO_VAR
- if (ch == '\n') {
- G.parse_lineno++;
- debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
- }
- #endif
- return ch;
- }
- static int i_peek(struct in_str *i)
- {
- int ch;
- if (!i->file) {
-
-
- return (unsigned char)*i->p;
- }
-
- #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
-
- if (i->p && *i->p != '\0')
- return (unsigned char)*i->p;
- #endif
-
- ch = i->peek_buf[0];
- if (ch != 0)
- return ch;
-
- ch = fgetc_interactive(i);
- debug_printf("file_peek: got '%c' %d\n", ch, ch);
-
- #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
- if (i->p) {
- i->p -= 1;
- return ch;
- }
- #endif
- i->peek_buf[0] = ch;
-
- return ch;
- }
- static int i_peek2(struct in_str *i)
- {
- int ch;
-
- if (i->p)
- return (unsigned char)i->p[1];
-
-
-
- ch = i->peek_buf[1];
- if (ch == 0) {
-
- do ch = hfgetc(i->file); while (ch == '\0');
- i->peek_buf[1] = ch;
- }
- debug_printf("file_peek2: got '%c' %d\n", ch, ch);
- return ch;
- }
- static int i_getch_and_eat_bkslash_nl(struct in_str *input)
- {
- for (;;) {
- int ch, ch2;
- ch = i_getch(input);
- if (ch != '\\')
- return ch;
- ch2 = i_peek(input);
- if (ch2 != '\n')
- return ch;
-
- i_getch(input);
- }
- }
- static int i_peek_and_eat_bkslash_nl(struct in_str *input)
- {
- for (;;) {
- int ch, ch2;
- ch = i_peek(input);
- if (ch != '\\')
- return ch;
- ch2 = i_peek2(input);
- if (ch2 != '\n')
- return ch;
-
- i_getch(input);
- i_getch(input);
- }
- }
- static void setup_file_in_str(struct in_str *i, HFILE *fp)
- {
- memset(i, 0, sizeof(*i));
- i->file = fp;
-
- }
- static void setup_string_in_str(struct in_str *i, const char *s)
- {
- memset(i, 0, sizeof(*i));
- ;
- i->p = s;
- }
- #define B_CHUNK (32 * sizeof(char*))
- static void o_reset_to_empty_unquoted(o_string *o)
- {
- o->length = 0;
- o->has_quoted_part = 0;
- if (o->data)
- o->data[0] = '\0';
- }
- static void o_free_and_set_NULL(o_string *o)
- {
- free(o->data);
- memset(o, 0, sizeof(*o));
- }
- static ALWAYS_INLINE void o_free(o_string *o)
- {
- free(o->data);
- }
- static void o_grow_by(o_string *o, int len)
- {
- if (o->length + len > o->maxlen) {
- o->maxlen += (2 * len) | (B_CHUNK-1);
- o->data = xrealloc(o->data, 1 + o->maxlen);
- }
- }
- static void o_addchr(o_string *o, int ch)
- {
- debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
- if (o->length < o->maxlen) {
-
- add:
- o->data[o->length] = ch;
- o->length++;
- o->data[o->length] = '\0';
- return;
- }
- o_grow_by(o, 1);
- goto add;
- }
- #if 0
- static void o_delchr(o_string *o)
- {
- o->length--;
- o->data[o->length] = '\0';
- }
- #endif
- static void o_addblock(o_string *o, const char *str, int len)
- {
- o_grow_by(o, len);
- ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
- o->length += len;
- }
- static void o_addstr(o_string *o, const char *str)
- {
- o_addblock(o, str, strlen(str));
- }
- static void o_addstr_with_NUL(o_string *o, const char *str)
- {
- o_addblock(o, str, strlen(str) + 1);
- }
- #if !BB_MMU
- static void nommu_addchr(o_string *o, int ch)
- {
- if (o)
- o_addchr(o, ch);
- }
- #else
- # define nommu_addchr(o, str) ((void)0)
- #endif
- #if ENABLE_HUSH_MODE_X
- static void x_mode_addchr(int ch)
- {
- o_addchr(&G.x_mode_buf, ch);
- }
- static void x_mode_addstr(const char *str)
- {
- o_addstr(&G.x_mode_buf, str);
- }
- static void x_mode_addblock(const char *str, int len)
- {
- o_addblock(&G.x_mode_buf, str, len);
- }
- static void x_mode_prefix(void)
- {
- int n = G.x_mode_depth;
- do x_mode_addchr('+'); while (--n >= 0);
- }
- static void x_mode_flush(void)
- {
- int len = G.x_mode_buf.length;
- if (len <= 0)
- return;
- if (G.x_mode_fd > 0) {
- G.x_mode_buf.data[len] = '\n';
- full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
- }
- G.x_mode_buf.length = 0;
- }
- #endif
- #if ENABLE_HUSH_BRACE_EXPANSION
- # define MAYBE_BRACES "{}"
- #else
- # define MAYBE_BRACES ""
- #endif
- static void o_addqchr(o_string *o, int ch)
- {
- int sz = 1;
-
- char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
- if (found)
- sz++;
- o_grow_by(o, sz);
- if (found) {
- o->data[o->length] = '\\';
- o->length++;
- }
- o->data[o->length] = ch;
- o->length++;
- o->data[o->length] = '\0';
- }
- static void o_addQchr(o_string *o, int ch)
- {
- int sz = 1;
- if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
- && strchr("*?[-\\" MAYBE_BRACES, ch)
- ) {
- sz++;
- o->data[o->length] = '\\';
- o->length++;
- }
- o_grow_by(o, sz);
- o->data[o->length] = ch;
- o->length++;
- o->data[o->length] = '\0';
- }
- static void o_addqblock(o_string *o, const char *str, int len)
- {
- while (len) {
- char ch;
- int sz;
- int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
- if (ordinary_cnt > len)
- ordinary_cnt = len;
- o_addblock(o, str, ordinary_cnt);
- if (ordinary_cnt == len)
- return;
- str += ordinary_cnt;
- len -= ordinary_cnt + 1;
- ch = *str++;
- sz = 1;
- if (ch) {
- sz++;
- o->data[o->length] = '\\';
- o->length++;
- }
- o_grow_by(o, sz);
- o->data[o->length] = ch;
- o->length++;
- }
- o->data[o->length] = '\0';
- }
- static void o_addQblock(o_string *o, const char *str, int len)
- {
- if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
- o_addblock(o, str, len);
- return;
- }
- o_addqblock(o, str, len);
- }
- static void o_addQstr(o_string *o, const char *str)
- {
- o_addQblock(o, str, strlen(str));
- }
- #if DEBUG_EXPAND || DEBUG_GLOB
- static void debug_print_list(const char *prefix, o_string *o, int n)
- {
- char **list = (char**)o->data;
- int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
- int i = 0;
- indent();
- fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
- prefix, list, n, string_start, o->length, o->maxlen,
- !!(o->o_expflags & EXP_FLAG_GLOB),
- o->has_quoted_part,
- !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
- while (i < n) {
- indent();
- fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
- o->data + (int)(uintptr_t)list[i] + string_start,
- o->data + (int)(uintptr_t)list[i] + string_start);
- i++;
- }
- if (n) {
- const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
- indent();
- fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
- }
- }
- #else
- # define debug_print_list(prefix, o, n) ((void)0)
- #endif
- static int o_save_ptr_helper(o_string *o, int n)
- {
- char **list = (char**)o->data;
- int string_start;
- int string_len;
- if (!o->has_empty_slot) {
- string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
- string_len = o->length - string_start;
- if (!(n & 0xf)) {
- debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
-
- o->maxlen += 0x10 * sizeof(list[0]);
- o->data = xrealloc(o->data, o->maxlen + 1);
- list = (char**)o->data;
- memmove(list + n + 0x10, list + n, string_len);
-
- list[n + 0x10 - 1] = 0;
- o->length += 0x10 * sizeof(list[0]);
- } else {
- debug_printf_list("list[%d]=%d string_start=%d\n",
- n, string_len, string_start);
- }
- } else {
-
- string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]);
- string_len = o->length - string_start;
- debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
- n, string_len, string_start);
- o->has_empty_slot = 0;
- }
- o->has_quoted_part = 0;
- list[n] = (char*)(uintptr_t)string_len;
- return n + 1;
- }
- static int o_get_last_ptr(o_string *o, int n)
- {
- char **list = (char**)o->data;
- int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
- return ((int)(uintptr_t)list[n-1]) + string_start;
- }
- #if ENABLE_HUSH_BRACE_EXPANSION
- static int glob_needed(const char *s)
- {
- while (*s) {
- if (*s == '\\') {
- if (!s[1])
- return 0;
- s += 2;
- continue;
- }
- if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
- return 1;
- s++;
- }
- return 0;
- }
- static const char *next_brace_sub(const char *cp)
- {
- unsigned depth = 0;
- cp++;
- while (*cp != '\0') {
- if (*cp == '\\') {
- if (*++cp == '\0')
- break;
- cp++;
- continue;
- }
- if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
- break;
- if (*cp++ == '{')
- depth++;
- }
- return *cp != '\0' ? cp : NULL;
- }
- static int glob_brace(char *pattern, o_string *o, int n)
- {
- char *new_pattern_buf;
- const char *begin;
- const char *next;
- const char *rest;
- const char *p;
- size_t rest_len;
- debug_printf_glob("glob_brace('%s')\n", pattern);
- begin = pattern;
- while (1) {
- if (*begin == '\0')
- goto simple_glob;
- if (*begin == '{') {
-
- next = next_brace_sub(begin);
- if (next == NULL) {
-
- goto simple_glob;
- }
- if (*next == '}') {
-
- begin = next + 1;
- continue;
- }
- break;
- }
- if (*begin == '\\' && begin[1] != '\0')
- begin++;
- begin++;
- }
- debug_printf_glob("begin:%s\n", begin);
- debug_printf_glob("next:%s\n", next);
-
- rest = next;
- while (*rest != '}') {
- rest = next_brace_sub(rest);
- if (rest == NULL) {
-
- goto simple_glob;
- }
- debug_printf_glob("rest:%s\n", rest);
- }
- rest_len = strlen(++rest) + 1;
-
-
- new_pattern_buf = xmalloc(strlen(pattern));
-
- p = begin + 1;
- while (1) {
-
- memcpy(
- mempcpy(
- mempcpy(new_pattern_buf,
-
- pattern, begin - pattern),
- p, next - p),
- rest, rest_len);
-
- n = glob_brace(new_pattern_buf, o, n);
- if (*next == '}') {
-
- break;
- }
- p = next + 1;
- next = next_brace_sub(next);
- }
- free(new_pattern_buf);
- return n;
- simple_glob:
- {
- int gr;
- glob_t globdata;
- memset(&globdata, 0, sizeof(globdata));
- gr = glob(pattern, 0, NULL, &globdata);
- debug_printf_glob("glob('%s'):%d\n", pattern, gr);
- if (gr != 0) {
- if (gr == GLOB_NOMATCH) {
- globfree(&globdata);
-
- unbackslash(pattern);
- o_addstr_with_NUL(o, pattern);
- debug_printf_glob("glob pattern '%s' is literal\n", pattern);
- return o_save_ptr_helper(o, n);
- }
- if (gr == GLOB_NOSPACE)
- bb_die_memory_exhausted();
-
- bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
- }
- if (globdata.gl_pathv && globdata.gl_pathv[0]) {
- char **argv = globdata.gl_pathv;
- while (1) {
- o_addstr_with_NUL(o, *argv);
- n = o_save_ptr_helper(o, n);
- argv++;
- if (!*argv)
- break;
- }
- }
- globfree(&globdata);
- }
- return n;
- }
- static int perform_glob(o_string *o, int n)
- {
- char *pattern, *copy;
- debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
- if (!o->data)
- return o_save_ptr_helper(o, n);
- pattern = o->data + o_get_last_ptr(o, n);
- debug_printf_glob("glob pattern '%s'\n", pattern);
- if (!glob_needed(pattern)) {
-
- o->length = unbackslash(pattern) - o->data;
- debug_printf_glob("glob pattern '%s' is literal\n", pattern);
- return o_save_ptr_helper(o, n);
- }
- copy = xstrdup(pattern);
-
- o->length = pattern - o->data;
- n = glob_brace(copy, o, n);
- free(copy);
- if (DEBUG_GLOB)
- debug_print_list("perform_glob returning", o, n);
- return n;
- }
- #else
- static int glob_needed(const char *s)
- {
- while (*s) {
- if (*s == '\\') {
- if (!s[1])
- return 0;
- s += 2;
- continue;
- }
- if (*s == '*' || *s == '[' || *s == '?')
- return 1;
- s++;
- }
- return 0;
- }
- static int perform_glob(o_string *o, int n)
- {
- glob_t globdata;
- int gr;
- char *pattern;
- debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
- if (!o->data)
- return o_save_ptr_helper(o, n);
- pattern = o->data + o_get_last_ptr(o, n);
- debug_printf_glob("glob pattern '%s'\n", pattern);
- if (!glob_needed(pattern)) {
- literal:
-
- o->length = unbackslash(pattern) - o->data;
- debug_printf_glob("glob pattern '%s' is literal\n", pattern);
- return o_save_ptr_helper(o, n);
- }
- memset(&globdata, 0, sizeof(globdata));
-
- gr = glob(pattern, 0, NULL, &globdata);
- debug_printf_glob("glob('%s'):%d\n", pattern, gr);
- if (gr != 0) {
- if (gr == GLOB_NOMATCH) {
- globfree(&globdata);
- goto literal;
- }
- if (gr == GLOB_NOSPACE)
- bb_die_memory_exhausted();
-
- bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
- }
- if (globdata.gl_pathv && globdata.gl_pathv[0]) {
- char **argv = globdata.gl_pathv;
-
- o->length = pattern - o->data;
- while (1) {
- o_addstr_with_NUL(o, *argv);
- n = o_save_ptr_helper(o, n);
- argv++;
- if (!*argv)
- break;
- }
- }
- globfree(&globdata);
- if (DEBUG_GLOB)
- debug_print_list("perform_glob returning", o, n);
- return n;
- }
- #endif
- static int o_save_ptr(o_string *o, int n)
- {
- if (o->o_expflags & EXP_FLAG_GLOB) {
-
- if (!o->has_empty_slot)
- return perform_glob(o, n);
- }
- return o_save_ptr_helper(o, n);
- }
- static char **o_finalize_list(o_string *o, int n)
- {
- char **list;
- int string_start;
- if (DEBUG_EXPAND)
- debug_print_list("finalized", o, n);
- debug_printf_expand("finalized n:%d\n", n);
- list = (char**)o->data;
- string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
- list[--n] = NULL;
- while (n) {
- n--;
- list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
- }
- return list;
- }
- static void free_pipe_list(struct pipe *pi);
- static struct pipe *free_pipe(struct pipe *pi)
- {
- struct pipe *next;
- int i;
- debug_printf_clean("free_pipe (pid %d)\n", getpid());
- for (i = 0; i < pi->num_cmds; i++) {
- struct command *command;
- struct redir_struct *r, *rnext;
- command = &pi->cmds[i];
- debug_printf_clean(" command %d:\n", i);
- if (command->argv) {
- if (DEBUG_CLEAN) {
- int a;
- char **p;
- for (a = 0, p = command->argv; *p; a++, p++) {
- debug_printf_clean(" argv[%d] = %s\n", a, *p);
- }
- }
- free_strings(command->argv);
-
- }
-
- if (command->group) {
- debug_printf_clean(" begin group (cmd_type:%d)\n",
- command->cmd_type);
- free_pipe_list(command->group);
- debug_printf_clean(" end group\n");
-
- }
-
- #if ENABLE_HUSH_FUNCTIONS
- else if (command->child_func) {
- debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
- command->child_func->parent_cmd = NULL;
- }
- #endif
- #if !BB_MMU
- free(command->group_as_string);
-
- #endif
- for (r = command->redirects; r; r = rnext) {
- debug_printf_clean(" redirect %d%s",
- r->rd_fd, redir_table[r->rd_type].descrip);
-
- if (r->rd_filename) {
- debug_printf_clean(" fname:'%s'\n", r->rd_filename);
- free(r->rd_filename);
-
- }
- debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
- rnext = r->next;
- free(r);
- }
-
- }
- free(pi->cmds);
-
- #if ENABLE_HUSH_JOB
- free(pi->cmdtext);
-
- #endif
- next = pi->next;
- free(pi);
- return next;
- }
- static void free_pipe_list(struct pipe *pi)
- {
- while (pi) {
- #if HAS_KEYWORDS
- debug_printf_clean("pipe reserved word %d\n", pi->res_word);
- #endif
- debug_printf_clean("pipe followup code %d\n", pi->followup);
- pi = free_pipe(pi);
- }
- }
- #ifndef debug_print_tree
- static void debug_print_tree(struct pipe *pi, int lvl)
- {
- static const char *const PIPE[] ALIGN_PTR = {
- [PIPE_SEQ] = "SEQ",
- [PIPE_AND] = "AND",
- [PIPE_OR ] = "OR" ,
- [PIPE_BG ] = "BG" ,
- };
- static const char *RES[] = {
- [RES_NONE ] = "NONE" ,
- # if ENABLE_HUSH_IF
- [RES_IF ] = "IF" ,
- [RES_THEN ] = "THEN" ,
- [RES_ELIF ] = "ELIF" ,
- [RES_ELSE ] = "ELSE" ,
- [RES_FI ] = "FI" ,
- # endif
- # if ENABLE_HUSH_LOOPS
- [RES_FOR ] = "FOR" ,
- [RES_WHILE] = "WHILE",
- [RES_UNTIL] = "UNTIL",
- [RES_DO ] = "DO" ,
- [RES_DONE ] = "DONE" ,
- # endif
- # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
- [RES_IN ] = "IN" ,
- # endif
- # if ENABLE_HUSH_CASE
- [RES_CASE ] = "CASE" ,
- [RES_CASE_IN ] = "CASE_IN" ,
- [RES_MATCH] = "MATCH",
- [RES_CASE_BODY] = "CASE_BODY",
- [RES_ESAC ] = "ESAC" ,
- # endif
- [RES_XXXX ] = "XXXX" ,
- [RES_SNTX ] = "SNTX" ,
- };
- static const char *const CMDTYPE[] ALIGN_PTR = {
- "{}",
- "()",
- "[noglob]",
- # if ENABLE_HUSH_FUNCTIONS
- "func()",
- # endif
- };
- int pin, prn;
- pin = 0;
- while (pi) {
- fdprintf(2, "%*spipe %d #cmds:%d %sres_word=%s followup=%d %s\n",
- lvl*2, "",
- pin,
- pi->num_cmds,
- (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
- RES[pi->res_word],
- pi->followup, PIPE[pi->followup]
- );
- prn = 0;
- while (prn < pi->num_cmds) {
- struct command *command = &pi->cmds[prn];
- char **argv = command->argv;
- fdprintf(2, "%*s cmd %d assignment_cnt:%d",
- lvl*2, "", prn,
- command->assignment_cnt);
- # if ENABLE_HUSH_LINENO_VAR
- fdprintf(2, " LINENO:%u", command->lineno);
- # endif
- if (command->group) {
- fdprintf(2, " group %s: (argv=%p)%s%s\n",
- CMDTYPE[command->cmd_type],
- argv
- # if !BB_MMU
- , " group_as_string:", command->group_as_string
- # else
- , "", ""
- # endif
- );
- debug_print_tree(command->group, lvl+1);
- prn++;
- continue;
- }
- if (argv) while (*argv) {
- fdprintf(2, " '%s'", *argv);
- argv++;
- }
- if (command->redirects)
- fdprintf(2, " {redir}");
- fdprintf(2, "\n");
- prn++;
- }
- pi = pi->next;
- pin++;
- }
- }
- #endif
- static struct pipe *new_pipe(void)
- {
- struct pipe *pi;
- pi = xzalloc(sizeof(struct pipe));
-
- return pi;
- }
- static int done_command(struct parse_context *ctx)
- {
-
- struct pipe *pi = ctx->pipe;
- struct command *command = ctx->command;
- #if 0
- if (ctx->pending_redirect) {
-
- syntax_error("invalid redirect");
- ctx->pending_redirect = NULL;
- }
- #endif
- if (command) {
- if (IS_NULL_CMD(command)) {
- debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
- goto clear_and_ret;
- }
- pi->num_cmds++;
- debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
-
- } else {
- debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
- }
-
- pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
- ctx->command = command = &pi->cmds[pi->num_cmds];
- clear_and_ret:
- memset(command, 0, sizeof(*command));
- #if ENABLE_HUSH_LINENO_VAR
- command->lineno = G.parse_lineno;
- debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
- #endif
- return pi->num_cmds;
- }
- static void done_pipe(struct parse_context *ctx, pipe_style type)
- {
- int not_null;
- debug_printf_parse("done_pipe entered, followup %d\n", type);
-
- not_null = done_command(ctx);
- #if HAS_KEYWORDS
- ctx->pipe->pi_inverted = ctx->ctx_inverted;
- ctx->ctx_inverted = 0;
- ctx->pipe->res_word = ctx->ctx_res_w;
- #endif
- if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
-
- struct pipe *pi;
- struct command *command;
-
- pi = ctx->list_head;
- while (pi != ctx->pipe) {
- if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
- goto no_conv;
- pi = pi->next;
- }
- debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
- pi->followup = PIPE_SEQ;
- pi = xzalloc(sizeof(*pi));
- pi->followup = PIPE_BG;
- pi->num_cmds = 1;
- pi->cmds = xzalloc(sizeof(pi->cmds[0]));
- command = &pi->cmds[0];
- if (CMD_NORMAL != 0)
- command->cmd_type = CMD_NORMAL;
- command->group = ctx->list_head;
- #if !BB_MMU
- command->group_as_string = xstrndup(
- ctx->as_string.data,
- ctx->as_string.length - 1
- );
- #endif
-
- ctx->list_head = ctx->pipe = pi;
-
- not_null = 1;
- } else {
- no_conv:
- ctx->pipe->followup = type;
- }
-
- if (not_null
- #if ENABLE_HUSH_IF
- || ctx->ctx_res_w == RES_FI
- #endif
- #if ENABLE_HUSH_LOOPS
- || ctx->ctx_res_w == RES_DONE
- || ctx->ctx_res_w == RES_FOR
- || ctx->ctx_res_w == RES_IN
- #endif
- #if ENABLE_HUSH_CASE
- || ctx->ctx_res_w == RES_ESAC
- #endif
- ) {
- struct pipe *new_p;
- debug_printf_parse("done_pipe: adding new pipe: "
- "not_null:%d ctx->ctx_res_w:%d\n",
- not_null, ctx->ctx_res_w);
- new_p = new_pipe();
- ctx->pipe->next = new_p;
- ctx->pipe = new_p;
-
- #if ENABLE_HUSH_LOOPS
- if (ctx->ctx_res_w == RES_FOR
- || ctx->ctx_res_w == RES_IN)
- ctx->ctx_res_w = RES_NONE;
- #endif
- #if ENABLE_HUSH_CASE
- if (ctx->ctx_res_w == RES_MATCH)
- ctx->ctx_res_w = RES_CASE_BODY;
- if (ctx->ctx_res_w == RES_CASE)
- ctx->ctx_res_w = RES_CASE_IN;
- #endif
- ctx->command = NULL;
-
- done_command(ctx);
-
- }
- debug_printf_parse("done_pipe return\n");
- }
- static void initialize_context(struct parse_context *ctx)
- {
- memset(ctx, 0, sizeof(*ctx));
- if (MAYBE_ASSIGNMENT != 0)
- ctx->is_assignment = MAYBE_ASSIGNMENT;
- ctx->pipe = ctx->list_head = new_pipe();
-
- done_command(ctx);
- }
- #if HAS_KEYWORDS
- struct reserved_combo {
- char literal[6];
- unsigned char res;
- unsigned char assignment_flag;
- uint32_t flag;
- };
- enum {
- FLAG_END = (1 << RES_NONE ),
- # if ENABLE_HUSH_IF
- FLAG_IF = (1 << RES_IF ),
- FLAG_THEN = (1 << RES_THEN ),
- FLAG_ELIF = (1 << RES_ELIF ),
- FLAG_ELSE = (1 << RES_ELSE ),
- FLAG_FI = (1 << RES_FI ),
- # endif
- # if ENABLE_HUSH_LOOPS
- FLAG_FOR = (1 << RES_FOR ),
- FLAG_WHILE = (1 << RES_WHILE),
- FLAG_UNTIL = (1 << RES_UNTIL),
- FLAG_DO = (1 << RES_DO ),
- FLAG_DONE = (1 << RES_DONE ),
- FLAG_IN = (1 << RES_IN ),
- # endif
- # if ENABLE_HUSH_CASE
- FLAG_MATCH = (1 << RES_MATCH),
- FLAG_ESAC = (1 << RES_ESAC ),
- # endif
- FLAG_START = (1 << RES_XXXX ),
- };
- static const struct reserved_combo* match_reserved_word(o_string *word)
- {
-
- static const struct reserved_combo reserved_list[] ALIGN4 = {
- # if ENABLE_HUSH_IF
- { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
- { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
- { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
- { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
- { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
- { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
- # endif
- # if ENABLE_HUSH_LOOPS
- { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
- { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
- { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
- { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
- { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
- { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
- # endif
- # if ENABLE_HUSH_CASE
- { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
- { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
- # endif
- };
- const struct reserved_combo *r;
- for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
- if (strcmp(word->data, r->literal) == 0)
- return r;
- }
- return NULL;
- }
- static const struct reserved_combo* reserved_word(struct parse_context *ctx)
- {
- # if ENABLE_HUSH_CASE
- static const struct reserved_combo reserved_match = {
- "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
- };
- # endif
- const struct reserved_combo *r;
- if (ctx->word.has_quoted_part)
- return 0;
- r = match_reserved_word(&ctx->word);
- if (!r)
- return r;
- debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
- # if ENABLE_HUSH_CASE
- if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
-
- r = &reserved_match;
- } else
- # endif
- if (r->flag == 0) {
- if (ctx->ctx_inverted) {
- syntax_error("! ! command");
- ctx->ctx_res_w = RES_SNTX;
- }
- ctx->ctx_inverted = 1;
- return r;
- }
- if (r->flag & FLAG_START) {
- struct parse_context *old;
- old = xmemdup(ctx, sizeof(*ctx));
- debug_printf_parse("push stack %p\n", old);
- initialize_context(ctx);
- ctx->stack = old;
- } else if ( !(ctx->old_flag & (1 << r->res))) {
- syntax_error_at(ctx->word.data);
- ctx->ctx_res_w = RES_SNTX;
- return r;
- } else {
-
- if (ctx->command->group)
- done_pipe(ctx, PIPE_SEQ);
- }
- ctx->ctx_res_w = r->res;
- ctx->old_flag = r->flag;
- ctx->is_assignment = r->assignment_flag;
- debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
- if (ctx->old_flag & FLAG_END) {
- struct parse_context *old;
- done_pipe(ctx, PIPE_SEQ);
- debug_printf_parse("pop stack %p\n", ctx->stack);
- old = ctx->stack;
- old->command->group = ctx->list_head;
- old->command->cmd_type = CMD_NORMAL;
- # if !BB_MMU
-
- {
- char *str;
- int len = old->as_string.length;
-
- o_addstr(&old->as_string, ctx->as_string.data);
- o_free(&ctx->as_string);
-
- str = old->as_string.data + len;
- if (str > old->as_string.data)
- str--;
- while (str > old->as_string.data && isalpha(str[-1]))
- str--;
-
- old->command->group_as_string = xstrdup(str);
- debug_printf_parse("pop, remembering as:'%s'\n",
- old->command->group_as_string);
- }
- # endif
- *ctx = *old;
- free(old);
- }
- return r;
- }
- #endif
- static int done_word(struct parse_context *ctx)
- {
- struct command *command = ctx->command;
- debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
- if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
- debug_printf_parse("done_word return 0: true null, ignored\n");
- return 0;
- }
- if (ctx->pending_redirect) {
-
-
- ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
-
- if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
- unbackslash(ctx->pending_redirect->rd_filename);
-
- if (ctx->word.has_quoted_part) {
- ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
- }
- }
- debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
- ctx->pending_redirect = NULL;
- } else {
- #if HAS_KEYWORDS
- # if ENABLE_HUSH_CASE
- if (ctx->ctx_dsemicolon
- && strcmp(ctx->word.data, "esac") != 0
- ) {
-
-
- ctx->ctx_dsemicolon = 0;
- } else
- # endif
- # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
- if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
- && strcmp(ctx->word.data, "]]") == 0
- ) {
-
- command->cmd_type = CMD_SINGLEWORD_NOGLOB;
- } else
- # endif
- if (!command->argv
- # if ENABLE_HUSH_LOOPS
- && ctx->ctx_res_w != RES_FOR
- && ctx->ctx_res_w != RES_IN
- # endif
- # if ENABLE_HUSH_CASE
- && ctx->ctx_res_w != RES_CASE
- # endif
- ) {
- const struct reserved_combo *reserved;
- reserved = reserved_word(ctx);
- debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
- if (reserved) {
- # if ENABLE_HUSH_LINENO_VAR
- if (0
- IF_HUSH_IF(|| reserved->res == RES_THEN)
- IF_HUSH_IF(|| reserved->res == RES_ELIF)
- IF_HUSH_IF(|| reserved->res == RES_ELSE)
- IF_HUSH_LOOPS(|| reserved->res == RES_DO)
- ) {
- done_pipe(ctx, PIPE_SEQ);
- }
- # endif
- o_reset_to_empty_unquoted(&ctx->word);
- debug_printf_parse("done_word return %d\n",
- (ctx->ctx_res_w == RES_SNTX));
- return (ctx->ctx_res_w == RES_SNTX);
- }
- # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
- if (strcmp(ctx->word.data, "[[") == 0) {
- command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
- } else
- # endif
- # if defined(CMD_SINGLEWORD_NOGLOB)
- if (0
-
- IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
- IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
- IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
- ) {
- command->cmd_type = CMD_SINGLEWORD_NOGLOB;
- }
- # else
- { }
- # endif
- }
- #endif
- if (command->group) {
-
- syntax_error_at(ctx->word.data);
- debug_printf_parse("done_word return 1: syntax error, "
- "groups and arglists don't mix\n");
- return 1;
- }
-
- if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
- && ctx->is_assignment != WORD_IS_KEYWORD
- ) {
- ctx->is_assignment = NOT_ASSIGNMENT;
- } else {
- if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
- command->assignment_cnt++;
- debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
- }
- debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
- ctx->is_assignment = MAYBE_ASSIGNMENT;
- }
- debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
- command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
- debug_print_strings("word appended to argv", command->argv);
- }
- #if ENABLE_HUSH_LOOPS
- if (ctx->ctx_res_w == RES_FOR) {
- if (ctx->word.has_quoted_part
- || endofname(command->argv[0])[0] != '\0'
- ) {
-
- syntax_error("bad for loop variable");
- return 1;
- }
-
-
- done_pipe(ctx, PIPE_SEQ);
- }
- #endif
- #if ENABLE_HUSH_CASE
-
- if (ctx->ctx_res_w == RES_CASE) {
- done_pipe(ctx, PIPE_SEQ);
- }
- #endif
- o_reset_to_empty_unquoted(&ctx->word);
- debug_printf_parse("done_word return 0\n");
- return 0;
- }
- #if BB_MMU
- #define parse_redir_right_fd(as_string, input) \
- parse_redir_right_fd(input)
- #endif
- static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
- {
- int ch, d, ok;
- ch = i_peek(input);
- if (ch != '&')
- return REDIRFD_TO_FILE;
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- ch = i_peek(input);
- if (ch == '-') {
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- return REDIRFD_CLOSE;
- }
- d = 0;
- ok = 0;
- while (ch != EOF && isdigit(ch)) {
- d = d*10 + (ch-'0');
- ok = 1;
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- ch = i_peek(input);
- }
- if (ok) return d;
- bb_simple_error_msg("ambiguous redirect");
- return REDIRFD_SYNTAX_ERR;
- }
- static int parse_redirect(struct parse_context *ctx,
- int fd,
- redir_type style,
- struct in_str *input)
- {
- struct command *command = ctx->command;
- struct redir_struct *redir;
- struct redir_struct **redirp;
- int dup_num;
- dup_num = REDIRFD_TO_FILE;
- if (style != REDIRECT_HEREDOC) {
-
- dup_num = parse_redir_right_fd(&ctx->as_string, input);
- if (dup_num == REDIRFD_SYNTAX_ERR)
- return 1;
- } else {
- int ch = i_peek_and_eat_bkslash_nl(input);
- dup_num = (ch == '-');
- if (dup_num) {
- ch = i_getch(input);
- nommu_addchr(&ctx->as_string, ch);
- ch = i_peek(input);
- }
- }
- if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
- int ch = i_peek_and_eat_bkslash_nl(input);
- if (ch == '|') {
-
- ch = i_getch(input);
- nommu_addchr(&ctx->as_string, ch);
- }
- }
-
- redirp = &command->redirects;
- while ((redir = *redirp) != NULL) {
- redirp = &(redir->next);
- }
- *redirp = redir = xzalloc(sizeof(*redir));
-
-
- redir->rd_type = style;
- redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
- debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
- redir_table[style].descrip);
- redir->rd_dup = dup_num;
- if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
-
- debug_printf_parse("duplicating redirect '%d>&%d'\n",
- redir->rd_fd, redir->rd_dup);
- } else {
- #if 0
- if (ctx->pending_redirect) {
-
- syntax_error("invalid redirect");
- }
- #endif
-
- ctx->pending_redirect = redir;
- }
- return 0;
- }
- static int redirect_opt_num(o_string *o)
- {
- int num;
- if (o->data == NULL)
- return -1;
- num = bb_strtou(o->data, NULL, 10);
- if (errno || num < 0)
- return -1;
- o_reset_to_empty_unquoted(o);
- return num;
- }
- #if BB_MMU
- #define fetch_till_str(as_string, input, word, skip_tabs) \
- fetch_till_str(input, word, skip_tabs)
- #endif
- static char *fetch_till_str(o_string *as_string,
- struct in_str *input,
- const char *word,
- int heredoc_flags)
- {
- o_string heredoc = NULL_O_STRING;
- unsigned past_EOL;
- int prev = 0;
- int ch;
-
- heredoc.data = xzalloc(1);
- goto jump_in;
- while (1) {
- ch = i_getch(input);
- if (ch != EOF)
- nommu_addchr(as_string, ch);
- if (ch == '\n' || ch == EOF) {
- check_heredoc_end:
- if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
-
- if (strcmp(heredoc.data + past_EOL, word) == 0) {
- heredoc.data[past_EOL] = '\0';
- debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
- return heredoc.data;
- }
- if (ch == '\n') {
-
- o_addchr(&heredoc, ch);
- prev = ch;
- jump_in:
- past_EOL = heredoc.length;
-
- do {
- ch = i_getch(input);
- if (ch != EOF)
- nommu_addchr(as_string, ch);
- } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
-
- if (ch == '\n')
- goto check_heredoc_end;
- }
- } else {
-
- heredoc.data[--heredoc.length] = '\0';
- prev = 0;
- continue;
- }
- }
- if (ch == EOF) {
- o_free(&heredoc);
- return NULL;
- }
- o_addchr(&heredoc, ch);
- nommu_addchr(as_string, ch);
- if (prev == '\\' && ch == '\\')
-
- prev = 0;
- else
- prev = ch;
- }
- }
- #if BB_MMU
- #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
- fetch_heredocs(pi, heredoc_cnt, input)
- #endif
- static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
- {
- while (pi && heredoc_cnt) {
- int i;
- struct command *cmd = pi->cmds;
- debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
- pi->num_cmds,
- cmd->argv ? cmd->argv[0] : "NONE"
- );
- for (i = 0; i < pi->num_cmds; i++) {
- struct redir_struct *redir = cmd->redirects;
- debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
- i, cmd->argv ? cmd->argv[0] : "NONE");
- while (redir) {
- if (redir->rd_type == REDIRECT_HEREDOC) {
- char *p;
- redir->rd_type = REDIRECT_HEREDOC2;
-
- p = fetch_till_str(as_string, input,
- redir->rd_filename, redir->rd_dup);
- if (!p) {
- syntax_error("unexpected EOF in here document");
- return -1;
- }
- free(redir->rd_filename);
- redir->rd_filename = p;
- heredoc_cnt--;
- }
- redir = redir->next;
- }
- if (cmd->group) {
-
- heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
-
- if (heredoc_cnt < 0)
- return heredoc_cnt;
- }
- cmd++;
- }
- pi = pi->next;
- }
- return heredoc_cnt;
- }
- static int run_list(struct pipe *pi);
- #if BB_MMU
- #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
- parse_stream(heredoc_cnt_ptr, input, end_trigger)
- #endif
- static struct pipe *parse_stream(char **pstring,
- int *heredoc_cnt_ptr,
- struct in_str *input,
- int end_trigger);
- static int parse_group(struct parse_context *ctx,
- struct in_str *input, int ch)
- {
-
- #if BB_MMU
- # define as_string NULL
- #else
- char *as_string = NULL;
- #endif
- struct pipe *pipe_list;
- int heredoc_cnt = 0;
- int endch;
- struct command *command = ctx->command;
- debug_printf_parse("parse_group entered\n");
- #if ENABLE_HUSH_FUNCTIONS
- if (ch == '(' && !ctx->word.has_quoted_part) {
- if (ctx->word.length)
- if (done_word(ctx))
- return -1;
- if (!command->argv)
- goto skip;
- if (command->argv[1]) {
- syntax_error_unexpected_ch('(');
- return -1;
- }
-
- do
- ch = i_getch(input);
- while (ch == ' ' || ch == '\t');
- if (ch != ')') {
- syntax_error_unexpected_ch(ch);
- return -1;
- }
- nommu_addchr(&ctx->as_string, ch);
- do
- ch = i_getch(input);
- while (ch == ' ' || ch == '\t' || ch == '\n');
- if (ch != '{' && ch != '(') {
- syntax_error_unexpected_ch(ch);
- return -1;
- }
- nommu_addchr(&ctx->as_string, ch);
- command->cmd_type = CMD_FUNCDEF;
- goto skip;
- }
- #endif
- #if 0
- if (command->argv
- || ctx->word.length
- || ctx->word.has_quoted_part
- ) {
- syntax_error(NULL);
- debug_printf_parse("parse_group return -1: "
- "syntax error, groups and arglists don't mix\n");
- return -1;
- }
- #endif
- IF_HUSH_FUNCTIONS(skip:)
- endch = '}';
- if (ch == '(') {
- endch = ')';
- IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
- command->cmd_type = CMD_SUBSHELL;
- } else {
-
- ch = i_peek(input);
- if (ch != ' ' && ch != '\t' && ch != '\n'
- && ch != '('
- ) {
- syntax_error_unexpected_ch(ch);
- return -1;
- }
- if (ch != '(') {
- ch = i_getch(input);
- nommu_addchr(&ctx->as_string, ch);
- }
- }
- debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
- pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
- debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
- #if !BB_MMU
- if (as_string)
- o_addstr(&ctx->as_string, as_string);
- #endif
-
- if (!pipe_list || pipe_list == ERR_PTR) {
-
- if (!BB_MMU)
- free(as_string);
- debug_printf_parse("parse_group return -1: "
- "parse_stream returned %p\n", pipe_list);
- return -1;
- }
- #if !BB_MMU
- as_string[strlen(as_string) - 1] = '\0';
- command->group_as_string = as_string;
- debug_printf_parse("end of group, remembering as:'%s'\n",
- command->group_as_string);
- #endif
- #if ENABLE_HUSH_FUNCTIONS
-
- if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
- struct command *cmd2;
- cmd2 = xzalloc(sizeof(*cmd2));
- cmd2->cmd_type = CMD_SUBSHELL;
- cmd2->group = pipe_list;
- # if !BB_MMU
- cmd2->group_as_string = command->group_as_string;
- command->group_as_string = xasprintf("(%s)", command->group_as_string);
- # endif
- pipe_list = new_pipe();
- pipe_list->cmds = cmd2;
- pipe_list->num_cmds = 1;
- }
- #endif
- command->group = pipe_list;
- debug_printf_parse("parse_group return %d\n", heredoc_cnt);
- return heredoc_cnt;
-
- #undef as_string
- }
- #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
- static int add_till_single_quote(o_string *dest, struct in_str *input)
- {
- while (1) {
- int ch = i_getch(input);
- if (ch == EOF) {
- syntax_error_unterm_ch('\'');
- return 0;
- }
- if (ch == '\'')
- return 1;
- o_addchr(dest, ch);
- }
- }
- static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
- {
- while (1) {
- int ch = i_getch(input);
- if (ch == EOF) {
- syntax_error_unterm_ch('\'');
- return 0;
- }
- if (ch == '\'')
- return 1;
- o_addqchr(dest, ch);
- }
- }
- static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
- static int add_till_double_quote(o_string *dest, struct in_str *input)
- {
- while (1) {
- int ch = i_getch(input);
- if (ch == EOF) {
- syntax_error_unterm_ch('"');
- return 0;
- }
- if (ch == '"')
- return 1;
- if (ch == '\\') {
- o_addchr(dest, ch);
- ch = i_getch(input);
- }
- o_addchr(dest, ch);
- if (ch == '`') {
- if (!add_till_backquote(dest, input, 1))
- return 0;
- o_addchr(dest, ch);
- continue;
- }
-
- }
- }
- static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
- {
- while (1) {
- int ch = i_getch(input);
- if (ch == '`')
- return 1;
- if (ch == '\\') {
-
- ch = i_getch(input);
- if (ch != '`'
- && ch != '$'
- && ch != '\\'
- && (!in_dquote || ch != '"')
- ) {
- o_addchr(dest, '\\');
- }
- }
- if (ch == EOF) {
- syntax_error_unterm_ch('`');
- return 0;
- }
- o_addchr(dest, ch);
- }
- }
- #define DOUBLE_CLOSE_CHAR_FLAG 0x80
- static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
- {
- int ch;
- char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
- # if BASH_SUBSTR || BASH_PATTERN_SUBST
- char end_char2 = end_ch >> 8;
- # endif
- end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
- # if ENABLE_HUSH_INTERACTIVE
- G.promptmode = 1;
- # endif
- debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
- while (1) {
- ch = i_getch(input);
- if (ch == EOF) {
- syntax_error_unterm_ch(end_ch);
- return 0;
- }
- if (ch == end_ch
- # if BASH_SUBSTR || BASH_PATTERN_SUBST
- || ch == end_char2
- # endif
- ) {
- if (!dbl)
- break;
-
- if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
- i_getch(input);
- break;
- }
- }
- o_addchr(dest, ch);
-
- if (ch == '(' || ch == '{') {
- ch = (ch == '(' ? ')' : '}');
- if (!add_till_closing_bracket(dest, input, ch))
- return 0;
- o_addchr(dest, ch);
- continue;
- }
- if (ch == '\'') {
- if (!add_till_single_quote(dest, input))
- return 0;
- o_addchr(dest, ch);
- continue;
- }
- if (ch == '"') {
- if (!add_till_double_quote(dest, input))
- return 0;
- o_addchr(dest, ch);
- continue;
- }
- if (ch == '`') {
- if (!add_till_backquote(dest, input, 0))
- return 0;
- o_addchr(dest, ch);
- continue;
- }
- if (ch == '\\') {
-
- ch = i_getch(input);
- if (ch == EOF) {
- syntax_error_unterm_ch(end_ch);
- return 0;
- }
- # if 0
- if (ch == '\n') {
-
- o_delchr(dest);
- continue;
- }
- # endif
- o_addchr(dest, ch);
-
- continue;
- }
- }
- debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
- return ch;
- }
- #endif
- #if BASH_DOLLAR_SQUOTE
- # if BB_MMU
- #define parse_dollar_squote(as_string, dest, input) \
- parse_dollar_squote(dest, input)
- #define as_string NULL
- # endif
- static int parse_dollar_squote(o_string *as_string, o_string *dest, struct in_str *input)
- {
- int start;
- int ch = i_peek_and_eat_bkslash_nl(input);
- debug_printf_parse("parse_dollar_squote entered: ch='%c'\n", ch);
- if (ch != '\'')
- return 0;
- dest->has_quoted_part = 1;
- start = dest->length;
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- while (1) {
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- if (ch == EOF) {
- syntax_error_unterm_ch('\'');
- return 0;
- }
- if (ch == '\'')
- break;
- if (ch == SPECIAL_VAR_SYMBOL) {
-
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
-
- } else if (ch == '\\') {
- static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- if (strchr(C_escapes, ch)) {
- char buf[4];
- char *p = buf;
- int cnt = 2;
- buf[0] = ch;
- if ((unsigned char)(ch - '0') <= 7) {
- do {
- ch = i_peek(input);
- if ((unsigned char)(ch - '0') > 7)
- break;
- *++p = ch = i_getch(input);
- nommu_addchr(as_string, ch);
- } while (--cnt != 0);
- } else if (ch == 'x') {
- do {
- ch = i_peek(input);
- if (!isxdigit(ch))
- break;
- *++p = ch = i_getch(input);
- nommu_addchr(as_string, ch);
- } while (--cnt != 0);
- if (cnt == 2) {
- ch = 'x';
- goto unrecognized;
- }
- }
- *++p = '\0';
- p = buf;
- ch = bb_process_escape_sequence((void*)&p);
-
- if (ch == '\0')
- continue;
- } else {
- if (ch != '\'' && ch != '"') {
- unrecognized:
- o_addqchr(dest, '\\');
- }
- }
- }
- o_addqchr(dest, ch);
- }
- if (dest->length == start) {
-
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- }
- return 1;
- # undef as_string
- }
- #else
- # define parse_dollar_squote(as_string, dest, input) 0
- #endif
- #if BB_MMU
- #define parse_dollar(as_string, dest, input, quote_mask) \
- parse_dollar(dest, input, quote_mask)
- #define as_string NULL
- #endif
- static int parse_dollar(o_string *as_string,
- o_string *dest,
- struct in_str *input, unsigned char quote_mask)
- {
- int ch = i_peek_and_eat_bkslash_nl(input);
- debug_printf_parse("parse_dollar entered: ch='%c' quote_mask:0x%x\n", ch, quote_mask);
- if (isalpha(ch)) {
- make_var:
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
-
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- while (1) {
- debug_printf_parse(": '%c'\n", ch);
- o_addchr(dest, ch | quote_mask);
- quote_mask = 0;
- ch = i_peek_and_eat_bkslash_nl(input);
- if (!isalnum(ch) && ch != '_') {
-
- break;
- }
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- }
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- } else if (isdigit(ch)) {
- make_one_char_var:
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- debug_printf_parse(": '%c'\n", ch);
- o_addchr(dest, ch | quote_mask);
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- } else switch (ch) {
- case '$':
- case '!':
- case '?':
- case '#':
- case '*':
- case '@':
- case '-':
- goto make_one_char_var;
- case '{': {
- char len_single_ch;
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- ch = i_getch_and_eat_bkslash_nl(input);
-
- if (ch == EOF
- || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch))
- ) {
- bad_dollar_syntax:
- syntax_error_unterm_str("${name}");
- debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
- return 0;
- }
- nommu_addchr(as_string, ch);
- len_single_ch = ch;
- ch |= quote_mask;
-
- if (isdigit(len_single_ch)
- || (len_single_ch == '#' && isdigit(i_peek_and_eat_bkslash_nl(input)))
- ) {
-
- unsigned cnt = 9;
- while (1) {
- o_addchr(dest, ch);
- debug_printf_parse(": '%c'\n", ch);
- ch = i_getch_and_eat_bkslash_nl(input);
- nommu_addchr(as_string, ch);
- if (ch == '}')
- break;
- if (--cnt == 0)
- goto bad_dollar_syntax;
- if (len_single_ch != '#' && strchr(VAR_SUBST_OPS, ch))
-
- goto eat_until_closing;
- if (!isdigit(ch))
- goto bad_dollar_syntax;
- }
- } else
- while (1) {
- unsigned pos;
- o_addchr(dest, ch);
- debug_printf_parse(": '%c'\n", ch);
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- if (ch == '}')
- break;
- if (!isalnum(ch) && ch != '_') {
- unsigned end_ch;
- unsigned char last_ch;
-
- if (!strchr(VAR_SUBST_OPS, ch)) {
- if (len_single_ch != '#'
-
- || i_peek(input) != '}'
- ) {
- goto bad_dollar_syntax;
- }
-
- }
- eat_until_closing:
-
- end_ch = '}';
- if (BASH_SUBSTR
- && ch == ':'
- && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
- ) {
-
- end_ch = '}' * 0x100 + ':';
- }
- if (BASH_PATTERN_SUBST
- && ch == '/'
- ) {
-
- if (i_peek(input) == '/') {
- i_getch(input);
- nommu_addchr(as_string, '/');
- ch = '\\';
- }
- end_ch = '}' * 0x100 + '/';
- }
- o_addchr(dest, ch);
-
- if (i_peek(input) == '/') {
- o_addchr(dest, i_getch(input));
- }
- again:
- if (!BB_MMU)
- pos = dest->length;
- #if ENABLE_HUSH_DOLLAR_OPS
- last_ch = add_till_closing_bracket(dest, input, end_ch);
- if (last_ch == 0)
- return 0;
- #else
- # error Simple code to only allow ${var} is not implemented
- #endif
- if (as_string) {
- o_addstr(as_string, dest->data + pos);
- o_addchr(as_string, last_ch);
- }
- if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
- && (end_ch & 0xff00)
- ) {
-
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
-
- if ((end_ch & 0xff) == last_ch) {
-
- end_ch = '}';
- goto again;
- }
-
- if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
-
- o_addstr(dest, "999999999");
- }
- }
- break;
- }
- len_single_ch = 0;
- }
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- break;
- }
- #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
- case '(': {
- unsigned pos;
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- # if ENABLE_FEATURE_SH_MATH
- if (i_peek_and_eat_bkslash_nl(input) == '(') {
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- o_addchr(dest, quote_mask | '+');
- if (!BB_MMU)
- pos = dest->length;
- if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
- return 0;
- if (as_string) {
- o_addstr(as_string, dest->data + pos);
- o_addchr(as_string, ')');
- o_addchr(as_string, ')');
- }
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- break;
- }
- # endif
- # if ENABLE_HUSH_TICK
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- o_addchr(dest, quote_mask | '`');
- if (!BB_MMU)
- pos = dest->length;
- if (!add_till_closing_bracket(dest, input, ')'))
- return 0;
- if (as_string) {
- o_addstr(as_string, dest->data + pos);
- o_addchr(as_string, ')');
- }
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- # endif
- break;
- }
- #endif
- case '_':
- goto make_var;
- #if 0
-
-
- ch = i_getch(input);
- nommu_addchr(as_string, ch);
- ch = i_peek_and_eat_bkslash_nl(input);
- if (isalnum(ch)) {
- ch = '_';
- goto make_var1;
- }
-
- #endif
- default:
- o_addQchr(dest, '$');
- }
- debug_printf_parse("parse_dollar return 1 (ok)\n");
- return 1;
- #undef as_string
- }
- #if BB_MMU
- #define encode_string(as_string, dest, input, dquote_end) \
- encode_string(dest, input, dquote_end)
- #define as_string NULL
- #endif
- static int encode_string(o_string *as_string,
- o_string *dest,
- struct in_str *input,
- int dquote_end)
- {
- int ch;
- int next;
- again:
- ch = i_getch(input);
- if (ch != EOF)
- nommu_addchr(as_string, ch);
- if (ch == dquote_end) {
- debug_printf_parse("encode_string return 1 (ok)\n");
- return 1;
- }
-
- if (ch == EOF) {
- syntax_error_unterm_ch('"');
- return 0;
- }
- next = '\0';
- if (ch != '\n') {
- next = i_peek(input);
- }
- debug_printf_parse("\" ch=%c (%d) escape=%d\n",
- ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
- if (ch == '\\') {
- if (next == EOF) {
-
- syntax_error_unterm_ch('"');
- return 0;
- }
-
- if (next == dquote_end || strchr("$`\\\n", next)) {
- ch = i_getch(input);
- if (ch == '\n')
- goto again;
- }
- o_addqchr(dest, ch);
- nommu_addchr(as_string, ch);
- goto again;
- }
- if (ch == '$') {
-
-
- if (!parse_dollar(as_string, dest, input, 0x80)) {
- debug_printf_parse("encode_string return 0: "
- "parse_dollar returned 0 (error)\n");
- return 0;
- }
- goto again;
- }
- #if ENABLE_HUSH_TICK
- if (ch == '`') {
-
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- o_addchr(dest, 0x80 | '`');
- if (!add_till_backquote(dest, input, dquote_end == '"'))
- return 0;
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
-
- goto again;
- }
- #endif
- o_addQchr(dest, ch);
- if (ch == SPECIAL_VAR_SYMBOL) {
-
- o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
- o_addchr(dest, SPECIAL_VAR_SYMBOL);
- }
- goto again;
- #undef as_string
- }
- static struct pipe *parse_stream(char **pstring,
- int *heredoc_cnt_ptr,
- struct in_str *input,
- int end_trigger)
- {
- struct parse_context ctx;
- int heredoc_cnt;
-
- debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
- end_trigger ? end_trigger : 'X');
- debug_enter();
- initialize_context(&ctx);
-
- ctx.word.data = xzalloc(1);
-
- heredoc_cnt = 0;
- while (1) {
- const char *is_blank;
- const char *is_special;
- int ch;
- int next;
- int redir_fd;
- redir_type redir_style;
- ch = i_getch(input);
- debug_printf_parse(": ch=%c (%d) escape=%d\n",
- ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
- if (ch == EOF) {
- struct pipe *pi;
- if (heredoc_cnt) {
- syntax_error_unterm_str("here document");
- goto parse_error_exitcode1;
- }
- if (end_trigger == ')') {
- syntax_error_unterm_ch('(');
- goto parse_error_exitcode1;
- }
- if (end_trigger == '}') {
- syntax_error_unterm_ch('{');
- goto parse_error_exitcode1;
- }
- if (done_word(&ctx)) {
- goto parse_error_exitcode1;
- }
- o_free_and_set_NULL(&ctx.word);
- done_pipe(&ctx, PIPE_SEQ);
-
- if (HAS_KEYWORDS
- IF_HAS_KEYWORDS(&& (ctx.ctx_res_w != RES_NONE || ctx.old_flag != 0))
- ) {
- syntax_error_unterm_str("compound statement");
- goto parse_error_exitcode1;
- }
- pi = ctx.list_head;
-
-
- if (pi->num_cmds == 0
- IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
- ) {
- free_pipe_list(pi);
- pi = NULL;
- }
- #if !BB_MMU
- debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
- if (pstring)
- *pstring = ctx.as_string.data;
- else
- o_free(&ctx.as_string);
- #endif
-
-
-
- debug_leave();
- debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
- debug_printf_parse("parse_stream return %p: EOF\n", pi);
- return pi;
- }
-
- if (ch == '\\') {
- ch = i_getch(input);
- if (ch == '\n')
- continue;
- nommu_addchr(&ctx.as_string, '\\');
- if (ch == SPECIAL_VAR_SYMBOL) {
- nommu_addchr(&ctx.as_string, ch);
-
- goto case_SPECIAL_VAR_SYMBOL;
- }
- o_addchr(&ctx.word, '\\');
- if (ch == EOF) {
-
-
- continue;
- }
-
- ctx.word.has_quoted_part = 1;
- nommu_addchr(&ctx.as_string, ch);
- o_addchr(&ctx.word, ch);
- continue;
- }
- nommu_addchr(&ctx.as_string, ch);
- if (ch == '\'') {
- ctx.word.has_quoted_part = 1;
- next = i_getch(input);
- if (next == '\'' && !ctx.pending_redirect)
- goto insert_empty_quoted_str_marker;
- ch = next;
- while (1) {
- if (ch == EOF) {
- syntax_error_unterm_ch('\'');
- goto parse_error_exitcode1;
- }
- nommu_addchr(&ctx.as_string, ch);
- if (ch == '\'')
- break;
- if (ch == SPECIAL_VAR_SYMBOL) {
-
- o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
- o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
- }
- o_addqchr(&ctx.word, ch);
- ch = i_getch(input);
- }
- continue;
- }
- next = '\0';
- if (ch != '\n')
- next = i_peek_and_eat_bkslash_nl(input);
- is_special = "{}<>&|();#"
- "$\"" IF_HUSH_TICK("`")
- SPECIAL_VAR_SYMBOL_STR;
- #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
- if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
-
- is_special += 8;
- } else
- #endif
-
- if (ctx.command->argv
- || ctx.word.length
- || ctx.word.has_quoted_part
- || (next != ';'
- && next != ')'
- && next != '('
- && next != '&'
- && next != '|'
- && !strchr(defifs, next)
- )
- ) {
-
- is_special += 2;
- }
- is_special = strchr(is_special, ch);
- is_blank = strchr(defifs, ch);
- if (!is_special && !is_blank) {
- ordinary_char:
- o_addQchr(&ctx.word, ch);
- if ((ctx.is_assignment == MAYBE_ASSIGNMENT
- || ctx.is_assignment == WORD_IS_KEYWORD)
- && ch == '='
- && endofname(ctx.word.data)[0] == '='
- ) {
- ctx.is_assignment = DEFINITELY_ASSIGNMENT;
- debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
- }
- continue;
- }
- if (is_blank) {
- #if ENABLE_HUSH_LINENO_VAR
- while (ch != '\n') {
- next = i_peek(input);
- if (next != ' ' && next != '\t' && next != '\n')
- break;
- ch = i_getch(input);
- }
-
- #endif
- if (done_word(&ctx)) {
- goto parse_error_exitcode1;
- }
- if (ch == '\n') {
-
- if (IS_NULL_CMD(ctx.command)
- && ctx.word.length == 0
- && !ctx.word.has_quoted_part
- && heredoc_cnt == 0
- ) {
-
- struct pipe *pi = ctx.list_head;
- if (pi->num_cmds != 0
- && pi->followup != PIPE_BG
- ) {
- continue;
- }
- }
-
- done_pipe(&ctx, PIPE_SEQ);
- debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
- if (heredoc_cnt) {
- heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
- if (heredoc_cnt != 0)
- goto parse_error_exitcode1;
- }
- ctx.is_assignment = MAYBE_ASSIGNMENT;
- debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
- ch = ';';
-
- }
- }
-
- if (ch == '}') {
- if (ctx.word.length != 0
- || ctx.word.has_quoted_part
- ) {
- goto ordinary_char;
- }
- if (!IS_NULL_CMD(ctx.command)) {
-
- if (ctx.command->group)
- goto term_group;
- goto ordinary_char;
- }
- if (!IS_NULL_PIPE(ctx.pipe))
-
- goto skip_end_trigger;
-
- }
- term_group:
- if (end_trigger && end_trigger == ch
- && (ch != ';' || heredoc_cnt == 0)
- #if ENABLE_HUSH_CASE
- && (ch != ')'
- || ctx.ctx_res_w != RES_MATCH
- || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
- )
- #endif
- ) {
- if (done_word(&ctx)) {
- goto parse_error_exitcode1;
- }
- done_pipe(&ctx, PIPE_SEQ);
- ctx.is_assignment = MAYBE_ASSIGNMENT;
- debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
-
- if (!HAS_KEYWORDS
- IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
- ) {
- o_free_and_set_NULL(&ctx.word);
- #if !BB_MMU
- debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
- if (pstring)
- *pstring = ctx.as_string.data;
- else
- o_free(&ctx.as_string);
- #endif
- if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
-
- G.last_exitcode = 2;
- syntax_error_unexpected_ch(ch);
- goto parse_error;
- }
- if (heredoc_cnt_ptr)
- *heredoc_cnt_ptr = heredoc_cnt;
- debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
- debug_printf_parse("parse_stream return %p: "
- "end_trigger char found\n",
- ctx.list_head);
- debug_leave();
- return ctx.list_head;
- }
- }
- if (is_blank)
- continue;
-
- switch (ch) {
- case '>':
- redir_fd = redirect_opt_num(&ctx.word);
- if (done_word(&ctx)) {
- goto parse_error_exitcode1;
- }
- redir_style = REDIRECT_OVERWRITE;
- if (next == '>') {
- redir_style = REDIRECT_APPEND;
- ch = i_getch(input);
- nommu_addchr(&ctx.as_string, ch);
- }
- #if 0
- else if (next == '(') {
- syntax_error(">(process) not supported");
- goto parse_error_exitcode1;
- }
- #endif
- if (parse_redirect(&ctx, redir_fd, redir_style, input))
- goto parse_error_exitcode1;
- continue;
- case '<':
- redir_fd = redirect_opt_num(&ctx.word);
- if (done_word(&ctx)) {
- goto parse_error_exitcode1;
- }
- redir_style = REDIRECT_INPUT;
- if (next == '<') {
- redir_style = REDIRECT_HEREDOC;
- heredoc_cnt++;
- debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
- ch = i_getch(input);
- nommu_addchr(&ctx.as_string, ch);
- } else if (next == '>') {
- redir_style = REDIRECT_IO;
- ch = i_getch(input);
- nommu_addchr(&ctx.as_string, ch);
- }
- #if 0
- else if (next == '(') {
- syntax_error("<(process) not supported");
- goto parse_error_exitcode1;
- }
- #endif
- if (parse_redirect(&ctx, redir_fd, redir_style, input))
- goto parse_error_exitcode1;
- continue;
- case '#':
- if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
-
-
- while (1) {
- ch = i_peek(input);
- if (ch == '\n') {
- nommu_addchr(&ctx.as_string, '\n');
- break;
- }
- ch = i_getch(input);
- if (ch == EOF)
- break;
- }
- continue;
- }
- break;
- }
- skip_end_trigger:
- if (ctx.is_assignment == MAYBE_ASSIGNMENT
-
- && !ctx.pending_redirect
- ) {
-
- ctx.is_assignment = NOT_ASSIGNMENT;
- debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
- }
-
- switch (ch) {
- case_SPECIAL_VAR_SYMBOL:
- case SPECIAL_VAR_SYMBOL:
-
- o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
- o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
-
- case '#':
-
- o_addchr(&ctx.word, ch);
- continue;
- case '$':
- if (parse_dollar_squote(&ctx.as_string, &ctx.word, input))
- continue;
- if (!parse_dollar(&ctx.as_string, &ctx.word, input, 0)) {
- debug_printf_parse("parse_stream parse error: "
- "parse_dollar returned 0 (error)\n");
- goto parse_error_exitcode1;
- }
- continue;
- case '"':
- ctx.word.has_quoted_part = 1;
- if (next == '"' && !ctx.pending_redirect) {
- i_getch(input);
- insert_empty_quoted_str_marker:
- nommu_addchr(&ctx.as_string, next);
- o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
- o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
- continue;
- }
- if (ctx.is_assignment == NOT_ASSIGNMENT)
- ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
- if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
- goto parse_error_exitcode1;
- ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
- continue;
- #if ENABLE_HUSH_TICK
- case '`': {
- USE_FOR_NOMMU(unsigned pos;)
- o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
- o_addchr(&ctx.word, '`');
- USE_FOR_NOMMU(pos = ctx.word.length;)
- if (!add_till_backquote(&ctx.word, input, 0))
- goto parse_error_exitcode1;
- # if !BB_MMU
- o_addstr(&ctx.as_string, ctx.word.data + pos);
- o_addchr(&ctx.as_string, '`');
- # endif
- o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
-
- continue;
- }
- #endif
- case ';':
- #if ENABLE_HUSH_CASE
- case_semi:
- #endif
- if (done_word(&ctx)) {
- goto parse_error_exitcode1;
- }
- done_pipe(&ctx, PIPE_SEQ);
- #if ENABLE_HUSH_CASE
-
- while (1) {
- ch = i_peek_and_eat_bkslash_nl(input);
- if (ch != ';')
- break;
- ch = i_getch(input);
- nommu_addchr(&ctx.as_string, ch);
- if (ctx.ctx_res_w == RES_CASE_BODY) {
- ctx.ctx_dsemicolon = 1;
- ctx.ctx_res_w = RES_MATCH;
- break;
- }
- }
- #endif
- new_cmd:
-
- ctx.is_assignment = MAYBE_ASSIGNMENT;
- debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
- continue;
- case '&':
- if (done_word(&ctx)) {
- goto parse_error_exitcode1;
- }
- if (next == '&') {
- ch = i_getch(input);
- nommu_addchr(&ctx.as_string, ch);
- done_pipe(&ctx, PIPE_AND);
- } else {
- done_pipe(&ctx, PIPE_BG);
- }
- goto new_cmd;
- case '|':
- if (done_word(&ctx)) {
- goto parse_error_exitcode1;
- }
- #if ENABLE_HUSH_CASE
- if (ctx.ctx_res_w == RES_MATCH)
- break;
- #endif
- if (next == '|') {
- ch = i_getch(input);
- nommu_addchr(&ctx.as_string, ch);
- done_pipe(&ctx, PIPE_OR);
- } else {
-
- done_command(&ctx);
- }
- goto new_cmd;
- case '(':
- #if ENABLE_HUSH_CASE
-
- if (ctx.ctx_res_w == RES_MATCH
- && ctx.command->argv == NULL
- && ctx.word.length == 0
- && ctx.word.has_quoted_part == 0
- ) {
- continue;
- }
- #endif
-
- case '{': {
- int n = parse_group(&ctx, input, ch);
- if (n < 0) {
- goto parse_error_exitcode1;
- }
- debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
- heredoc_cnt += n;
- goto new_cmd;
- }
- case ')':
- #if ENABLE_HUSH_CASE
- if (ctx.ctx_res_w == RES_MATCH)
- goto case_semi;
- #endif
- case '}':
-
- G.last_exitcode = 2;
- syntax_error_unexpected_ch(ch);
- goto parse_error;
- default:
- if (HUSH_DEBUG)
- bb_error_msg_and_die("BUG: unexpected %c", ch);
- }
- }
- parse_error_exitcode1:
- G.last_exitcode = 1;
- parse_error:
- {
- struct parse_context *pctx;
- IF_HAS_KEYWORDS(struct parse_context *p2;)
-
- pctx = &ctx;
- do {
-
- done_pipe(pctx, PIPE_SEQ);
- debug_printf_clean("freeing list %p from ctx %p\n",
- pctx->list_head, pctx);
- debug_print_tree(pctx->list_head, 0);
- free_pipe_list(pctx->list_head);
- debug_printf_clean("freed list %p\n", pctx->list_head);
- #if !BB_MMU
- o_free(&pctx->as_string);
- #endif
- IF_HAS_KEYWORDS(p2 = pctx->stack;)
- if (pctx != &ctx) {
- free(pctx);
- }
- IF_HAS_KEYWORDS(pctx = p2;)
- } while (HAS_KEYWORDS && pctx);
- o_free(&ctx.word);
- #if !BB_MMU
- if (pstring)
- *pstring = NULL;
- #endif
- debug_leave();
- return ERR_PTR;
- }
- }
- #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
- #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
- expand_string_to_string(str)
- #endif
- static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
- #if ENABLE_HUSH_TICK
- static int process_command_subs(o_string *dest, const char *s);
- #endif
- static int expand_vars_to_list(o_string *output, int n, char *arg);
- static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
- {
- while (--len >= 0) {
- char c = *str++;
- #if ENABLE_HUSH_BRACE_EXPANSION
- if (c == '{' || c == '}') {
-
- o_addchr(o, '\\');
-
- }
- #endif
- o_addchr(o, c);
- if (c == '\\') {
-
- o_addchr(o, '\\');
- if (len) {
- len--;
- o_addchr(o, '\\');
- o_addchr(o, *str++);
- }
- }
- }
- }
- static int expand_on_ifs(o_string *output, int n, const char *str)
- {
- int last_is_ifs = 0;
- while (1) {
- int word_len;
- if (!*str)
- break;
- word_len = strcspn(str, G.ifs);
- if (word_len) {
-
- if (!(output->o_expflags & EXP_FLAG_GLOB)) {
- o_addblock(output, str, word_len);
- } else {
-
- o_addblock_duplicate_backslash(output, str, word_len);
-
-
-
- }
- last_is_ifs = 0;
- str += word_len;
- if (!*str)
- break;
- }
-
- last_is_ifs = 1;
- str += strspn(str, G.ifs_whitespace);
- if (!*str)
- break;
- if (G.ifs_whitespace != G.ifs
- && strchr(G.ifs, *str)
- ) {
-
-
- str++;
- str += strspn(str, G.ifs_whitespace);
- goto new_word;
- }
-
-
- if (output->has_quoted_part
-
- || output->data[output->length - 1]
- ) {
- new_word:
- o_addchr(output, '\0');
- debug_print_list("expand_on_ifs", output, n);
- n = o_save_ptr(output, n);
- }
- }
- output->ended_in_ifs = last_is_ifs;
- debug_print_list("expand_on_ifs[1]", output, n);
- return n;
- }
- static char *encode_then_expand_string(const char *str)
- {
- char *exp_str;
- struct in_str input;
- o_string dest = NULL_O_STRING;
- const char *cp;
- cp = str;
- for (;;) {
- if (!*cp) return NULL;
- if (*cp == '$') break;
- if (*cp == '\\') break;
- #if ENABLE_HUSH_TICK
- if (*cp == '`') break;
- #endif
- cp++;
- }
-
- setup_string_in_str(&input, str);
- encode_string(NULL, &dest, &input, EOF);
-
- exp_str = expand_string_to_string(dest.data,
- EXP_FLAG_ESC_GLOB_CHARS,
- 1
- );
-
- o_free(&dest);
- return exp_str;
- }
- static const char *first_special_char_in_vararg(const char *cp)
- {
- for (;;) {
- if (!*cp) return NULL;
- if (*cp == '$') return cp;
- if (*cp == '\\') return cp;
- if (*cp == '\'') return cp;
- if (*cp == '"') return cp;
- #if ENABLE_HUSH_TICK
- if (*cp == '`') return cp;
- #endif
-
- if (*cp == '*') return cp;
- if (*cp == '?') return cp;
- if (*cp == '[') return cp;
- cp++;
- }
- }
- #if !BASH_PATTERN_SUBST
- #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
- encode_then_expand_vararg(str, handle_squotes)
- #endif
- static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
- {
- #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
- const int do_unbackslash = 0;
- #endif
- char *exp_str;
- struct in_str input;
- o_string dest = NULL_O_STRING;
- if (!first_special_char_in_vararg(str)) {
-
- return NULL;
- }
- setup_string_in_str(&input, str);
- dest.data = xzalloc(1);
- exp_str = NULL;
- for (;;) {
- int ch;
- ch = i_getch(&input);
- debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
- __func__, ch, ch, !!dest.o_expflags);
- if (!dest.o_expflags) {
- if (ch == EOF)
- break;
- if (handle_squotes && ch == '\'') {
- if (!add_till_single_quote_dquoted(&dest, &input))
- goto ret;
- continue;
- }
- }
- if (ch == EOF) {
- syntax_error_unterm_ch('"');
- goto ret;
- }
- if (ch == '"') {
- dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
- continue;
- }
- if (ch == '\\') {
- ch = i_getch(&input);
- if (ch == EOF) {
- debug_printf_parse("%s: error: \\<eof>\n", __func__);
- goto ret;
- }
- o_addqchr(&dest, ch);
- continue;
- }
- if (ch == '$') {
- if (parse_dollar_squote(NULL, &dest, &input))
- continue;
- if (!parse_dollar(NULL, &dest, &input, 0x80)) {
- debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
- goto ret;
- }
- continue;
- }
- #if ENABLE_HUSH_TICK
- if (ch == '`') {
-
- o_addchr(&dest, SPECIAL_VAR_SYMBOL);
- o_addchr(&dest, 0x80 | '`');
- if (!add_till_backquote(&dest, &input,
- dest.o_expflags
- )
- ) {
- goto ret;
- }
- o_addchr(&dest, SPECIAL_VAR_SYMBOL);
-
- continue;
- }
- #endif
- o_addQchr(&dest, ch);
- }
- debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
- exp_str = expand_string_to_string(dest.data,
- do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
- do_unbackslash
- );
- ret:
- debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
- o_free(&dest);
- return exp_str;
- }
- static NOINLINE int encode_then_append_var_plusminus(o_string *output, int n,
- char *str, int dquoted)
- {
- struct in_str input;
- o_string dest = NULL_O_STRING;
- if (!first_special_char_in_vararg(str)
- && '\0' == str[strcspn(str, G.ifs)]
- ) {
-
- if (dquoted) {
-
- output->has_quoted_part = 1;
- }
- return expand_vars_to_list(output, n, str);
- }
- setup_string_in_str(&input, str);
- for (;;) {
- int ch;
- ch = i_getch(&input);
- debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
- __func__, ch, ch, dest.o_expflags);
- if (!dest.o_expflags) {
- if (ch == EOF)
- break;
- if (!dquoted && !(output->o_expflags & EXP_FLAG_SINGLEWORD) && strchr(G.ifs, ch)) {
-
- if (dest.data) {
- n = expand_vars_to_list(output, n, dest.data);
- o_free_and_set_NULL(&dest);
- o_addchr(output, '\0');
- n = o_save_ptr(output, n);
- } else
- if (output->length != o_get_last_ptr(output, n)
- || output->has_quoted_part
- ) {
-
- o_addchr(output, '\0');
- n = o_save_ptr(output, n);
- }
- continue;
- }
- if (!dquoted && ch == '\'') {
- if (!add_till_single_quote_dquoted(&dest, &input))
- goto ret;
- o_addchr(&dest, SPECIAL_VAR_SYMBOL);
- o_addchr(&dest, SPECIAL_VAR_SYMBOL);
- continue;
- }
- }
- if (ch == EOF) {
- syntax_error_unterm_ch('"');
- goto ret;
- }
- if (ch == '"') {
- dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
- if (dest.o_expflags) {
- o_addchr(&dest, SPECIAL_VAR_SYMBOL);
- o_addchr(&dest, SPECIAL_VAR_SYMBOL);
- }
- continue;
- }
- if (ch == '\\') {
- ch = i_getch(&input);
- if (ch == EOF) {
- debug_printf_parse("%s: error: \\<eof>\n", __func__);
- goto ret;
- }
- o_addqchr(&dest, ch);
- continue;
- }
- if (ch == '$') {
- if (!parse_dollar(NULL, &dest, &input, (dest.o_expflags || dquoted) ? 0x80 : 0)) {
- debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
- goto ret;
- }
- continue;
- }
- #if ENABLE_HUSH_TICK
- if (ch == '`') {
-
- o_addchr(&dest, SPECIAL_VAR_SYMBOL);
- o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
- if (!add_till_backquote(&dest, &input,
- dest.o_expflags
- )
- ) {
- goto ret;
- }
- o_addchr(&dest, SPECIAL_VAR_SYMBOL);
-
- continue;
- }
- #endif
- if (dquoted) {
-
- o_addqchr(&dest, ch);
- } else {
-
- o_addQchr(&dest, ch);
- }
- }
- if (dest.data) {
- n = expand_vars_to_list(output, n, dest.data);
- }
- ret:
- o_free(&dest);
- return n;
- }
- #if ENABLE_FEATURE_SH_MATH
- static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
- {
- arith_state_t math_state;
- arith_t res;
- char *exp_str;
- math_state.lookupvar = get_local_var_value;
- math_state.setvar = set_local_var_from_halves;
-
- exp_str = encode_then_expand_string(arg);
- res = arith(&math_state, exp_str ? exp_str : arg);
- free(exp_str);
- if (errmsg_p)
- *errmsg_p = math_state.errmsg;
- if (math_state.errmsg)
- msg_and_die_if_script(math_state.errmsg);
- return res;
- }
- #endif
- #if BASH_PATTERN_SUBST
- static char *strstr_pattern(char *val, const char *pattern, int *size)
- {
- int first_escaped = (pattern[0] == '\\' && pattern[1]);
-
- int sz = strcspn(pattern + first_escaped * 2, "*?[\\");
- if ((pattern + first_escaped * 2)[sz] == '\0') {
-
- *size = sz + first_escaped;
- return strstr(val, pattern + first_escaped);
- }
- while (1) {
- char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
- debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
- if (end) {
- *size = end - val;
- return val;
- }
- if (*val == '\0')
- return NULL;
-
- if (pattern[0] == '*')
- return NULL;
- val++;
- }
- }
- static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
- {
- char *result = NULL;
- unsigned res_len = 0;
- unsigned repl_len = strlen(repl);
-
- if (!pattern[0])
- return result;
- while (1) {
- int size;
- char *s = strstr_pattern(val, pattern, &size);
- if (!s)
- break;
- result = xrealloc(result, res_len + (s - val) + repl_len + 1);
- strcpy(mempcpy(result + res_len, val, s - val), repl);
- res_len += (s - val) + repl_len;
- debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
- val = s + size;
- if (exp_op == '/')
- break;
- }
- if (*val && result) {
- result = xrealloc(result, res_len + strlen(val) + 1);
- strcpy(result + res_len, val);
- debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
- }
- debug_printf_varexp("result:'%s'\n", result);
- return result;
- }
- #endif
- static int append_str_maybe_ifs_split(o_string *output, int n,
- int first_ch, const char *val)
- {
- if (!(first_ch & 0x80)) {
- debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
- !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
- if (val && val[0])
- n = expand_on_ifs(output, n, val);
- } else {
- output->has_quoted_part = 1;
- debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
- !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
- if (val && val[0])
- o_addQstr(output, val);
- }
- return n;
- }
- static NOINLINE int expand_one_var(o_string *output, int n,
- int first_ch, char *arg, char **pp)
- {
- const char *val;
- char *to_be_freed;
- char *p;
- char *var;
- char exp_op;
- char exp_save = exp_save;
- char *exp_saveptr;
- char *exp_word = exp_word;
- char arg0;
- val = NULL;
- to_be_freed = NULL;
- p = *pp;
- *p = '\0';
- var = arg;
- exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
- arg0 = arg[0];
- arg[0] = (arg0 & 0x7f);
- exp_op = 0;
- if (arg[0] == '#' && arg[1]
- && (!exp_saveptr
- || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1]))
- )
- ) {
-
- var++;
- exp_op = 'L';
- } else {
-
- if (exp_saveptr
- && strchr(NUMERIC_SPECVARS_STR, arg[0])
- ) {
-
- exp_saveptr = var + 1;
- } else {
-
- exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
- }
- exp_op = exp_save = *exp_saveptr;
- if (exp_op) {
- exp_word = exp_saveptr + 1;
- if (exp_op == ':') {
- exp_op = *exp_word++;
- if (BASH_SUBSTR
- && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
- ) {
-
- exp_op = ':';
- exp_word--;
- }
- }
- *exp_saveptr = '\0';
- }
- }
-
- if (isdigit(var[0])) {
-
- int nn = xatoi_positive(var);
- if (nn < G.global_argc)
- val = G.global_argv[nn];
-
- } else {
- switch (var[0]) {
- case '$':
- val = utoa(G.root_pid);
- break;
- case '!':
- val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
- break;
- case '?':
- val = utoa(G.last_exitcode);
- break;
- case '#':
- val = utoa(G.global_argc ? G.global_argc-1 : 0);
- break;
- case '-': {
-
- char *cp;
- val = cp = G.optstring_buf;
- if (G.o_opt[OPT_O_ERREXIT])
- *cp++ = 'e';
- if (G_interactive_fd)
- *cp++ = 'i';
- if (G_x_mode)
- *cp++ = 'x';
-
- if (G.opt_c)
- *cp++ = 'c';
- if (G.opt_s)
- *cp++ = 's';
- *cp = '\0';
- break;
- }
- default:
- val = get_local_var_value(var);
- }
- }
-
- if (exp_op == 'L') {
- reinit_unicode_for_hush();
- debug_printf_expand("expand: length(%s)=", val);
- val = utoa(val ? unicode_strlen(val) : 0);
- debug_printf_expand("%s\n", val);
- } else if (exp_op) {
- if (exp_op == '%' || exp_op == '#') {
-
-
- if (val && val[0]) {
- char *t;
- char *exp_exp_word;
- char *loc;
- unsigned scan_flags = pick_scan(exp_op, *exp_word);
- if (exp_op == *exp_word)
- exp_word++;
- debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
- exp_exp_word = encode_then_expand_vararg(exp_word, 1, 0);
- if (exp_exp_word)
- exp_word = exp_exp_word;
- debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
-
- t = (char*)val;
- loc = scan_and_match(t, exp_word, scan_flags);
- debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
- free(exp_exp_word);
- if (loc) {
- if (scan_flags & SCAN_MATCH_LEFT_HALF)
- val = loc;
- else
- val = to_be_freed = xstrndup(val, loc - val);
- }
- }
- }
- #if BASH_PATTERN_SUBST
- else if (exp_op == '/' || exp_op == '\\') {
-
-
- if (val ) {
-
- char *pattern, *repl, *t;
- pattern = encode_then_expand_vararg(exp_word, 1, 0);
- if (!pattern)
- pattern = xstrdup(exp_word);
- debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
- *p++ = SPECIAL_VAR_SYMBOL;
- exp_word = p;
- p = strchr(p, SPECIAL_VAR_SYMBOL);
- *p = '\0';
- repl = encode_then_expand_vararg(exp_word, 1, 1);
- debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
-
- t = (char*)val;
- to_be_freed = replace_pattern(t,
- pattern,
- (repl ? repl : exp_word),
- exp_op);
- if (to_be_freed)
- val = to_be_freed;
- free(pattern);
- free(repl);
- } else {
-
-
-
-
- *p++ = SPECIAL_VAR_SYMBOL;
- p = strchr(p, SPECIAL_VAR_SYMBOL);
- *p = '\0';
- }
- }
- #endif
- else if (exp_op == ':') {
- #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
-
- arith_t beg, len;
- unsigned vallen;
- const char *errmsg;
- beg = expand_and_evaluate_arith(exp_word, &errmsg);
- if (errmsg)
- goto empty_result;
- debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
- *p++ = SPECIAL_VAR_SYMBOL;
- exp_word = p;
- p = strchr(p, SPECIAL_VAR_SYMBOL);
- *p = '\0';
- vallen = val ? strlen(val) : 0;
- if (beg < 0) {
-
- beg = (arith_t)vallen + beg;
- }
-
- if (!val || beg < 0 || beg > vallen) {
-
- goto empty_result;
- }
- len = expand_and_evaluate_arith(exp_word, &errmsg);
- if (errmsg)
- goto empty_result;
- debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
- debug_printf_varexp("from val:'%s'\n", val);
- if (len < 0) {
-
- len = (arith_t)vallen - beg + len;
- if (len < 0)
- msg_and_die_if_script("%s: substring expression < 0", var);
- }
- if (len <= 0 || !val ) {
- empty_result:
- val = NULL;
- } else {
-
- if (len > INT_MAX)
- len = INT_MAX;
- val = to_be_freed = xstrndup(val + beg, len);
- }
- debug_printf_varexp("val:'%s'\n", val);
- #else
- msg_and_die_if_script("malformed ${%s:...}", var);
- val = NULL;
- #endif
- } else {
-
- int use_word = (!val || ((exp_save == ':') && !val[0]));
- if (exp_op == '+')
- use_word = !use_word;
- debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
- (exp_save == ':') ? "true" : "false", use_word);
- if (use_word) {
- if (exp_op == '+' || exp_op == '-') {
-
-
- n = encode_then_append_var_plusminus(output, n, exp_word,
- (arg0 & 0x80)
- );
- val = NULL;
- } else {
-
-
- to_be_freed = encode_then_expand_vararg(exp_word,
- !(arg0 & 0x80),
- 0
- );
- if (to_be_freed)
- exp_word = to_be_freed;
- if (exp_op == '?') {
-
- msg_and_die_if_script("%s: %s",
- var,
- exp_word[0]
- ? exp_word
- : "parameter null or not set"
-
-
- );
- } else {
- val = exp_word;
- }
- if (exp_op == '=') {
-
- if (isdigit(var[0]) || var[0] == '#') {
-
- msg_and_die_if_script("$%s: cannot assign in this way", var);
- val = NULL;
- } else {
- char *new_var = xasprintf("%s=%s", var, val);
- set_local_var0(new_var);
- }
- }
- }
- }
- }
- *exp_saveptr = exp_save;
- }
- arg[0] = arg0;
- *pp = p;
- n = append_str_maybe_ifs_split(output, n, first_ch, val);
- free(to_be_freed);
- return n;
- }
- static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
- {
-
- char cant_be_null = 0;
- char *p;
- debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
- !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
- debug_print_list("expand_vars_to_list[0]", output, n);
- while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
- char first_ch;
- #if ENABLE_FEATURE_SH_MATH
- char arith_buf[sizeof(arith_t)*3 + 2];
- #endif
- if (output->ended_in_ifs) {
- o_addchr(output, '\0');
- n = o_save_ptr(output, n);
- output->ended_in_ifs = 0;
- }
- o_addblock(output, arg, p - arg);
- debug_print_list("expand_vars_to_list[1]", output, n);
- arg = ++p;
- p = strchr(p, SPECIAL_VAR_SYMBOL);
-
- first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
-
- if ((first_ch & 0x7f) != '@')
- cant_be_null |= first_ch;
- switch (first_ch & 0x7f) {
-
- case '*':
- case '@': {
- int i;
- if (!G.global_argv[1])
- break;
- i = 1;
- cant_be_null |= first_ch;
- if (!(first_ch & 0x80)) {
- while (G.global_argv[i]) {
- n = expand_on_ifs(output, n, G.global_argv[i]);
- debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
- if (G.global_argv[i++][0] && G.global_argv[i]) {
-
- o_addchr(output, '\0');
- debug_print_list("expand_vars_to_list[2]", output, n);
- n = o_save_ptr(output, n);
- debug_print_list("expand_vars_to_list[3]", output, n);
- }
- }
- } else
-
- if (first_ch == (char)('@'|0x80)
- && !(output->o_expflags & EXP_FLAG_SINGLEWORD)
- ) {
- while (1) {
- o_addQstr(output, G.global_argv[i]);
- if (++i >= G.global_argc)
- break;
- o_addchr(output, '\0');
- debug_print_list("expand_vars_to_list[4]", output, n);
- n = o_save_ptr(output, n);
- }
- } else {
- while (1) {
- o_addQstr(output, G.global_argv[i]);
- if (!G.global_argv[++i])
- break;
- if (G.ifs[0])
- o_addchr(output, G.ifs[0]);
- }
- output->has_quoted_part = 1;
- }
- break;
- }
- case SPECIAL_VAR_SYMBOL: {
-
-
- output->has_quoted_part = 1;
- cant_be_null = 0x80;
- arg++;
- break;
- }
- case SPECIAL_VAR_QUOTED_SVS:
-
-
- o_addchr(output, SPECIAL_VAR_SYMBOL);
- arg++;
- break;
- #if ENABLE_HUSH_TICK
- case '`': {
-
- o_string subst_result = NULL_O_STRING;
- *p = '\0';
- arg++;
-
- debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
- G.last_exitcode = process_command_subs(&subst_result, arg);
- G.expand_exitcode = G.last_exitcode;
- debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
- n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
- o_free(&subst_result);
- break;
- }
- #endif
- #if ENABLE_FEATURE_SH_MATH
- case '+': {
-
- arith_t res;
- arg++;
- *p = '\0';
- debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
- res = expand_and_evaluate_arith(arg, NULL);
- debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
- sprintf(arith_buf, ARITH_FMT, res);
- if (res < 0
- && first_ch == (char)('+'|0x80)
-
- ) {
-
- o_grow_by(output, 1);
- output->data[output->length++] = '\\';
- }
- o_addstr(output, arith_buf);
- break;
- }
- #endif
- default:
-
- n = expand_one_var(output, n, first_ch, arg, &p);
- break;
- }
-
- if (*p != SPECIAL_VAR_SYMBOL)
- *p = SPECIAL_VAR_SYMBOL;
- arg = ++p;
- }
- if (*arg) {
-
- if (output->ended_in_ifs) {
- o_addchr(output, '\0');
- n = o_save_ptr(output, n);
- }
- debug_print_list("expand_vars_to_list[a]", output, n);
-
- o_addstr(output, arg);
- debug_print_list("expand_vars_to_list[b]", output, n);
- } else
- if (output->length == o_get_last_ptr(output, n)
- && !(cant_be_null & 0x80)
- && !output->has_quoted_part
- ) {
- n--;
-
- output->has_empty_slot = 1;
- }
- return n;
- }
- static char **expand_variables(char **argv, unsigned expflags)
- {
- int n;
- char **list;
- o_string output = NULL_O_STRING;
- output.o_expflags = expflags;
- n = 0;
- for (;;) {
-
- output.ended_in_ifs = 0;
- n = o_save_ptr(&output, n);
- if (!*argv)
- break;
-
- n = expand_vars_to_list(&output, n, *argv++);
-
- o_addchr(&output, '\0');
- }
- debug_print_list("expand_variables", &output, n);
-
- list = o_finalize_list(&output, n);
- debug_print_strings("expand_variables[1]", list);
- return list;
- }
- static char **expand_strvec_to_strvec(char **argv)
- {
- return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
- }
- #if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
- static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
- {
- return expand_variables(argv, EXP_FLAG_SINGLEWORD);
- }
- #endif
- static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
- {
- #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
- const int do_unbackslash = 1;
- const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
- #endif
- char *argv[2], **list;
- debug_printf_expand("string_to_string<='%s'\n", str);
-
- if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
-
- debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
- return xstrdup(str);
- }
- argv[0] = (char*)str;
- argv[1] = NULL;
- list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
- if (!list[0]) {
-
- ((char*)list)[0] = '\0';
- } else {
- if (HUSH_DEBUG)
- if (list[1])
- bb_simple_error_msg_and_die("BUG in varexp2");
-
- overlapping_strcpy((char*)list, list[0]);
- if (do_unbackslash)
- unbackslash((char*)list);
- }
- debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
- return (char*)list;
- }
- #if 0
- static char* expand_strvec_to_string(char **argv)
- {
- char **list;
- list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
-
- if (list[0]) {
- int n = 1;
- while (list[n]) {
- if (HUSH_DEBUG)
- if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
- bb_error_msg_and_die("BUG in varexp3");
-
- list[n][-1] = ' ';
- n++;
- }
- }
- overlapping_strcpy((char*)list, list[0] ? list[0] : "");
- debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
- return (char*)list;
- }
- #endif
- static char **expand_assignments(char **argv, int count)
- {
- int i;
- char **p;
- G.expanded_assignments = p = NULL;
-
- for (i = 0; i < count; i++) {
- p = add_string_to_strings(p,
- expand_string_to_string(argv[i],
- EXP_FLAG_ESC_GLOB_CHARS,
- 1
- )
- );
- G.expanded_assignments = p;
- }
- G.expanded_assignments = NULL;
- return p;
- }
- static void switch_off_special_sigs(unsigned mask)
- {
- unsigned sig = 0;
- while ((mask >>= 1) != 0) {
- sig++;
- if (!(mask & 1))
- continue;
- #if ENABLE_HUSH_TRAP
- if (G_traps) {
- if (G_traps[sig] && !G_traps[sig][0])
-
- continue;
- free(G_traps[sig]);
- G_traps[sig] = NULL;
- }
- #endif
-
- install_sighandler(sig, SIG_DFL);
- }
- }
- #if BB_MMU
- void re_execute_shell(char ***to_free, const char *s,
- char *g_argv0, char **g_argv,
- char **builtin_argv) NORETURN;
- static void reset_traps_to_defaults(void)
- {
-
- IF_HUSH_TRAP(unsigned sig;)
- unsigned mask;
-
- mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
- if (!G_traps && !mask)
- return;
-
- switch_off_special_sigs(mask);
- # if ENABLE_HUSH_JOB
- G_fatal_sig_mask = 0;
- # endif
- G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
-
- # if ENABLE_HUSH_TRAP
- if (!G_traps)
- return;
-
- for (sig = 0; sig < NSIG; sig++) {
- if (!G_traps[sig])
- continue;
- if (!G_traps[sig][0])
- continue;
-
- free(G_traps[sig]);
- G_traps[sig] = NULL;
-
- if (sig == 0)
- continue;
- install_sighandler(sig, pick_sighandler(sig));
- }
- # endif
- }
- #else
- static void re_execute_shell(char ***to_free, const char *s,
- char *g_argv0, char **g_argv,
- char **builtin_argv) NORETURN;
- static void re_execute_shell(char ***to_free, const char *s,
- char *g_argv0, char **g_argv,
- char **builtin_argv)
- {
- # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
-
- char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
- char *heredoc_argv[4];
- struct variable *cur;
- # if ENABLE_HUSH_FUNCTIONS
- struct function *funcp;
- # endif
- char **argv, **pp;
- unsigned cnt;
- unsigned long long empty_trap_mask;
- if (!g_argv0) {
- argv = heredoc_argv;
- argv[0] = (char *) G.argv0_for_re_execing;
- argv[1] = (char *) "-<";
- argv[2] = (char *) s;
- argv[3] = NULL;
- pp = &argv[3];
- goto do_exec;
- }
- cnt = 0;
- pp = builtin_argv;
- if (pp) while (*pp++)
- cnt++;
- empty_trap_mask = 0;
- if (G_traps) {
- int sig;
- for (sig = 1; sig < NSIG; sig++) {
- if (G_traps[sig] && !G_traps[sig][0])
- empty_trap_mask |= 1LL << sig;
- }
- }
- sprintf(param_buf, NOMMU_HACK_FMT
- , (unsigned) G.root_pid
- , (unsigned) G.root_ppid
- , (unsigned) G.last_bg_pid
- , (unsigned) G.last_exitcode
- , cnt
- , empty_trap_mask
- IF_HUSH_LOOPS(, G.depth_of_loop)
- );
- # undef NOMMU_HACK_FMT
-
- cnt += 6;
- for (cur = G.top_var; cur; cur = cur->next) {
- if (!cur->flg_export || cur->flg_read_only)
- cnt += 2;
- }
- # if ENABLE_HUSH_LINENO_VAR
- cnt += 2;
- # endif
- # if ENABLE_HUSH_FUNCTIONS
- for (funcp = G.top_func; funcp; funcp = funcp->next)
- cnt += 3;
- # endif
- pp = g_argv;
- while (*pp++)
- cnt++;
- *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
- *pp++ = (char *) G.argv0_for_re_execing;
- *pp++ = param_buf;
- for (cur = G.top_var; cur; cur = cur->next) {
- if (strcmp(cur->varstr, hush_version_str) == 0)
- continue;
- if (cur->flg_read_only) {
- *pp++ = (char *) "-R";
- *pp++ = cur->varstr;
- } else if (!cur->flg_export) {
- *pp++ = (char *) "-V";
- *pp++ = cur->varstr;
- }
- }
- # if ENABLE_HUSH_LINENO_VAR
- *pp++ = (char *) "-L";
- *pp++ = utoa(G.execute_lineno);
- # endif
- # if ENABLE_HUSH_FUNCTIONS
- for (funcp = G.top_func; funcp; funcp = funcp->next) {
- *pp++ = (char *) "-F";
- *pp++ = funcp->name;
- *pp++ = funcp->body_as_string;
- }
- # endif
-
- *pp++ = (char *) "-c";
- *pp++ = (char *) s;
- if (builtin_argv) {
- while (*++builtin_argv)
- *pp++ = *builtin_argv;
- *pp++ = (char *) "";
- }
- *pp++ = g_argv0;
- while (*g_argv)
- *pp++ = *g_argv++;
-
- pp = environ;
- do_exec:
- debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
-
- if (SPECIAL_JOBSTOP_SIGS != 0)
- switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
- execve(bb_busybox_exec_path, argv, pp);
-
- if (argv[0][0] == '/')
- execve(argv[0], argv, pp);
- xfunc_error_retval = 127;
- bb_simple_error_msg_and_die("can't re-execute the shell");
- }
- #endif
- static int run_and_free_list(struct pipe *pi);
- static void parse_and_run_stream(struct in_str *inp, int end_trigger)
- {
-
- bool empty = 1;
- while (1) {
- struct pipe *pipe_list;
- #if ENABLE_HUSH_INTERACTIVE
- if (end_trigger == ';') {
- G.promptmode = 0;
- debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
- }
- #endif
- pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
- if (!pipe_list || pipe_list == ERR_PTR) {
-
- if (pipe_list == ERR_PTR && end_trigger == ';') {
-
- int ch = inp->last_char;
- while (ch != EOF && ch != '\n') {
-
- ch = i_getch(inp);
- }
-
- inp->p = NULL;
-
- if (inp->peek_buf[0] == EOF)
- inp->peek_buf[0] = 0;
-
- empty = 0;
- continue;
- }
- if (!pipe_list && empty)
- G.last_exitcode = 0;
- break;
- }
- debug_print_tree(pipe_list, 0);
- debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
- run_and_free_list(pipe_list);
- empty = 0;
- if (G_flag_return_in_progress == 1)
- break;
- }
- }
- static void parse_and_run_string(const char *s)
- {
- struct in_str input;
- IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
- setup_string_in_str(&input, s);
- parse_and_run_stream(&input, '\0');
- IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
- }
- static void parse_and_run_file(HFILE *fp)
- {
- struct in_str input;
- IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
- IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
- setup_file_in_str(&input, fp);
- parse_and_run_stream(&input, ';');
- IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
- }
- #if ENABLE_HUSH_TICK
- static int generate_stream_from_string(const char *s, pid_t *pid_p)
- {
- pid_t pid;
- int channel[2];
- # if !BB_MMU
- char **to_free = NULL;
- # endif
- xpipe(channel);
- pid = BB_MMU ? xfork() : xvfork();
- if (pid == 0) {
- disable_restore_tty_pgrp_on_exit();
-
- bb_signals(0
- + (1 << SIGTSTP)
- + (1 << SIGTTIN)
- + (1 << SIGTTOU)
- , SIG_IGN);
- close(channel[0]);
- xmove_fd(channel[1], 1);
- # if ENABLE_HUSH_TRAP
-
- s = skip_whitespace(s);
- if (is_prefixed_with(s, "trap")
- && skip_whitespace(s + 4)[0] == '\0'
- ) {
- static const char *const argv[] ALIGN_PTR = { NULL, NULL };
- builtin_trap((char**)argv);
- fflush_all();
- _exit(0);
- }
- # endif
- # if BB_MMU
-
- IF_HUSH_JOB(G.run_list_level = 1;)
- CLEAR_RANDOM_T(&G.random_gen);
- reset_traps_to_defaults();
- IF_HUSH_MODE_X(G.x_mode_depth++;)
-
- parse_and_run_string(s);
- _exit(G.last_exitcode);
- # else
-
- re_execute_shell(&to_free,
- s,
- G.global_argv[0],
- G.global_argv + 1,
- NULL);
- # endif
- }
-
- *pid_p = pid;
- # if ENABLE_HUSH_FAST
- G.count_SIGCHLD++;
- # endif
- enable_restore_tty_pgrp_on_exit();
- # if !BB_MMU
- free(to_free);
- # endif
- close(channel[1]);
- return channel[0];
- }
- static int process_command_subs(o_string *dest, const char *s)
- {
- FILE *fp;
- pid_t pid;
- int status, ch, eol_cnt;
- fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
-
- eol_cnt = 0;
- while ((ch = getc(fp)) != EOF) {
- if (ch == '\0')
- continue;
- if (ch == '\n') {
- eol_cnt++;
- continue;
- }
- while (eol_cnt) {
- o_addchr(dest, '\n');
- eol_cnt--;
- }
- o_addQchr(dest, ch);
- }
- debug_printf("done reading from `cmd` pipe, closing it\n");
- fclose(fp);
-
- safe_waitpid(pid, &status, 0);
- debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
- return WEXITSTATUS(status);
- }
- #endif
- static void setup_heredoc(struct redir_struct *redir)
- {
- struct fd_pair pair;
- pid_t pid;
- int len, written;
-
- const char *heredoc = redir->rd_filename;
- char *expanded;
- #if !BB_MMU
- char **to_free;
- #endif
- expanded = NULL;
- if (!(redir->rd_dup & HEREDOC_QUOTED)) {
- expanded = encode_then_expand_string(heredoc);
- if (expanded)
- heredoc = expanded;
- }
- len = strlen(heredoc);
- close(redir->rd_fd);
- xpiped_pair(pair);
- xmove_fd(pair.rd, redir->rd_fd);
-
- ndelay_on(pair.wr);
- while (1) {
- written = write(pair.wr, heredoc, len);
- if (written <= 0)
- break;
- len -= written;
- if (len == 0) {
- close(pair.wr);
- free(expanded);
- return;
- }
- heredoc += written;
- }
- ndelay_off(pair.wr);
-
-
- #if !BB_MMU
- to_free = NULL;
- #endif
- pid = xvfork();
- if (pid == 0) {
-
- disable_restore_tty_pgrp_on_exit();
- pid = BB_MMU ? xfork() : xvfork();
- if (pid != 0)
- _exit(0);
-
- close(redir->rd_fd);
- #if BB_MMU
- full_write(pair.wr, heredoc, len);
- _exit(0);
- #else
-
- xmove_fd(pair.wr, STDOUT_FILENO);
- re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
- #endif
- }
-
- #if ENABLE_HUSH_FAST
- G.count_SIGCHLD++;
- #endif
- enable_restore_tty_pgrp_on_exit();
- #if !BB_MMU
- free(to_free);
- #endif
- close(pair.wr);
- free(expanded);
- wait(NULL);
- }
- struct squirrel {
- int orig_fd;
- int moved_to;
-
-
- };
- static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
- {
- sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
- sq[i].orig_fd = orig;
- sq[i].moved_to = moved;
- sq[i+1].orig_fd = -1;
- return sq;
- }
- static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
- {
- int moved_to;
- int i;
- i = 0;
- if (sq) for (; sq[i].orig_fd >= 0; i++) {
-
- if (fd == sq[i].moved_to) {
- moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
- debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, moved_to);
- if (moved_to < 0) {
-
- return NULL;
- }
- sq[i].moved_to = moved_to;
- return sq;
- }
- if (fd == sq[i].orig_fd) {
-
- debug_printf_redir("redirect_fd %d: already moved\n", fd);
- return sq;
- }
- }
-
- moved_to = dup_CLOEXEC(fd, avoid_fd);
- debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
- if (moved_to < 0 && errno != EBADF)
- return NULL;
- return append_squirrel(sq, i, fd, moved_to);
- }
- static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
- {
- int i;
- i = 0;
- if (sq) for (; sq[i].orig_fd >= 0; i++) {
-
- if (fd == sq[i].orig_fd) {
-
- debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
- return sq;
- }
- }
- debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
- return append_squirrel(sq, i, fd, -1);
- }
- static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
- {
- struct squirrel *new_squirrel;
- if (avoid_fd < 9)
- avoid_fd = 9;
- #if ENABLE_HUSH_INTERACTIVE
- if (fd != 0
- && fd == G_interactive_fd
- ) {
-
- G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
- debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
- return 1;
- }
- #endif
-
- if (sqp == NULL) {
-
-
- return 0;
- }
-
- if (move_HFILEs_on_redirect(fd, avoid_fd))
- return 1;
-
- if (sqp == ERR_PTR) {
-
-
- return 0;
- }
-
- new_squirrel = add_squirrel(*sqp, fd, avoid_fd);
- if (!new_squirrel)
- return -1;
- *sqp = new_squirrel;
- return 0;
- }
- static void restore_redirects(struct squirrel *sq)
- {
- if (sq) {
- int i;
- for (i = 0; sq[i].orig_fd >= 0; i++) {
- if (sq[i].moved_to >= 0) {
-
- debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
- xmove_fd(sq[i].moved_to, sq[i].orig_fd);
- } else {
-
- debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
- close(sq[i].orig_fd);
- }
- }
- free(sq);
- }
- if (G.HFILE_stdin
- && G.HFILE_stdin->fd > STDIN_FILENO
-
- ) {
-
- debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
- xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
- G.HFILE_stdin->fd = STDIN_FILENO;
- }
-
- }
- #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
- static void close_saved_fds_and_FILE_fds(void)
- {
- if (G_interactive_fd)
- close(G_interactive_fd);
- close_all_HFILE_list();
- }
- #endif
- static int internally_opened_fd(int fd, struct squirrel *sq)
- {
- int i;
- #if ENABLE_HUSH_INTERACTIVE
- if (fd == G_interactive_fd)
- return 1;
- #endif
-
- if (fd_in_HFILEs(fd))
- return 1;
- if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
- if (fd == sq[i].moved_to)
- return 1;
- }
- return 0;
- }
- static int setup_redirects(struct command *prog, struct squirrel **sqp)
- {
- struct redir_struct *redir;
- for (redir = prog->redirects; redir; redir = redir->next) {
- int newfd;
- int closed;
- if (redir->rd_type == REDIRECT_HEREDOC2) {
-
- if (save_fd_on_redirect(redir->rd_fd, 0, sqp) < 0)
- return 1;
-
- debug_printf_redir("set heredoc '%s'\n",
- redir->rd_filename);
- setup_heredoc(redir);
- continue;
- }
- if (redir->rd_dup == REDIRFD_TO_FILE) {
-
- char *p;
- int mode;
- if (redir->rd_filename == NULL) {
-
- syntax_error("invalid redirect");
- return 1;
- }
- mode = redir_table[redir->rd_type].mode;
- p = expand_string_to_string(redir->rd_filename,
- EXP_FLAG_ESC_GLOB_CHARS, 1);
- newfd = open_or_warn(p, mode);
- free(p);
- if (newfd < 0) {
-
- return 1;
- }
- if (newfd == redir->rd_fd && sqp
- && sqp != ERR_PTR
- ) {
-
- *sqp = add_squirrel_closed(*sqp, newfd);
- debug_printf_redir("redir to previously closed fd %d\n", newfd);
- }
- } else {
-
- newfd = redir->rd_dup;
- }
- if (newfd == redir->rd_fd)
- continue;
-
-
-
- closed = save_fd_on_redirect(redir->rd_fd, newfd, sqp);
- if (closed < 0)
- return 1;
- if (newfd == REDIRFD_CLOSE) {
-
- if (!closed) {
-
- close(redir->rd_fd);
- }
-
- } else {
-
- if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
- bb_error_msg("fd#%d is not open", newfd);
- return 1;
- }
- if (dup2(newfd, redir->rd_fd) < 0) {
-
- bb_perror_msg("dup2(%d,%d)", newfd, redir->rd_fd);
- return 1;
- }
- if (redir->rd_dup == REDIRFD_TO_FILE)
-
- close(newfd);
-
- }
- }
- return 0;
- }
- static char *find_in_PATH(const char *name)
- {
- char *p = (char*) get_local_var_value("PATH");
- if (!p)
- return NULL;
- while (1) {
- const char *end = strchrnul(p, ':');
- int sz = end - p;
- if (sz != 0) {
- p = xasprintf("%.*s/%s", sz, p, name);
- } else {
-
- p = xstrdup(name);
- }
- if (access(p, F_OK) == 0)
- return p;
- free(p);
- if (*end == '\0')
- return NULL;
- p = (char *) end + 1;
- }
- }
- #if ENABLE_HUSH_TYPE || ENABLE_HUSH_COMMAND
- static char *find_executable_in_PATH(const char *name)
- {
- const char *PATH;
- if (strchr(name, '/')) {
-
- if (file_is_executable(name))
- return xstrdup(name);
- return NULL;
- }
- PATH = get_local_var_value("PATH");
- return find_executable(name, &PATH);
- }
- #endif
- static const struct built_in_command *find_builtin_helper(const char *name,
- const struct built_in_command *x,
- const struct built_in_command *end)
- {
- while (x != end) {
- if (strcmp(name, x->b_cmd) != 0) {
- x++;
- continue;
- }
- debug_printf_exec("found builtin '%s'\n", name);
- return x;
- }
- return NULL;
- }
- static const struct built_in_command *find_builtin1(const char *name)
- {
- return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
- }
- static const struct built_in_command *find_builtin(const char *name)
- {
- const struct built_in_command *x = find_builtin1(name);
- if (x)
- return x;
- return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
- }
- #if ENABLE_HUSH_JOB && ENABLE_FEATURE_TAB_COMPLETION
- static const char * FAST_FUNC hush_command_name(int i)
- {
- if ( i < ARRAY_SIZE(bltins1)) {
- return bltins1[i].b_cmd;
- }
- i -= ARRAY_SIZE(bltins1);
- if (i < ARRAY_SIZE(bltins2)) {
- return bltins2[i].b_cmd;
- }
- # if ENABLE_HUSH_FUNCTIONS
- {
- struct function *funcp;
- i -= ARRAY_SIZE(bltins2);
- for (funcp = G.top_func; funcp; funcp = funcp->next) {
- if (--i < 0)
- return funcp->name;
- }
- }
- # endif
- return NULL;
- }
- #endif
- static void remove_nested_vars(void)
- {
- struct variable *cur;
- struct variable **cur_pp;
- cur_pp = &G.top_var;
- while ((cur = *cur_pp) != NULL) {
- if (cur->var_nest_level <= G.var_nest_level) {
- cur_pp = &cur->next;
- continue;
- }
-
- if (cur->flg_export) {
- debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
- bb_unsetenv(cur->varstr);
- }
-
- *cur_pp = cur->next;
-
- if (!cur->max_len) {
- debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
- free(cur->varstr);
- }
- free(cur);
- }
- }
- static void enter_var_nest_level(void)
- {
- G.var_nest_level++;
- debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
-
- if (G.var_nest_level > 0xff00)
- bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
- }
- static void leave_var_nest_level(void)
- {
- G.var_nest_level--;
- debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
- if (HUSH_DEBUG && (int)G.var_nest_level < 0)
- bb_simple_error_msg_and_die("BUG: nesting underflow");
- remove_nested_vars();
- }
- #if ENABLE_HUSH_FUNCTIONS
- static struct function **find_function_slot(const char *name)
- {
- struct function *funcp;
- struct function **funcpp = &G.top_func;
- while ((funcp = *funcpp) != NULL) {
- if (strcmp(name, funcp->name) == 0) {
- debug_printf_exec("found function '%s'\n", name);
- break;
- }
- funcpp = &funcp->next;
- }
- return funcpp;
- }
- static ALWAYS_INLINE const struct function *find_function(const char *name)
- {
- const struct function *funcp = *find_function_slot(name);
- return funcp;
- }
- static struct function *new_function(char *name)
- {
- struct function **funcpp = find_function_slot(name);
- struct function *funcp = *funcpp;
- if (funcp != NULL) {
- struct command *cmd = funcp->parent_cmd;
- debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
- if (!cmd) {
- debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
- free(funcp->name);
-
- if (funcp->body) {
- free_pipe_list(funcp->body);
- # if !BB_MMU
- free(funcp->body_as_string);
- # endif
- }
- } else {
- debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
- cmd->argv[0] = funcp->name;
- cmd->group = funcp->body;
- # if !BB_MMU
- cmd->group_as_string = funcp->body_as_string;
- # endif
- }
- } else {
- debug_printf_exec("remembering new function '%s'\n", name);
- funcp = *funcpp = xzalloc(sizeof(*funcp));
-
- }
- funcp->name = name;
- return funcp;
- }
- # if ENABLE_HUSH_UNSET
- static void unset_func(const char *name)
- {
- struct function **funcpp = find_function_slot(name);
- struct function *funcp = *funcpp;
- if (funcp != NULL) {
- debug_printf_exec("freeing function '%s'\n", funcp->name);
- *funcpp = funcp->next;
-
- if (funcp->body) {
- free_pipe_list(funcp->body);
- free(funcp->name);
- # if !BB_MMU
- free(funcp->body_as_string);
- # endif
- }
- free(funcp);
- }
- }
- # endif
- # if BB_MMU
- #define exec_function(to_free, funcp, argv) \
- exec_function(funcp, argv)
- # endif
- static void exec_function(char ***to_free,
- const struct function *funcp,
- char **argv) NORETURN;
- static void exec_function(char ***to_free,
- const struct function *funcp,
- char **argv)
- {
- # if BB_MMU
- int n;
- argv[0] = G.global_argv[0];
- G.global_argv = argv;
- G.global_argc = n = 1 + string_array_len(argv + 1);
-
- G_flag_return_in_progress = -1;
- enter_var_nest_level();
- IF_HUSH_LOCAL(G.func_nest_level++;)
-
- n = run_list(funcp->body);
- _exit(n);
- # else
- re_execute_shell(to_free,
- funcp->body_as_string,
- G.global_argv[0],
- argv + 1,
- NULL);
- # endif
- }
- static int run_function(const struct function *funcp, char **argv)
- {
- int rc;
- save_arg_t sv;
- smallint sv_flg;
- save_and_replace_G_args(&sv, argv);
-
- sv_flg = G_flag_return_in_progress;
- G_flag_return_in_progress = -1;
-
- IF_HUSH_LOCAL(enter_var_nest_level();)
- IF_HUSH_LOCAL(G.func_nest_level++;)
-
- # if !BB_MMU
- if (!funcp->body) {
-
- parse_and_run_string(funcp->body_as_string);
- rc = G.last_exitcode;
- } else
- # endif
- {
- rc = run_list(funcp->body);
- }
- IF_HUSH_LOCAL(G.func_nest_level--;)
- IF_HUSH_LOCAL(leave_var_nest_level();)
- G_flag_return_in_progress = sv_flg;
- # if ENABLE_HUSH_TRAP
- debug_printf_exec("G.return_exitcode=-1\n");
- G.return_exitcode = -1;
- # endif
- restore_G_args(&sv, argv);
- return rc;
- }
- #endif
- #if BB_MMU
- #define exec_builtin(to_free, x, argv) \
- exec_builtin(x, argv)
- #else
- #define exec_builtin(to_free, x, argv) \
- exec_builtin(to_free, argv)
- #endif
- static void exec_builtin(char ***to_free,
- const struct built_in_command *x,
- char **argv) NORETURN;
- static void exec_builtin(char ***to_free,
- const struct built_in_command *x,
- char **argv)
- {
- #if BB_MMU
- int rcode;
- rcode = x->b_function(argv);
- fflush_all();
- _exit(rcode);
- #else
- fflush_all();
-
- re_execute_shell(to_free,
- argv[0],
- G.global_argv[0],
- G.global_argv + 1,
- argv);
- #endif
- }
- static void execvp_or_die(char **argv) NORETURN;
- static void execvp_or_die(char **argv)
- {
- int e;
- debug_printf_exec("execing '%s'\n", argv[0]);
-
- if (SPECIAL_JOBSTOP_SIGS != 0)
- switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
- execvp(argv[0], argv);
- e = 2;
- if (errno == EACCES) e = 126;
- if (errno == ENOENT) e = 127;
- bb_perror_msg("can't execute '%s'", argv[0]);
- _exit(e);
- }
- #if ENABLE_HUSH_MODE_X
- static void x_mode_print_optionally_squoted(const char *str)
- {
- unsigned len;
- const char *cp;
- cp = str;
-
-
- if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
- " " "\001\002\003\004\005\006\007"
- "\010\011\012\013\014\015\016\017"
- "\020\021\022\023\024\025\026\027"
- "\030\031\032\033\034\035\036\037"
- )
- ] == '\0'
- ) {
-
- x_mode_addstr(str);
- return;
- }
- cp = str;
- for (;;) {
-
- len = (int)(strchrnul(cp, '\'') - cp);
- if (len != 0) {
- x_mode_addchr('\'');
- x_mode_addblock(cp, len);
- x_mode_addchr('\'');
- cp += len;
- }
- if (*cp == '\0')
- break;
-
- x_mode_addchr('\\');
- x_mode_addchr('\'');
- cp++;
- }
- }
- static void dump_cmd_in_x_mode(char **argv)
- {
- if (G_x_mode && argv) {
- unsigned n;
-
- x_mode_prefix();
- n = 0;
- while (argv[n]) {
- x_mode_addchr(' ');
- if (argv[n][0] == '\0') {
- x_mode_addchr('\'');
- x_mode_addchr('\'');
- } else {
- x_mode_print_optionally_squoted(argv[n]);
- }
- n++;
- }
- x_mode_flush();
- }
- }
- #else
- # define dump_cmd_in_x_mode(argv) ((void)0)
- #endif
- #if ENABLE_HUSH_COMMAND
- static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
- {
- char *to_free;
- if (!opt_vV)
- return;
- to_free = NULL;
- if (!explanation) {
- explanation = to_free = find_executable_in_PATH(cmd);
- if (!explanation) {
- bb_error_msg("%s: %s: not found", "command", cmd);
- _exit(1);
- }
- if (opt_vV != 'V')
- cmd = to_free;
- }
- printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
- free(to_free);
- fflush_all();
- _exit(0);
- }
- #else
- # define if_command_vV_print_and_exit(a,b,c) ((void)0)
- #endif
- #if BB_MMU
- #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
- pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
- #define pseudo_exec(nommu_save, command, argv_expanded) \
- pseudo_exec(command, argv_expanded)
- #endif
- static void pseudo_exec_argv(nommu_save_t *nommu_save,
- char **argv, int assignment_cnt,
- char **argv_expanded) NORETURN;
- static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
- char **argv, int assignment_cnt,
- char **argv_expanded)
- {
- const struct built_in_command *x;
- struct variable **sv_shadowed;
- char **new_env;
- IF_HUSH_COMMAND(char opt_vV = 0;)
- IF_HUSH_FUNCTIONS(const struct function *funcp;)
- new_env = expand_assignments(argv, assignment_cnt);
- dump_cmd_in_x_mode(new_env);
- if (!argv[assignment_cnt]) {
-
- free_strings(new_env);
- _exit_SUCCESS();
- }
- sv_shadowed = G.shadowed_vars_pp;
- #if BB_MMU
- G.shadowed_vars_pp = NULL;
- #else
- G.shadowed_vars_pp = &nommu_save->old_vars;
- G.var_nest_level++;
- #endif
- set_vars_and_save_old(new_env);
- G.shadowed_vars_pp = sv_shadowed;
- if (argv_expanded) {
- argv = argv_expanded;
- } else {
- argv = expand_strvec_to_strvec(argv + assignment_cnt);
- #if !BB_MMU
- nommu_save->argv = argv;
- #endif
- }
- dump_cmd_in_x_mode(argv);
- #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
- if (strchr(argv[0], '/') != NULL)
- goto skip;
- #endif
- #if ENABLE_HUSH_FUNCTIONS
-
- funcp = find_function(argv[0]);
- if (funcp)
- exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
- #endif
- #if ENABLE_HUSH_COMMAND
-
- while (strcmp(argv[0], "command") == 0 && argv[1]) {
- char *p;
- argv++;
- p = *argv;
- if (p[0] != '-' || !p[1])
- continue;
- for (;;) {
- p++;
- switch (*p) {
- case '\0':
- argv++;
- p = *argv;
- if (p[0] != '-' || !p[1])
- goto after_opts;
- continue;
- case 'v':
- case 'V':
- opt_vV = *p;
- continue;
- default:
- bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
- }
- }
- }
- after_opts:
- # if ENABLE_HUSH_FUNCTIONS
- if (opt_vV && find_function(argv[0]))
- if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
- # endif
- #endif
-
-
- x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
- if (x) {
- if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
- exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
- }
- #if ENABLE_FEATURE_SH_STANDALONE
-
- {
- int a = find_applet_by_name(argv[0]);
- if (a >= 0) {
- if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
- # if BB_MMU
- if (APPLET_IS_NOEXEC(a)) {
-
- close_saved_fds_and_FILE_fds();
-
- switch_off_special_sigs(G.special_sig_mask);
- debug_printf_exec("running applet '%s'\n", argv[0]);
- run_noexec_applet_and_exit(a, argv[0], argv);
- }
- # endif
-
- debug_printf_exec("re-execing applet '%s'\n", argv[0]);
-
- if (SPECIAL_JOBSTOP_SIGS != 0)
- switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
- execv(bb_busybox_exec_path, argv);
-
- }
- }
- #endif
- #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
- skip:
- #endif
- if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
- execvp_or_die(argv);
- }
- static void pseudo_exec(nommu_save_t *nommu_save,
- struct command *command,
- char **argv_expanded) NORETURN;
- static void pseudo_exec(nommu_save_t *nommu_save,
- struct command *command,
- char **argv_expanded)
- {
- #if ENABLE_HUSH_FUNCTIONS
- if (command->cmd_type == CMD_FUNCDEF) {
-
- _exit(0);
- }
- #endif
- if (command->argv) {
- pseudo_exec_argv(nommu_save, command->argv,
- command->assignment_cnt, argv_expanded);
- }
- if (command->group) {
-
- #if BB_MMU
- int rcode;
- debug_printf_exec("pseudo_exec: run_list\n");
- reset_traps_to_defaults();
- rcode = run_list(command->group);
-
- _exit(rcode);
- #else
- re_execute_shell(&nommu_save->argv_from_re_execing,
- command->group_as_string,
- G.global_argv[0],
- G.global_argv + 1,
- NULL);
- #endif
- }
-
- debug_printf_exec("pseudo_exec'ed null command\n");
- _exit_SUCCESS();
- }
- #if ENABLE_HUSH_JOB
- static const char *get_cmdtext(struct pipe *pi)
- {
- char **argv;
- char *p;
- int len;
-
- if (pi->cmdtext)
- return pi->cmdtext;
- argv = pi->cmds[0].argv;
- if (!argv) {
- pi->cmdtext = xzalloc(1);
- return pi->cmdtext;
- }
- len = 0;
- do {
- len += strlen(*argv) + 1;
- } while (*++argv);
- p = xmalloc(len);
- pi->cmdtext = p;
- argv = pi->cmds[0].argv;
- do {
- p = stpcpy(p, *argv);
- *p++ = ' ';
- } while (*++argv);
- p[-1] = '\0';
- return pi->cmdtext;
- }
- static void remove_job_from_table(struct pipe *pi)
- {
- struct pipe *prev_pipe;
- if (pi == G.job_list) {
- G.job_list = pi->next;
- } else {
- prev_pipe = G.job_list;
- while (prev_pipe->next != pi)
- prev_pipe = prev_pipe->next;
- prev_pipe->next = pi->next;
- }
- G.last_jobid = 0;
- if (G.job_list)
- G.last_jobid = G.job_list->jobid;
- }
- static void delete_finished_job(struct pipe *pi)
- {
- remove_job_from_table(pi);
- free_pipe(pi);
- }
- static void clean_up_last_dead_job(void)
- {
- if (G.job_list && !G.job_list->alive_cmds)
- delete_finished_job(G.job_list);
- }
- static void insert_job_into_table(struct pipe *pi)
- {
- struct pipe *job, **jobp;
- int i;
- clean_up_last_dead_job();
-
- i = 0;
- jobp = &G.job_list;
- while ((job = *jobp) != NULL) {
- if (job->jobid > i)
- i = job->jobid;
- jobp = &job->next;
- }
- pi->jobid = i + 1;
-
- job = *jobp = xmemdup(pi, sizeof(*pi));
- job->next = NULL;
- job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
-
- for (i = 0; i < pi->num_cmds; i++) {
- job->cmds[i].pid = pi->cmds[i].pid;
-
- }
- job->cmdtext = xstrdup(get_cmdtext(pi));
- if (G_interactive_fd)
- printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
- G.last_jobid = job->jobid;
- }
- #endif
- static int job_exited_or_stopped(struct pipe *pi)
- {
- int rcode, i;
- if (pi->alive_cmds != pi->stopped_cmds)
- return -1;
-
- rcode = 0;
- i = pi->num_cmds;
- while (--i >= 0) {
- rcode = pi->cmds[i].cmd_exitcode;
-
- if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
- break;
- }
- IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
- return rcode;
- }
- static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
- {
- #if ENABLE_HUSH_JOB
- struct pipe *pi;
- #endif
- int i, dead;
- dead = WIFEXITED(status) || WIFSIGNALED(status);
- #if DEBUG_JOBS
- if (WIFSTOPPED(status))
- debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
- childpid, WSTOPSIG(status), WEXITSTATUS(status));
- if (WIFSIGNALED(status))
- debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
- childpid, WTERMSIG(status), WEXITSTATUS(status));
- if (WIFEXITED(status))
- debug_printf_jobs("pid %d exited, exitcode %d\n",
- childpid, WEXITSTATUS(status));
- #endif
-
- if (fg_pipe) {
- i = fg_pipe->num_cmds;
- while (--i >= 0) {
- int rcode;
- debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
- if (fg_pipe->cmds[i].pid != childpid)
- continue;
- if (dead) {
- int ex;
- fg_pipe->cmds[i].pid = 0;
- fg_pipe->alive_cmds--;
- ex = WEXITSTATUS(status);
-
- if (WIFSIGNALED(status)) {
- int sig = WTERMSIG(status);
- #if ENABLE_HUSH_JOB
- if (G.run_list_level == 1
-
- && i == fg_pipe->num_cmds-1
- ) {
-
- puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
- }
- #endif
-
-
- ex = 128 | sig;
- }
- fg_pipe->cmds[i].cmd_exitcode = ex;
- } else {
- fg_pipe->stopped_cmds++;
- }
- debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
- fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
- rcode = job_exited_or_stopped(fg_pipe);
- if (rcode >= 0) {
- if (G_interactive_fd) {
- #if ENABLE_HUSH_JOB
- if (fg_pipe->alive_cmds != 0)
- insert_job_into_table(fg_pipe);
- #endif
- return rcode;
- }
- if (fg_pipe->alive_cmds == 0)
- return rcode;
- }
-
- return -1;
- }
-
- }
- #if ENABLE_HUSH_JOB
-
-
- for (pi = G.job_list; pi; pi = pi->next) {
- for (i = 0; i < pi->num_cmds; i++) {
- if (pi->cmds[i].pid == childpid)
- goto found_pi_and_prognum;
- }
- }
-
- debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
- return -1;
- found_pi_and_prognum:
- if (dead) {
-
- int rcode = WEXITSTATUS(status);
- if (WIFSIGNALED(status))
-
- rcode = 128 | WTERMSIG(status);
- pi->cmds[i].cmd_exitcode = rcode;
- if (G.last_bg_pid == pi->cmds[i].pid)
- G.last_bg_pid_exitcode = rcode;
- pi->cmds[i].pid = 0;
- pi->alive_cmds--;
- if (!pi->alive_cmds) {
- # if ENABLE_HUSH_BASH_COMPAT
- G.dead_job_exitcode = job_exited_or_stopped(pi);
- # endif
- if (G_interactive_fd) {
- printf(JOB_STATUS_FORMAT, pi->jobid,
- "Done", pi->cmdtext);
- delete_finished_job(pi);
- } else {
- if (pi != G.job_list)
- delete_finished_job(pi);
- }
- }
- } else {
-
- pi->stopped_cmds++;
- }
- #endif
- return -1;
- }
- static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
- {
- int attributes;
- int status;
- int rcode = 0;
- debug_printf_jobs("checkjobs %p\n", fg_pipe);
- attributes = WUNTRACED;
- if (fg_pipe == NULL)
- attributes |= WNOHANG;
- errno = 0;
- #if ENABLE_HUSH_FAST
- if (G.handled_SIGCHLD == G.count_SIGCHLD) {
-
-
- if (!G.we_have_children) {
- errno = ECHILD;
- return -1;
- }
- if (fg_pipe == NULL) {
-
- return 0;
- }
-
- }
- #endif
- while (1) {
- pid_t childpid;
- #if ENABLE_HUSH_FAST
- int i;
- i = G.count_SIGCHLD;
- #endif
- childpid = waitpid(-1, &status, attributes);
- if (childpid <= 0) {
- if (childpid && errno != ECHILD)
- bb_simple_perror_msg("waitpid");
- #if ENABLE_HUSH_FAST
- else {
- G.we_have_children = (childpid == 0);
- G.handled_SIGCHLD = i;
- }
- #endif
-
- rcode = childpid;
- break;
- }
- rcode = process_wait_result(fg_pipe, childpid, status);
- if (rcode >= 0) {
-
- break;
- }
- if (childpid == waitfor_pid) {
- debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
- rcode = WEXITSTATUS(status);
- if (WIFSIGNALED(status))
- rcode = 128 | WTERMSIG(status);
- if (WIFSTOPPED(status))
-
- rcode = 128 | WSTOPSIG(status);
- rcode++;
- break;
- }
- #if ENABLE_HUSH_BASH_COMPAT
- if (-1 == waitfor_pid
- && G.dead_job_exitcode >= 0
- ) {
- debug_printf_exec("waitfor_pid:-1\n");
- rcode = G.dead_job_exitcode + 1;
- break;
- }
- #endif
-
-
- }
- return rcode;
- }
- #if ENABLE_HUSH_JOB
- static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
- {
- pid_t p;
- int rcode = checkjobs(fg_pipe, 0 );
- if (G_saved_tty_pgrp) {
-
- p = getpgrp();
- debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
- tcsetpgrp(G_interactive_fd, p);
- }
- return rcode;
- }
- #endif
- static void set_G_ifs(void)
- {
-
- if (G.ifs_whitespace != G.ifs)
- free(G.ifs_whitespace);
- G.ifs = get_local_var_value("IFS");
- if (G.ifs) {
- char *p;
- G.ifs_whitespace = (char*)G.ifs;
- p = skip_whitespace(G.ifs);
- if (*p) {
-
- char *d;
- int len = p - G.ifs;
- p = skip_non_whitespace(p);
- G.ifs_whitespace = xmalloc(len + strlen(p) + 1);
- d = mempcpy(G.ifs_whitespace, G.ifs, len);
- while (*p) {
- if (isspace(*p))
- *d++ = *p;
- p++;
- }
- *d = '\0';
- }
- } else {
- G.ifs = defifs;
- G.ifs_whitespace = (char*)G.ifs;
- }
- }
- #if !ENABLE_HUSH_MODE_X
- #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
- redirect_and_varexp_helper(command, sqp)
- #endif
- static int redirect_and_varexp_helper(
- struct command *command,
- struct squirrel **sqp,
- char **argv_expanded)
- {
-
- char **new_env = expand_assignments(command->argv, command->assignment_cnt);
- dump_cmd_in_x_mode(new_env);
- dump_cmd_in_x_mode(argv_expanded);
-
- set_vars_and_save_old(new_env);
- return setup_redirects(command, sqp);
- }
- static NOINLINE int run_pipe(struct pipe *pi)
- {
- static const char *const null_ptr = NULL;
- int cmd_no;
- int next_infd;
- struct command *command;
- char **argv_expanded;
- char **argv;
- struct squirrel *squirrel = NULL;
- int rcode;
- debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
- debug_enter();
- set_G_ifs();
- IF_HUSH_JOB(pi->pgrp = -1;)
- pi->stopped_cmds = 0;
- command = &pi->cmds[0];
- argv_expanded = NULL;
- if (pi->num_cmds != 1
- || pi->followup == PIPE_BG
- || command->cmd_type == CMD_SUBSHELL
- ) {
- goto must_fork;
- }
- pi->alive_cmds = 1;
- debug_printf_exec(": group:%p argv:'%s'\n",
- command->group, command->argv ? command->argv[0] : "NONE");
- if (command->group) {
- #if ENABLE_HUSH_FUNCTIONS
- if (command->cmd_type == CMD_FUNCDEF) {
-
- struct function *funcp;
- funcp = new_function(command->argv[0]);
-
- funcp->body = command->group;
- # if !BB_MMU
- funcp->body_as_string = command->group_as_string;
- command->group_as_string = NULL;
- # endif
- command->group = NULL;
- command->argv[0] = NULL;
- debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
- funcp->parent_cmd = command;
- command->child_func = funcp;
- debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
- debug_leave();
- return EXIT_SUCCESS;
- }
- #endif
-
- debug_printf_exec("non-subshell group\n");
- rcode = 1;
- if (setup_redirects(command, &squirrel) == 0) {
- debug_printf_exec(": run_list\n");
- rcode = run_list(command->group) & 0xff;
- }
- restore_redirects(squirrel);
- IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
- debug_leave();
- debug_printf_exec("run_pipe: return %d\n", rcode);
- return rcode;
- }
- argv = command->argv ? command->argv : (char **) &null_ptr;
- {
- const struct built_in_command *x;
- IF_HUSH_FUNCTIONS(const struct function *funcp;)
- IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
- struct variable **sv_shadowed;
- struct variable *old_vars;
- #if ENABLE_HUSH_LINENO_VAR
- G.execute_lineno = command->lineno;
- #endif
- if (argv[command->assignment_cnt] == NULL) {
-
- unsigned i;
- G.expand_exitcode = 0;
- only_assignments:
- rcode = setup_redirects(command, &squirrel);
- restore_redirects(squirrel);
-
- i = 0;
- while (i < command->assignment_cnt) {
- char *p = expand_string_to_string(argv[i],
- EXP_FLAG_ESC_GLOB_CHARS,
- 1
- );
- #if ENABLE_HUSH_MODE_X
- if (G_x_mode) {
- char *eq;
- if (i == 0)
- x_mode_prefix();
- x_mode_addchr(' ');
- eq = strchrnul(p, '=');
- if (*eq) eq++;
- x_mode_addblock(p, (eq - p));
- x_mode_print_optionally_squoted(eq);
- x_mode_flush();
- }
- #endif
- debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
- if (set_local_var0(p)) {
-
- rcode = 1;
- }
- i++;
- }
-
- if (rcode == 0)
- rcode = G.expand_exitcode;
- IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
- debug_leave();
- debug_printf_exec("run_pipe: return %d\n", rcode);
- return rcode;
- }
-
- #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
- if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
- argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
- else
- #endif
- #if defined(CMD_SINGLEWORD_NOGLOB)
- if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
- argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
- else
- #endif
- argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
-
- if (!argv_expanded[0]) {
- free(argv_expanded);
-
- G.expand_exitcode = G.last_exitcode;
- goto only_assignments;
- }
- old_vars = NULL;
- sv_shadowed = G.shadowed_vars_pp;
-
- IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
- IF_HUSH_FUNCTIONS(x = NULL;)
- IF_HUSH_FUNCTIONS(if (!funcp))
- x = find_builtin(argv_expanded[0]);
- if (x || funcp) {
- if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
- debug_printf("exec with redirects only\n");
-
- enter_var_nest_level();
- G.shadowed_vars_pp = &old_vars;
- rcode = redirect_and_varexp_helper(command,
- ERR_PTR,
- argv_expanded
- );
- G.shadowed_vars_pp = sv_shadowed;
-
- goto clean_up_and_ret1;
- }
-
- enter_var_nest_level();
-
- G.shadowed_vars_pp = &old_vars;
- rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
- if (rcode == 0) {
- if (!funcp) {
-
- G.shadowed_vars_pp = sv_shadowed;
- debug_printf_exec(": builtin '%s' '%s'...\n",
- x->b_cmd, argv_expanded[1]);
- fflush_all();
- rcode = x->b_function(argv_expanded) & 0xff;
- fflush_all();
- }
- #if ENABLE_HUSH_FUNCTIONS
- else {
- debug_printf_exec(": function '%s' '%s'...\n",
- funcp->name, argv_expanded[1]);
- rcode = run_function(funcp, argv_expanded) & 0xff;
-
- G.shadowed_vars_pp = sv_shadowed;
- }
- #endif
- }
- } else
- if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
- int n = find_applet_by_name(argv_expanded[0]);
- if (n < 0 || !APPLET_IS_NOFORK(n))
- goto must_fork;
- enter_var_nest_level();
-
- G.shadowed_vars_pp = &old_vars;
- rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
- G.shadowed_vars_pp = sv_shadowed;
- if (rcode == 0) {
- debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
- argv_expanded[0], argv_expanded[1]);
-
- rcode = run_nofork_applet(n, argv_expanded);
- }
- } else
- goto must_fork;
- restore_redirects(squirrel);
- clean_up_and_ret1:
- leave_var_nest_level();
- add_vars(old_vars);
-
- if (!funcp) {
-
- if (sigismember(&G.pending_set, SIGINT))
- rcode = 128 | SIGINT;
- }
- free(argv_expanded);
- IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
- debug_leave();
- debug_printf_exec("run_pipe return %d\n", rcode);
- return rcode;
- }
- must_fork:
-
-
- pi->alive_cmds = 0;
- next_infd = 0;
- cmd_no = 0;
- while (cmd_no < pi->num_cmds) {
- struct fd_pair pipefds;
- #if !BB_MMU
- int sv_var_nest_level = G.var_nest_level;
- volatile nommu_save_t nommu_save;
- nommu_save.old_vars = NULL;
- nommu_save.argv = NULL;
- nommu_save.argv_from_re_execing = NULL;
- #endif
- command = &pi->cmds[cmd_no];
- cmd_no++;
- if (command->argv) {
- debug_printf_exec(": pipe member '%s' '%s'...\n",
- command->argv[0], command->argv[1]);
- } else {
- debug_printf_exec(": pipe member with no argv\n");
- }
-
- pipefds.rd = 0;
- pipefds.wr = 1;
- if (cmd_no < pi->num_cmds)
- xpiped_pair(pipefds);
- #if ENABLE_HUSH_LINENO_VAR
- G.execute_lineno = command->lineno;
- #endif
- command->pid = BB_MMU ? fork() : vfork();
- if (!command->pid) {
- #if ENABLE_HUSH_JOB
- disable_restore_tty_pgrp_on_exit();
- CLEAR_RANDOM_T(&G.random_gen);
-
- if (G.run_list_level == 1 && G_interactive_fd) {
- pid_t pgrp;
- pgrp = pi->pgrp;
- if (pgrp < 0)
- pgrp = getpid();
- if (setpgid(0, pgrp) == 0
- && pi->followup != PIPE_BG
- && G_saved_tty_pgrp
- ) {
-
- tcsetpgrp(G_interactive_fd, pgrp);
- }
- }
- #endif
- if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
-
- close(0);
- if (open(bb_dev_null, O_RDONLY))
- xopen("/", O_RDONLY);
- } else {
- xmove_fd(next_infd, 0);
- }
- xmove_fd(pipefds.wr, 1);
- if (pipefds.rd > 1)
- close(pipefds.rd);
-
- if (setup_redirects(command, NULL)) {
-
- _exit(1);
- }
-
-
- pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
-
- }
-
- #if ENABLE_HUSH_FAST
- G.count_SIGCHLD++;
- #endif
- enable_restore_tty_pgrp_on_exit();
- #if !BB_MMU
-
- free(nommu_save.argv);
- free(nommu_save.argv_from_re_execing);
- G.var_nest_level = sv_var_nest_level;
- remove_nested_vars();
- add_vars(nommu_save.old_vars);
- #endif
- free(argv_expanded);
- argv_expanded = NULL;
- if (command->pid < 0) {
-
- bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
- } else {
- pi->alive_cmds++;
- #if ENABLE_HUSH_JOB
-
- if (pi->pgrp < 0)
- pi->pgrp = command->pid;
- #endif
- }
- if (cmd_no > 1)
- close(next_infd);
- if (cmd_no < pi->num_cmds)
- close(pipefds.wr);
-
- next_infd = pipefds.rd;
- }
- if (!pi->alive_cmds) {
- debug_leave();
- debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
- return 1;
- }
- debug_leave();
- debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
- return -1;
- }
- static int run_list(struct pipe *pi)
- {
- #if ENABLE_HUSH_CASE
- char *case_word = NULL;
- #endif
- #if ENABLE_HUSH_LOOPS
- struct pipe *loop_top = NULL;
- char **for_lcur = NULL;
- char **for_list = NULL;
- #endif
- smallint last_followup;
- smalluint rcode;
- #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
- smalluint cond_code = 0;
- #else
- enum { cond_code = 0 };
- #endif
- #if HAS_KEYWORDS
- smallint rword;
- smallint last_rword;
- #endif
- debug_printf_exec("run_list lvl %d start\n", G.run_list_level);
- debug_enter();
- set_G_ifs();
- #if ENABLE_HUSH_LOOPS
-
- {
- struct pipe *cpipe;
- for (cpipe = pi; cpipe; cpipe = cpipe->next) {
- if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
- continue;
-
- if (cpipe->next == NULL) {
- syntax_error("malformed for");
- debug_leave();
- debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
- return 1;
- }
-
- if (cpipe->next->res_word == RES_DO)
- continue;
-
- if (cpipe->res_word == RES_IN
- || cpipe->next->res_word != RES_IN
- ) {
- syntax_error("malformed for");
- debug_leave();
- debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
- return 1;
- }
- }
- }
- #endif
-
- #if ENABLE_HUSH_JOB
- G.run_list_level++;
- #endif
- #if HAS_KEYWORDS
- rword = RES_NONE;
- last_rword = RES_XXXX;
- #endif
- last_followup = PIPE_SEQ;
- rcode = G.last_exitcode;
-
- for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
- int r;
- int sv_errexit_depth;
- if (G.flag_SIGINT)
- break;
- if (G_flag_return_in_progress == 1)
- break;
- IF_HAS_KEYWORDS(rword = pi->res_word;)
- debug_printf_exec(": rword:%d cond_code:%d last_rword:%d\n",
- rword, cond_code, last_rword);
- sv_errexit_depth = G.errexit_depth;
- if (
- #if ENABLE_HUSH_IF
- rword == RES_IF || rword == RES_ELIF ||
- #endif
- pi->followup != PIPE_SEQ
- ) {
- G.errexit_depth++;
- }
- #if ENABLE_HUSH_LOOPS
- if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
- && loop_top == NULL
- ) {
-
- loop_top = pi;
- G.depth_of_loop++;
- }
- #endif
-
- if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
- if ((rcode == 0 && last_followup == PIPE_OR)
- || (rcode != 0 && last_followup == PIPE_AND)
- ) {
-
- debug_printf_exec("skipped cmd because of || or &&\n");
- last_followup = pi->followup;
- goto dont_check_jobs_but_continue;
- }
- }
- last_followup = pi->followup;
- #if ENABLE_HUSH_IF
- if (cond_code != 0) {
- if (rword == RES_THEN) {
-
- G.last_exitcode = rcode = EXIT_SUCCESS;
-
- debug_printf_exec("skipped THEN cmd because IF condition was false\n");
- last_rword = rword;
- continue;
- }
- } else {
- if (rword == RES_ELSE
- || (rword == RES_ELIF && last_rword != RES_ELIF)
- ) {
-
- debug_printf_exec("skipped ELSE/ELIF branch because IF condition was true\n");
- break;
- }
-
- }
- #endif
- IF_HAS_KEYWORDS(last_rword = rword;)
- #if ENABLE_HUSH_LOOPS
- if (rword == RES_FOR) {
- if (!for_lcur) {
-
- static const char encoded_dollar_at[] ALIGN1 = {
- SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
- };
- static const char *const encoded_dollar_at_argv[] ALIGN_PTR = {
- encoded_dollar_at, NULL
- };
- char **vals;
- G.last_exitcode = rcode = EXIT_SUCCESS;
- vals = (char**)encoded_dollar_at_argv;
- if (pi->next->res_word == RES_IN) {
-
- if (!pi->next->cmds[0].argv) {
- debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
- break;
- }
- vals = pi->next->cmds[0].argv;
- }
-
- debug_print_strings("for_list made from", vals);
- for_list = expand_strvec_to_strvec(vals);
- for_lcur = for_list;
- debug_print_strings("for_list", for_list);
- }
- if (!*for_lcur) {
-
- free(for_list);
- for_list = NULL;
- for_lcur = NULL;
- break;
- }
-
-
- set_local_var_from_halves(pi->cmds[0].argv[0], *for_lcur++);
- continue;
- }
- if (rword == RES_IN) {
- continue;
- }
- if (rword == RES_DONE) {
- continue;
- }
- #endif
- #if ENABLE_HUSH_CASE
- if (rword == RES_CASE) {
- debug_printf_exec("CASE cond_code:%d\n", cond_code);
- case_word = expand_string_to_string(pi->cmds->argv[0],
- EXP_FLAG_ESC_GLOB_CHARS, 1);
- debug_printf_exec("CASE word1:'%s'\n", case_word);
-
-
- continue;
- }
- if (rword == RES_MATCH) {
- char **argv;
- debug_printf_exec("MATCH cond_code:%d\n", cond_code);
- if (!case_word)
- break;
-
- argv = pi->cmds->argv;
- while (*argv) {
- char *pattern;
- debug_printf_exec("expand_string_to_string('%s')\n", *argv);
- pattern = expand_string_to_string(*argv,
- EXP_FLAG_ESC_GLOB_CHARS,
- 0
- );
-
- cond_code = (fnmatch(pattern, case_word, 0) != 0);
- debug_printf_exec("cond_code=fnmatch(pattern:'%s',str:'%s'):%d\n",
- pattern, case_word, cond_code);
- free(pattern);
- if (cond_code == 0) {
-
- free(case_word);
- case_word = NULL;
- break;
- }
- argv++;
- }
- continue;
- }
- if (rword == RES_CASE_BODY) {
- debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
- if (cond_code != 0)
- continue;
- }
- if (rword == RES_ESAC) {
- debug_printf_exec("ESAC cond_code:%d\n", cond_code);
- if (case_word) {
-
- G.last_exitcode = rcode = EXIT_SUCCESS;
- }
- }
- #endif
-
- if (pi->num_cmds == 0) {
- if (G_interactive_fd)
- goto check_jobs_and_continue;
- continue;
- }
-
- debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
- #if ENABLE_HUSH_LOOPS
- G.flag_break_continue = 0;
- #endif
- rcode = r = G.o_opt[OPT_O_NOEXEC] ? 0 : run_pipe(pi);
-
- if (r != -1) {
-
- debug_printf_exec(": builtin/func exitcode %d\n", rcode);
- G.last_exitcode = rcode;
- check_and_run_traps();
- #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
- rcode = G.last_exitcode;
- #endif
- #if ENABLE_HUSH_LOOPS
-
- if (G.flag_break_continue) {
- smallint fbc = G.flag_break_continue;
-
- if (loop_top) {
- G.depth_break_continue--;
- if (G.depth_break_continue == 0)
- G.flag_break_continue = 0;
-
- }
- if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
- checkjobs(NULL, 0 );
- break;
- }
-
- rword = RES_DONE;
- continue;
- }
- #endif
- if (G_flag_return_in_progress == 1) {
- checkjobs(NULL, 0 );
- break;
- }
- } else if (pi->followup == PIPE_BG) {
-
-
- #if ENABLE_HUSH_JOB
- if (G.run_list_level == 1)
- insert_job_into_table(pi);
- #endif
-
- G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
- G.last_bg_pid_exitcode = 0;
- debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
- rcode = EXIT_SUCCESS;
- goto check_traps;
- } else {
- #if ENABLE_HUSH_JOB
- if (G.run_list_level == 1 && G_interactive_fd) {
-
- rcode = checkjobs_and_fg_shell(pi);
- debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
- goto check_traps;
- }
- #endif
-
- rcode = checkjobs(pi, 0 );
- debug_printf_exec(": checkjobs exitcode %d\n", rcode);
- check_traps:
- G.last_exitcode = rcode;
- check_and_run_traps();
- #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
- rcode = G.last_exitcode;
- #endif
- }
-
- if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
- debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
- if (G.errexit_depth == 0)
- hush_exit(rcode);
- }
- G.errexit_depth = sv_errexit_depth;
-
- #if ENABLE_HUSH_IF
- if (rword == RES_IF || rword == RES_ELIF) {
- debug_printf_exec("cond_code=rcode:%d\n", rcode);
- cond_code = rcode;
- }
- #endif
- check_jobs_and_continue:
- checkjobs(NULL, 0 );
- dont_check_jobs_but_continue: ;
- #if ENABLE_HUSH_LOOPS
-
- if (pi->next
- && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
-
- ) {
- if (rword == RES_WHILE) {
- if (rcode) {
-
- G.last_exitcode = rcode = EXIT_SUCCESS;
- debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
- break;
- }
- }
- if (rword == RES_UNTIL) {
- if (!rcode) {
- debug_printf_exec(": until expr is true: breaking\n");
- break;
- }
- }
- }
- #endif
- }
- #if ENABLE_HUSH_JOB
- G.run_list_level--;
- #endif
- #if ENABLE_HUSH_LOOPS
- if (loop_top)
- G.depth_of_loop--;
- free(for_list);
- #endif
- #if ENABLE_HUSH_CASE
- free(case_word);
- #endif
- debug_leave();
- debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level, rcode);
- return rcode;
- }
- static int run_and_free_list(struct pipe *pi)
- {
- int rcode = 0;
- debug_printf_exec("run_and_free_list entered\n");
- if (!G.o_opt[OPT_O_NOEXEC]) {
- debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
- rcode = run_list(pi);
- }
-
- free_pipe_list(pi);
- debug_printf_exec("run_and_free_list return %d\n", rcode);
- return rcode;
- }
- static void install_sighandlers(unsigned mask)
- {
- sighandler_t old_handler;
- unsigned sig = 0;
- while ((mask >>= 1) != 0) {
- sig++;
- if (!(mask & 1))
- continue;
- old_handler = install_sighandler(sig, pick_sighandler(sig));
-
- if (sig == SIGCHLD)
- continue;
-
- if (sig == SIGHUP && G_interactive_fd)
- continue;
-
- if (old_handler == SIG_IGN) {
-
- install_sighandler(sig, old_handler);
- #if ENABLE_HUSH_TRAP
- if (!G_traps)
- G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
- free(G_traps[sig]);
- G_traps[sig] = xzalloc(1);
- #endif
- }
- }
- }
- static void install_special_sighandlers(void)
- {
- unsigned mask;
-
- mask = (1 << SIGQUIT) | (1 << SIGCHLD);
- if (G_interactive_fd) {
- mask |= SPECIAL_INTERACTIVE_SIGS;
- if (G_saved_tty_pgrp)
- mask |= SPECIAL_JOBSTOP_SIGS;
- }
-
- if (G.special_sig_mask != mask) {
- unsigned diff = mask & ~G.special_sig_mask;
- G.special_sig_mask = mask;
- install_sighandlers(diff);
- }
- }
- #if ENABLE_HUSH_JOB
- static void install_fatal_sighandlers(void)
- {
- unsigned mask;
-
- mask = 0
-
-
- + (1 << SIGBUS ) * HUSH_DEBUG
- + (1 << SIGSEGV) * HUSH_DEBUG
-
- + (1 << SIGABRT)
-
- + (1 << SIGPIPE)
- + (1 << SIGALRM)
-
-
-
-
- ;
- G_fatal_sig_mask = mask;
- install_sighandlers(mask);
- }
- #endif
- static int set_mode(int state, char mode, const char *o_opt)
- {
- int idx;
- switch (mode) {
- case 'n':
-
-
- if (!G_interactive_fd)
- G.o_opt[OPT_O_NOEXEC] = state;
- break;
- case 'x':
- IF_HUSH_MODE_X(G_x_mode = state;)
- IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
- break;
- case 'e':
- G.o_opt[OPT_O_ERREXIT] = state;
- break;
- case 'o':
- if (!o_opt) {
-
- const char *p = o_opt_strings;
- idx = 0;
- while (*p) {
- printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
- idx++;
- p += strlen(p) + 1;
- }
- break;
- }
- idx = index_in_strings(o_opt_strings, o_opt);
- if (idx >= 0) {
- G.o_opt[idx] = state;
- break;
- }
-
- default:
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
- int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
- int hush_main(int argc, char **argv)
- {
- pid_t cached_getpid;
- enum {
- OPT_login = (1 << 0),
- };
- unsigned flags;
- #if !BB_MMU
- unsigned builtin_argc = 0;
- #endif
- char **e;
- struct variable *cur_var;
- struct variable *shell_ver;
- INIT_G();
- if (EXIT_SUCCESS != 0)
- G.last_exitcode = EXIT_SUCCESS;
- #if !BB_MMU
-
- if (argv[1]
- && argv[1][0] == '-' && argv[1][1] == '<'
-
- ) {
- full_write1_str(argv[2]);
- _exit(0);
- }
- G.argv0_for_re_execing = argv[0];
- if (G.argv0_for_re_execing[0] == '-')
-
- G.argv0_for_re_execing++;
- #endif
- #if ENABLE_HUSH_TRAP
- # if ENABLE_HUSH_FUNCTIONS
- G.return_exitcode = -1;
- # endif
- G.pre_trap_exitcode = -1;
- #endif
- #if ENABLE_HUSH_FAST
- G.count_SIGCHLD++;
- #endif
- cached_getpid = getpid();
- G.root_pid = cached_getpid;
- G.root_ppid = getppid();
-
- debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
- unsetenv("HUSH_VERSION");
- shell_ver = xzalloc(sizeof(*shell_ver));
- shell_ver->flg_export = 1;
- shell_ver->flg_read_only = 1;
-
- shell_ver->varstr = xstrdup(hush_version_str);
-
- G.top_var = shell_ver;
- cur_var = G.top_var;
- e = environ;
- if (e) while (*e) {
- char *value = strchr(*e, '=');
- if (value) {
- cur_var->next = xzalloc(sizeof(*cur_var));
- cur_var = cur_var->next;
- cur_var->varstr = *e;
- cur_var->max_len = strlen(*e);
- cur_var->flg_export = 1;
- }
- e++;
- }
-
- debug_printf_env("putenv '%s'\n", shell_ver->varstr);
- putenv(shell_ver->varstr);
-
- set_pwd_var(SETFLAG_EXPORT);
- #if BASH_HOSTNAME_VAR
-
- if (!get_local_var_value("HOSTNAME")) {
- struct utsname uts;
- uname(&uts);
- set_local_var_from_halves("HOSTNAME", uts.nodename);
- }
- #endif
-
- set_local_var_from_halves("IFS", defifs);
- if (!get_local_var_value("PATH"))
- set_local_var_from_halves("PATH", bb_default_root_path);
-
-
- #if NUM_SCRIPTS > 0
- if (argc < 0) {
- char *script = get_script_content(-argc - 1);
- G.global_argv = argv;
- G.global_argc = string_array_len(argv);
-
- parse_and_run_string(script);
- goto final_return;
- }
- #endif
-
- die_func = restore_ttypgrp_and__exit;
-
-
-
- flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
- while (1) {
- int opt = getopt(argc, argv, "+"
- "cexinsl"
- #if !BB_MMU
- "$:R:V:"
- # if ENABLE_HUSH_LINENO_VAR
- "L:"
- # endif
- # if ENABLE_HUSH_FUNCTIONS
- "F:"
- # endif
- #endif
- );
- if (opt <= 0)
- break;
- switch (opt) {
- case 'c':
-
- G.opt_c = 1;
- break;
- case 'i':
-
-
- break;
- case 's':
- G.opt_s = 1;
- break;
- case 'l':
- flags |= OPT_login;
- break;
- #if !BB_MMU
- case '$': {
- unsigned long long empty_trap_mask;
- G.root_pid = bb_strtou(optarg, &optarg, 16);
- optarg++;
- G.root_ppid = bb_strtou(optarg, &optarg, 16);
- optarg++;
- G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
- optarg++;
- G.last_exitcode = bb_strtou(optarg, &optarg, 16);
- optarg++;
- builtin_argc = bb_strtou(optarg, &optarg, 16);
- optarg++;
- empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
- if (empty_trap_mask != 0) {
- IF_HUSH_TRAP(int sig;)
- install_special_sighandlers();
- # if ENABLE_HUSH_TRAP
- G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
- for (sig = 1; sig < NSIG; sig++) {
- if (empty_trap_mask & (1LL << sig)) {
- G_traps[sig] = xzalloc(1);
- install_sighandler(sig, SIG_IGN);
- }
- }
- # endif
- }
- # if ENABLE_HUSH_LOOPS
- optarg++;
- G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
- # endif
-
- IF_HUSH_JOB(G.run_list_level = 1;)
- # if ENABLE_HUSH_FUNCTIONS
-
- G_flag_return_in_progress = -1;
- # endif
- break;
- }
- case 'R':
- case 'V':
- set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
- break;
- # if ENABLE_HUSH_LINENO_VAR
- case 'L':
- G.parse_lineno = xatou(optarg);
- break;
- # endif
- # if ENABLE_HUSH_FUNCTIONS
- case 'F': {
- struct function *funcp = new_function(optarg);
-
-
- funcp->body_as_string = argv[optind];
- optind++;
- break;
- }
- # endif
- #endif
-
-
-
-
- default:
- if (set_mode(1, opt, NULL) == 0)
- break;
- bb_show_usage();
- }
- }
-
- G.global_argc = argc - (optind - 1);
- G.global_argv = argv + (optind - 1);
- G.global_argv[0] = argv[0];
-
- if (flags & OPT_login) {
- const char *hp = NULL;
- HFILE *input;
- debug_printf("sourcing /etc/profile\n");
- input = hfopen("/etc/profile");
- run_profile:
- if (input != NULL) {
- install_special_sighandlers();
- parse_and_run_file(input);
- hfclose(input);
- }
-
- if (!hp) {
- hp = get_local_var_value("HOME");
- if (hp && hp[0]) {
- debug_printf("sourcing ~/.profile\n");
- hp = concat_path_file(hp, ".profile");
- input = hfopen(hp);
- free((char*)hp);
- goto run_profile;
- }
- }
- }
-
- if (G.opt_c) {
-
- char *script;
- install_special_sighandlers();
- G.global_argc--;
- G.global_argv++;
- #if !BB_MMU
- if (builtin_argc) {
-
- const struct built_in_command *x;
- x = find_builtin(G.global_argv[0]);
- if (x) {
- argv = G.global_argv;
- G.global_argc -= builtin_argc + 1;
- G.global_argv += builtin_argc + 1;
- G.global_argv[-1] = NULL;
- G.last_exitcode = x->b_function(argv);
- }
- goto final_return;
- }
- #endif
- script = G.global_argv[0];
- if (!script)
- bb_error_msg_and_die(bb_msg_requires_arg, "-c");
- if (!G.global_argv[1]) {
-
- G.global_argv[0] = argv[0];
- } else {
- G.global_argc--;
- G.global_argv++;
- }
- parse_and_run_string(script);
- goto final_return;
- }
-
- if (!G.opt_s && G.global_argv[1]) {
- HFILE *input;
-
- G.global_argc--;
- G.global_argv++;
- debug_printf("running script '%s'\n", G.global_argv[0]);
- xfunc_error_retval = 127;
- input = hfopen(G.global_argv[0]);
- if (!input) {
- bb_simple_perror_msg_and_die(G.global_argv[0]);
- }
- xfunc_error_retval = 1;
- install_special_sighandlers();
- parse_and_run_file(input);
- #if ENABLE_FEATURE_CLEAN_UP
- hfclose(input);
- #endif
- goto final_return;
- }
-
- G.opt_s = 1;
-
-
- #if ENABLE_HUSH_JOB
- if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
- G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
- debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
- if (G_saved_tty_pgrp < 0)
- G_saved_tty_pgrp = 0;
-
- G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
- if (G_interactive_fd < 0) {
-
- G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
- if (G_interactive_fd < 0) {
-
- G_interactive_fd = 0;
- G_saved_tty_pgrp = 0;
- }
- }
- }
- debug_printf("interactive_fd:%d\n", G_interactive_fd);
- if (G_interactive_fd) {
- if (G_saved_tty_pgrp) {
-
- while (1) {
- pid_t shell_pgrp = getpgrp();
- G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
- if (G_saved_tty_pgrp == shell_pgrp)
- break;
-
- kill(- shell_pgrp, SIGTTIN);
- }
- }
-
- install_special_sighandlers();
- if (G_saved_tty_pgrp) {
-
- install_fatal_sighandlers();
-
- bb_setpgrp();
-
- tcsetpgrp(G_interactive_fd, cached_getpid);
- }
- enable_restore_tty_pgrp_on_exit();
- # if ENABLE_FEATURE_EDITING
- G.line_input_state = new_line_input_t(FOR_SHELL);
- # if ENABLE_FEATURE_TAB_COMPLETION
- G.line_input_state->get_exe_name = hush_command_name;
- # endif
- # if EDITING_HAS_sh_get_var
- G.line_input_state->sh_get_var = get_local_var_value;
- # endif
- # endif
- # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
- {
- const char *hp = get_local_var_value("HISTFILE");
- if (!hp) {
- hp = get_local_var_value("HOME");
- if (hp)
- hp = concat_path_file(hp, ".hush_history");
- } else {
- hp = xstrdup(hp);
- }
- if (hp) {
- G.line_input_state->hist_file = hp;
-
- }
- # if ENABLE_FEATURE_SH_HISTFILESIZE
- hp = get_local_var_value("HISTFILESIZE");
- G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
- # endif
- }
- # endif
- } else {
- install_special_sighandlers();
- }
- #elif ENABLE_HUSH_INTERACTIVE
-
- if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
- G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
- if (G_interactive_fd < 0) {
-
- G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
- if (G_interactive_fd < 0)
-
- G_interactive_fd = 0;
- }
- }
- install_special_sighandlers();
- #else
-
- install_special_sighandlers();
- #endif
-
- if (G_interactive_fd) {
- #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
-
- if (!get_local_var_value("PS1"))
- set_local_var_from_halves("PS1", "\\w \\$ ");
- if (!get_local_var_value("PS2"))
- set_local_var_from_halves("PS2", "> ");
- #endif
- if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
-
- printf("\n\n%s %s\n"
- IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
- "\n",
- bb_banner,
- "hush - the humble shell"
- );
- }
- }
- parse_and_run_file(hfopen(NULL));
- final_return:
- hush_exit(G.last_exitcode);
- }
- static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
- {
- return 0;
- }
- static int FAST_FUNC builtin_false(char **argv UNUSED_PARAM)
- {
- return 1;
- }
- #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
- static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
- {
- int argc = string_array_len(argv);
- return applet_main_func(argc, argv);
- }
- #endif
- #if ENABLE_HUSH_TEST || BASH_TEST2
- static int FAST_FUNC builtin_test(char **argv)
- {
- int argc = string_array_len(argv);
- return test_main2(&G.groupinfo, argc, argv);
- }
- #endif
- #if ENABLE_HUSH_ECHO
- static int FAST_FUNC builtin_echo(char **argv)
- {
- return run_applet_main(argv, echo_main);
- }
- #endif
- #if ENABLE_HUSH_PRINTF
- static int FAST_FUNC builtin_printf(char **argv)
- {
- return run_applet_main(argv, printf_main);
- }
- #endif
- #if ENABLE_HUSH_HELP
- static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
- {
- const struct built_in_command *x;
- printf(
- "Built-in commands:\n"
- "------------------\n");
- for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
- if (x->b_descr)
- printf("%-10s%s\n", x->b_cmd, x->b_descr);
- }
- return EXIT_SUCCESS;
- }
- #endif
- #if MAX_HISTORY && ENABLE_FEATURE_EDITING
- static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
- {
- show_history(G.line_input_state);
- return EXIT_SUCCESS;
- }
- #endif
- static int FAST_FUNC builtin_cd(char **argv)
- {
- const char *newdir;
- argv = skip_dash_dash(argv);
- newdir = argv[0];
- if (newdir == NULL) {
-
- const char *home = get_local_var_value("HOME");
- newdir = home ? home : "/";
- }
- if (chdir(newdir)) {
-
- bb_perror_msg("cd: %s", newdir);
- return EXIT_FAILURE;
- }
-
- set_pwd_var( 0);
- return EXIT_SUCCESS;
- }
- static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
- {
- puts(get_cwd(0));
- return EXIT_SUCCESS;
- }
- static int FAST_FUNC builtin_eval(char **argv)
- {
- argv = skip_dash_dash(argv);
- if (!argv[0])
- return EXIT_SUCCESS;
- IF_HUSH_MODE_X(G.x_mode_depth++;)
-
- if (!argv[1]) {
-
- parse_and_run_string(argv[0]);
- } else {
-
- char *str, *p;
- unsigned len = 0;
- char **pp = argv;
- do
- len += strlen(*pp) + 1;
- while (*++pp);
- str = p = xmalloc(len);
- pp = argv;
- for (;;) {
- p = stpcpy(p, *pp);
- pp++;
- if (!*pp)
- break;
- *p++ = ' ';
- }
- parse_and_run_string(str);
- free(str);
- }
- IF_HUSH_MODE_X(G.x_mode_depth--;)
-
- return G.last_exitcode;
- }
- static int FAST_FUNC builtin_exec(char **argv)
- {
- argv = skip_dash_dash(argv);
- if (argv[0] == NULL)
- return EXIT_SUCCESS;
-
- if (G_saved_tty_pgrp && getpid() == G.root_pid)
- tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
-
-
-
- execvp_or_die(argv);
- }
- static int FAST_FUNC builtin_exit(char **argv)
- {
- debug_printf_exec("%s()\n", __func__);
-
-
- argv = skip_dash_dash(argv);
- if (argv[0] == NULL) {
- #if ENABLE_HUSH_TRAP
- if (G.pre_trap_exitcode >= 0)
- hush_exit(G.pre_trap_exitcode);
- #endif
- hush_exit(G.last_exitcode);
- }
-
- xfunc_error_retval = 255;
-
- hush_exit(xatoi(argv[0]) & 0xff);
- }
- #if ENABLE_HUSH_TYPE
- static int FAST_FUNC builtin_type(char **argv)
- {
- int ret = EXIT_SUCCESS;
- while (*++argv) {
- const char *type;
- char *path = NULL;
- if (0) {}
-
- # if ENABLE_HUSH_FUNCTIONS
- else if (find_function(*argv))
- type = "a function";
- # endif
- else if (find_builtin(*argv))
- type = "a shell builtin";
- else {
- path = find_executable_in_PATH(*argv);
- if (path)
- type = path;
- else {
- bb_error_msg("%s: %s: not found", "type", *argv);
- ret = EXIT_FAILURE;
- continue;
- }
- }
- printf("%s is %s\n", *argv, type);
- free(path);
- }
- return ret;
- }
- #endif
- #if ENABLE_HUSH_READ
- static int FAST_FUNC builtin_read(char **argv)
- {
- const char *r;
- struct builtin_read_params params;
- memset(¶ms, 0, sizeof(params));
-
- params.read_flags = getopt32(argv,
- # if BASH_READ_D
- IF_NOT_HUSH_BASH_COMPAT("^")
- "!srn:p:t:u:d:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"),
- ¶ms.opt_n, ¶ms.opt_p, ¶ms.opt_t, ¶ms.opt_u, ¶ms.opt_d
- # else
- IF_NOT_HUSH_BASH_COMPAT("^")
- "!srn:p:t:u:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"),
- ¶ms.opt_n, ¶ms.opt_p, ¶ms.opt_t, ¶ms.opt_u
- # endif
- );
- if ((uint32_t)params.read_flags == (uint32_t)-1)
- return EXIT_FAILURE;
- argv += optind;
- params.argv = argv;
- params.setvar = set_local_var_from_halves;
- params.ifs = get_local_var_value("IFS");
- again:
- r = shell_builtin_read(¶ms);
- if ((uintptr_t)r == 1 && errno == EINTR) {
- unsigned sig = check_and_run_traps();
- if (sig != SIGINT)
- goto again;
- }
- if ((uintptr_t)r > 1) {
- bb_simple_error_msg(r);
- r = (char*)(uintptr_t)1;
- }
- return (uintptr_t)r;
- }
- #endif
- #if ENABLE_HUSH_UMASK
- static int FAST_FUNC builtin_umask(char **argv)
- {
- int rc;
- mode_t mask;
- rc = 1;
- mask = umask(0);
- argv = skip_dash_dash(argv);
- if (argv[0]) {
- mode_t old_mask = mask;
-
-
- if (!isdigit(argv[0][0]))
- mask ^= 0777;
- mask = bb_parse_mode(argv[0], mask);
- if (!isdigit(argv[0][0]))
- mask ^= 0777;
- if ((unsigned)mask > 0777) {
- mask = old_mask;
-
- bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
- rc = 0;
- }
- } else {
-
- printf("%04o\n", (unsigned) mask);
-
- }
- umask(mask);
- return !rc;
- }
- #endif
- #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY || ENABLE_HUSH_SET || ENABLE_HUSH_TRAP
- static void print_escaped(const char *s)
- {
- if (*s == '\'')
- goto squote;
- do {
- const char *p = strchrnul(s, '\'');
-
- printf("'%.*s'", (int)(p - s), s);
- if (*p == '\0')
- break;
- s = p;
- squote:
-
- putchar('"');
- do putchar('\''); while (*++s == '\'');
- putchar('"');
- } while (*s);
- }
- #endif
- #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
- static int helper_export_local(char **argv, unsigned flags)
- {
- do {
- char *name = *argv;
- const char *name_end = endofname(name);
- if (*name_end == '\0') {
- struct variable *var, **vpp;
- vpp = get_ptr_to_local_var(name);
- var = vpp ? *vpp : NULL;
- if (flags & SETFLAG_UNEXPORT) {
-
- if (var) {
- var->flg_export = 0;
- debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
- unsetenv(name);
- }
- continue;
- }
- if (flags & SETFLAG_EXPORT) {
-
- if (var) {
- var->flg_export = 1;
- debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
- putenv(var->varstr);
- continue;
- }
- }
- if (flags & SETFLAG_MAKE_RO) {
-
- if (var) {
- var->flg_read_only = 1;
- continue;
- }
- }
- # if ENABLE_HUSH_LOCAL
-
- if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
- unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
- if (var && var->var_nest_level == lvl) {
-
- continue;
- }
- }
- # endif
-
-
-
- name = xasprintf("%s=", name);
- } else {
- if (*name_end != '=') {
- bb_error_msg("'%s': bad variable name", name);
-
- return 1;
- }
-
- name = xstrdup(name);
-
- unbackslash(name);
- }
- debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
- if (set_local_var(name, flags))
- return EXIT_FAILURE;
- } while (*++argv);
- return EXIT_SUCCESS;
- }
- #endif
- #if ENABLE_HUSH_EXPORT
- static int FAST_FUNC builtin_export(char **argv)
- {
- unsigned opt_unexport;
- # if ENABLE_HUSH_EXPORT_N
-
- opt_unexport = getopt32(argv, "!n");
- if (opt_unexport == (uint32_t)-1)
- return EXIT_FAILURE;
- argv += optind;
- # else
- opt_unexport = 0;
- argv++;
- # endif
- if (argv[0] == NULL) {
- char **e = environ;
- if (e) {
- while (*e) {
- # if 0
- puts(*e++);
- # else
-
- const char *s = *e++;
- const char *p = strchr(s, '=');
- if (!p)
- continue;
-
- printf("%s %.*s", "export", (int)(p - s) + 1, s);
- print_escaped(p + 1);
- putchar('\n');
- # endif
- }
-
- }
- return EXIT_SUCCESS;
- }
- return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
- }
- #endif
- #if ENABLE_HUSH_LOCAL
- static int FAST_FUNC builtin_local(char **argv)
- {
- if (G.func_nest_level == 0) {
- bb_error_msg("%s: not in a function", argv[0]);
- return EXIT_FAILURE;
- }
- argv++;
-
- return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
- }
- #endif
- #if ENABLE_HUSH_READONLY
- static int FAST_FUNC builtin_readonly(char **argv)
- {
- argv++;
- if (*argv == NULL) {
-
- struct variable *e;
- for (e = G.top_var; e; e = e->next) {
- if (e->flg_read_only) {
- const char *s = e->varstr;
- const char *p = strchr(s, '=');
- if (!p)
- continue;
-
- printf("%s %.*s", "readonly", (int)(p - s) + 1, s);
- print_escaped(p + 1);
- putchar('\n');
- }
- }
- return EXIT_SUCCESS;
- }
- return helper_export_local(argv, SETFLAG_MAKE_RO);
- }
- #endif
- #if ENABLE_HUSH_UNSET
- static int FAST_FUNC builtin_unset(char **argv)
- {
- int ret;
- unsigned opts;
-
-
- opts = getopt32(argv, "!+vf");
- if (opts == (unsigned)-1)
- return EXIT_FAILURE;
- if (opts == 3) {
- bb_simple_error_msg("unset: -v and -f are exclusive");
- return EXIT_FAILURE;
- }
- argv += optind;
- ret = EXIT_SUCCESS;
- while (*argv) {
- if (!(opts & 2)) {
- if (unset_local_var(*argv)) {
-
- ret = EXIT_FAILURE;
- }
- }
- # if ENABLE_HUSH_FUNCTIONS
- else {
- unset_func(*argv);
- }
- # endif
- argv++;
- }
- return ret;
- }
- #endif
- #if ENABLE_HUSH_SET
- static int FAST_FUNC builtin_set(char **argv)
- {
- int n;
- char **pp, **g_argv;
- char *arg = *++argv;
- if (arg == NULL) {
- struct variable *e;
- for (e = G.top_var; e; e = e->next) {
- const char *s = e->varstr;
- const char *p = strchr(s, '=');
- if (!p)
- continue;
-
- printf("%.*s", (int)(p - s) + 1, s);
- print_escaped(p + 1);
- putchar('\n');
- }
- return EXIT_SUCCESS;
- }
- do {
- if (strcmp(arg, "--") == 0) {
- ++argv;
- goto set_argv;
- }
- if (arg[0] != '+' && arg[0] != '-')
- break;
- for (n = 1; arg[n]; ++n) {
- if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
- bb_error_msg("%s: %s: invalid option", "set", arg);
- return EXIT_FAILURE;
- }
- if (arg[n] == 'o' && argv[1])
- argv++;
- }
- } while ((arg = *++argv) != NULL);
-
- if (arg == NULL)
- return EXIT_SUCCESS;
- set_argv:
-
- g_argv = G.global_argv;
- if (G.global_args_malloced) {
- pp = g_argv;
- while (*++pp)
- free(*pp);
- g_argv[1] = NULL;
- } else {
- G.global_args_malloced = 1;
- pp = xzalloc(sizeof(pp[0]) * 2);
- pp[0] = g_argv[0];
- g_argv = pp;
- }
-
- G.global_argv = pp = add_strings_to_strings(g_argv, argv, 1);
- G.global_argc = 1 + string_array_len(pp + 1);
- return EXIT_SUCCESS;
- }
- #endif
- static int FAST_FUNC builtin_shift(char **argv)
- {
- int n = 1;
- argv = skip_dash_dash(argv);
- if (argv[0]) {
- n = bb_strtou(argv[0], NULL, 10);
- if (errno || n < 0) {
-
- bb_error_msg("Illegal number: %s", argv[0]);
-
- }
- }
- if (n >= 0 && n < G.global_argc) {
- if (G_global_args_malloced) {
- int m = 1;
- while (m <= n)
- free(G.global_argv[m++]);
- }
- G.global_argc -= n;
- memmove(&G.global_argv[1], &G.global_argv[n+1],
- G.global_argc * sizeof(G.global_argv[0]));
- return EXIT_SUCCESS;
- }
- return EXIT_FAILURE;
- }
- #if ENABLE_HUSH_GETOPTS
- static int FAST_FUNC builtin_getopts(char **argv)
- {
- char cbuf[2];
- const char *cp, *optstring, *var;
- int c, n, exitcode, my_opterr;
- unsigned count;
- optstring = *++argv;
- if (!optstring || !(var = *++argv)) {
- bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
- return EXIT_FAILURE;
- }
- if (argv[1])
- argv[0] = G.global_argv[0];
- else
- argv = G.global_argv;
- cbuf[1] = '\0';
- my_opterr = 0;
- if (optstring[0] != ':') {
- cp = get_local_var_value("OPTERR");
-
- my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
- }
-
- {
- char *s = alloca(strlen(optstring) + 2);
- sprintf(s, "+%s", optstring);
- optstring = s;
- }
-
- GETOPT_RESET();
- count = 0;
- n = string_array_len(argv);
- do {
- optarg = NULL;
- opterr = (count < G.getopt_count) ? 0 : my_opterr;
- c = getopt(n, argv, optstring);
- if (c < 0)
- break;
- count++;
- } while (count <= G.getopt_count);
-
- set_local_var_from_halves("OPTIND", utoa(optind));
- G.getopt_count = count;
- GETOPT_RESET();
-
-
- cp = optarg;
- if (c == '?') {
-
- if (optstring[1] == ':') {
- cbuf[0] = optopt;
- cp = cbuf;
- }
- }
- if (cp)
- set_local_var_from_halves("OPTARG", cp);
- else
- unset_local_var("OPTARG");
-
- exitcode = EXIT_SUCCESS;
- if (c < 0) {
- exitcode = EXIT_FAILURE;
- c = '?';
- }
-
- cbuf[0] = c;
- set_local_var_from_halves(var, cbuf);
- return exitcode;
- }
- #endif
- static int FAST_FUNC builtin_source(char **argv)
- {
- char *arg_path, *filename;
- HFILE *input;
- save_arg_t sv;
- char *args_need_save;
- #if ENABLE_HUSH_FUNCTIONS
- smallint sv_flg;
- #endif
- argv = skip_dash_dash(argv);
- filename = argv[0];
- if (!filename) {
-
- return 2;
- }
- arg_path = NULL;
- if (!strchr(filename, '/')) {
- arg_path = find_in_PATH(filename);
- if (arg_path)
- filename = arg_path;
- else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
- errno = ENOENT;
- bb_simple_perror_msg(filename);
- return EXIT_FAILURE;
- }
- }
- input = hfopen(filename);
- free(arg_path);
- if (!input) {
- bb_perror_msg("%s", filename);
-
- return EXIT_FAILURE;
- }
- #if ENABLE_HUSH_FUNCTIONS
- sv_flg = G_flag_return_in_progress;
-
- G_flag_return_in_progress = -1;
- #endif
- args_need_save = argv[1];
- if (args_need_save)
- save_and_replace_G_args(&sv, argv);
-
- G.last_exitcode = 0;
- parse_and_run_file(input);
- hfclose(input);
- if (args_need_save)
- restore_G_args(&sv, argv);
- #if ENABLE_HUSH_FUNCTIONS
- G_flag_return_in_progress = sv_flg;
- #endif
- return G.last_exitcode;
- }
- #if ENABLE_HUSH_TRAP
- static int FAST_FUNC builtin_trap(char **argv)
- {
- int sig;
- char *new_cmd;
- if (!G_traps)
- G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
- argv++;
- if (!*argv) {
- int i;
-
- for (i = 0; i < NSIG; ++i) {
- if (G_traps[i]) {
- printf("trap -- ");
- print_escaped(G_traps[i]);
-
- printf(" %s\n", get_signame(i));
- }
- }
-
- return EXIT_SUCCESS;
- }
- new_cmd = NULL;
-
- sig = bb_strtou(*argv, NULL, 10);
- if (errno == 0) {
- int ret;
- process_sig_list:
- ret = EXIT_SUCCESS;
- while (*argv) {
- sighandler_t handler;
- sig = get_signum(*argv++);
- if (sig < 0) {
- ret = EXIT_FAILURE;
-
- bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
- continue;
- }
- free(G_traps[sig]);
- G_traps[sig] = xstrdup(new_cmd);
- debug_printf("trap: setting SIG%s (%i) to '%s'\n",
- get_signame(sig), sig, G_traps[sig]);
-
- if (sig == 0)
- continue;
- if (new_cmd)
- handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
- else
-
- handler = pick_sighandler(sig);
- install_sighandler(sig, handler);
- }
- return ret;
- }
- if (!argv[1]) {
- bb_simple_error_msg("trap: invalid arguments");
- return EXIT_FAILURE;
- }
-
-
-
- if (argv[0][0] == '-') {
- if (argv[0][1] == '\0') {
-
- goto reset_traps;
- }
- if (argv[0][1] == '-' && argv[0][2] == '\0') {
- argv++;
- }
-
- }
- new_cmd = *argv;
- reset_traps:
- argv++;
- goto process_sig_list;
- }
- #endif
- #if ENABLE_HUSH_JOB
- static struct pipe *parse_jobspec(const char *str)
- {
- struct pipe *pi;
- unsigned jobnum;
- if (sscanf(str, "%%%u", &jobnum) != 1) {
- if (str[0] != '%'
- || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
- ) {
- bb_error_msg("bad argument '%s'", str);
- return NULL;
- }
-
- jobnum = G.last_jobid;
- if (jobnum == 0) {
- bb_simple_error_msg("no current job");
- return NULL;
- }
- }
- for (pi = G.job_list; pi; pi = pi->next) {
- if (pi->jobid == jobnum) {
- return pi;
- }
- }
- bb_error_msg("%u: no such job", jobnum);
- return NULL;
- }
- static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
- {
- struct pipe *job;
- const char *status_string;
- checkjobs(NULL, 0 );
- for (job = G.job_list; job; job = job->next) {
- if (job->alive_cmds == job->stopped_cmds)
- status_string = "Stopped";
- else
- status_string = "Running";
- printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
- }
- clean_up_last_dead_job();
- return EXIT_SUCCESS;
- }
- static int FAST_FUNC builtin_fg_bg(char **argv)
- {
- int i;
- struct pipe *pi;
- if (!G_interactive_fd)
- return EXIT_FAILURE;
-
- if (!argv[1]) {
- for (pi = G.job_list; pi; pi = pi->next) {
- if (pi->jobid == G.last_jobid) {
- goto found;
- }
- }
- bb_error_msg("%s: no current job", argv[0]);
- return EXIT_FAILURE;
- }
- pi = parse_jobspec(argv[1]);
- if (!pi)
- return EXIT_FAILURE;
- found:
-
- if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
-
- tcsetpgrp(G_interactive_fd, pi->pgrp);
- }
-
- debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
- for (i = 0; i < pi->num_cmds; i++) {
- debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
- }
- pi->stopped_cmds = 0;
- i = kill(- pi->pgrp, SIGCONT);
- if (i < 0) {
- if (errno == ESRCH) {
- delete_finished_job(pi);
- return EXIT_SUCCESS;
- }
- bb_simple_perror_msg("kill (SIGCONT)");
- }
- if (argv[0][0] == 'f') {
- remove_job_from_table(pi);
- return checkjobs_and_fg_shell(pi);
- }
- return EXIT_SUCCESS;
- }
- #endif
- #if ENABLE_HUSH_KILL
- static int FAST_FUNC builtin_kill(char **argv)
- {
- int ret = 0;
- # if ENABLE_HUSH_JOB
- if (argv[1] && strcmp(argv[1], "-l") != 0) {
- int i = 1;
- do {
- struct pipe *pi;
- char *dst;
- int j, n;
- if (argv[i][0] != '%')
- continue;
-
- pi = parse_jobspec(argv[i]);
- if (!pi) {
-
- j = i;
- do {
- j++;
- argv[j - 1] = argv[j];
- } while (argv[j]);
- ret = 1;
- i--;
- continue;
- }
-
- n = G_interactive_fd ? 1 : pi->num_cmds;
- dst = alloca(n * sizeof(int)*4);
- argv[i] = dst;
- if (G_interactive_fd)
- dst += sprintf(dst, " -%u", (int)pi->pgrp);
- else for (j = 0; j < n; j++) {
- struct command *cmd = &pi->cmds[j];
-
- if (cmd->pid == 0)
- continue;
-
- dst += sprintf(dst, " %u", (int)cmd->pid);
- }
- *dst = '\0';
- } while (argv[++i]);
- }
- # endif
- if (argv[1] || ret == 0) {
- ret = run_applet_main(argv, kill_main);
- }
-
- return ret;
- }
- #endif
- #if ENABLE_HUSH_WAIT
- # if !ENABLE_HUSH_JOB
- # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
- # endif
- static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
- {
- int ret = 0;
- for (;;) {
- int sig;
- sigset_t oldset;
- if (!sigisemptyset(&G.pending_set))
- goto check_sig;
-
-
- sigfillset(&oldset);
- sigprocmask2(SIG_SETMASK, &oldset);
- if (!sigisemptyset(&G.pending_set)) {
-
- goto restore;
- }
-
- ret = checkjobs(NULL, waitfor_pid);
- debug_printf_exec("checkjobs:%d\n", ret);
- # if ENABLE_HUSH_JOB
- if (waitfor_pipe) {
- int rcode = job_exited_or_stopped(waitfor_pipe);
- debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
- if (rcode >= 0) {
- ret = rcode;
- sigprocmask(SIG_SETMASK, &oldset, NULL);
- break;
- }
- }
- # endif
-
-
-
- if (errno == ECHILD || ret) {
- ret--;
- if (ret < 0)
- ret = 0;
- # if ENABLE_HUSH_BASH_COMPAT
- if (waitfor_pid == -1 && errno == ECHILD) {
-
- ret = 127;
- }
- # endif
- sigprocmask(SIG_SETMASK, &oldset, NULL);
- break;
- }
-
-
-
- sigsuspend(&oldset);
-
- restore:
- sigprocmask(SIG_SETMASK, &oldset, NULL);
- check_sig:
-
- sig = check_and_run_traps();
- if (sig ) {
-
- ret = 128 | sig;
- break;
- }
-
- }
- return ret;
- }
- static int FAST_FUNC builtin_wait(char **argv)
- {
- int ret;
- int status;
- argv = skip_dash_dash(argv);
- # if ENABLE_HUSH_BASH_COMPAT
- if (argv[0] && strcmp(argv[0], "-n") == 0) {
-
-
- G.dead_job_exitcode = -1;
- return wait_for_child_or_signal(NULL, -1 );
- }
- # endif
- if (argv[0] == NULL) {
-
-
-
-
- return wait_for_child_or_signal(NULL, 0 );
- }
- do {
- pid_t pid = bb_strtou(*argv, NULL, 10);
- if (errno || pid <= 0) {
- # if ENABLE_HUSH_JOB
- if (argv[0][0] == '%') {
- struct pipe *wait_pipe;
- ret = 127;
- wait_pipe = parse_jobspec(*argv);
- if (wait_pipe) {
- ret = job_exited_or_stopped(wait_pipe);
- if (ret < 0) {
- ret = wait_for_child_or_signal(wait_pipe, 0);
- } else {
-
- clean_up_last_dead_job();
- }
- }
-
- continue;
- }
- # endif
-
- bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
- ret = EXIT_FAILURE;
- continue;
- }
-
- ret = waitpid(pid, &status, WNOHANG);
- if (ret < 0) {
-
- ret = 127;
- if (errno == ECHILD) {
- if (pid == G.last_bg_pid) {
-
- ret = G.last_bg_pid_exitcode;
- } else {
-
- bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
- }
- } else {
-
- bb_perror_msg("wait %s", *argv);
- }
- continue;
- }
- if (ret == 0) {
-
- ret = wait_for_child_or_signal(NULL, pid);
- } else {
-
- process_wait_result(NULL, pid, status);
- ret = WEXITSTATUS(status);
- if (WIFSIGNALED(status))
- ret = 128 | WTERMSIG(status);
- }
- } while (*++argv);
- return ret;
- }
- #endif
- #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
- static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
- {
- if (argv[1]) {
- def = bb_strtou(argv[1], NULL, 10);
- if (errno || def < def_min || argv[2]) {
- bb_error_msg("%s: bad arguments", argv[0]);
- def = UINT_MAX;
- }
- }
- return def;
- }
- #endif
- #if ENABLE_HUSH_LOOPS
- static int FAST_FUNC builtin_break(char **argv)
- {
- unsigned depth;
- if (G.depth_of_loop == 0) {
- bb_error_msg("%s: only meaningful in a loop", argv[0]);
-
- G.flag_break_continue = 0;
- return EXIT_SUCCESS;
- }
- G.flag_break_continue++;
- G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
- if (depth == UINT_MAX)
- G.flag_break_continue = BC_BREAK;
- if (G.depth_of_loop < depth)
- G.depth_break_continue = G.depth_of_loop;
- return EXIT_SUCCESS;
- }
- static int FAST_FUNC builtin_continue(char **argv)
- {
- G.flag_break_continue = 1;
- return builtin_break(argv);
- }
- #endif
- #if ENABLE_HUSH_FUNCTIONS
- static int FAST_FUNC builtin_return(char **argv)
- {
- int rc;
- if (G_flag_return_in_progress != -1) {
- bb_error_msg("%s: not in a function or sourced script", argv[0]);
- return EXIT_FAILURE;
- }
- G_flag_return_in_progress = 1;
-
- rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
- # if ENABLE_HUSH_TRAP
- if (argv[1]) {
- debug_printf_exec("G.return_exitcode=%d\n", rc);
- G.return_exitcode = rc;
- }
- # endif
- return rc;
- }
- #endif
- #if ENABLE_HUSH_TIMES
- static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
- {
- static const uint8_t times_tbl[] ALIGN1 = {
- ' ', offsetof(struct tms, tms_utime),
- '\n', offsetof(struct tms, tms_stime),
- ' ', offsetof(struct tms, tms_cutime),
- '\n', offsetof(struct tms, tms_cstime),
- 0
- };
- const uint8_t *p;
- unsigned clk_tck;
- struct tms buf;
- clk_tck = bb_clk_tck();
- times(&buf);
- p = times_tbl;
- do {
- unsigned sec, frac;
- unsigned long t;
- t = *(clock_t *)(((char *) &buf) + p[1]);
- sec = t / clk_tck;
- frac = t % clk_tck;
- printf("%um%u.%03us%c",
- sec / 60, sec % 60,
- (frac * 1000) / clk_tck,
- p[0]);
- p += 2;
- } while (*p);
- return EXIT_SUCCESS;
- }
- #endif
- #if ENABLE_HUSH_MEMLEAK
- static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
- {
- void *p;
- unsigned long l;
- # ifdef M_TRIM_THRESHOLD
-
- malloc_trim(0);
- # endif
-
- p = malloc(240);
- l = (unsigned long)p;
- free(p);
- p = malloc(3400);
- if (l < (unsigned long)p) l = (unsigned long)p;
- free(p);
- # if 0
- {
- struct mallinfo mi = mallinfo();
- printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
- mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
- }
- # endif
- if (!G.memleak_value)
- G.memleak_value = l;
- l -= G.memleak_value;
- if ((long)l < 0)
- l = 0;
- l /= 1024;
- if (l > 127)
- l = 127;
-
- return l;
- }
- #endif
|