ash.c 332 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * This code is derived from software contributed to Berkeley by
  6. * Kenneth Almquist.
  7. *
  8. * Original BSD copyright notice is retained at the end of this file.
  9. *
  10. * Copyright (c) 1989, 1991, 1993, 1994
  11. * The Regents of the University of California. All rights reserved.
  12. *
  13. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  14. * was re-ported from NetBSD and debianized.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  17. */
  18. //config:config SHELL_ASH
  19. //config: bool #hidden option
  20. //config: depends on !NOMMU
  21. //config:
  22. //config:config ASH
  23. //config: bool "ash (78 kb)"
  24. //config: default y
  25. //config: depends on !NOMMU
  26. //config: select SHELL_ASH
  27. //config: help
  28. //config: The most complete and most pedantically correct shell included with
  29. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  30. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  31. //config: (written by Kenneth Almquist) from NetBSD.
  32. //config:
  33. //config:# ash options
  34. //config:# note: Don't remove !NOMMU part in the next line; it would break
  35. //config:# menuconfig's indenting.
  36. //config:if !NOMMU && (SHELL_ASH || ASH || SH_IS_ASH || BASH_IS_ASH)
  37. //config:
  38. //config:config ASH_OPTIMIZE_FOR_SIZE
  39. //config: bool "Optimize for size instead of speed"
  40. //config: default y
  41. //config: depends on SHELL_ASH
  42. //config:
  43. //config:config ASH_INTERNAL_GLOB
  44. //config: bool "Use internal glob() implementation"
  45. //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
  46. //config: depends on SHELL_ASH
  47. //config: help
  48. //config: Do not use glob() function from libc, use internal implementation.
  49. //config: Use this if you are getting "glob.h: No such file or directory"
  50. //config: or similar build errors.
  51. //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
  52. //config: which would break ash if you select N here.
  53. //config:
  54. //config:config ASH_BASH_COMPAT
  55. //config: bool "bash-compatible extensions"
  56. //config: default y
  57. //config: depends on SHELL_ASH
  58. //config:
  59. //config:config ASH_BASH_SOURCE_CURDIR
  60. //config: bool "'source' and '.' builtins search current directory after $PATH"
  61. //config: default n # do not encourage non-standard behavior
  62. //config: depends on ASH_BASH_COMPAT
  63. //config: help
  64. //config: This is not compliant with standards. Avoid if possible.
  65. //config:
  66. //config:config ASH_BASH_NOT_FOUND_HOOK
  67. //config: bool "command_not_found_handle hook support"
  68. //config: default y
  69. //config: depends on ASH_BASH_COMPAT
  70. //config: help
  71. //config: Enable support for the 'command_not_found_handle' hook function,
  72. //config: from GNU bash, which allows for alternative command not found
  73. //config: handling.
  74. //config:
  75. //config:config ASH_JOB_CONTROL
  76. //config: bool "Job control"
  77. //config: default y
  78. //config: depends on SHELL_ASH
  79. //config:
  80. //config:config ASH_ALIAS
  81. //config: bool "Alias support"
  82. //config: default y
  83. //config: depends on SHELL_ASH
  84. //config:
  85. //config:config ASH_RANDOM_SUPPORT
  86. //config: bool "Pseudorandom generator and $RANDOM variable"
  87. //config: default y
  88. //config: depends on SHELL_ASH
  89. //config: help
  90. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  91. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  92. //config: You can reset the generator by using a specified start value.
  93. //config: After "unset RANDOM" the generator will switch off and this
  94. //config: variable will no longer have special treatment.
  95. //config:
  96. //config:config ASH_EXPAND_PRMT
  97. //config: bool "Expand prompt string"
  98. //config: default y
  99. //config: depends on SHELL_ASH
  100. //config: help
  101. //config: $PS# may contain volatile content, such as backquote commands.
  102. //config: This option recreates the prompt string from the environment
  103. //config: variable each time it is displayed.
  104. //config:
  105. //config:config ASH_IDLE_TIMEOUT
  106. //config: bool "Idle timeout variable $TMOUT"
  107. //config: default y
  108. //config: depends on SHELL_ASH
  109. //config: help
  110. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  111. //config:
  112. //config:config ASH_MAIL
  113. //config: bool "Check for new mail in interactive shell"
  114. //config: default y
  115. //config: depends on SHELL_ASH
  116. //config: help
  117. //config: Enable "check for new mail" function:
  118. //config: if set, $MAIL file and $MAILPATH list of files
  119. //config: are checked for mtime changes, and "you have mail"
  120. //config: message is printed if change is detected.
  121. //config:
  122. //config:config ASH_ECHO
  123. //config: bool "echo builtin"
  124. //config: default y
  125. //config: depends on SHELL_ASH
  126. //config:
  127. //config:config ASH_PRINTF
  128. //config: bool "printf builtin"
  129. //config: default y
  130. //config: depends on SHELL_ASH
  131. //config:
  132. //config:config ASH_TEST
  133. //config: bool "test builtin"
  134. //config: default y
  135. //config: depends on SHELL_ASH
  136. //config:
  137. //config:config ASH_HELP
  138. //config: bool "help builtin"
  139. //config: default y
  140. //config: depends on SHELL_ASH
  141. //config:
  142. //config:config ASH_GETOPTS
  143. //config: bool "getopts builtin"
  144. //config: default y
  145. //config: depends on SHELL_ASH
  146. //config:
  147. //config:config ASH_CMDCMD
  148. //config: bool "command builtin"
  149. //config: default y
  150. //config: depends on SHELL_ASH
  151. //config: help
  152. //config: Enable support for the 'command' builtin, which allows
  153. //config: you to run the specified command or builtin,
  154. //config: even when there is a function with the same name.
  155. //config:
  156. //config:endif # ash options
  157. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  158. // APPLET_ODDNAME:name main location suid_type help
  159. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  160. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  161. //kbuild:lib-$(CONFIG_SHELL_ASH) += ash.o ash_ptr_hack.o shell_common.o
  162. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  163. /*
  164. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  165. * DEBUG=2 to compile in and turn on debugging.
  166. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  167. * debugging info is written to ./trace, quit signal generates core dump.
  168. */
  169. #define DEBUG 0
  170. /* Tweak debug output verbosity here */
  171. #define DEBUG_TIME 0
  172. #define DEBUG_PID 1
  173. #define DEBUG_SIG 1
  174. #define DEBUG_INTONOFF 0
  175. #define PROFILE 0
  176. #define JOBS ENABLE_ASH_JOB_CONTROL
  177. #include <fnmatch.h>
  178. #include <sys/times.h>
  179. #include <sys/utsname.h> /* for setting $HOSTNAME */
  180. #include "busybox.h" /* for applet_names */
  181. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
  182. # include "embedded_scripts.h"
  183. #else
  184. # define NUM_SCRIPTS 0
  185. #endif
  186. /* So far, all bash compat is controlled by one config option */
  187. /* Separate defines document which part of code implements what */
  188. /* function keyword */
  189. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  190. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  191. /* &>file */
  192. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  193. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  194. /* $'...' */
  195. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  196. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  197. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  198. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  199. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  200. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  201. /* BASH_TEST2: [[ EXPR ]]
  202. * Status of [[ support:
  203. * && and || work as they should
  204. * = is glob match operator, not equality operator: STR = GLOB
  205. * == same as =
  206. * =~ is regex match operator: STR =~ REGEX
  207. * TODO:
  208. * singleword+noglob expansion:
  209. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  210. * [[ /bin/n* ]]; echo 0:$?
  211. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  212. * ( ) < > should not have special meaning (IOW: should not require quoting)
  213. * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
  214. */
  215. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  216. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  217. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  218. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  219. #define BASH_EPOCH_VARS ENABLE_ASH_BASH_COMPAT
  220. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  221. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  222. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  223. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  224. #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
  225. /* <(...) and >(...) */
  226. #if HAVE_DEV_FD
  227. # define BASH_PROCESS_SUBST ENABLE_ASH_BASH_COMPAT
  228. # define IF_BASH_PROCESS_SUBST IF_ASH_BASH_COMPAT
  229. #else
  230. # define BASH_PROCESS_SUBST 0
  231. # define IF_BASH_PROCESS_SUBST(...)
  232. #endif
  233. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  234. /* Bionic at least up to version 24 has no glob() */
  235. # undef ENABLE_ASH_INTERNAL_GLOB
  236. # define ENABLE_ASH_INTERNAL_GLOB 1
  237. #endif
  238. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  239. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  240. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  241. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  242. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  243. # error fails to match dirname, subsequently not expanding <pattern> in it.
  244. // Testcase:
  245. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  246. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  247. #endif
  248. #if !ENABLE_ASH_INTERNAL_GLOB
  249. # include <glob.h>
  250. #endif
  251. #include "unicode.h"
  252. #include "shell_common.h"
  253. #if ENABLE_FEATURE_SH_MATH
  254. # include "math.h"
  255. #else
  256. typedef long arith_t;
  257. # define ARITH_FMT "%ld"
  258. #endif
  259. #if ENABLE_ASH_RANDOM_SUPPORT
  260. # include "random.h"
  261. #else
  262. # define CLEAR_RANDOM_T(rnd) ((void)0)
  263. #endif
  264. #include "NUM_APPLETS.h"
  265. #if NUM_APPLETS == 1
  266. /* STANDALONE does not make sense, and won't compile */
  267. # undef CONFIG_FEATURE_SH_STANDALONE
  268. # undef ENABLE_FEATURE_SH_STANDALONE
  269. # undef IF_FEATURE_SH_STANDALONE
  270. # undef IF_NOT_FEATURE_SH_STANDALONE
  271. # define ENABLE_FEATURE_SH_STANDALONE 0
  272. # define IF_FEATURE_SH_STANDALONE(...)
  273. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  274. #endif
  275. #ifndef F_DUPFD_CLOEXEC
  276. # define F_DUPFD_CLOEXEC F_DUPFD
  277. #endif
  278. #ifndef O_CLOEXEC
  279. # define O_CLOEXEC 0
  280. #endif
  281. #ifndef PIPE_BUF
  282. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  283. #endif
  284. #ifndef unlikely
  285. # define unlikely(cond) (cond)
  286. #endif
  287. #if !BB_MMU
  288. # error "Do not even bother, ash will not run on NOMMU machine"
  289. #endif
  290. /* ============ Hash table sizes. Configurable. */
  291. #define VTABSIZE 39
  292. #define ATABSIZE 39
  293. #define CMDTABLESIZE 31 /* should be prime */
  294. /* ============ Shell options */
  295. /* If you add/change options hare, update --help text too */
  296. static const char *const optletters_optnames[] = {
  297. "e" "errexit",
  298. "f" "noglob",
  299. /* bash has '-o ignoreeof', but no short synonym -I for it */
  300. /* (in bash, set -I disables invisible variables (what's that?)) */
  301. "I" "ignoreeof",
  302. /* The below allowed this invocation:
  303. * ash -c 'set -i; echo $-; sleep 5; echo $-'
  304. * to be ^C-ed and get to interactive ash prompt.
  305. * bash does not support such "set -i".
  306. * In our code, this is denoted by empty long name:
  307. */
  308. "i" "",
  309. /* (removing "i" altogether would remove it from "$-", not good) */
  310. "m" "monitor",
  311. "n" "noexec",
  312. /* Ditto: bash has no "set -s", "set -c" */
  313. "s" "",
  314. "c" "",
  315. "x" "xtrace",
  316. "v" "verbose",
  317. "C" "noclobber",
  318. "a" "allexport",
  319. "b" "notify",
  320. "u" "nounset",
  321. "E" "errtrace",
  322. "\0" "vi"
  323. #if BASH_PIPEFAIL
  324. ,"\0" "pipefail"
  325. #endif
  326. #if DEBUG
  327. ,"\0" "nolog"
  328. ,"\0" "debug"
  329. #endif
  330. };
  331. //bash 4.4.23 also has these opts (with these defaults):
  332. //braceexpand on
  333. //emacs on
  334. //errtrace off
  335. //functrace off
  336. //hashall on
  337. //histexpand off
  338. //history on
  339. //interactive-comments on
  340. //keyword off
  341. //onecmd off
  342. //physical off
  343. //posix off
  344. //privileged off
  345. #define optletters(n) optletters_optnames[n][0]
  346. #define optnames(n) (optletters_optnames[n] + 1)
  347. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  348. /* ============ Misc data */
  349. #define msg_illnum "Illegal number: %s"
  350. /*
  351. * We enclose jmp_buf in a structure so that we can declare pointers to
  352. * jump locations. The global variable handler contains the location to
  353. * jump to when an exception occurs, and the global variable exception_type
  354. * contains a code identifying the exception. To implement nested
  355. * exception handlers, the user should save the value of handler on entry
  356. * to an inner scope, set handler to point to a jmploc structure for the
  357. * inner scope, and restore handler on exit from the scope.
  358. */
  359. struct jmploc {
  360. jmp_buf loc;
  361. };
  362. struct globals_misc {
  363. uint8_t exitstatus; /* exit status of last command */
  364. uint8_t back_exitstatus;/* exit status of backquoted command */
  365. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  366. smallint inps4; /* Prevent PS4 nesting. */
  367. int savestatus; /* exit status of last command outside traps */
  368. int rootpid; /* pid of main shell */
  369. /* shell level: 0 for the main shell, 1 for its children, and so on */
  370. int shlvl;
  371. #define rootshell (!shlvl)
  372. int errlinno;
  373. char *minusc; /* argument to -c option */
  374. char *curdir; // = nullstr; /* current working directory */
  375. char *physdir; // = nullstr; /* physical working directory */
  376. char *arg0; /* value of $0 */
  377. struct jmploc *exception_handler;
  378. volatile int suppress_int; /* counter */
  379. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  380. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  381. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  382. smallint exception_type; /* kind of exception: */
  383. #define EXINT 0 /* SIGINT received */
  384. #define EXERROR 1 /* a generic error */
  385. #define EXEND 3 /* exit the shell */
  386. #define EXEXIT 4 /* exit the shell via exitcmd */
  387. char nullstr[1]; /* zero length string */
  388. char optlist[NOPTS];
  389. #define eflag optlist[0]
  390. #define fflag optlist[1]
  391. #define Iflag optlist[2]
  392. #define iflag optlist[3]
  393. #define mflag optlist[4]
  394. #define nflag optlist[5]
  395. #define sflag optlist[6]
  396. #define cflag optlist[7]
  397. #define xflag optlist[8]
  398. #define vflag optlist[9]
  399. #define Cflag optlist[10]
  400. #define aflag optlist[11]
  401. #define bflag optlist[12]
  402. #define uflag optlist[13]
  403. #define Eflag optlist[14]
  404. #define viflag optlist[15]
  405. #if BASH_PIPEFAIL
  406. # define pipefail optlist[16]
  407. #else
  408. # define pipefail 0
  409. #endif
  410. #if DEBUG
  411. # define nolog optlist[16 + BASH_PIPEFAIL]
  412. # define debug optlist[17 + BASH_PIPEFAIL]
  413. #endif
  414. /* trap handler commands */
  415. /*
  416. * Sigmode records the current value of the signal handlers for the various
  417. * modes. A value of zero means that the current handler is not known.
  418. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  419. */
  420. char sigmode[NSIG - 1];
  421. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  422. #define S_CATCH 2 /* signal is caught */
  423. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  424. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  425. /* indicates specified signal received */
  426. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  427. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  428. char *trap[NSIG + 1];
  429. /* trap[0] is EXIT trap, trap[NTRAP_ERR] is ERR trap, other trap[i] are signal traps */
  430. #define NTRAP_ERR NSIG
  431. #define NTRAP_LAST NSIG
  432. char **trap_ptr; /* used only by "trap hack" */
  433. /* Rarely referenced stuff */
  434. #if ENABLE_ASH_RANDOM_SUPPORT
  435. random_t random_gen;
  436. #endif
  437. pid_t backgndpid; /* pid of last background process */
  438. };
  439. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  440. #define G_misc (*ash_ptr_to_globals_misc)
  441. #define exitstatus (G_misc.exitstatus )
  442. #define back_exitstatus (G_misc.back_exitstatus )
  443. #define job_warning (G_misc.job_warning)
  444. #define inps4 (G_misc.inps4 )
  445. #define savestatus (G_misc.savestatus )
  446. #define rootpid (G_misc.rootpid )
  447. #define shlvl (G_misc.shlvl )
  448. #define errlinno (G_misc.errlinno )
  449. #define minusc (G_misc.minusc )
  450. #define curdir (G_misc.curdir )
  451. #define physdir (G_misc.physdir )
  452. #define arg0 (G_misc.arg0 )
  453. #define exception_handler (G_misc.exception_handler)
  454. #define exception_type (G_misc.exception_type )
  455. #define suppress_int (G_misc.suppress_int )
  456. #define pending_int (G_misc.pending_int )
  457. #define got_sigchld (G_misc.got_sigchld )
  458. #define pending_sig (G_misc.pending_sig )
  459. #define nullstr (G_misc.nullstr )
  460. #define optlist (G_misc.optlist )
  461. #define sigmode (G_misc.sigmode )
  462. #define gotsig (G_misc.gotsig )
  463. #define may_have_traps (G_misc.may_have_traps )
  464. #define trap (G_misc.trap )
  465. #define trap_ptr (G_misc.trap_ptr )
  466. #define random_gen (G_misc.random_gen )
  467. #define backgndpid (G_misc.backgndpid )
  468. #define INIT_G_misc() do { \
  469. XZALLOC_CONST_PTR(&ash_ptr_to_globals_misc, sizeof(G_misc)); \
  470. savestatus = -1; \
  471. curdir = nullstr; \
  472. physdir = nullstr; \
  473. trap_ptr = trap; \
  474. } while (0)
  475. /* ============ DEBUG */
  476. #if DEBUG
  477. static void trace_printf(const char *fmt, ...);
  478. static void trace_vprintf(const char *fmt, va_list va);
  479. # define TRACE(param) trace_printf param
  480. # define TRACEV(param) trace_vprintf param
  481. # define close(fd) do { \
  482. int dfd = (fd); \
  483. if (close(dfd) < 0) \
  484. bb_error_msg("bug on %d: closing %d(0x%x)", \
  485. __LINE__, dfd, dfd); \
  486. } while (0)
  487. #else
  488. # define TRACE(param)
  489. # define TRACEV(param)
  490. #endif
  491. /* ============ Utility functions */
  492. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  493. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  494. static int
  495. isdigit_str9(const char *str)
  496. {
  497. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  498. while (--maxlen && isdigit(*str))
  499. str++;
  500. return (*str == '\0');
  501. }
  502. static const char *
  503. var_end(const char *var)
  504. {
  505. while (*var)
  506. if (*var++ == '=')
  507. break;
  508. return var;
  509. }
  510. /* ============ Parser data */
  511. /*
  512. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  513. */
  514. struct strlist {
  515. struct strlist *next;
  516. char *text;
  517. };
  518. struct alias;
  519. struct strpush {
  520. struct strpush *prev; /* preceding string on stack */
  521. char *prev_string;
  522. int prev_left_in_line;
  523. #if ENABLE_ASH_ALIAS
  524. struct alias *ap; /* if push was associated with an alias */
  525. #endif
  526. char *string; /* remember the string since it may change */
  527. /* Delay freeing so we can stop nested aliases. */
  528. struct strpush *spfree;
  529. /* Remember last two characters for pungetc. */
  530. int lastc[2];
  531. /* Number of outstanding calls to pungetc. */
  532. int unget;
  533. };
  534. /*
  535. * The parsefile structure pointed to by the global variable parsefile
  536. * contains information about the current file being read.
  537. */
  538. struct parsefile {
  539. struct parsefile *prev; /* preceding file on stack */
  540. int linno; /* current line */
  541. int pf_fd; /* file descriptor (or -1 if string) */
  542. int left_in_line; /* number of chars left in this line */
  543. int left_in_buffer; /* number of chars left in this buffer past the line */
  544. char *next_to_pgetc; /* next char in buffer */
  545. char *buf; /* input buffer */
  546. struct strpush *strpush; /* for pushing strings at this level */
  547. struct strpush basestrpush; /* so pushing one is fast */
  548. /* Delay freeing so we can stop nested aliases. */
  549. struct strpush *spfree;
  550. /* Remember last two characters for pungetc. */
  551. int lastc[2];
  552. /* Number of outstanding calls to pungetc. */
  553. int unget;
  554. };
  555. static struct parsefile basepf; /* top level input file */
  556. static struct parsefile *g_parsefile = &basepf; /* current input file */
  557. static char *commandname; /* currently executing command */
  558. /* ============ Interrupts / exceptions */
  559. static void exitshell(void) NORETURN;
  560. /*
  561. * These macros allow the user to suspend the handling of interrupt signals
  562. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  563. * much more efficient and portable. (But hacking the kernel is so much
  564. * more fun than worrying about efficiency and portability. :-))
  565. */
  566. #if DEBUG_INTONOFF
  567. # define INT_OFF do { \
  568. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  569. suppress_int++; \
  570. barrier(); \
  571. } while (0)
  572. #else
  573. # define INT_OFF do { \
  574. suppress_int++; \
  575. barrier(); \
  576. } while (0)
  577. #endif
  578. /*
  579. * Called to raise an exception. Since C doesn't include exceptions, we
  580. * just do a longjmp to the exception handler. The type of exception is
  581. * stored in the global variable "exception_type".
  582. */
  583. static void raise_exception(int) NORETURN;
  584. static void
  585. raise_exception(int e)
  586. {
  587. #if DEBUG
  588. if (exception_handler == NULL)
  589. abort();
  590. #endif
  591. INT_OFF;
  592. exception_type = e;
  593. longjmp(exception_handler->loc, 1);
  594. }
  595. #if DEBUG
  596. #define raise_exception(e) do { \
  597. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  598. raise_exception(e); \
  599. } while (0)
  600. #endif
  601. /*
  602. * Called when a SIGINT is received. (If the user specifies
  603. * that SIGINT is to be trapped or ignored using the trap builtin, then
  604. * this routine is not called.) suppress_int is nonzero when interrupts
  605. * are held using the INT_OFF macro. (The test for iflag is just
  606. * defensive programming.)
  607. */
  608. static void raise_interrupt(void) NORETURN;
  609. static void
  610. raise_interrupt(void)
  611. {
  612. pending_int = 0;
  613. /* Signal is not automatically unmasked after it is raised,
  614. * do it ourself - unmask all signals */
  615. sigprocmask_allsigs(SIG_UNBLOCK);
  616. /* pending_sig = 0; - now done in signal_handler() */
  617. if (!(rootshell && iflag)) {
  618. /* Kill ourself with SIGINT */
  619. signal(SIGINT, SIG_DFL);
  620. raise(SIGINT);
  621. }
  622. /* bash: ^C even on empty command line sets $? */
  623. exitstatus = SIGINT + 128;
  624. raise_exception(EXINT);
  625. /* NOTREACHED */
  626. }
  627. #if DEBUG
  628. #define raise_interrupt() do { \
  629. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  630. raise_interrupt(); \
  631. } while (0)
  632. #endif
  633. static IF_NOT_ASH_OPTIMIZE_FOR_SIZE(inline) void
  634. int_on(void)
  635. {
  636. barrier();
  637. if (--suppress_int == 0 && pending_int)
  638. raise_interrupt();
  639. }
  640. #if DEBUG_INTONOFF
  641. # define INT_ON do { \
  642. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  643. int_on(); \
  644. } while (0)
  645. #else
  646. # define INT_ON int_on()
  647. #endif
  648. static IF_NOT_ASH_OPTIMIZE_FOR_SIZE(inline) void
  649. force_int_on(void)
  650. {
  651. barrier();
  652. suppress_int = 0;
  653. if (pending_int)
  654. raise_interrupt();
  655. }
  656. #define FORCE_INT_ON force_int_on()
  657. #define SAVE_INT(v) ((v) = suppress_int)
  658. #define RESTORE_INT(v) do { \
  659. barrier(); \
  660. suppress_int = (v); \
  661. if (suppress_int == 0 && pending_int) \
  662. raise_interrupt(); \
  663. } while (0)
  664. /* ============ Stdout/stderr output */
  665. static void
  666. outstr(const char *p, FILE *file)
  667. {
  668. INT_OFF;
  669. fputs(p, file);
  670. INT_ON;
  671. }
  672. static void
  673. flush_stdout_stderr(void)
  674. {
  675. INT_OFF;
  676. fflush_all();
  677. INT_ON;
  678. }
  679. /* Was called outcslow(c,FILE*), but c was always '\n' */
  680. static void
  681. newline_and_flush(FILE *dest)
  682. {
  683. INT_OFF;
  684. putc('\n', dest);
  685. fflush(dest);
  686. INT_ON;
  687. }
  688. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  689. static int
  690. out1fmt(const char *fmt, ...)
  691. {
  692. va_list ap;
  693. int r;
  694. INT_OFF;
  695. va_start(ap, fmt);
  696. r = vprintf(fmt, ap);
  697. va_end(ap);
  698. INT_ON;
  699. return r;
  700. }
  701. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  702. static int
  703. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  704. {
  705. va_list ap;
  706. int ret;
  707. INT_OFF;
  708. va_start(ap, fmt);
  709. ret = vsnprintf(outbuf, length, fmt, ap);
  710. va_end(ap);
  711. INT_ON;
  712. return ret > (int)length ? length : ret;
  713. }
  714. static void
  715. out1str(const char *p)
  716. {
  717. outstr(p, stdout);
  718. }
  719. static void
  720. out2str(const char *p)
  721. {
  722. outstr(p, stderr);
  723. flush_stdout_stderr();
  724. }
  725. /* ============ Parser structures */
  726. /* control characters in argument strings */
  727. #define CTL_FIRST CTLESC
  728. #define CTLESC ((unsigned char)'\201') /* escape next character */
  729. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  730. #define CTLENDVAR ((unsigned char)'\203')
  731. #define CTLBACKQ ((unsigned char)'\204')
  732. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  733. #define CTLENDARI ((unsigned char)'\207')
  734. #define CTLQUOTEMARK ((unsigned char)'\210')
  735. #define CTL_LAST CTLQUOTEMARK
  736. #if BASH_PROCESS_SUBST
  737. # define CTLTOPROC ((unsigned char)'\211')
  738. # define CTLFROMPROC ((unsigned char)'\212')
  739. # undef CTL_LAST
  740. # define CTL_LAST CTLFROMPROC
  741. #endif
  742. /* variable substitution byte (follows CTLVAR) */
  743. #define VSTYPE 0x0f /* type of variable substitution */
  744. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  745. /* values of VSTYPE field */
  746. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  747. #define VSMINUS 0x2 /* ${var-text} */
  748. #define VSPLUS 0x3 /* ${var+text} */
  749. #define VSQUESTION 0x4 /* ${var?message} */
  750. #define VSASSIGN 0x5 /* ${var=text} */
  751. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  752. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  753. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  754. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  755. #define VSLENGTH 0xa /* ${#var} */
  756. #if BASH_SUBSTR
  757. #define VSSUBSTR 0xc /* ${var:position:length} */
  758. #endif
  759. #if BASH_PATTERN_SUBST
  760. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  761. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  762. #endif
  763. static const char dolatstr[] ALIGN1 = {
  764. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  765. };
  766. #define DOLATSTRLEN 6
  767. #define NCMD 0
  768. #define NPIPE 1
  769. #define NREDIR 2
  770. #define NBACKGND 3
  771. #define NSUBSHELL 4
  772. #define NAND 5
  773. #define NOR 6
  774. #define NSEMI 7
  775. #define NIF 8
  776. #define NWHILE 9
  777. #define NUNTIL 10
  778. #define NFOR 11
  779. #define NCASE 12
  780. #define NCLIST 13
  781. #define NDEFUN 14
  782. #define NARG 15
  783. #define NTO 16
  784. #if BASH_REDIR_OUTPUT
  785. #define NTO2 17
  786. #endif
  787. #define NCLOBBER 18
  788. #define NFROM 19
  789. #define NFROMTO 20
  790. #define NAPPEND 21
  791. #define NTOFD 22
  792. #define NFROMFD 23
  793. #define NHERE 24
  794. #define NXHERE 25
  795. #define NNOT 26
  796. #define N_NUMBER 27
  797. union node;
  798. struct ncmd {
  799. smallint type; /* Nxxxx */
  800. int linno;
  801. union node *assign;
  802. union node *args;
  803. union node *redirect;
  804. };
  805. struct npipe {
  806. smallint type;
  807. smallint pipe_backgnd;
  808. struct nodelist *cmdlist;
  809. };
  810. struct nredir {
  811. smallint type;
  812. int linno;
  813. union node *n;
  814. union node *redirect;
  815. };
  816. struct nbinary {
  817. smallint type;
  818. union node *ch1;
  819. union node *ch2;
  820. };
  821. struct nif {
  822. smallint type;
  823. union node *test;
  824. union node *ifpart;
  825. union node *elsepart;
  826. };
  827. struct nfor {
  828. smallint type;
  829. int linno;
  830. union node *args;
  831. union node *body;
  832. char *var;
  833. };
  834. struct ncase {
  835. smallint type;
  836. int linno;
  837. union node *expr;
  838. union node *cases;
  839. };
  840. struct nclist {
  841. smallint type;
  842. union node *next;
  843. union node *pattern;
  844. union node *body;
  845. };
  846. struct ndefun {
  847. smallint type;
  848. int linno;
  849. char *text;
  850. union node *body;
  851. };
  852. struct narg {
  853. smallint type;
  854. union node *next;
  855. char *text;
  856. struct nodelist *backquote;
  857. };
  858. /* nfile and ndup layout must match!
  859. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  860. * that it is actually NTO2 (>&file), and change its type.
  861. */
  862. struct nfile {
  863. smallint type;
  864. union node *next;
  865. int fd;
  866. int _unused_dupfd;
  867. union node *fname;
  868. char *expfname;
  869. };
  870. struct ndup {
  871. smallint type;
  872. union node *next;
  873. int fd;
  874. int dupfd;
  875. union node *vname;
  876. char *_unused_expfname;
  877. };
  878. struct nhere {
  879. smallint type;
  880. union node *next;
  881. int fd;
  882. union node *doc;
  883. };
  884. struct nnot {
  885. smallint type;
  886. union node *com;
  887. };
  888. union node {
  889. smallint type;
  890. struct ncmd ncmd;
  891. struct npipe npipe;
  892. struct nredir nredir;
  893. struct nbinary nbinary;
  894. struct nif nif;
  895. struct nfor nfor;
  896. struct ncase ncase;
  897. struct nclist nclist;
  898. struct ndefun ndefun;
  899. struct narg narg;
  900. struct nfile nfile;
  901. struct ndup ndup;
  902. struct nhere nhere;
  903. struct nnot nnot;
  904. };
  905. /*
  906. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  907. * It must be distinct from NULL.
  908. */
  909. #define NODE_EOF ((union node *) -1L)
  910. struct nodelist {
  911. struct nodelist *next;
  912. union node *n;
  913. };
  914. struct funcnode {
  915. int count;
  916. union node n;
  917. };
  918. /*
  919. * Free a parse tree.
  920. */
  921. static void
  922. freefunc(struct funcnode *f)
  923. {
  924. if (f && --f->count < 0)
  925. free(f);
  926. }
  927. /* ============ Debugging output */
  928. #if DEBUG
  929. static FILE *tracefile;
  930. static void
  931. trace_printf(const char *fmt, ...)
  932. {
  933. va_list va;
  934. if (debug != 1)
  935. return;
  936. if (DEBUG_TIME)
  937. fprintf(tracefile, "%u ", (int) time(NULL));
  938. if (DEBUG_PID)
  939. fprintf(tracefile, "[%u] ", (int) getpid());
  940. if (DEBUG_SIG)
  941. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  942. va_start(va, fmt);
  943. vfprintf(tracefile, fmt, va);
  944. va_end(va);
  945. }
  946. static void
  947. trace_vprintf(const char *fmt, va_list va)
  948. {
  949. if (debug != 1)
  950. return;
  951. vfprintf(tracefile, fmt, va);
  952. fprintf(tracefile, "\n");
  953. }
  954. static void
  955. trace_puts(const char *s)
  956. {
  957. if (debug != 1)
  958. return;
  959. fputs(s, tracefile);
  960. }
  961. static void
  962. trace_puts_quoted(char *s)
  963. {
  964. char *p;
  965. char c;
  966. if (debug != 1)
  967. return;
  968. putc('"', tracefile);
  969. for (p = s; *p; p++) {
  970. switch ((unsigned char)*p) {
  971. case '\n': c = 'n'; goto backslash;
  972. case '\t': c = 't'; goto backslash;
  973. case '\r': c = 'r'; goto backslash;
  974. case '\"': c = '\"'; goto backslash;
  975. case '\\': c = '\\'; goto backslash;
  976. case CTLESC: c = 'e'; goto backslash;
  977. case CTLVAR: c = 'v'; goto backslash;
  978. case CTLBACKQ: c = 'q'; goto backslash;
  979. #if BASH_PROCESS_SUBST
  980. case CTLTOPROC: c = 'p'; goto backslash;
  981. case CTLFROMPROC: c = 'P'; goto backslash;
  982. #endif
  983. backslash:
  984. putc('\\', tracefile);
  985. putc(c, tracefile);
  986. break;
  987. default:
  988. if (*p >= ' ' && *p <= '~')
  989. putc(*p, tracefile);
  990. else {
  991. putc('\\', tracefile);
  992. putc((*p >> 6) & 03, tracefile);
  993. putc((*p >> 3) & 07, tracefile);
  994. putc(*p & 07, tracefile);
  995. }
  996. break;
  997. }
  998. }
  999. putc('"', tracefile);
  1000. }
  1001. static void
  1002. trace_puts_args(char **ap)
  1003. {
  1004. if (debug != 1)
  1005. return;
  1006. if (!*ap)
  1007. return;
  1008. while (1) {
  1009. trace_puts_quoted(*ap);
  1010. if (!*++ap) {
  1011. putc('\n', tracefile);
  1012. break;
  1013. }
  1014. putc(' ', tracefile);
  1015. }
  1016. }
  1017. static void
  1018. opentrace(void)
  1019. {
  1020. char s[100];
  1021. #ifdef O_APPEND
  1022. int flags;
  1023. #endif
  1024. if (debug != 1) {
  1025. if (tracefile)
  1026. fflush(tracefile);
  1027. /* leave open because libedit might be using it */
  1028. return;
  1029. }
  1030. strcpy(s, "./trace");
  1031. if (tracefile) {
  1032. if (!freopen(s, "a", tracefile)) {
  1033. fprintf(stderr, "Can't re-open %s\n", s);
  1034. debug = 0;
  1035. return;
  1036. }
  1037. } else {
  1038. tracefile = fopen(s, "a");
  1039. if (tracefile == NULL) {
  1040. fprintf(stderr, "Can't open %s\n", s);
  1041. debug = 0;
  1042. return;
  1043. }
  1044. }
  1045. #ifdef O_APPEND
  1046. flags = fcntl(fileno(tracefile), F_GETFL);
  1047. if (flags >= 0)
  1048. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  1049. #endif
  1050. setlinebuf(tracefile);
  1051. fputs("\nTracing started.\n", tracefile);
  1052. }
  1053. static void
  1054. indent(int amount, char *pfx, FILE *fp)
  1055. {
  1056. int i;
  1057. for (i = 0; i < amount; i++) {
  1058. if (pfx && i == amount - 1)
  1059. fputs(pfx, fp);
  1060. putc('\t', fp);
  1061. }
  1062. }
  1063. /* little circular references here... */
  1064. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  1065. static void
  1066. sharg(union node *arg, FILE *fp)
  1067. {
  1068. char *p;
  1069. struct nodelist *bqlist;
  1070. unsigned char subtype;
  1071. if (arg->type != NARG) {
  1072. out1fmt("<node type %d>\n", arg->type);
  1073. abort();
  1074. }
  1075. bqlist = arg->narg.backquote;
  1076. for (p = arg->narg.text; *p; p++) {
  1077. switch ((unsigned char)*p) {
  1078. case CTLESC:
  1079. p++;
  1080. putc(*p, fp);
  1081. break;
  1082. case CTLVAR:
  1083. putc('$', fp);
  1084. putc('{', fp);
  1085. subtype = *++p;
  1086. if (subtype == VSLENGTH)
  1087. putc('#', fp);
  1088. while (*p != '=') {
  1089. putc(*p, fp);
  1090. p++;
  1091. }
  1092. if (subtype & VSNUL)
  1093. putc(':', fp);
  1094. switch (subtype & VSTYPE) {
  1095. case VSNORMAL:
  1096. putc('}', fp);
  1097. break;
  1098. case VSMINUS:
  1099. putc('-', fp);
  1100. break;
  1101. case VSPLUS:
  1102. putc('+', fp);
  1103. break;
  1104. case VSQUESTION:
  1105. putc('?', fp);
  1106. break;
  1107. case VSASSIGN:
  1108. putc('=', fp);
  1109. break;
  1110. case VSTRIMLEFT:
  1111. putc('#', fp);
  1112. break;
  1113. case VSTRIMLEFTMAX:
  1114. putc('#', fp);
  1115. putc('#', fp);
  1116. break;
  1117. case VSTRIMRIGHT:
  1118. putc('%', fp);
  1119. break;
  1120. case VSTRIMRIGHTMAX:
  1121. putc('%', fp);
  1122. putc('%', fp);
  1123. break;
  1124. case VSLENGTH:
  1125. break;
  1126. default:
  1127. out1fmt("<subtype %d>", subtype);
  1128. }
  1129. break;
  1130. case CTLENDVAR:
  1131. putc('}', fp);
  1132. break;
  1133. #if BASH_PROCESS_SUBST
  1134. case CTLTOPROC:
  1135. putc('>', fp);
  1136. goto backq;
  1137. case CTLFROMPROC:
  1138. putc('<', fp);
  1139. goto backq;
  1140. #endif
  1141. case CTLBACKQ:
  1142. putc('$', fp);
  1143. IF_BASH_PROCESS_SUBST(backq:)
  1144. putc('(', fp);
  1145. shtree(bqlist->n, -1, NULL, fp);
  1146. putc(')', fp);
  1147. break;
  1148. default:
  1149. putc(*p, fp);
  1150. break;
  1151. }
  1152. }
  1153. }
  1154. static void
  1155. shcmd(union node *cmd, FILE *fp)
  1156. {
  1157. union node *np;
  1158. int first;
  1159. const char *s;
  1160. int dftfd;
  1161. first = 1;
  1162. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1163. if (!first)
  1164. putc(' ', fp);
  1165. sharg(np, fp);
  1166. first = 0;
  1167. }
  1168. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1169. if (!first)
  1170. putc(' ', fp);
  1171. dftfd = 0;
  1172. switch (np->nfile.type) {
  1173. case NTO: s = ">>"+1; dftfd = 1; break;
  1174. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1175. case NAPPEND: s = ">>"; dftfd = 1; break;
  1176. #if BASH_REDIR_OUTPUT
  1177. case NTO2:
  1178. #endif
  1179. case NTOFD: s = ">&"; dftfd = 1; break;
  1180. case NFROM: s = "<"; break;
  1181. case NFROMFD: s = "<&"; break;
  1182. case NFROMTO: s = "<>"; break;
  1183. default: s = "*error*"; break;
  1184. }
  1185. if (np->nfile.fd != dftfd)
  1186. fprintf(fp, "%d", np->nfile.fd);
  1187. fputs(s, fp);
  1188. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1189. fprintf(fp, "%d", np->ndup.dupfd);
  1190. } else {
  1191. sharg(np->nfile.fname, fp);
  1192. }
  1193. first = 0;
  1194. }
  1195. }
  1196. static void
  1197. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1198. {
  1199. struct nodelist *lp;
  1200. const char *s;
  1201. if (n == NULL)
  1202. return;
  1203. indent(ind, pfx, fp);
  1204. if (n == NODE_EOF) {
  1205. fputs("<EOF>", fp);
  1206. return;
  1207. }
  1208. switch (n->type) {
  1209. case NSEMI:
  1210. s = "; ";
  1211. goto binop;
  1212. case NAND:
  1213. s = " && ";
  1214. goto binop;
  1215. case NOR:
  1216. s = " || ";
  1217. binop:
  1218. shtree(n->nbinary.ch1, ind, NULL, fp);
  1219. /* if (ind < 0) */
  1220. fputs(s, fp);
  1221. shtree(n->nbinary.ch2, ind, NULL, fp);
  1222. break;
  1223. case NCMD:
  1224. shcmd(n, fp);
  1225. if (ind >= 0)
  1226. putc('\n', fp);
  1227. break;
  1228. case NPIPE:
  1229. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1230. shtree(lp->n, 0, NULL, fp);
  1231. if (lp->next)
  1232. fputs(" | ", fp);
  1233. }
  1234. if (n->npipe.pipe_backgnd)
  1235. fputs(" &", fp);
  1236. if (ind >= 0)
  1237. putc('\n', fp);
  1238. break;
  1239. default:
  1240. fprintf(fp, "<node type %d>", n->type);
  1241. if (ind >= 0)
  1242. putc('\n', fp);
  1243. break;
  1244. }
  1245. }
  1246. static void
  1247. showtree(union node *n)
  1248. {
  1249. trace_puts("showtree called\n");
  1250. shtree(n, 1, NULL, stderr);
  1251. }
  1252. #endif /* DEBUG */
  1253. /* ============ Message printing */
  1254. static void
  1255. ash_vmsg(const char *msg, va_list ap)
  1256. {
  1257. fprintf(stderr, "%s: ", arg0);
  1258. if (commandname) {
  1259. if (strcmp(arg0, commandname))
  1260. fprintf(stderr, "%s: ", commandname);
  1261. if (!iflag || g_parsefile->pf_fd > 0)
  1262. fprintf(stderr, "line %d: ", errlinno);
  1263. }
  1264. vfprintf(stderr, msg, ap);
  1265. newline_and_flush(stderr);
  1266. }
  1267. /*
  1268. * Exverror is called to raise the error exception. If the second argument
  1269. * is not NULL then error prints an error message using printf style
  1270. * formatting. It then raises the error exception.
  1271. */
  1272. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1273. static void
  1274. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1275. {
  1276. #if DEBUG
  1277. if (msg) {
  1278. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1279. TRACEV((msg, ap));
  1280. } else
  1281. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1282. if (msg)
  1283. #endif
  1284. ash_vmsg(msg, ap);
  1285. flush_stdout_stderr();
  1286. raise_exception(cond);
  1287. /* NOTREACHED */
  1288. }
  1289. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1290. static void
  1291. ash_msg_and_raise_error(const char *msg, ...)
  1292. {
  1293. va_list ap;
  1294. exitstatus = 2;
  1295. va_start(ap, msg);
  1296. ash_vmsg_and_raise(EXERROR, msg, ap);
  1297. /* NOTREACHED */
  1298. va_end(ap);
  1299. }
  1300. /*
  1301. * 'fmt' must be a string literal.
  1302. */
  1303. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1304. static void raise_error_syntax(const char *) NORETURN;
  1305. static void
  1306. raise_error_syntax(const char *msg)
  1307. {
  1308. errlinno = g_parsefile->linno;
  1309. ash_msg_and_raise_error("syntax error: %s", msg);
  1310. /* NOTREACHED */
  1311. }
  1312. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1313. static void
  1314. ash_msg_and_raise(int cond, const char *msg, ...)
  1315. {
  1316. va_list ap;
  1317. va_start(ap, msg);
  1318. ash_vmsg_and_raise(cond, msg, ap);
  1319. /* NOTREACHED */
  1320. va_end(ap);
  1321. }
  1322. /*
  1323. * error/warning routines for external builtins
  1324. */
  1325. static void
  1326. ash_msg(const char *fmt, ...)
  1327. {
  1328. va_list ap;
  1329. va_start(ap, fmt);
  1330. ash_vmsg(fmt, ap);
  1331. va_end(ap);
  1332. }
  1333. /*
  1334. * Return a string describing an error. The returned string may be a
  1335. * pointer to a static buffer that will be overwritten on the next call.
  1336. * Action describes the operation that got the error.
  1337. */
  1338. static const char *
  1339. errmsg(int e, const char *em)
  1340. {
  1341. if (e == ENOENT || e == ENOTDIR) {
  1342. return em;
  1343. }
  1344. return strerror(e);
  1345. }
  1346. /* ============ Memory allocation */
  1347. #if 0
  1348. /* I consider these wrappers nearly useless:
  1349. * ok, they return you to nearest exception handler, but
  1350. * how much memory do you leak in the process, making
  1351. * memory starvation worse?
  1352. */
  1353. static void *
  1354. ckrealloc(void * p, size_t nbytes)
  1355. {
  1356. p = realloc(p, nbytes);
  1357. if (!p)
  1358. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1359. return p;
  1360. }
  1361. static void *
  1362. ckmalloc(size_t nbytes)
  1363. {
  1364. return ckrealloc(NULL, nbytes);
  1365. }
  1366. static void *
  1367. ckzalloc(size_t nbytes)
  1368. {
  1369. return memset(ckmalloc(nbytes), 0, nbytes);
  1370. }
  1371. static char *
  1372. ckstrdup(const char *s)
  1373. {
  1374. char *p = strdup(s);
  1375. if (!p)
  1376. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1377. return p;
  1378. }
  1379. #else
  1380. /* Using bbox equivalents. They exit if out of memory */
  1381. # define ckrealloc xrealloc
  1382. # define ckmalloc xmalloc
  1383. # define ckzalloc xzalloc
  1384. # define ckstrdup xstrdup
  1385. #endif
  1386. /*
  1387. * It appears that grabstackstr() will barf with such alignments
  1388. * because stalloc() will return a string allocated in a new stackblock.
  1389. */
  1390. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1391. enum {
  1392. /* Most machines require the value returned from malloc to be aligned
  1393. * in some way. The following macro will get this right
  1394. * on many machines. */
  1395. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1396. /* Minimum size of a block */
  1397. MINSIZE = SHELL_ALIGN(504),
  1398. };
  1399. struct stack_block {
  1400. struct stack_block *prev;
  1401. char space[MINSIZE];
  1402. };
  1403. struct stackmark {
  1404. struct stack_block *stackp;
  1405. char *stacknxt;
  1406. size_t stacknleft;
  1407. };
  1408. struct globals_memstack {
  1409. struct stack_block *g_stackp; // = &stackbase;
  1410. char *g_stacknxt; // = stackbase.space;
  1411. char *sstrend; // = stackbase.space + MINSIZE;
  1412. size_t g_stacknleft; // = MINSIZE;
  1413. struct stack_block stackbase;
  1414. };
  1415. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1416. #define G_memstack (*ash_ptr_to_globals_memstack)
  1417. #define g_stackp (G_memstack.g_stackp )
  1418. #define g_stacknxt (G_memstack.g_stacknxt )
  1419. #define sstrend (G_memstack.sstrend )
  1420. #define g_stacknleft (G_memstack.g_stacknleft)
  1421. #define stackbase (G_memstack.stackbase )
  1422. #define INIT_G_memstack() do { \
  1423. XZALLOC_CONST_PTR(&ash_ptr_to_globals_memstack, sizeof(G_memstack)); \
  1424. g_stackp = &stackbase; \
  1425. g_stacknxt = stackbase.space; \
  1426. g_stacknleft = MINSIZE; \
  1427. sstrend = stackbase.space + MINSIZE; \
  1428. } while (0)
  1429. #define stackblock() ((void *)g_stacknxt)
  1430. #define stackblocksize() g_stacknleft
  1431. /*
  1432. * Parse trees for commands are allocated in lifo order, so we use a stack
  1433. * to make this more efficient, and also to avoid all sorts of exception
  1434. * handling code to handle interrupts in the middle of a parse.
  1435. *
  1436. * The size 504 was chosen because the Ultrix malloc handles that size
  1437. * well.
  1438. */
  1439. static void *
  1440. stalloc(size_t nbytes)
  1441. {
  1442. char *p;
  1443. size_t aligned;
  1444. aligned = SHELL_ALIGN(nbytes);
  1445. if (aligned > g_stacknleft) {
  1446. size_t len;
  1447. size_t blocksize;
  1448. struct stack_block *sp;
  1449. blocksize = aligned;
  1450. if (blocksize < MINSIZE)
  1451. blocksize = MINSIZE;
  1452. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1453. if (len < blocksize)
  1454. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1455. INT_OFF;
  1456. sp = ckmalloc(len);
  1457. sp->prev = g_stackp;
  1458. g_stacknxt = sp->space;
  1459. g_stacknleft = blocksize;
  1460. sstrend = g_stacknxt + blocksize;
  1461. g_stackp = sp;
  1462. INT_ON;
  1463. }
  1464. p = g_stacknxt;
  1465. g_stacknxt += aligned;
  1466. g_stacknleft -= aligned;
  1467. return p;
  1468. }
  1469. static void *
  1470. stzalloc(size_t nbytes)
  1471. {
  1472. return memset(stalloc(nbytes), 0, nbytes);
  1473. }
  1474. static void
  1475. stunalloc(void *p)
  1476. {
  1477. #if DEBUG
  1478. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1479. write(STDERR_FILENO, "stunalloc\n", 10);
  1480. abort();
  1481. }
  1482. #endif
  1483. g_stacknleft += g_stacknxt - (char *)p;
  1484. g_stacknxt = p;
  1485. }
  1486. /*
  1487. * Like strdup but works with the ash stack.
  1488. */
  1489. static char *
  1490. sstrdup(const char *p)
  1491. {
  1492. size_t len = strlen(p) + 1;
  1493. return memcpy(stalloc(len), p, len);
  1494. }
  1495. static ALWAYS_INLINE void
  1496. grabstackblock(size_t len)
  1497. {
  1498. stalloc(len);
  1499. }
  1500. static void
  1501. pushstackmark(struct stackmark *mark, size_t len)
  1502. {
  1503. mark->stackp = g_stackp;
  1504. mark->stacknxt = g_stacknxt;
  1505. mark->stacknleft = g_stacknleft;
  1506. grabstackblock(len);
  1507. }
  1508. static void
  1509. setstackmark(struct stackmark *mark)
  1510. {
  1511. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1512. }
  1513. static void
  1514. popstackmark(struct stackmark *mark)
  1515. {
  1516. struct stack_block *sp;
  1517. if (!mark->stackp)
  1518. return;
  1519. INT_OFF;
  1520. while (g_stackp != mark->stackp) {
  1521. sp = g_stackp;
  1522. g_stackp = sp->prev;
  1523. free(sp);
  1524. }
  1525. g_stacknxt = mark->stacknxt;
  1526. g_stacknleft = mark->stacknleft;
  1527. sstrend = mark->stacknxt + mark->stacknleft;
  1528. INT_ON;
  1529. }
  1530. /*
  1531. * When the parser reads in a string, it wants to stick the string on the
  1532. * stack and only adjust the stack pointer when it knows how big the
  1533. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1534. * of space on top of the stack and stackblocklen returns the length of
  1535. * this block. Growstackblock will grow this space by at least one byte,
  1536. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1537. * part of the block that has been used.
  1538. */
  1539. static void
  1540. growstackblock(size_t min)
  1541. {
  1542. size_t newlen;
  1543. newlen = g_stacknleft * 2;
  1544. if (newlen < g_stacknleft)
  1545. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1546. min = SHELL_ALIGN(min | 128);
  1547. if (newlen < min)
  1548. newlen += min;
  1549. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1550. struct stack_block *sp;
  1551. struct stack_block *prevstackp;
  1552. size_t grosslen;
  1553. INT_OFF;
  1554. sp = g_stackp;
  1555. prevstackp = sp->prev;
  1556. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1557. sp = ckrealloc(sp, grosslen);
  1558. sp->prev = prevstackp;
  1559. g_stackp = sp;
  1560. g_stacknxt = sp->space;
  1561. g_stacknleft = newlen;
  1562. sstrend = sp->space + newlen;
  1563. INT_ON;
  1564. } else {
  1565. char *oldspace = g_stacknxt;
  1566. size_t oldlen = g_stacknleft;
  1567. char *p = stalloc(newlen);
  1568. /* free the space we just allocated */
  1569. g_stacknxt = memcpy(p, oldspace, oldlen);
  1570. g_stacknleft += newlen;
  1571. }
  1572. }
  1573. /*
  1574. * The following routines are somewhat easier to use than the above.
  1575. * The user declares a variable of type STACKSTR, which may be declared
  1576. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1577. * the user uses the macro STPUTC to add characters to the string. In
  1578. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1579. * grown as necessary. When the user is done, she can just leave the
  1580. * string there and refer to it using stackblock(). Or she can allocate
  1581. * the space for it using grabstackstr(). If it is necessary to allow
  1582. * someone else to use the stack temporarily and then continue to grow
  1583. * the string, the user should use grabstack to allocate the space, and
  1584. * then call ungrabstr(p) to return to the previous mode of operation.
  1585. *
  1586. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1587. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1588. * is space for at least one character.
  1589. */
  1590. static void *
  1591. growstackstr(void)
  1592. {
  1593. size_t len = stackblocksize();
  1594. growstackblock(0);
  1595. return (char *)stackblock() + len;
  1596. }
  1597. static char *
  1598. growstackto(size_t len)
  1599. {
  1600. if (stackblocksize() < len)
  1601. growstackblock(len);
  1602. return stackblock();
  1603. }
  1604. /*
  1605. * Called from CHECKSTRSPACE.
  1606. */
  1607. static char *
  1608. makestrspace(size_t newlen, char *p)
  1609. {
  1610. size_t len = p - g_stacknxt;
  1611. return growstackto(len + newlen) + len;
  1612. }
  1613. static char *
  1614. stnputs(const char *s, size_t n, char *p)
  1615. {
  1616. p = makestrspace(n, p);
  1617. p = (char *)mempcpy(p, s, n);
  1618. return p;
  1619. }
  1620. static char *
  1621. stack_putstr(const char *s, char *p)
  1622. {
  1623. return stnputs(s, strlen(s), p);
  1624. }
  1625. static char *
  1626. _STPUTC(int c, char *p)
  1627. {
  1628. if (p == sstrend)
  1629. p = growstackstr();
  1630. *p++ = c;
  1631. return p;
  1632. }
  1633. #define STARTSTACKSTR(p) ((p) = stackblock())
  1634. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1635. #define CHECKSTRSPACE(n, p) do { \
  1636. char *q = (p); \
  1637. size_t l = (n); \
  1638. size_t m = sstrend - q; \
  1639. if (l > m) \
  1640. (p) = makestrspace(l, q); \
  1641. } while (0)
  1642. #define USTPUTC(c, p) (*(p)++ = (c))
  1643. #define STACKSTRNUL(p) do { \
  1644. if ((p) == sstrend) \
  1645. (p) = growstackstr(); \
  1646. *(p) = '\0'; \
  1647. } while (0)
  1648. #define STUNPUTC(p) (--(p))
  1649. #define STTOPC(p) ((p)[-1])
  1650. #define STADJUST(amount, p) ((p) += (amount))
  1651. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1652. #define ungrabstackstr(s, p) stunalloc(s)
  1653. #define stackstrend() ((void *)sstrend)
  1654. /* ============ String helpers */
  1655. /*
  1656. * prefix -- see if pfx is a prefix of string.
  1657. */
  1658. static char *
  1659. prefix(const char *string, const char *pfx)
  1660. {
  1661. while (*pfx) {
  1662. if (*pfx++ != *string++)
  1663. return NULL;
  1664. }
  1665. return (char *) string;
  1666. }
  1667. /*
  1668. * Check for a valid number. This should be elsewhere.
  1669. */
  1670. static int
  1671. is_number(const char *p)
  1672. {
  1673. do {
  1674. if (!isdigit(*p))
  1675. return 0;
  1676. } while (*++p != '\0');
  1677. return 1;
  1678. }
  1679. /*
  1680. * Convert a string of digits to an integer, printing an error message on
  1681. * failure.
  1682. */
  1683. static int
  1684. number(const char *s)
  1685. {
  1686. if (!is_number(s))
  1687. ash_msg_and_raise_error(msg_illnum, s);
  1688. return atoi(s);
  1689. }
  1690. /*
  1691. * Produce a single quoted string suitable as input to the shell.
  1692. * The return string is allocated on the stack.
  1693. */
  1694. static char *
  1695. single_quote(const char *s)
  1696. {
  1697. char *p;
  1698. STARTSTACKSTR(p);
  1699. do {
  1700. char *q;
  1701. size_t len;
  1702. len = strchrnul(s, '\'') - s;
  1703. q = p = makestrspace(len + 3, p);
  1704. *q++ = '\'';
  1705. q = (char *)mempcpy(q, s, len);
  1706. *q++ = '\'';
  1707. s += len;
  1708. STADJUST(q - p, p);
  1709. if (*s != '\'')
  1710. break;
  1711. len = 0;
  1712. do len++; while (*++s == '\'');
  1713. q = p = makestrspace(len + 3, p);
  1714. *q++ = '"';
  1715. q = (char *)mempcpy(q, s - len, len);
  1716. *q++ = '"';
  1717. STADJUST(q - p, p);
  1718. } while (*s);
  1719. USTPUTC('\0', p);
  1720. return stackblock();
  1721. }
  1722. /*
  1723. * Produce a possibly single quoted string suitable as input to the shell.
  1724. * If quoting was done, the return string is allocated on the stack,
  1725. * otherwise a pointer to the original string is returned.
  1726. */
  1727. static const char *
  1728. maybe_single_quote(const char *s)
  1729. {
  1730. const char *p = s;
  1731. while (*p) {
  1732. /* Assuming ACSII */
  1733. /* quote ctrl_chars space !"#$%&'()* */
  1734. if (*p < '+')
  1735. goto need_quoting;
  1736. /* quote ;<=>? */
  1737. if (*p >= ';' && *p <= '?')
  1738. goto need_quoting;
  1739. /* quote `[\ */
  1740. if (*p == '`')
  1741. goto need_quoting;
  1742. if (*p == '[')
  1743. goto need_quoting;
  1744. if (*p == '\\')
  1745. goto need_quoting;
  1746. /* quote {|}~ DEL and high bytes */
  1747. if (*p > 'z')
  1748. goto need_quoting;
  1749. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1750. /* TODO: maybe avoid quoting % */
  1751. p++;
  1752. }
  1753. return s;
  1754. need_quoting:
  1755. return single_quote(s);
  1756. }
  1757. /* ============ nextopt */
  1758. static char **argptr; /* argument list for builtin commands */
  1759. static char *optionarg; /* set by nextopt (like getopt) */
  1760. static char *optptr; /* used by nextopt */
  1761. /*
  1762. * XXX - should get rid of. Have all builtins use getopt(3).
  1763. * The library getopt must have the BSD extension static variable
  1764. * "optreset", otherwise it can't be used within the shell safely.
  1765. *
  1766. * Standard option processing (a la getopt) for builtin routines.
  1767. * The only argument that is passed to nextopt is the option string;
  1768. * the other arguments are unnecessary. It returns the character,
  1769. * or '\0' on end of input.
  1770. */
  1771. static int
  1772. nextopt(const char *optstring)
  1773. {
  1774. char *p;
  1775. const char *q;
  1776. char c;
  1777. p = optptr;
  1778. if (p == NULL || *p == '\0') {
  1779. /* We ate entire "-param", take next one */
  1780. p = *argptr;
  1781. if (p == NULL)
  1782. return '\0';
  1783. if (*p != '-')
  1784. return '\0';
  1785. if (*++p == '\0') /* just "-" ? */
  1786. return '\0';
  1787. argptr++;
  1788. if (LONE_DASH(p)) /* "--" ? */
  1789. return '\0';
  1790. /* p => next "-param" */
  1791. }
  1792. /* p => some option char in the middle of a "-param" */
  1793. c = *p++;
  1794. for (q = optstring; *q != c;) {
  1795. if (*q == '\0')
  1796. ash_msg_and_raise_error("illegal option -%c", c);
  1797. if (*++q == ':')
  1798. q++;
  1799. }
  1800. if (*++q == ':') {
  1801. if (*p == '\0') {
  1802. p = *argptr++;
  1803. if (p == NULL)
  1804. ash_msg_and_raise_error("no arg for -%c option", c);
  1805. }
  1806. optionarg = p;
  1807. p = NULL;
  1808. }
  1809. optptr = p;
  1810. return c;
  1811. }
  1812. /* ============ Shell variables */
  1813. struct shparam {
  1814. int nparam; /* # of positional parameters (without $0) */
  1815. #if ENABLE_ASH_GETOPTS
  1816. int optind; /* next parameter to be processed by getopts */
  1817. int optoff; /* used by getopts */
  1818. #endif
  1819. unsigned char malloced; /* if parameter list dynamically allocated */
  1820. char **p; /* parameter list */
  1821. };
  1822. /*
  1823. * Free the list of positional parameters.
  1824. */
  1825. static void
  1826. freeparam(volatile struct shparam *param)
  1827. {
  1828. if (param->malloced) {
  1829. char **ap, **ap1;
  1830. ap = ap1 = param->p;
  1831. while (*ap)
  1832. free(*ap++);
  1833. free(ap1);
  1834. }
  1835. }
  1836. #if ENABLE_ASH_GETOPTS
  1837. static void FAST_FUNC getoptsreset(const char *value);
  1838. #endif
  1839. struct var {
  1840. struct var *next; /* next entry in hash list */
  1841. int flags; /* flags are defined above */
  1842. const char *var_text; /* name=value */
  1843. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1844. /* the variable gets set/unset */
  1845. };
  1846. struct localvar {
  1847. struct localvar *next; /* next local variable in list */
  1848. struct var *vp; /* the variable that was made local */
  1849. int flags; /* saved flags */
  1850. const char *text; /* saved text */
  1851. };
  1852. /* flags */
  1853. #define VEXPORT 0x01 /* variable is exported */
  1854. #define VREADONLY 0x02 /* variable cannot be modified */
  1855. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1856. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1857. #define VSTACK 0x10 /* text is allocated on the stack */
  1858. #define VUNSET 0x20 /* the variable is not set */
  1859. #define VNOFUNC 0x40 /* don't call the callback function */
  1860. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1861. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1862. #if ENABLE_ASH_RANDOM_SUPPORT
  1863. # define VDYNAMIC 0x200 /* dynamic variable */
  1864. #else
  1865. # define VDYNAMIC 0
  1866. #endif
  1867. /* Need to be before varinit_data[] */
  1868. #if ENABLE_LOCALE_SUPPORT
  1869. static void FAST_FUNC
  1870. change_lc_all(const char *value)
  1871. {
  1872. if (value && *value != '\0')
  1873. setlocale(LC_ALL, value);
  1874. }
  1875. static void FAST_FUNC
  1876. change_lc_ctype(const char *value)
  1877. {
  1878. if (value && *value != '\0')
  1879. setlocale(LC_CTYPE, value);
  1880. }
  1881. #endif
  1882. #if ENABLE_ASH_MAIL
  1883. static void chkmail(void);
  1884. static void changemail(const char *var_value) FAST_FUNC;
  1885. #else
  1886. # define chkmail() ((void)0)
  1887. #endif
  1888. static void changepath(const char *) FAST_FUNC;
  1889. #if ENABLE_ASH_RANDOM_SUPPORT
  1890. static void change_random(const char *) FAST_FUNC;
  1891. #endif
  1892. #if BASH_EPOCH_VARS
  1893. static void change_seconds(const char *) FAST_FUNC;
  1894. static void change_realtime(const char *) FAST_FUNC;
  1895. #endif
  1896. static const struct {
  1897. int flags;
  1898. const char *var_text;
  1899. void (*var_func)(const char *) FAST_FUNC;
  1900. } varinit_data[] ALIGN_PTR = {
  1901. /*
  1902. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1903. * some environment strings may be constant.
  1904. */
  1905. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1906. #if ENABLE_ASH_MAIL
  1907. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1908. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1909. #endif
  1910. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1911. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1912. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1913. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1914. #if ENABLE_ASH_GETOPTS
  1915. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1916. #endif
  1917. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1918. { VSTRFIXED|VTEXTFIXED , NULL /* inited to funcnamevar */, NULL },
  1919. #if ENABLE_ASH_RANDOM_SUPPORT
  1920. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1921. #endif
  1922. #if BASH_EPOCH_VARS
  1923. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
  1924. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
  1925. #endif
  1926. #if ENABLE_LOCALE_SUPPORT
  1927. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1928. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1929. #endif
  1930. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1931. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1932. #endif
  1933. };
  1934. struct redirtab;
  1935. struct globals_var {
  1936. struct shparam shellparam; /* $@ current positional parameters */
  1937. struct redirtab *redirlist;
  1938. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1939. struct var *vartab[VTABSIZE];
  1940. struct var varinit[ARRAY_SIZE(varinit_data)];
  1941. int lineno;
  1942. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1943. char funcnamevar[sizeof("FUNCNAME=") + 64];
  1944. char *funcname;
  1945. unsigned trap_depth;
  1946. bool in_trap_ERR; /* ERR cannot recurse, no need to be a counter */
  1947. };
  1948. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1949. #define G_var (*ash_ptr_to_globals_var)
  1950. #define shellparam (G_var.shellparam )
  1951. //#define redirlist (G_var.redirlist )
  1952. #define preverrout_fd (G_var.preverrout_fd)
  1953. #define vartab (G_var.vartab )
  1954. #define varinit (G_var.varinit )
  1955. #define lineno (G_var.lineno )
  1956. #define linenovar (G_var.linenovar )
  1957. #define funcnamevar (G_var.funcnamevar )
  1958. #define funcname (G_var.funcname )
  1959. #define trap_depth (G_var.trap_depth )
  1960. #define in_trap_ERR (G_var.in_trap_ERR )
  1961. #define vifs varinit[0]
  1962. #if ENABLE_ASH_MAIL
  1963. # define vmail varinit[1]
  1964. # define vmpath varinit[2]
  1965. #endif
  1966. #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
  1967. #define vpath varinit[VAR_OFFSET1 + 1]
  1968. #define vps1 varinit[VAR_OFFSET1 + 2]
  1969. #define vps2 varinit[VAR_OFFSET1 + 3]
  1970. #define vps4 varinit[VAR_OFFSET1 + 4]
  1971. #if ENABLE_ASH_GETOPTS
  1972. # define voptind varinit[VAR_OFFSET1 + 5]
  1973. #endif
  1974. #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
  1975. #define vlineno varinit[VAR_OFFSET2 + 5]
  1976. #define vfuncname varinit[VAR_OFFSET2 + 6]
  1977. #if ENABLE_ASH_RANDOM_SUPPORT
  1978. # define vrandom varinit[VAR_OFFSET2 + 7]
  1979. #endif
  1980. #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
  1981. #if BASH_EPOCH_VARS
  1982. # define vepochs varinit[VAR_OFFSET3 + 7]
  1983. # define vepochr varinit[VAR_OFFSET3 + 8]
  1984. #endif
  1985. #define INIT_G_var() do { \
  1986. unsigned i; \
  1987. XZALLOC_CONST_PTR(&ash_ptr_to_globals_var, sizeof(G_var)); \
  1988. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1989. varinit[i].flags = varinit_data[i].flags; \
  1990. varinit[i].var_text = varinit_data[i].var_text; \
  1991. varinit[i].var_func = varinit_data[i].var_func; \
  1992. } \
  1993. strcpy(linenovar, "LINENO="); \
  1994. vlineno.var_text = linenovar; \
  1995. strcpy(funcnamevar, "FUNCNAME="); \
  1996. vfuncname.var_text = funcnamevar; \
  1997. } while (0)
  1998. /*
  1999. * The following macros access the values of the above variables.
  2000. * They have to skip over the name. They return the null string
  2001. * for unset variables.
  2002. */
  2003. #define ifsval() (vifs.var_text + 4)
  2004. #define ifsset() ((vifs.flags & VUNSET) == 0)
  2005. #if ENABLE_ASH_MAIL
  2006. # define mailval() (vmail.var_text + 5)
  2007. # define mpathval() (vmpath.var_text + 9)
  2008. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  2009. #endif
  2010. #define pathval() (vpath.var_text + 5)
  2011. #define ps1val() (vps1.var_text + 4)
  2012. #define ps2val() (vps2.var_text + 4)
  2013. #define ps4val() (vps4.var_text + 4)
  2014. #if ENABLE_ASH_GETOPTS
  2015. # define optindval() (voptind.var_text + 7)
  2016. #endif
  2017. #if ENABLE_ASH_GETOPTS
  2018. static void FAST_FUNC
  2019. getoptsreset(const char *value)
  2020. {
  2021. shellparam.optind = 1;
  2022. if (is_number(value))
  2023. shellparam.optind = number(value) ?: 1;
  2024. shellparam.optoff = -1;
  2025. }
  2026. #endif
  2027. /*
  2028. * Compares two strings up to the first = or '\0'. The first
  2029. * string must be terminated by '='; the second may be terminated by
  2030. * either '=' or '\0'.
  2031. */
  2032. static int
  2033. varcmp(const char *p, const char *q)
  2034. {
  2035. int c, d;
  2036. while ((c = *p) == (d = *q)) {
  2037. if (c == '\0' || c == '=')
  2038. goto out;
  2039. p++;
  2040. q++;
  2041. }
  2042. if (c == '=')
  2043. c = '\0';
  2044. if (d == '=')
  2045. d = '\0';
  2046. out:
  2047. return c - d;
  2048. }
  2049. /*
  2050. * Find the appropriate entry in the hash table from the name.
  2051. */
  2052. static struct var **
  2053. hashvar(const char *p)
  2054. {
  2055. unsigned hashval;
  2056. hashval = ((unsigned char) *p) << 4;
  2057. while (*p && *p != '=')
  2058. hashval += (unsigned char) *p++;
  2059. return &vartab[hashval % VTABSIZE];
  2060. }
  2061. static int
  2062. vpcmp(const void *a, const void *b)
  2063. {
  2064. return varcmp(*(const char **)a, *(const char **)b);
  2065. }
  2066. /*
  2067. * This routine initializes the builtin variables.
  2068. */
  2069. static void
  2070. initvar(void)
  2071. {
  2072. struct var *vp;
  2073. struct var *end;
  2074. struct var **vpp;
  2075. /*
  2076. * PS1 depends on uid
  2077. */
  2078. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2079. vps1.var_text = "PS1=\\w \\$ ";
  2080. #else
  2081. if (!geteuid())
  2082. vps1.var_text = "PS1=# ";
  2083. #endif
  2084. vp = varinit;
  2085. end = vp + ARRAY_SIZE(varinit);
  2086. do {
  2087. vpp = hashvar(vp->var_text);
  2088. vp->next = *vpp;
  2089. *vpp = vp;
  2090. } while (++vp < end);
  2091. }
  2092. static struct var **
  2093. findvar(struct var **vpp, const char *name)
  2094. {
  2095. for (; *vpp; vpp = &(*vpp)->next) {
  2096. if (varcmp((*vpp)->var_text, name) == 0) {
  2097. break;
  2098. }
  2099. }
  2100. return vpp;
  2101. }
  2102. /*
  2103. * Find the value of a variable. Returns NULL if not set.
  2104. */
  2105. static const char* FAST_FUNC
  2106. lookupvar(const char *name)
  2107. {
  2108. struct var *v;
  2109. v = *findvar(hashvar(name), name);
  2110. if (v) {
  2111. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2112. /*
  2113. * Dynamic variables are implemented roughly the same way they are
  2114. * in bash. Namely, they're "special" so long as they aren't unset.
  2115. * As soon as they're unset, they're no longer dynamic, and dynamic
  2116. * lookup will no longer happen at that point. -- PFM.
  2117. */
  2118. if (v->flags & VDYNAMIC)
  2119. v->var_func(NULL);
  2120. #endif
  2121. if (!(v->flags & VUNSET)) {
  2122. if (v->var_text == linenovar) {
  2123. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2124. } else
  2125. if (v->var_text == funcnamevar) {
  2126. safe_strncpy(funcnamevar+9, funcname ? funcname : "", sizeof(funcnamevar)-9);
  2127. }
  2128. return var_end(v->var_text);
  2129. }
  2130. }
  2131. return NULL;
  2132. }
  2133. #if ENABLE_UNICODE_SUPPORT
  2134. static void
  2135. reinit_unicode_for_ash(void)
  2136. {
  2137. /* Unicode support should be activated even if LANG is set
  2138. * _during_ shell execution, not only if it was set when
  2139. * shell was started. Therefore, re-check LANG every time:
  2140. */
  2141. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2142. || ENABLE_UNICODE_USING_LOCALE
  2143. ) {
  2144. const char *s = lookupvar("LC_ALL");
  2145. if (!s) s = lookupvar("LC_CTYPE");
  2146. if (!s) s = lookupvar("LANG");
  2147. reinit_unicode(s);
  2148. }
  2149. }
  2150. #else
  2151. # define reinit_unicode_for_ash() ((void)0)
  2152. #endif
  2153. /*
  2154. * Search the environment of a builtin command.
  2155. */
  2156. static ALWAYS_INLINE const char *
  2157. bltinlookup(const char *name)
  2158. {
  2159. return lookupvar(name);
  2160. }
  2161. /*
  2162. * Same as setvar except that the variable and value are passed in
  2163. * the first argument as name=value. Since the first argument will
  2164. * be actually stored in the table, it should not be a string that
  2165. * will go away.
  2166. * Called with interrupts off.
  2167. */
  2168. static struct var *
  2169. setvareq(char *s, int flags)
  2170. {
  2171. struct var *vp, **vpp;
  2172. vpp = hashvar(s);
  2173. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2174. vpp = findvar(vpp, s);
  2175. vp = *vpp;
  2176. if (vp) {
  2177. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2178. const char *n;
  2179. if (flags & VNOSAVE)
  2180. free(s);
  2181. n = vp->var_text;
  2182. exitstatus = 1;
  2183. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2184. }
  2185. if (flags & VNOSET)
  2186. goto out;
  2187. if (vp->var_func && !(flags & VNOFUNC))
  2188. vp->var_func(var_end(s));
  2189. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2190. free((char*)vp->var_text);
  2191. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2192. *vpp = vp->next;
  2193. free(vp);
  2194. out_free:
  2195. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2196. free(s);
  2197. goto out;
  2198. }
  2199. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2200. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2201. if (flags & VUNSET)
  2202. flags &= ~VDYNAMIC;
  2203. #endif
  2204. } else {
  2205. /* variable s is not found */
  2206. if (flags & VNOSET)
  2207. goto out;
  2208. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2209. goto out_free;
  2210. vp = ckzalloc(sizeof(*vp));
  2211. vp->next = *vpp;
  2212. /*vp->func = NULL; - ckzalloc did it */
  2213. *vpp = vp;
  2214. }
  2215. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2216. s = ckstrdup(s);
  2217. vp->var_text = s;
  2218. vp->flags = flags;
  2219. out:
  2220. return vp;
  2221. }
  2222. /*
  2223. * Set the value of a variable. The flags argument is ored with the
  2224. * flags of the variable. If val is NULL, the variable is unset.
  2225. */
  2226. static struct var *
  2227. setvar(const char *name, const char *val, int flags)
  2228. {
  2229. const char *q;
  2230. char *p;
  2231. char *nameeq;
  2232. size_t namelen;
  2233. size_t vallen;
  2234. struct var *vp;
  2235. q = endofname(name);
  2236. p = strchrnul(q, '=');
  2237. namelen = p - name;
  2238. if (!namelen || p != q)
  2239. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2240. vallen = 0;
  2241. if (val == NULL) {
  2242. flags |= VUNSET;
  2243. } else {
  2244. vallen = strlen(val);
  2245. }
  2246. INT_OFF;
  2247. nameeq = ckzalloc(namelen + vallen + 2);
  2248. p = mempcpy(nameeq, name, namelen);
  2249. if (val) {
  2250. *p++ = '=';
  2251. memcpy(p, val, vallen);
  2252. }
  2253. vp = setvareq(nameeq, flags | VNOSAVE);
  2254. INT_ON;
  2255. return vp;
  2256. }
  2257. static void FAST_FUNC
  2258. setvar0(const char *name, const char *val)
  2259. {
  2260. setvar(name, val, 0);
  2261. }
  2262. /*
  2263. * Unset the specified variable.
  2264. */
  2265. static void
  2266. unsetvar(const char *s)
  2267. {
  2268. setvar(s, NULL, 0);
  2269. }
  2270. /*
  2271. * Generate a list of variables satisfying the given conditions.
  2272. */
  2273. #if !ENABLE_FEATURE_SH_NOFORK
  2274. # define listvars(on, off, lp, end) listvars(on, off, end)
  2275. #endif
  2276. static char **
  2277. listvars(int on, int off, struct strlist *lp, char ***end)
  2278. {
  2279. struct var **vpp;
  2280. struct var *vp;
  2281. char **ep;
  2282. int mask;
  2283. STARTSTACKSTR(ep);
  2284. vpp = vartab;
  2285. mask = on | off;
  2286. do {
  2287. for (vp = *vpp; vp; vp = vp->next) {
  2288. if ((vp->flags & mask) == on) {
  2289. #if ENABLE_FEATURE_SH_NOFORK
  2290. /* If variable with the same name is both
  2291. * exported and temporarily set for a command:
  2292. * export ZVAR=5
  2293. * ZVAR=6 printenv
  2294. * then "ZVAR=6" will be both in vartab and
  2295. * lp lists. Do not pass it twice to printenv.
  2296. */
  2297. struct strlist *lp1 = lp;
  2298. while (lp1) {
  2299. if (strcmp(lp1->text, vp->var_text) == 0)
  2300. goto skip;
  2301. lp1 = lp1->next;
  2302. }
  2303. #endif
  2304. if (ep == stackstrend())
  2305. ep = growstackstr();
  2306. *ep++ = (char*)vp->var_text;
  2307. #if ENABLE_FEATURE_SH_NOFORK
  2308. skip: ;
  2309. #endif
  2310. }
  2311. }
  2312. } while (++vpp < vartab + VTABSIZE);
  2313. #if ENABLE_FEATURE_SH_NOFORK
  2314. while (lp) {
  2315. if (ep == stackstrend())
  2316. ep = growstackstr();
  2317. *ep++ = lp->text;
  2318. lp = lp->next;
  2319. }
  2320. #endif
  2321. if (ep == stackstrend())
  2322. ep = growstackstr();
  2323. if (end)
  2324. *end = ep;
  2325. *ep++ = NULL;
  2326. return grabstackstr(ep);
  2327. }
  2328. /* ============ Path search helper */
  2329. static const char *
  2330. legal_pathopt(const char *opt, const char *term, int magic)
  2331. {
  2332. switch (magic) {
  2333. case 0:
  2334. opt = NULL;
  2335. break;
  2336. case 1:
  2337. opt = prefix(opt, "builtin") ?: prefix(opt, "func");
  2338. break;
  2339. default:
  2340. opt += strcspn(opt, term);
  2341. break;
  2342. }
  2343. if (opt && *opt == '%')
  2344. opt++;
  2345. return opt;
  2346. }
  2347. /*
  2348. * The variable path (passed by reference) should be set to the start
  2349. * of the path before the first call; padvance will update
  2350. * this value as it proceeds. Successive calls to padvance will return
  2351. * the possible path expansions in sequence. If an option (indicated by
  2352. * a percent sign) appears in the path entry then the global variable
  2353. * pathopt will be set to point to it; otherwise pathopt will be set to
  2354. * NULL.
  2355. *
  2356. * If magic is 0 then pathopt recognition will be disabled. If magic is
  2357. * 1 we shall recognise %builtin/%func. Otherwise we shall accept any
  2358. * pathopt.
  2359. */
  2360. static const char *pathopt; /* set by padvance */
  2361. static int
  2362. padvance_magic(const char **path, const char *name, int magic)
  2363. {
  2364. const char *term = "%:";
  2365. const char *lpathopt;
  2366. const char *p;
  2367. char *q;
  2368. const char *start;
  2369. size_t qlen;
  2370. size_t len;
  2371. if (*path == NULL)
  2372. return -1;
  2373. lpathopt = NULL;
  2374. start = *path;
  2375. if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) {
  2376. lpathopt = start + 1;
  2377. start = p;
  2378. term = ":";
  2379. }
  2380. len = strcspn(start, term);
  2381. p = start + len;
  2382. if (*p == '%') {
  2383. size_t extra = strchrnul(p, ':') - p;
  2384. if (legal_pathopt(p + 1, term, magic))
  2385. lpathopt = p + 1;
  2386. else
  2387. len += extra;
  2388. p += extra;
  2389. }
  2390. pathopt = lpathopt;
  2391. *path = *p == ':' ? p + 1 : NULL;
  2392. /* "2" is for '/' and '\0' */
  2393. qlen = len + strlen(name) + 2;
  2394. q = growstackto(qlen);
  2395. if (len) {
  2396. q = mempcpy(q, start, len);
  2397. *q++ = '/';
  2398. }
  2399. strcpy(q, name);
  2400. return qlen;
  2401. }
  2402. static int
  2403. padvance(const char **path, const char *name)
  2404. {
  2405. return padvance_magic(path, name, 1);
  2406. }
  2407. /* ============ Prompt */
  2408. static smallint doprompt; /* if set, prompt the user */
  2409. static smallint needprompt; /* true if interactive and at start of line */
  2410. #if ENABLE_FEATURE_EDITING
  2411. static line_input_t *line_input_state;
  2412. static const char *cmdedit_prompt;
  2413. static void
  2414. putprompt(const char *s)
  2415. {
  2416. if (ENABLE_ASH_EXPAND_PRMT) {
  2417. free((char*)cmdedit_prompt);
  2418. cmdedit_prompt = ckstrdup(s);
  2419. return;
  2420. }
  2421. cmdedit_prompt = s;
  2422. }
  2423. #else
  2424. static void
  2425. putprompt(const char *s)
  2426. {
  2427. out2str(s);
  2428. }
  2429. #endif
  2430. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2431. static const char *expandstr(const char *ps, int syntax_type);
  2432. /* Values for syntax param */
  2433. #define BASESYNTAX 0 /* not in quotes */
  2434. #define DQSYNTAX 1 /* in double quotes */
  2435. #define SQSYNTAX 2 /* in single quotes */
  2436. #define ARISYNTAX 3 /* in arithmetic */
  2437. #if ENABLE_ASH_EXPAND_PRMT
  2438. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2439. #endif
  2440. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2441. /*
  2442. * called by editline -- any expansions to the prompt should be added here.
  2443. */
  2444. static void
  2445. setprompt_if(smallint do_set, int whichprompt)
  2446. {
  2447. const char *prompt;
  2448. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2449. if (!do_set)
  2450. return;
  2451. needprompt = 0;
  2452. switch (whichprompt) {
  2453. case 1:
  2454. prompt = ps1val();
  2455. break;
  2456. case 2:
  2457. prompt = ps2val();
  2458. break;
  2459. default: /* 0 */
  2460. prompt = nullstr;
  2461. }
  2462. #if ENABLE_ASH_EXPAND_PRMT
  2463. pushstackmark(&smark, stackblocksize());
  2464. putprompt(expandstr(prompt, PSSYNTAX));
  2465. popstackmark(&smark);
  2466. #else
  2467. putprompt(prompt);
  2468. #endif
  2469. }
  2470. /* ============ The cd and pwd commands */
  2471. #define CD_PHYSICAL 1
  2472. #define CD_PRINT 2
  2473. static int
  2474. cdopt(void)
  2475. {
  2476. int flags = 0;
  2477. int i, j;
  2478. j = 'L';
  2479. while ((i = nextopt("LP")) != '\0') {
  2480. if (i != j) {
  2481. flags ^= CD_PHYSICAL;
  2482. j = i;
  2483. }
  2484. }
  2485. return flags;
  2486. }
  2487. /*
  2488. * Update curdir (the name of the current directory) in response to a
  2489. * cd command.
  2490. */
  2491. static const char *
  2492. updatepwd(const char *dir)
  2493. {
  2494. char *new;
  2495. char *p;
  2496. char *cdcomppath;
  2497. const char *lim;
  2498. cdcomppath = sstrdup(dir);
  2499. STARTSTACKSTR(new);
  2500. if (*dir != '/') {
  2501. if (curdir == nullstr)
  2502. return 0;
  2503. new = stack_putstr(curdir, new);
  2504. }
  2505. new = makestrspace(strlen(dir) + 2, new);
  2506. lim = (char *)stackblock() + 1;
  2507. if (*dir != '/') {
  2508. if (new[-1] != '/')
  2509. USTPUTC('/', new);
  2510. if (new > lim && *lim == '/')
  2511. lim++;
  2512. } else {
  2513. USTPUTC('/', new);
  2514. cdcomppath++;
  2515. if (dir[1] == '/' && dir[2] != '/') {
  2516. USTPUTC('/', new);
  2517. cdcomppath++;
  2518. lim++;
  2519. }
  2520. }
  2521. p = strtok_r(cdcomppath, "/", &cdcomppath);
  2522. while (p) {
  2523. switch (*p) {
  2524. case '.':
  2525. if (p[1] == '.' && p[2] == '\0') {
  2526. while (new > lim) {
  2527. STUNPUTC(new);
  2528. if (new[-1] == '/')
  2529. break;
  2530. }
  2531. break;
  2532. }
  2533. if (p[1] == '\0')
  2534. break;
  2535. /* fall through */
  2536. default:
  2537. new = stack_putstr(p, new);
  2538. USTPUTC('/', new);
  2539. }
  2540. p = strtok_r(NULL, "/", &cdcomppath);
  2541. }
  2542. if (new > lim)
  2543. STUNPUTC(new);
  2544. *new = 0;
  2545. return stackblock();
  2546. }
  2547. /*
  2548. * Find out what the current directory is. If we already know the current
  2549. * directory, this routine returns immediately.
  2550. */
  2551. static char *
  2552. getpwd(void)
  2553. {
  2554. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2555. return dir ? dir : nullstr;
  2556. }
  2557. static void
  2558. setpwd(const char *val, int setold)
  2559. {
  2560. char *oldcur, *dir;
  2561. oldcur = dir = curdir;
  2562. if (setold) {
  2563. setvar("OLDPWD", oldcur, VEXPORT);
  2564. }
  2565. INT_OFF;
  2566. if (physdir != nullstr) {
  2567. if (physdir != oldcur)
  2568. free(physdir);
  2569. physdir = nullstr;
  2570. }
  2571. if (oldcur == val || !val) {
  2572. char *s = getpwd();
  2573. physdir = s;
  2574. if (!val)
  2575. dir = s;
  2576. } else
  2577. dir = ckstrdup(val);
  2578. if (oldcur != dir && oldcur != nullstr) {
  2579. free(oldcur);
  2580. }
  2581. curdir = dir;
  2582. INT_ON;
  2583. setvar("PWD", dir, VEXPORT);
  2584. }
  2585. static void hashcd(void);
  2586. /*
  2587. * Actually do the chdir. We also call hashcd to let other routines
  2588. * know that the current directory has changed.
  2589. */
  2590. static int
  2591. docd(const char *dest, int flags)
  2592. {
  2593. const char *dir = NULL;
  2594. int err;
  2595. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2596. INT_OFF;
  2597. if (!(flags & CD_PHYSICAL)) {
  2598. dir = updatepwd(dest);
  2599. if (dir)
  2600. dest = dir;
  2601. }
  2602. err = chdir(dest);
  2603. if (err)
  2604. goto out;
  2605. setpwd(dir, 1);
  2606. hashcd();
  2607. out:
  2608. INT_ON;
  2609. return err;
  2610. }
  2611. static int FAST_FUNC
  2612. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2613. {
  2614. const char *dest;
  2615. const char *path;
  2616. const char *p;
  2617. char c;
  2618. struct stat statb;
  2619. int flags;
  2620. int len;
  2621. flags = cdopt();
  2622. dest = *argptr;
  2623. if (!dest)
  2624. dest = bltinlookup("HOME");
  2625. else if (LONE_DASH(dest)) {
  2626. dest = bltinlookup("OLDPWD");
  2627. flags |= CD_PRINT;
  2628. }
  2629. if (!dest)
  2630. dest = nullstr;
  2631. if (*dest == '/')
  2632. goto step6;
  2633. if (*dest == '.') {
  2634. c = dest[1];
  2635. dotdot:
  2636. switch (c) {
  2637. case '\0':
  2638. case '/':
  2639. goto step6;
  2640. case '.':
  2641. c = dest[2];
  2642. if (c != '.')
  2643. goto dotdot;
  2644. }
  2645. }
  2646. if (!*dest)
  2647. dest = ".";
  2648. path = bltinlookup("CDPATH");
  2649. while (p = path, (len = padvance(&path, dest)) >= 0) {
  2650. c = *p;
  2651. p = stalloc(len);
  2652. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2653. if (c && c != ':')
  2654. flags |= CD_PRINT;
  2655. docd:
  2656. if (!docd(p, flags))
  2657. goto out;
  2658. goto err;
  2659. }
  2660. }
  2661. step6:
  2662. p = dest;
  2663. goto docd;
  2664. err:
  2665. ash_msg_and_raise_perror("can't cd to %s", dest);
  2666. /* NOTREACHED */
  2667. out:
  2668. if (flags & CD_PRINT)
  2669. out1fmt("%s\n", curdir);
  2670. return 0;
  2671. }
  2672. static int FAST_FUNC
  2673. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2674. {
  2675. int flags;
  2676. const char *dir = curdir;
  2677. flags = cdopt();
  2678. if (flags) {
  2679. if (physdir == nullstr)
  2680. setpwd(dir, 0);
  2681. dir = physdir;
  2682. }
  2683. out1fmt("%s\n", dir);
  2684. return 0;
  2685. }
  2686. /* ============ ... */
  2687. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2688. /* Syntax classes */
  2689. #define CWORD 0 /* character is nothing special */
  2690. #define CNL 1 /* newline character */
  2691. #define CBACK 2 /* a backslash character */
  2692. #define CSQUOTE 3 /* single quote */
  2693. #define CDQUOTE 4 /* double quote */
  2694. #define CENDQUOTE 5 /* a terminating quote */
  2695. #define CBQUOTE 6 /* backwards single quote */
  2696. #define CVAR 7 /* a dollar sign */
  2697. #define CENDVAR 8 /* a '}' character */
  2698. #define CLP 9 /* a left paren in arithmetic */
  2699. #define CRP 10 /* a right paren in arithmetic */
  2700. #define CENDFILE 11 /* end of file */
  2701. #define CCTL 12 /* like CWORD, except it must be escaped */
  2702. #define CSPCL 13 /* these terminate a word */
  2703. #define PEOF 256
  2704. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2705. #if ENABLE_FEATURE_SH_MATH
  2706. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2707. #else
  2708. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2709. #endif
  2710. static const uint16_t S_I_T[] ALIGN2 = {
  2711. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 0, ' ' */
  2712. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 1, \n */
  2713. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 2, !*-/:=?[]~ */
  2714. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 3, '"' */
  2715. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 4, $ */
  2716. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 5, "'" */
  2717. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 6, ( */
  2718. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 7, ) */
  2719. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 8, \ */
  2720. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 9, ` */
  2721. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 10, } */
  2722. #if !USE_SIT_FUNCTION
  2723. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 11, PEOF */
  2724. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 12, 0-9A-Za-z */
  2725. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 13, CTLESC ... */
  2726. #endif
  2727. #undef SIT_ITEM
  2728. };
  2729. /* Constants below must match table above */
  2730. enum {
  2731. CSPCL_CWORD_CWORD_CWORD , /* 0 */
  2732. CNL_CNL_CNL_CNL , /* 1 */
  2733. CWORD_CCTL_CCTL_CWORD , /* 2 */
  2734. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 3 */
  2735. CVAR_CVAR_CWORD_CVAR , /* 4 */
  2736. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 5 */
  2737. CSPCL_CWORD_CWORD_CLP , /* 6 */
  2738. CSPCL_CWORD_CWORD_CRP , /* 7 */
  2739. CBACK_CBACK_CCTL_CBACK , /* 8 */
  2740. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 9 */
  2741. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 10 */
  2742. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 11 */
  2743. CWORD_CWORD_CWORD_CWORD , /* 12 */
  2744. CCTL_CCTL_CCTL_CCTL , /* 13 */
  2745. };
  2746. /* c in SIT(c, syntax) must be an *unsigned char* or PEOF,
  2747. * caller must ensure proper cast on it if c is *char_ptr!
  2748. */
  2749. #if USE_SIT_FUNCTION
  2750. static int
  2751. SIT(int c, int syntax)
  2752. {
  2753. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2754. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2755. /*
  2756. * This causes '/' to be prepended with CTLESC in dquoted string,
  2757. * making "./file"* treated incorrectly because we feed
  2758. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2759. * The "homegrown" glob implementation is okay with that,
  2760. * but glibc one isn't. With '/' always treated as CWORD,
  2761. * both work fine.
  2762. */
  2763. static const uint8_t syntax_index_table[] ALIGN1 = {
  2764. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2765. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2766. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2767. 10, 2 /* "}~" */
  2768. };
  2769. const char *s;
  2770. int indx;
  2771. if (c == PEOF)
  2772. return CENDFILE;
  2773. /* Cast is purely for paranoia here,
  2774. * just in case someone passed signed char to us */
  2775. if ((unsigned char)c >= CTL_FIRST
  2776. && (unsigned char)c <= CTL_LAST
  2777. ) {
  2778. return CCTL;
  2779. }
  2780. s = strchrnul(spec_symbls, c);
  2781. if (*s == '\0')
  2782. return CWORD;
  2783. indx = syntax_index_table[s - spec_symbls];
  2784. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2785. }
  2786. #else /* !USE_SIT_FUNCTION */
  2787. static const uint8_t syntax_index_table[] ALIGN1 = {
  2788. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2789. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2799. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2800. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2822. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2823. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2824. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2826. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2828. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2829. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2830. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2831. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2832. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2833. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2835. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2836. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2837. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2838. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2839. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2840. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2841. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2842. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2843. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2844. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2849. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2850. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2851. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2852. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2853. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2854. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2882. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2883. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2884. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2887. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2897. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2899. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2902. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2903. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2904. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2905. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2906. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2915. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2916. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2917. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2920. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2921. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2922. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2923. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2924. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2925. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2926. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2927. #if BASH_PROCESS_SUBST
  2928. /* 137 CTLTOPROC */ CCTL_CCTL_CCTL_CCTL,
  2929. /* 138 CTLFROMPROC */ CCTL_CCTL_CCTL_CCTL,
  2930. #else
  2931. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2932. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2933. #endif
  2934. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2935. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2936. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2937. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2967. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2968. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2969. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2970. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2971. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2972. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2973. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2974. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2975. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2976. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2977. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2978. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2979. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2980. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2981. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2982. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2983. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2984. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2985. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2986. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2987. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2988. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2989. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2990. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2991. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2992. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2993. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2994. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2995. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2996. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2997. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2998. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2999. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  3000. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  3001. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  3002. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  3003. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  3004. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  3005. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  3006. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  3007. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  3008. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  3009. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  3010. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  3011. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  3012. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  3013. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  3014. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  3015. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  3016. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  3017. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  3018. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  3019. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  3020. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  3021. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  3022. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  3023. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  3024. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  3025. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3026. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  3027. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  3028. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  3029. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  3030. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  3031. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  3032. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  3033. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  3034. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  3035. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3036. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  3037. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  3038. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  3039. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  3040. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  3041. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  3042. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  3043. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  3044. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  3045. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  3046. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  3047. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  3048. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  3049. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  3050. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  3051. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  3052. };
  3053. #if 1
  3054. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  3055. #else /* debug version, caught one signed char bug */
  3056. # define SIT(c, syntax) \
  3057. ({ \
  3058. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  3059. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3060. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  3061. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3062. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  3063. })
  3064. #endif
  3065. #endif /* !USE_SIT_FUNCTION */
  3066. /* ============ Alias handling */
  3067. #if ENABLE_ASH_ALIAS
  3068. #define ALIASINUSE 1
  3069. #define ALIASDEAD 2
  3070. struct alias {
  3071. struct alias *next;
  3072. char *name;
  3073. char *val;
  3074. int flag;
  3075. };
  3076. static struct alias **atab; // [ATABSIZE];
  3077. #define INIT_G_alias() do { \
  3078. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  3079. } while (0)
  3080. static struct alias **
  3081. __lookupalias(const char *name)
  3082. {
  3083. unsigned int hashval;
  3084. struct alias **app;
  3085. const char *p;
  3086. unsigned int ch;
  3087. p = name;
  3088. ch = (unsigned char)*p;
  3089. hashval = ch << 4;
  3090. while (ch) {
  3091. hashval += ch;
  3092. ch = (unsigned char)*++p;
  3093. }
  3094. app = &atab[hashval % ATABSIZE];
  3095. for (; *app; app = &(*app)->next) {
  3096. if (strcmp(name, (*app)->name) == 0) {
  3097. break;
  3098. }
  3099. }
  3100. return app;
  3101. }
  3102. static struct alias *
  3103. lookupalias(const char *name, int check)
  3104. {
  3105. struct alias *ap = *__lookupalias(name);
  3106. if (check && ap && (ap->flag & ALIASINUSE))
  3107. return NULL;
  3108. return ap;
  3109. }
  3110. static struct alias *
  3111. freealias(struct alias *ap)
  3112. {
  3113. struct alias *next;
  3114. if (ap->flag & ALIASINUSE) {
  3115. ap->flag |= ALIASDEAD;
  3116. return ap;
  3117. }
  3118. next = ap->next;
  3119. free(ap->name);
  3120. free(ap->val);
  3121. free(ap);
  3122. return next;
  3123. }
  3124. static void
  3125. setalias(const char *name, const char *val)
  3126. {
  3127. struct alias *ap, **app;
  3128. app = __lookupalias(name);
  3129. ap = *app;
  3130. INT_OFF;
  3131. if (ap) {
  3132. if (!(ap->flag & ALIASINUSE)) {
  3133. free(ap->val);
  3134. }
  3135. ap->val = ckstrdup(val);
  3136. ap->flag &= ~ALIASDEAD;
  3137. } else {
  3138. /* not found */
  3139. ap = ckzalloc(sizeof(struct alias));
  3140. ap->name = ckstrdup(name);
  3141. ap->val = ckstrdup(val);
  3142. /*ap->flag = 0; - ckzalloc did it */
  3143. /*ap->next = NULL;*/
  3144. *app = ap;
  3145. }
  3146. INT_ON;
  3147. }
  3148. static int
  3149. unalias(const char *name)
  3150. {
  3151. struct alias **app;
  3152. app = __lookupalias(name);
  3153. if (*app) {
  3154. INT_OFF;
  3155. *app = freealias(*app);
  3156. INT_ON;
  3157. return 0;
  3158. }
  3159. return 1;
  3160. }
  3161. static void
  3162. rmaliases(void)
  3163. {
  3164. struct alias *ap, **app;
  3165. int i;
  3166. INT_OFF;
  3167. for (i = 0; i < ATABSIZE; i++) {
  3168. app = &atab[i];
  3169. for (ap = *app; ap; ap = *app) {
  3170. *app = freealias(*app);
  3171. if (ap == *app) {
  3172. app = &ap->next;
  3173. }
  3174. }
  3175. }
  3176. INT_ON;
  3177. }
  3178. static void
  3179. printalias(const struct alias *ap)
  3180. {
  3181. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3182. }
  3183. /*
  3184. * TODO - sort output
  3185. */
  3186. static int FAST_FUNC
  3187. aliascmd(int argc UNUSED_PARAM, char **argv)
  3188. {
  3189. char *n, *v;
  3190. int ret = 0;
  3191. struct alias *ap;
  3192. if (!argv[1]) {
  3193. int i;
  3194. for (i = 0; i < ATABSIZE; i++) {
  3195. for (ap = atab[i]; ap; ap = ap->next) {
  3196. printalias(ap);
  3197. }
  3198. }
  3199. return 0;
  3200. }
  3201. while ((n = *++argv) != NULL) {
  3202. v = strchr(n+1, '=');
  3203. if (v == NULL) { /* n+1: funny ksh stuff */
  3204. ap = *__lookupalias(n);
  3205. if (ap == NULL) {
  3206. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3207. ret = 1;
  3208. } else
  3209. printalias(ap);
  3210. } else {
  3211. *v++ = '\0';
  3212. setalias(n, v);
  3213. }
  3214. }
  3215. return ret;
  3216. }
  3217. static int FAST_FUNC
  3218. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3219. {
  3220. int i;
  3221. while (nextopt("a") != '\0') {
  3222. rmaliases();
  3223. return 0;
  3224. }
  3225. for (i = 0; *argptr; argptr++) {
  3226. if (unalias(*argptr)) {
  3227. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3228. i = 1;
  3229. }
  3230. }
  3231. return i;
  3232. }
  3233. #endif /* ASH_ALIAS */
  3234. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3235. #define FORK_FG 0
  3236. #define FORK_BG 1
  3237. #define FORK_NOJOB 2
  3238. /* mode flags for showjob(s) */
  3239. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3240. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3241. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3242. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3243. /*
  3244. * A job structure contains information about a job. A job is either a
  3245. * single process or a set of processes contained in a pipeline. In the
  3246. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3247. * array of pids.
  3248. */
  3249. struct procstat {
  3250. pid_t ps_pid; /* process id */
  3251. int ps_status; /* last process status from wait() */
  3252. char *ps_cmd; /* text of command being run */
  3253. };
  3254. struct job {
  3255. struct procstat ps0; /* status of process */
  3256. struct procstat *ps; /* status of processes when more than one */
  3257. #if JOBS
  3258. int stopstatus; /* status of a stopped job */
  3259. #endif
  3260. unsigned nprocs; /* number of processes */
  3261. #define JOBRUNNING 0 /* at least one proc running */
  3262. #define JOBSTOPPED 1 /* all procs are stopped */
  3263. #define JOBDONE 2 /* all procs are completed */
  3264. unsigned
  3265. state: 8,
  3266. #if JOBS
  3267. sigint: 1, /* job was killed by SIGINT */
  3268. jobctl: 1, /* job running under job control */
  3269. #endif
  3270. waited: 1, /* true if this entry has been waited for */
  3271. used: 1, /* true if this entry is in used */
  3272. changed: 1; /* true if status has changed */
  3273. struct job *prev_job; /* previous job */
  3274. };
  3275. static struct job *makejob(/*union node *,*/ int);
  3276. static int forkshell(struct job *, union node *, int);
  3277. static int waitforjob(struct job *);
  3278. #if !JOBS
  3279. enum { doing_jobctl = 0 };
  3280. #define setjobctl(on) do {} while (0)
  3281. #else
  3282. static smallint doing_jobctl; //references:8
  3283. static void setjobctl(int);
  3284. #endif
  3285. /*
  3286. * Ignore a signal.
  3287. */
  3288. static void
  3289. ignoresig(int signo)
  3290. {
  3291. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3292. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3293. /* No, need to do it */
  3294. signal(signo, SIG_IGN);
  3295. }
  3296. sigmode[signo - 1] = S_HARD_IGN;
  3297. }
  3298. /*
  3299. * Only one usage site - in setsignal()
  3300. */
  3301. static void
  3302. signal_handler(int signo)
  3303. {
  3304. if (signo == SIGCHLD) {
  3305. got_sigchld = 1;
  3306. if (!trap[SIGCHLD])
  3307. return;
  3308. }
  3309. #if ENABLE_FEATURE_EDITING
  3310. bb_got_signal = signo; /* for read_line_input: "we got a signal" */
  3311. #endif
  3312. gotsig[signo - 1] = 1;
  3313. pending_sig = signo;
  3314. if (signo == SIGINT && !trap[SIGINT]) {
  3315. if (!suppress_int) {
  3316. pending_sig = 0;
  3317. raise_interrupt(); /* does not return */
  3318. }
  3319. pending_int = 1;
  3320. }
  3321. }
  3322. /*
  3323. * Set the signal handler for the specified signal. The routine figures
  3324. * out what it should be set to.
  3325. */
  3326. static void
  3327. setsignal(int signo)
  3328. {
  3329. char *t;
  3330. char cur_act, new_act;
  3331. struct sigaction act;
  3332. t = trap[signo];
  3333. new_act = S_DFL;
  3334. if (t != NULL) { /* trap for this sig is set */
  3335. new_act = S_CATCH;
  3336. if (t[0] == '\0') /* trap is "": ignore this sig */
  3337. new_act = S_IGN;
  3338. }
  3339. if (rootshell && new_act == S_DFL) {
  3340. switch (signo) {
  3341. case SIGINT:
  3342. if (iflag || minusc || sflag == 0)
  3343. new_act = S_CATCH;
  3344. break;
  3345. case SIGQUIT:
  3346. #if DEBUG
  3347. if (debug)
  3348. break;
  3349. #endif
  3350. /* man bash:
  3351. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3352. * commands run by bash have signal handlers
  3353. * set to the values inherited by the shell
  3354. * from its parent". */
  3355. new_act = S_IGN;
  3356. break;
  3357. case SIGTERM:
  3358. if (iflag)
  3359. new_act = S_IGN;
  3360. break;
  3361. #if JOBS
  3362. case SIGTSTP:
  3363. case SIGTTOU:
  3364. if (mflag)
  3365. new_act = S_IGN;
  3366. break;
  3367. #endif
  3368. }
  3369. }
  3370. /* if !rootshell, we reset SIGQUIT to DFL,
  3371. * whereas we have to restore it to what shell got on entry.
  3372. * This is handled by the fact that if signal was IGNored on entry,
  3373. * then cur_act is S_HARD_IGN and we never change its sigaction
  3374. * (see code below).
  3375. */
  3376. if (signo == SIGCHLD)
  3377. new_act = S_CATCH;
  3378. t = &sigmode[signo - 1];
  3379. cur_act = *t;
  3380. if (cur_act == 0) {
  3381. /* current setting is not yet known */
  3382. if (sigaction(signo, NULL, &act)) {
  3383. /* pretend it worked; maybe we should give a warning,
  3384. * but other shells don't. We don't alter sigmode,
  3385. * so we retry every time.
  3386. * btw, in Linux it never fails. --vda */
  3387. return;
  3388. }
  3389. if (act.sa_handler == SIG_IGN) {
  3390. cur_act = S_HARD_IGN;
  3391. if (mflag
  3392. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3393. ) {
  3394. cur_act = S_IGN; /* don't hard ignore these */
  3395. }
  3396. }
  3397. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3398. /* installing SIG_DFL over SIG_DFL is a no-op */
  3399. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3400. *t = S_DFL;
  3401. return;
  3402. }
  3403. }
  3404. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3405. return;
  3406. *t = new_act;
  3407. act.sa_handler = SIG_DFL;
  3408. switch (new_act) {
  3409. case S_CATCH:
  3410. act.sa_handler = signal_handler;
  3411. break;
  3412. case S_IGN:
  3413. act.sa_handler = SIG_IGN;
  3414. break;
  3415. }
  3416. /* flags and mask matter only if !DFL and !IGN, but we do it
  3417. * for all cases for more deterministic behavior:
  3418. */
  3419. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3420. sigfillset(&act.sa_mask);
  3421. sigaction_set(signo, &act);
  3422. }
  3423. /* mode flags for set_curjob */
  3424. #define CUR_DELETE 2
  3425. #define CUR_RUNNING 1
  3426. #define CUR_STOPPED 0
  3427. #if JOBS
  3428. /* pgrp of shell on invocation */
  3429. static int initialpgrp; //references:2
  3430. static int ttyfd = -1; //5
  3431. #endif
  3432. /* array of jobs */
  3433. static struct job *jobtab; //5
  3434. /* size of array */
  3435. static unsigned njobs; //4
  3436. /* current job */
  3437. static struct job *curjob; //lots
  3438. #if 0
  3439. /* Bash has a feature: it restores termios after a successful wait for
  3440. * a foreground job which had at least one stopped or sigkilled member.
  3441. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3442. * properly restoring tty state. Should we do this too?
  3443. * A reproducer: ^Z an interactive python:
  3444. *
  3445. * # python
  3446. * Python 2.7.12 (...)
  3447. * >>> ^Z
  3448. * { python leaves tty in -icanon -echo state. We do survive that... }
  3449. * [1]+ Stopped python
  3450. * { ...however, next program (python #2) does not survive it well: }
  3451. * # python
  3452. * Python 2.7.12 (...)
  3453. * >>> Traceback (most recent call last):
  3454. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3455. * File "<stdin>", line 1, in <module>
  3456. * NameError: name 'qwerty' is not defined
  3457. *
  3458. * The implementation below is modeled on bash code and seems to work.
  3459. * However, I'm not sure we should do this. For one: what if I'd fg
  3460. * the stopped python instead? It'll be confused by "restored" tty state.
  3461. */
  3462. static struct termios shell_tty_info;
  3463. static void
  3464. get_tty_state(void)
  3465. {
  3466. if (rootshell && ttyfd >= 0)
  3467. tcgetattr(ttyfd, &shell_tty_info);
  3468. }
  3469. static void
  3470. set_tty_state(void)
  3471. {
  3472. /* if (rootshell) - caller ensures this */
  3473. if (ttyfd >= 0)
  3474. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3475. }
  3476. static int
  3477. job_signal_status(struct job *jp)
  3478. {
  3479. int status;
  3480. unsigned i;
  3481. struct procstat *ps = jp->ps;
  3482. for (i = 0; i < jp->nprocs; i++) {
  3483. status = ps[i].ps_status;
  3484. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3485. return status;
  3486. }
  3487. return 0;
  3488. }
  3489. static void
  3490. restore_tty_if_stopped_or_signaled(struct job *jp)
  3491. {
  3492. //TODO: check what happens if we come from waitforjob() in expbackq()
  3493. if (rootshell) {
  3494. int s = job_signal_status(jp);
  3495. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3496. set_tty_state();
  3497. }
  3498. }
  3499. #else
  3500. # define get_tty_state() ((void)0)
  3501. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3502. #endif
  3503. static void
  3504. set_curjob(struct job *jp, unsigned mode)
  3505. {
  3506. struct job *jp1;
  3507. struct job **jpp, **curp;
  3508. /* first remove from list */
  3509. jpp = curp = &curjob;
  3510. while (1) {
  3511. jp1 = *jpp;
  3512. if (jp1 == jp)
  3513. break;
  3514. jpp = &jp1->prev_job;
  3515. }
  3516. *jpp = jp1->prev_job;
  3517. /* Then re-insert in correct position */
  3518. jpp = curp;
  3519. switch (mode) {
  3520. default:
  3521. #if DEBUG
  3522. abort();
  3523. #endif
  3524. case CUR_DELETE:
  3525. /* job being deleted */
  3526. break;
  3527. case CUR_RUNNING:
  3528. /* newly created job or backgrounded job,
  3529. * put after all stopped jobs.
  3530. */
  3531. while (1) {
  3532. jp1 = *jpp;
  3533. #if JOBS
  3534. if (!jp1 || jp1->state != JOBSTOPPED)
  3535. #endif
  3536. break;
  3537. jpp = &jp1->prev_job;
  3538. }
  3539. /* FALLTHROUGH */
  3540. #if JOBS
  3541. case CUR_STOPPED:
  3542. #endif
  3543. /* newly stopped job - becomes curjob */
  3544. jp->prev_job = *jpp;
  3545. *jpp = jp;
  3546. break;
  3547. }
  3548. }
  3549. #if JOBS || DEBUG
  3550. static int
  3551. jobno(const struct job *jp)
  3552. {
  3553. return jp - jobtab + 1;
  3554. }
  3555. #endif
  3556. /*
  3557. * Convert a job name to a job structure.
  3558. */
  3559. #if !JOBS
  3560. #define getjob(name, getctl) getjob(name)
  3561. #endif
  3562. static struct job *
  3563. getjob(const char *name, int getctl)
  3564. {
  3565. struct job *jp;
  3566. struct job *found;
  3567. const char *err_msg = "%s: no such job";
  3568. unsigned num;
  3569. int c;
  3570. const char *p;
  3571. char *(*match)(const char *, const char *);
  3572. jp = curjob;
  3573. p = name;
  3574. if (!p)
  3575. goto currentjob;
  3576. if (*p != '%')
  3577. goto err;
  3578. c = *++p;
  3579. if (!c)
  3580. goto currentjob;
  3581. if (!p[1]) {
  3582. if (c == '+' || c == '%') {
  3583. currentjob:
  3584. err_msg = "No current job";
  3585. goto check;
  3586. }
  3587. if (c == '-') {
  3588. if (jp)
  3589. jp = jp->prev_job;
  3590. err_msg = "No previous job";
  3591. check:
  3592. if (!jp)
  3593. goto err;
  3594. goto gotit;
  3595. }
  3596. }
  3597. if (is_number(p)) {
  3598. num = atoi(p);
  3599. if (num > 0 && num <= njobs) {
  3600. jp = jobtab + num - 1;
  3601. if (jp->used)
  3602. goto gotit;
  3603. goto err;
  3604. }
  3605. }
  3606. match = prefix;
  3607. if (*p == '?') {
  3608. match = strstr;
  3609. p++;
  3610. }
  3611. found = NULL;
  3612. while (jp) {
  3613. if (match(jp->ps[0].ps_cmd, p)) {
  3614. if (found)
  3615. goto err;
  3616. found = jp;
  3617. err_msg = "%s: ambiguous";
  3618. }
  3619. jp = jp->prev_job;
  3620. }
  3621. if (!found)
  3622. goto err;
  3623. jp = found;
  3624. gotit:
  3625. #if JOBS
  3626. err_msg = "job %s not created under job control";
  3627. if (getctl && jp->jobctl == 0)
  3628. goto err;
  3629. #endif
  3630. return jp;
  3631. err:
  3632. ash_msg_and_raise_error(err_msg, name);
  3633. }
  3634. /*
  3635. * Mark a job structure as unused.
  3636. */
  3637. static void
  3638. freejob(struct job *jp)
  3639. {
  3640. struct procstat *ps;
  3641. int i;
  3642. INT_OFF;
  3643. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3644. if (ps->ps_cmd != nullstr)
  3645. free(ps->ps_cmd);
  3646. }
  3647. if (jp->ps != &jp->ps0)
  3648. free(jp->ps);
  3649. jp->used = 0;
  3650. set_curjob(jp, CUR_DELETE);
  3651. INT_ON;
  3652. }
  3653. #if JOBS
  3654. static void
  3655. xtcsetpgrp(int fd, pid_t pgrp)
  3656. {
  3657. if (tcsetpgrp(fd, pgrp))
  3658. ash_msg_and_raise_perror("can't set tty process group");
  3659. }
  3660. /*
  3661. * Turn job control on and off.
  3662. *
  3663. * Note: This code assumes that the third arg to ioctl is a character
  3664. * pointer, which is true on Berkeley systems but not System V. Since
  3665. * System V doesn't have job control yet, this isn't a problem now.
  3666. *
  3667. * Called with interrupts off.
  3668. */
  3669. static void
  3670. setjobctl(int on)
  3671. {
  3672. int fd;
  3673. int pgrp;
  3674. if (on == doing_jobctl || rootshell == 0)
  3675. return;
  3676. if (on) {
  3677. int ofd;
  3678. ofd = fd = open(_PATH_TTY, O_RDWR);
  3679. if (fd < 0) {
  3680. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3681. * That sometimes helps to acquire controlling tty.
  3682. * Obviously, a workaround for bugs when someone
  3683. * failed to provide a controlling tty to bash! :) */
  3684. fd = 2;
  3685. while (!isatty(fd))
  3686. if (--fd < 0)
  3687. goto out;
  3688. }
  3689. /* fd is a tty at this point */
  3690. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3691. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3692. close(ofd);
  3693. if (fd < 0)
  3694. goto out; /* F_DUPFD failed */
  3695. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3696. close_on_exec_on(fd);
  3697. while (1) { /* while we are in the background */
  3698. pgrp = tcgetpgrp(fd);
  3699. if (pgrp < 0) {
  3700. out:
  3701. ash_msg("can't access tty; job control turned off");
  3702. mflag = on = 0;
  3703. goto close;
  3704. }
  3705. if (pgrp == getpgrp())
  3706. break;
  3707. killpg(0, SIGTTIN);
  3708. }
  3709. initialpgrp = pgrp;
  3710. setsignal(SIGTSTP);
  3711. setsignal(SIGTTOU);
  3712. setsignal(SIGTTIN);
  3713. pgrp = rootpid;
  3714. setpgid(0, pgrp);
  3715. xtcsetpgrp(fd, pgrp);
  3716. } else {
  3717. /* turning job control off */
  3718. fd = ttyfd;
  3719. pgrp = initialpgrp;
  3720. /* was xtcsetpgrp, but this can make exiting ash
  3721. * loop forever if pty is already deleted */
  3722. tcsetpgrp(fd, pgrp);
  3723. setpgid(0, pgrp);
  3724. setsignal(SIGTSTP);
  3725. setsignal(SIGTTOU);
  3726. setsignal(SIGTTIN);
  3727. close:
  3728. if (fd >= 0)
  3729. close(fd);
  3730. fd = -1;
  3731. }
  3732. ttyfd = fd;
  3733. doing_jobctl = on;
  3734. }
  3735. static int FAST_FUNC
  3736. killcmd(int argc, char **argv)
  3737. {
  3738. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3739. int i = 1;
  3740. do {
  3741. if (argv[i][0] == '%') {
  3742. /*
  3743. * "kill %N" - job kill
  3744. * Converting to pgrp / pid kill
  3745. */
  3746. struct job *jp;
  3747. char *dst;
  3748. int j, n;
  3749. jp = getjob(argv[i], 0);
  3750. /*
  3751. * In jobs started under job control, we signal
  3752. * entire process group by kill -PGRP_ID.
  3753. * This happens, f.e., in interactive shell.
  3754. *
  3755. * Otherwise, we signal each child via
  3756. * kill PID1 PID2 PID3.
  3757. * Testcases:
  3758. * sh -c 'sleep 1|sleep 1 & kill %1'
  3759. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3760. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3761. */
  3762. n = jp->nprocs; /* can't be 0 (I hope) */
  3763. if (jp->jobctl)
  3764. n = 1;
  3765. dst = alloca(n * sizeof(int)*4);
  3766. argv[i] = dst;
  3767. for (j = 0; j < n; j++) {
  3768. struct procstat *ps = &jp->ps[j];
  3769. /* Skip non-running and not-stopped members
  3770. * (i.e. dead members) of the job
  3771. */
  3772. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3773. continue;
  3774. /*
  3775. * kill_main has matching code to expect
  3776. * leading space. Needed to not confuse
  3777. * negative pids with "kill -SIGNAL_NO" syntax
  3778. */
  3779. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3780. }
  3781. *dst = '\0';
  3782. }
  3783. } while (argv[++i]);
  3784. }
  3785. return kill_main(argc, argv);
  3786. }
  3787. static void
  3788. showpipe(struct job *jp /*, FILE *out*/)
  3789. {
  3790. struct procstat *ps;
  3791. struct procstat *psend;
  3792. psend = jp->ps + jp->nprocs;
  3793. for (ps = jp->ps + 1; ps < psend; ps++)
  3794. printf(" | %s", ps->ps_cmd);
  3795. newline_and_flush(stdout);
  3796. flush_stdout_stderr();
  3797. }
  3798. static int
  3799. restartjob(struct job *jp, int mode)
  3800. {
  3801. struct procstat *ps;
  3802. int i;
  3803. int status;
  3804. pid_t pgid;
  3805. INT_OFF;
  3806. if (jp->state == JOBDONE)
  3807. goto out;
  3808. jp->state = JOBRUNNING;
  3809. pgid = jp->ps[0].ps_pid;
  3810. if (mode == FORK_FG) {
  3811. get_tty_state();
  3812. xtcsetpgrp(ttyfd, pgid);
  3813. }
  3814. killpg(pgid, SIGCONT);
  3815. ps = jp->ps;
  3816. i = jp->nprocs;
  3817. do {
  3818. if (WIFSTOPPED(ps->ps_status)) {
  3819. ps->ps_status = -1;
  3820. }
  3821. ps++;
  3822. } while (--i);
  3823. out:
  3824. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3825. INT_ON;
  3826. return status;
  3827. }
  3828. static int FAST_FUNC
  3829. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3830. {
  3831. struct job *jp;
  3832. int mode;
  3833. int retval;
  3834. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3835. nextopt(nullstr);
  3836. argv = argptr;
  3837. do {
  3838. jp = getjob(*argv, 1);
  3839. if (mode == FORK_BG) {
  3840. set_curjob(jp, CUR_RUNNING);
  3841. printf("[%d] ", jobno(jp));
  3842. }
  3843. out1str(jp->ps[0].ps_cmd);
  3844. showpipe(jp /*, stdout*/);
  3845. retval = restartjob(jp, mode);
  3846. } while (*argv && *++argv);
  3847. return retval;
  3848. }
  3849. #endif
  3850. static int
  3851. sprint_status48(char *os, int status, int sigonly)
  3852. {
  3853. char *s = os;
  3854. int st;
  3855. if (!WIFEXITED(status)) {
  3856. #if JOBS
  3857. if (WIFSTOPPED(status))
  3858. st = WSTOPSIG(status);
  3859. else
  3860. #endif
  3861. st = WTERMSIG(status);
  3862. if (sigonly) {
  3863. if (st == SIGINT || st == SIGPIPE)
  3864. goto out;
  3865. #if JOBS
  3866. if (WIFSTOPPED(status))
  3867. goto out;
  3868. #endif
  3869. }
  3870. st &= 0x7f;
  3871. s = stpncpy(s, strsignal(st), 32);
  3872. if (WCOREDUMP(status)) {
  3873. s = stpcpy(s, " (core dumped)");
  3874. }
  3875. } else if (!sigonly) {
  3876. st = WEXITSTATUS(status);
  3877. s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3878. }
  3879. out:
  3880. return s - os;
  3881. }
  3882. #define DOWAIT_NONBLOCK 0
  3883. #define DOWAIT_BLOCK 1
  3884. #define DOWAIT_BLOCK_OR_SIG 2
  3885. #if BASH_WAIT_N
  3886. # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
  3887. #endif
  3888. static int
  3889. waitproc(int block, int *status)
  3890. {
  3891. sigset_t oldmask;
  3892. int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG;
  3893. int err;
  3894. #if JOBS
  3895. if (doing_jobctl)
  3896. flags |= WUNTRACED;
  3897. #endif
  3898. do {
  3899. got_sigchld = 0;
  3900. do
  3901. err = waitpid(-1, status, flags);
  3902. while (err < 0 && errno == EINTR);
  3903. if (err || (err = -!block))
  3904. break;
  3905. sigfillset(&oldmask);
  3906. sigprocmask2(SIG_SETMASK, &oldmask); /* mask is updated */
  3907. while (!got_sigchld && !pending_sig)
  3908. sigsuspend(&oldmask);
  3909. sigprocmask(SIG_SETMASK, &oldmask, NULL);
  3910. //simpler, but unsafe: a signal can set pending_sig after check, but before pause():
  3911. //while (!got_sigchld && !pending_sig)
  3912. // pause();
  3913. } while (got_sigchld);
  3914. return err;
  3915. }
  3916. static int
  3917. waitone(int block, struct job *job)
  3918. {
  3919. int pid;
  3920. int status;
  3921. struct job *jp;
  3922. struct job *thisjob = NULL;
  3923. #if BASH_WAIT_N
  3924. bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
  3925. block = (block & ~DOWAIT_JOBSTATUS);
  3926. #endif
  3927. TRACE(("dowait(0x%x) called\n", block));
  3928. /* It's wrong to call waitpid() outside of INT_OFF region:
  3929. * signal can arrive just after syscall return and handler can
  3930. * longjmp away, losing stop/exit notification processing.
  3931. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3932. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3933. *
  3934. * However, for "wait" builtin it is wrong to simply call waitpid()
  3935. * in INT_OFF region: "wait" needs to wait for any running job
  3936. * to change state, but should exit on any trap too.
  3937. * In INT_OFF region, a signal just before syscall entry can set
  3938. * pending_sig variables, but we can't check them, and we would
  3939. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3940. *
  3941. * Because of this, we run inside INT_OFF, but use a special routine
  3942. * which combines waitpid() and sigsuspend().
  3943. * This is the reason why we need to have a handler for SIGCHLD:
  3944. * SIG_DFL handler does not wake sigsuspend().
  3945. */
  3946. INT_OFF;
  3947. pid = waitproc(block, &status);
  3948. TRACE(("wait returns pid %d, status=%d\n", pid, status));
  3949. if (pid <= 0)
  3950. goto out;
  3951. for (jp = curjob; jp; jp = jp->prev_job) {
  3952. int jobstate;
  3953. struct procstat *ps;
  3954. struct procstat *psend;
  3955. if (jp->state == JOBDONE)
  3956. continue;
  3957. jobstate = JOBDONE;
  3958. ps = jp->ps;
  3959. psend = ps + jp->nprocs;
  3960. do {
  3961. if (ps->ps_pid == pid) {
  3962. TRACE(("Job %d: changing status of proc %d "
  3963. "from 0x%x to 0x%x\n",
  3964. jobno(jp), pid, ps->ps_status, status));
  3965. ps->ps_status = status;
  3966. thisjob = jp;
  3967. }
  3968. if (ps->ps_status == -1)
  3969. jobstate = JOBRUNNING;
  3970. #if JOBS
  3971. if (jobstate == JOBRUNNING)
  3972. continue;
  3973. if (WIFSTOPPED(ps->ps_status)) {
  3974. jp->stopstatus = ps->ps_status;
  3975. jobstate = JOBSTOPPED;
  3976. }
  3977. #endif
  3978. } while (++ps < psend);
  3979. if (!thisjob)
  3980. continue;
  3981. /* Found the job where one of its processes changed its state.
  3982. * Is there at least one live and running process in this job? */
  3983. if (jobstate != JOBRUNNING) {
  3984. /* No. All live processes in the job are stopped
  3985. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3986. */
  3987. thisjob->changed = 1;
  3988. if (thisjob->state != jobstate) {
  3989. TRACE(("Job %d: changing state from %d to %d\n",
  3990. jobno(thisjob), thisjob->state, jobstate));
  3991. thisjob->state = jobstate;
  3992. #if JOBS
  3993. if (jobstate == JOBSTOPPED)
  3994. set_curjob(thisjob, CUR_STOPPED);
  3995. #endif
  3996. }
  3997. }
  3998. goto out;
  3999. }
  4000. /* The process wasn't found in job list */
  4001. out:
  4002. INT_ON;
  4003. #if BASH_WAIT_N
  4004. if (want_jobexitstatus) {
  4005. pid = -1;
  4006. if (thisjob && thisjob->state == JOBDONE)
  4007. pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
  4008. }
  4009. #endif
  4010. if (thisjob && thisjob == job) {
  4011. char s[48 + 1];
  4012. int len;
  4013. len = sprint_status48(s, status, 1);
  4014. if (len) {
  4015. s[len] = '\n';
  4016. s[len + 1] = '\0';
  4017. out2str(s);
  4018. }
  4019. }
  4020. return pid;
  4021. }
  4022. static int
  4023. dowait(int block, struct job *jp)
  4024. {
  4025. smallint gotchld = *(volatile smallint *)&got_sigchld;
  4026. int rpid;
  4027. int pid;
  4028. if (jp && jp->state != JOBRUNNING)
  4029. block = DOWAIT_NONBLOCK;
  4030. if (block == DOWAIT_NONBLOCK && !gotchld)
  4031. return 1;
  4032. rpid = 1;
  4033. do {
  4034. pid = waitone(block, jp);
  4035. rpid &= !!pid;
  4036. if (!pid || (jp && jp->state != JOBRUNNING))
  4037. block = DOWAIT_NONBLOCK;
  4038. } while (pid >= 0);
  4039. return rpid;
  4040. }
  4041. #if JOBS
  4042. static void
  4043. showjob(struct job *jp, int mode)
  4044. {
  4045. struct procstat *ps;
  4046. struct procstat *psend;
  4047. int col;
  4048. int indent_col;
  4049. char s[16 + 16 + 48];
  4050. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  4051. ps = jp->ps;
  4052. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  4053. /* just output process (group) id of pipeline */
  4054. fprintf(out, "%d\n", ps->ps_pid);
  4055. return;
  4056. }
  4057. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  4058. indent_col = col;
  4059. if (jp == curjob)
  4060. s[col - 3] = '+';
  4061. else if (curjob && jp == curjob->prev_job)
  4062. s[col - 3] = '-';
  4063. if (mode & SHOW_PIDS)
  4064. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  4065. psend = ps + jp->nprocs;
  4066. if (jp->state == JOBRUNNING) {
  4067. strcpy(s + col, "Running");
  4068. col += sizeof("Running") - 1;
  4069. } else {
  4070. int status = psend[-1].ps_status;
  4071. if (jp->state == JOBSTOPPED)
  4072. status = jp->stopstatus;
  4073. col += sprint_status48(s + col, status, 0);
  4074. }
  4075. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  4076. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  4077. * or prints several "PID | <cmdN>" lines,
  4078. * depending on SHOW_PIDS bit.
  4079. * We do not print status of individual processes
  4080. * between PID and <cmdN>. bash does it, but not very well:
  4081. * first line shows overall job status, not process status,
  4082. * making it impossible to know 1st process status.
  4083. */
  4084. goto start;
  4085. do {
  4086. /* for each process */
  4087. s[0] = '\0';
  4088. col = 33;
  4089. if (mode & SHOW_PIDS)
  4090. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  4091. start:
  4092. fprintf(out, "%s%*c%s%s",
  4093. s,
  4094. 33 - col >= 0 ? 33 - col : 0, ' ',
  4095. ps == jp->ps ? "" : "| ",
  4096. ps->ps_cmd
  4097. );
  4098. } while (++ps != psend);
  4099. newline_and_flush(out);
  4100. jp->changed = 0;
  4101. if (jp->state == JOBDONE) {
  4102. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4103. freejob(jp);
  4104. }
  4105. }
  4106. /*
  4107. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4108. * statuses have changed since the last call to showjobs.
  4109. */
  4110. static void
  4111. showjobs(int mode)
  4112. {
  4113. struct job *jp;
  4114. TRACE(("showjobs(0x%x) called\n", mode));
  4115. /* Handle all finished jobs */
  4116. dowait(DOWAIT_NONBLOCK, NULL);
  4117. for (jp = curjob; jp; jp = jp->prev_job) {
  4118. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4119. showjob(jp, mode);
  4120. }
  4121. }
  4122. }
  4123. static int FAST_FUNC
  4124. jobscmd(int argc UNUSED_PARAM, char **argv)
  4125. {
  4126. int mode, m;
  4127. mode = 0;
  4128. while ((m = nextopt("lp")) != '\0') {
  4129. if (m == 'l')
  4130. mode |= SHOW_PIDS;
  4131. else
  4132. mode |= SHOW_ONLY_PGID;
  4133. }
  4134. argv = argptr;
  4135. if (*argv) {
  4136. do
  4137. showjob(getjob(*argv, 0), mode);
  4138. while (*++argv);
  4139. } else {
  4140. showjobs(mode);
  4141. }
  4142. return 0;
  4143. }
  4144. #endif /* JOBS */
  4145. /* Called only on finished or stopped jobs (no members are running) */
  4146. static int
  4147. getstatus(struct job *job)
  4148. {
  4149. int status;
  4150. int retval;
  4151. struct procstat *ps;
  4152. /* Fetch last member's status */
  4153. ps = job->ps + job->nprocs - 1;
  4154. status = ps->ps_status;
  4155. if (pipefail) {
  4156. /* "set -o pipefail" mode: use last _nonzero_ status */
  4157. while (status == 0 && --ps >= job->ps)
  4158. status = ps->ps_status;
  4159. }
  4160. retval = WEXITSTATUS(status);
  4161. if (!WIFEXITED(status)) {
  4162. #if JOBS
  4163. retval = WSTOPSIG(status);
  4164. if (!WIFSTOPPED(status))
  4165. #endif
  4166. {
  4167. /* XXX: limits number of signals */
  4168. retval = WTERMSIG(status);
  4169. #if JOBS
  4170. if (retval == SIGINT)
  4171. job->sigint = 1;
  4172. #endif
  4173. }
  4174. retval |= 128;
  4175. }
  4176. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4177. jobno(job), job->nprocs, status, retval));
  4178. return retval;
  4179. }
  4180. static int FAST_FUNC
  4181. waitcmd(int argc UNUSED_PARAM, char **argv)
  4182. {
  4183. struct job *job;
  4184. int retval;
  4185. struct job *jp;
  4186. #if BASH_WAIT_N
  4187. int status;
  4188. char one = nextopt("n");
  4189. #else
  4190. nextopt(nullstr);
  4191. #endif
  4192. retval = 0;
  4193. argv = argptr;
  4194. if (!argv[0]) {
  4195. /* wait for all jobs / one job if -n */
  4196. for (;;) {
  4197. jp = curjob;
  4198. #if BASH_WAIT_N
  4199. if (one && !jp)
  4200. /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
  4201. retval = 127;
  4202. #endif
  4203. while (1) {
  4204. if (!jp) /* no running procs */
  4205. goto ret;
  4206. if (jp->state == JOBRUNNING)
  4207. break;
  4208. jp->waited = 1;
  4209. jp = jp->prev_job;
  4210. }
  4211. /* man bash:
  4212. * "When bash is waiting for an asynchronous command via
  4213. * the wait builtin, the reception of a signal for which a trap
  4214. * has been set will cause the wait builtin to return immediately
  4215. * with an exit status greater than 128, immediately after which
  4216. * the trap is executed."
  4217. */
  4218. #if BASH_WAIT_N
  4219. status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
  4220. #else
  4221. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4222. #endif
  4223. /* if child sends us a signal *and immediately exits*,
  4224. * dowait() returns pid > 0. Check this case,
  4225. * not "if (dowait() < 0)"!
  4226. */
  4227. if (pending_sig)
  4228. goto sigout;
  4229. #if BASH_WAIT_N
  4230. if (one) {
  4231. /* wait -n waits for one _job_, not one _process_.
  4232. * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
  4233. * should wait for 2 seconds. Not 1 or 3.
  4234. */
  4235. if (status != -1 && !WIFSTOPPED(status)) {
  4236. retval = WEXITSTATUS(status);
  4237. if (WIFSIGNALED(status))
  4238. retval = 128 | WTERMSIG(status);
  4239. goto ret;
  4240. }
  4241. }
  4242. #endif
  4243. }
  4244. }
  4245. retval = 127;
  4246. do {
  4247. if (**argv != '%') {
  4248. pid_t pid = number(*argv);
  4249. job = curjob;
  4250. while (1) {
  4251. if (!job)
  4252. goto repeat;
  4253. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4254. break;
  4255. job = job->prev_job;
  4256. }
  4257. } else {
  4258. job = getjob(*argv, 0);
  4259. }
  4260. /* loop until process terminated or stopped */
  4261. dowait(DOWAIT_BLOCK_OR_SIG, job);
  4262. if (pending_sig)
  4263. goto sigout;
  4264. job->waited = 1;
  4265. retval = getstatus(job);
  4266. repeat: ;
  4267. } while (*++argv);
  4268. ret:
  4269. return retval;
  4270. sigout:
  4271. retval = 128 | pending_sig;
  4272. return retval;
  4273. }
  4274. static struct job *
  4275. growjobtab(void)
  4276. {
  4277. size_t len;
  4278. ptrdiff_t offset;
  4279. struct job *jp, *jq;
  4280. len = njobs * sizeof(*jp);
  4281. jq = jobtab;
  4282. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4283. offset = (char *)jp - (char *)jq;
  4284. if (offset) {
  4285. /* Relocate pointers */
  4286. size_t l = len;
  4287. jq = (struct job *)((char *)jq + l);
  4288. while (l) {
  4289. l -= sizeof(*jp);
  4290. jq--;
  4291. #define joff(p) ((struct job *)((char *)(p) + l))
  4292. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4293. if (joff(jp)->ps == &jq->ps0)
  4294. jmove(joff(jp)->ps);
  4295. if (joff(jp)->prev_job)
  4296. jmove(joff(jp)->prev_job);
  4297. }
  4298. if (curjob)
  4299. jmove(curjob);
  4300. #undef joff
  4301. #undef jmove
  4302. }
  4303. njobs += 4;
  4304. jobtab = jp;
  4305. jp = (struct job *)((char *)jp + len);
  4306. jq = jp + 3;
  4307. do {
  4308. jq->used = 0;
  4309. } while (--jq >= jp);
  4310. return jp;
  4311. }
  4312. /*
  4313. * Return a new job structure.
  4314. * Called with interrupts off.
  4315. */
  4316. static struct job *
  4317. makejob(/*union node *node,*/ int nprocs)
  4318. {
  4319. int i;
  4320. struct job *jp;
  4321. for (i = njobs, jp = jobtab; ; jp++) {
  4322. if (--i < 0) {
  4323. jp = growjobtab();
  4324. break;
  4325. }
  4326. if (jp->used == 0)
  4327. break;
  4328. if (jp->state != JOBDONE || !jp->waited)
  4329. continue;
  4330. #if JOBS
  4331. if (doing_jobctl)
  4332. continue;
  4333. #endif
  4334. freejob(jp);
  4335. break;
  4336. }
  4337. memset(jp, 0, sizeof(*jp));
  4338. #if JOBS
  4339. /* jp->jobctl is a bitfield.
  4340. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4341. if (doing_jobctl)
  4342. jp->jobctl = 1;
  4343. #endif
  4344. jp->prev_job = curjob;
  4345. curjob = jp;
  4346. jp->used = 1;
  4347. jp->ps = &jp->ps0;
  4348. if (nprocs > 1) {
  4349. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4350. }
  4351. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4352. jobno(jp)));
  4353. return jp;
  4354. }
  4355. #if JOBS
  4356. /*
  4357. * Return a string identifying a command (to be printed by the
  4358. * jobs command).
  4359. */
  4360. static char *cmdnextc;
  4361. static void
  4362. cmdputs(const char *s)
  4363. {
  4364. static const char vstype[VSTYPE + 1][3] ALIGN1 = {
  4365. "", "}", "-", "+", "?", "=",
  4366. "%", "%%", "#", "##"
  4367. IF_BASH_SUBSTR(, ":")
  4368. IF_BASH_PATTERN_SUBST(, "/", "//")
  4369. };
  4370. const char *p, *str;
  4371. char cc[2];
  4372. char *nextc;
  4373. unsigned char c;
  4374. unsigned char subtype = 0;
  4375. int quoted = 0;
  4376. cc[1] = '\0';
  4377. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4378. p = s;
  4379. while ((c = *p++) != '\0') {
  4380. str = NULL;
  4381. switch (c) {
  4382. case CTLESC:
  4383. c = *p++;
  4384. break;
  4385. case CTLVAR:
  4386. subtype = *p++;
  4387. if ((subtype & VSTYPE) == VSLENGTH)
  4388. str = "${#";
  4389. else
  4390. str = "${";
  4391. goto dostr;
  4392. case CTLENDVAR:
  4393. str = "\"}";
  4394. str += !(quoted & 1);
  4395. quoted >>= 1;
  4396. subtype = 0;
  4397. goto dostr;
  4398. #if BASH_PROCESS_SUBST
  4399. case CTLBACKQ:
  4400. c = '$';
  4401. str = "(...)";
  4402. break;
  4403. case CTLTOPROC:
  4404. c = '>';
  4405. str = "(...)";
  4406. break;
  4407. case CTLFROMPROC:
  4408. c = '<';
  4409. str = "(...)";
  4410. break;
  4411. #else
  4412. case CTLBACKQ:
  4413. str = "$(...)";
  4414. goto dostr;
  4415. #endif
  4416. #if ENABLE_FEATURE_SH_MATH
  4417. case CTLARI:
  4418. str = "$((";
  4419. goto dostr;
  4420. case CTLENDARI:
  4421. str = "))";
  4422. goto dostr;
  4423. #endif
  4424. case CTLQUOTEMARK:
  4425. quoted ^= 1;
  4426. c = '"';
  4427. break;
  4428. case '=':
  4429. if (subtype == 0)
  4430. break;
  4431. if ((subtype & VSTYPE) != VSNORMAL)
  4432. quoted <<= 1;
  4433. str = vstype[subtype & VSTYPE];
  4434. if (subtype & VSNUL)
  4435. c = ':';
  4436. else
  4437. goto checkstr;
  4438. break;
  4439. case '\'':
  4440. case '\\':
  4441. case '"':
  4442. case '$':
  4443. /* These can only happen inside quotes */
  4444. cc[0] = c;
  4445. str = cc;
  4446. //FIXME:
  4447. // $ true $$ &
  4448. // $ <cr>
  4449. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4450. c = '\\';
  4451. break;
  4452. default:
  4453. break;
  4454. }
  4455. USTPUTC(c, nextc);
  4456. checkstr:
  4457. if (!str)
  4458. continue;
  4459. dostr:
  4460. while ((c = *str++) != '\0') {
  4461. USTPUTC(c, nextc);
  4462. }
  4463. } /* while *p++ not NUL */
  4464. if (quoted & 1) {
  4465. USTPUTC('"', nextc);
  4466. }
  4467. *nextc = 0;
  4468. cmdnextc = nextc;
  4469. }
  4470. /* cmdtxt() and cmdlist() call each other */
  4471. static void cmdtxt(union node *n);
  4472. static void
  4473. cmdlist(union node *np, int sep)
  4474. {
  4475. for (; np; np = np->narg.next) {
  4476. if (!sep)
  4477. cmdputs(" ");
  4478. cmdtxt(np);
  4479. if (sep && np->narg.next)
  4480. cmdputs(" ");
  4481. }
  4482. }
  4483. static void
  4484. cmdtxt(union node *n)
  4485. {
  4486. union node *np;
  4487. struct nodelist *lp;
  4488. const char *p;
  4489. if (!n)
  4490. return;
  4491. switch (n->type) {
  4492. default:
  4493. #if DEBUG
  4494. abort();
  4495. #endif
  4496. case NPIPE:
  4497. lp = n->npipe.cmdlist;
  4498. for (;;) {
  4499. cmdtxt(lp->n);
  4500. lp = lp->next;
  4501. if (!lp)
  4502. break;
  4503. cmdputs(" | ");
  4504. }
  4505. break;
  4506. case NSEMI:
  4507. p = "; ";
  4508. goto binop;
  4509. case NAND:
  4510. p = " && ";
  4511. goto binop;
  4512. case NOR:
  4513. p = " || ";
  4514. binop:
  4515. cmdtxt(n->nbinary.ch1);
  4516. cmdputs(p);
  4517. n = n->nbinary.ch2;
  4518. goto donode;
  4519. case NREDIR:
  4520. case NBACKGND:
  4521. n = n->nredir.n;
  4522. goto donode;
  4523. case NNOT:
  4524. cmdputs("!");
  4525. n = n->nnot.com;
  4526. donode:
  4527. cmdtxt(n);
  4528. break;
  4529. case NIF:
  4530. cmdputs("if ");
  4531. cmdtxt(n->nif.test);
  4532. cmdputs("; then ");
  4533. if (n->nif.elsepart) {
  4534. cmdtxt(n->nif.ifpart);
  4535. cmdputs("; else ");
  4536. n = n->nif.elsepart;
  4537. } else {
  4538. n = n->nif.ifpart;
  4539. }
  4540. p = "; fi";
  4541. goto dotail;
  4542. case NSUBSHELL:
  4543. cmdputs("(");
  4544. n = n->nredir.n;
  4545. p = ")";
  4546. goto dotail;
  4547. case NWHILE:
  4548. p = "while ";
  4549. goto until;
  4550. case NUNTIL:
  4551. p = "until ";
  4552. until:
  4553. cmdputs(p);
  4554. cmdtxt(n->nbinary.ch1);
  4555. n = n->nbinary.ch2;
  4556. p = "; done";
  4557. dodo:
  4558. cmdputs("; do ");
  4559. dotail:
  4560. cmdtxt(n);
  4561. goto dotail2;
  4562. case NFOR:
  4563. cmdputs("for ");
  4564. cmdputs(n->nfor.var);
  4565. cmdputs(" in ");
  4566. cmdlist(n->nfor.args, 1);
  4567. n = n->nfor.body;
  4568. p = "; done";
  4569. goto dodo;
  4570. case NDEFUN:
  4571. cmdputs(n->ndefun.text);
  4572. p = "() { ... }";
  4573. goto dotail2;
  4574. case NCMD:
  4575. cmdlist(n->ncmd.args, 1);
  4576. cmdlist(n->ncmd.redirect, 0);
  4577. break;
  4578. case NARG:
  4579. p = n->narg.text;
  4580. dotail2:
  4581. cmdputs(p);
  4582. break;
  4583. case NHERE:
  4584. case NXHERE:
  4585. p = "<<...";
  4586. goto dotail2;
  4587. case NCASE:
  4588. cmdputs("case ");
  4589. cmdputs(n->ncase.expr->narg.text);
  4590. cmdputs(" in ");
  4591. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4592. cmdtxt(np->nclist.pattern);
  4593. cmdputs(") ");
  4594. cmdtxt(np->nclist.body);
  4595. cmdputs(";; ");
  4596. }
  4597. p = "esac";
  4598. goto dotail2;
  4599. case NTO:
  4600. p = ">";
  4601. goto redir;
  4602. case NCLOBBER:
  4603. p = ">|";
  4604. goto redir;
  4605. case NAPPEND:
  4606. p = ">>";
  4607. goto redir;
  4608. #if BASH_REDIR_OUTPUT
  4609. case NTO2:
  4610. #endif
  4611. case NTOFD:
  4612. p = ">&";
  4613. goto redir;
  4614. case NFROM:
  4615. p = "<";
  4616. goto redir;
  4617. case NFROMFD:
  4618. p = "<&";
  4619. goto redir;
  4620. case NFROMTO:
  4621. p = "<>";
  4622. redir:
  4623. cmdputs(utoa(n->nfile.fd));
  4624. cmdputs(p);
  4625. if (n->type == NTOFD || n->type == NFROMFD) {
  4626. if (n->ndup.dupfd >= 0)
  4627. cmdputs(utoa(n->ndup.dupfd));
  4628. else
  4629. cmdputs("-");
  4630. break;
  4631. }
  4632. n = n->nfile.fname;
  4633. goto donode;
  4634. }
  4635. }
  4636. static char *
  4637. commandtext(union node *n)
  4638. {
  4639. char *name;
  4640. STARTSTACKSTR(cmdnextc);
  4641. cmdtxt(n);
  4642. name = stackblock();
  4643. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4644. return ckstrdup(name);
  4645. }
  4646. #endif /* JOBS */
  4647. /*
  4648. * Fork off a subshell. If we are doing job control, give the subshell its
  4649. * own process group. Jp is a job structure that the job is to be added to.
  4650. * N is the command that will be evaluated by the child. Both jp and n may
  4651. * be NULL. The mode parameter can be one of the following:
  4652. * FORK_FG - Fork off a foreground process.
  4653. * FORK_BG - Fork off a background process.
  4654. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4655. * process group even if job control is on.
  4656. *
  4657. * When job control is turned off, background processes have their standard
  4658. * input redirected to /dev/null (except for the second and later processes
  4659. * in a pipeline).
  4660. *
  4661. * Called with interrupts off.
  4662. */
  4663. /*
  4664. * Clear traps on a fork.
  4665. */
  4666. static void
  4667. clear_traps(void)
  4668. {
  4669. char **tp;
  4670. INT_OFF;
  4671. for (tp = trap; tp <= &trap[NTRAP_LAST]; tp++) {
  4672. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4673. if (trap_ptr == trap)
  4674. free(*tp);
  4675. /* else: it "belongs" to trap_ptr vector, don't free */
  4676. *tp = NULL;
  4677. if ((tp - trap) != 0 && (tp - trap) < NSIG)
  4678. setsignal(tp - trap);
  4679. }
  4680. }
  4681. may_have_traps = 0;
  4682. INT_ON;
  4683. }
  4684. /* Lives far away from here, needed for forkchild */
  4685. static void closescript(void);
  4686. /* Called after fork(), in child */
  4687. /* jp and n are NULL when called by openhere() for heredoc support */
  4688. static NOINLINE void
  4689. forkchild(struct job *jp, union node *n, int mode)
  4690. {
  4691. int oldlvl;
  4692. TRACE(("Child shell %d\n", getpid()));
  4693. oldlvl = shlvl;
  4694. shlvl++;
  4695. /* man bash: "Non-builtin commands run by bash have signal handlers
  4696. * set to the values inherited by the shell from its parent".
  4697. * Do we do it correctly? */
  4698. closescript();
  4699. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4700. && n && n->type == NCMD /* is it single cmd? */
  4701. /* && n->ncmd.args->type == NARG - always true? */
  4702. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4703. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4704. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4705. ) {
  4706. TRACE(("Trap hack\n"));
  4707. /* Awful hack for `trap` or $(trap).
  4708. *
  4709. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4710. * contains an example where "trap" is executed in a subshell:
  4711. *
  4712. * save_traps=$(trap)
  4713. * ...
  4714. * eval "$save_traps"
  4715. *
  4716. * Standard does not say that "trap" in subshell shall print
  4717. * parent shell's traps. It only says that its output
  4718. * must have suitable form, but then, in the above example
  4719. * (which is not supposed to be normative), it implies that.
  4720. *
  4721. * bash (and probably other shell) does implement it
  4722. * (traps are reset to defaults, but "trap" still shows them),
  4723. * but as a result, "trap" logic is hopelessly messed up:
  4724. *
  4725. * # trap
  4726. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4727. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4728. * # true | trap <--- trap is in subshell - no output (ditto)
  4729. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4730. * trap -- 'echo Ho' SIGWINCH
  4731. * # echo `(trap)` <--- in subshell in subshell - output
  4732. * trap -- 'echo Ho' SIGWINCH
  4733. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4734. * trap -- 'echo Ho' SIGWINCH
  4735. *
  4736. * The rules when to forget and when to not forget traps
  4737. * get really complex and nonsensical.
  4738. *
  4739. * Our solution: ONLY bare $(trap) or `trap` is special.
  4740. */
  4741. /* Save trap handler strings for trap builtin to print */
  4742. trap_ptr = xmemdup(trap, sizeof(trap));
  4743. /* Fall through into clearing traps */
  4744. }
  4745. clear_traps();
  4746. #if JOBS
  4747. /* do job control only in root shell */
  4748. doing_jobctl = 0;
  4749. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4750. pid_t pgrp;
  4751. if (jp->nprocs == 0)
  4752. pgrp = getpid();
  4753. else
  4754. pgrp = jp->ps[0].ps_pid;
  4755. /* this can fail because we are doing it in the parent also */
  4756. setpgid(0, pgrp);
  4757. if (mode == FORK_FG)
  4758. xtcsetpgrp(ttyfd, pgrp);
  4759. setsignal(SIGTSTP);
  4760. setsignal(SIGTTOU);
  4761. } else
  4762. #endif
  4763. if (mode == FORK_BG) {
  4764. /* man bash: "When job control is not in effect,
  4765. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4766. ignoresig(SIGINT);
  4767. ignoresig(SIGQUIT);
  4768. if (jp->nprocs == 0) {
  4769. close(0);
  4770. if (open(bb_dev_null, O_RDONLY) != 0)
  4771. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4772. }
  4773. }
  4774. if (oldlvl == 0) {
  4775. if (iflag) { /* why if iflag only? */
  4776. setsignal(SIGINT);
  4777. setsignal(SIGTERM);
  4778. }
  4779. /* man bash:
  4780. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4781. * commands run by bash have signal handlers
  4782. * set to the values inherited by the shell
  4783. * from its parent".
  4784. * Take care of the second rule: */
  4785. setsignal(SIGQUIT);
  4786. }
  4787. #if JOBS
  4788. if (n && n->type == NCMD
  4789. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4790. ) {
  4791. TRACE(("Job hack\n"));
  4792. /* "jobs": we do not want to clear job list for it,
  4793. * instead we remove only _its_ own_ job from job list.
  4794. * This makes "jobs .... | cat" more useful.
  4795. */
  4796. freejob(curjob);
  4797. return;
  4798. }
  4799. #endif
  4800. for (jp = curjob; jp; jp = jp->prev_job)
  4801. freejob(jp);
  4802. }
  4803. /* Called after fork(), in parent */
  4804. #if !JOBS
  4805. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4806. #endif
  4807. static void
  4808. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4809. {
  4810. TRACE(("In parent shell: child = %d\n", pid));
  4811. if (!jp) /* jp is NULL when called by openhere() for heredoc support */
  4812. return;
  4813. #if JOBS
  4814. if (mode != FORK_NOJOB && jp->jobctl) {
  4815. int pgrp;
  4816. if (jp->nprocs == 0)
  4817. pgrp = pid;
  4818. else
  4819. pgrp = jp->ps[0].ps_pid;
  4820. /* This can fail because we are doing it in the child also */
  4821. setpgid(pid, pgrp);
  4822. }
  4823. #endif
  4824. if (mode == FORK_BG) {
  4825. backgndpid = pid; /* set $! */
  4826. set_curjob(jp, CUR_RUNNING);
  4827. }
  4828. if (jp) {
  4829. struct procstat *ps = &jp->ps[jp->nprocs++];
  4830. ps->ps_pid = pid;
  4831. ps->ps_status = -1;
  4832. ps->ps_cmd = nullstr;
  4833. #if JOBS
  4834. if (doing_jobctl && n)
  4835. ps->ps_cmd = commandtext(n);
  4836. #endif
  4837. }
  4838. }
  4839. /* jp and n are NULL when called by openhere() for heredoc support */
  4840. static int
  4841. forkshell(struct job *jp, union node *n, int mode)
  4842. {
  4843. int pid;
  4844. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4845. pid = fork();
  4846. if (pid < 0) {
  4847. TRACE(("Fork failed, errno=%d", errno));
  4848. if (jp)
  4849. freejob(jp);
  4850. ash_msg_and_raise_perror("can't fork");
  4851. }
  4852. if (pid == 0) {
  4853. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4854. forkchild(jp, n, mode);
  4855. } else {
  4856. forkparent(jp, n, mode, pid);
  4857. }
  4858. return pid;
  4859. }
  4860. /*
  4861. * Wait for job to finish.
  4862. *
  4863. * Under job control we have the problem that while a child process
  4864. * is running interrupts generated by the user are sent to the child
  4865. * but not to the shell. This means that an infinite loop started by
  4866. * an interactive user may be hard to kill. With job control turned off,
  4867. * an interactive user may place an interactive program inside a loop.
  4868. * If the interactive program catches interrupts, the user doesn't want
  4869. * these interrupts to also abort the loop. The approach we take here
  4870. * is to have the shell ignore interrupt signals while waiting for a
  4871. * foreground process to terminate, and then send itself an interrupt
  4872. * signal if the child process was terminated by an interrupt signal.
  4873. * Unfortunately, some programs want to do a bit of cleanup and then
  4874. * exit on interrupt; unless these processes terminate themselves by
  4875. * sending a signal to themselves (instead of calling exit) they will
  4876. * confuse this approach.
  4877. *
  4878. * Called with interrupts off.
  4879. */
  4880. static int
  4881. waitforjob(struct job *jp)
  4882. {
  4883. int st;
  4884. TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0));
  4885. /* In non-interactive shells, we _can_ get
  4886. * a keyboard signal here and be EINTRed, but we just loop
  4887. * inside dowait(), waiting for command to complete.
  4888. *
  4889. * man bash:
  4890. * "If bash is waiting for a command to complete and receives
  4891. * a signal for which a trap has been set, the trap
  4892. * will not be executed until the command completes."
  4893. *
  4894. * Reality is that even if trap is not set, bash
  4895. * will not act on the signal until command completes.
  4896. * Try this. sleep5intoff.c:
  4897. * #include <signal.h>
  4898. * #include <unistd.h>
  4899. * int main() {
  4900. * sigset_t set;
  4901. * sigemptyset(&set);
  4902. * sigaddset(&set, SIGINT);
  4903. * sigaddset(&set, SIGQUIT);
  4904. * sigprocmask(SIG_BLOCK, &set, NULL);
  4905. * sleep(5);
  4906. * return 0;
  4907. * }
  4908. * $ bash -c './sleep5intoff; echo hi'
  4909. * ^C^C^C^C <--- pressing ^C once a second
  4910. * $ _
  4911. * $ bash -c './sleep5intoff; echo hi'
  4912. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4913. * $ _
  4914. */
  4915. dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp);
  4916. if (!jp)
  4917. return exitstatus;
  4918. st = getstatus(jp);
  4919. #if JOBS
  4920. if (jp->jobctl) {
  4921. xtcsetpgrp(ttyfd, rootpid);
  4922. restore_tty_if_stopped_or_signaled(jp);
  4923. /*
  4924. * This is truly gross.
  4925. * If we're doing job control, then we did a TIOCSPGRP which
  4926. * caused us (the shell) to no longer be in the controlling
  4927. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4928. * intuit from the subprocess exit status whether a SIGINT
  4929. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4930. */
  4931. if (jp->sigint) /* TODO: do the same with all signals */
  4932. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4933. }
  4934. if (jp->state == JOBDONE)
  4935. #endif
  4936. freejob(jp);
  4937. return st;
  4938. }
  4939. /*
  4940. * return 1 if there are stopped jobs, otherwise 0
  4941. */
  4942. static int
  4943. stoppedjobs(void)
  4944. {
  4945. struct job *jp;
  4946. int retval;
  4947. retval = 0;
  4948. if (!iflag || job_warning)
  4949. goto out;
  4950. jp = curjob;
  4951. if (jp && jp->state == JOBSTOPPED) {
  4952. out2str("You have stopped jobs.\n");
  4953. job_warning = 2;
  4954. retval++;
  4955. }
  4956. out:
  4957. return retval;
  4958. }
  4959. /*
  4960. * Code for dealing with input/output redirection.
  4961. */
  4962. #undef EMPTY
  4963. #undef CLOSED
  4964. #define EMPTY -2 /* marks an unused slot in redirtab */
  4965. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4966. /*
  4967. * Handle here documents. Normally we fork off a process to write the
  4968. * data to a pipe. If the document is short, we can stuff the data in
  4969. * the pipe without forking.
  4970. */
  4971. /* openhere needs this forward reference */
  4972. static void expandhere(union node *arg);
  4973. static int
  4974. openhere(union node *redir)
  4975. {
  4976. char *p;
  4977. int pip[2];
  4978. size_t len = 0;
  4979. if (pipe(pip) < 0)
  4980. ash_msg_and_raise_perror("can't create pipe");
  4981. p = redir->nhere.doc->narg.text;
  4982. if (redir->type == NXHERE) {
  4983. expandhere(redir->nhere.doc);
  4984. p = stackblock();
  4985. }
  4986. len = strlen(p);
  4987. if (len <= PIPE_BUF) {
  4988. xwrite(pip[1], p, len);
  4989. goto out;
  4990. }
  4991. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4992. /* child */
  4993. close(pip[0]);
  4994. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4995. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4996. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4997. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4998. signal(SIGPIPE, SIG_DFL);
  4999. xwrite(pip[1], p, len);
  5000. _exit_SUCCESS();
  5001. }
  5002. out:
  5003. close(pip[1]);
  5004. return pip[0];
  5005. }
  5006. static int
  5007. openredirect(union node *redir)
  5008. {
  5009. struct stat sb;
  5010. char *fname;
  5011. int f;
  5012. switch (redir->nfile.type) {
  5013. /* Can't happen, our single caller does this itself */
  5014. // case NTOFD:
  5015. // case NFROMFD:
  5016. // return -1;
  5017. case NHERE:
  5018. case NXHERE:
  5019. return openhere(redir);
  5020. }
  5021. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  5022. * allocated space. Do it only when we know it is safe.
  5023. */
  5024. fname = redir->nfile.expfname;
  5025. switch (redir->nfile.type) {
  5026. default:
  5027. #if DEBUG
  5028. abort();
  5029. #endif
  5030. case NFROM:
  5031. f = open(fname, O_RDONLY);
  5032. if (f < 0)
  5033. goto eopen;
  5034. break;
  5035. case NFROMTO:
  5036. f = open(fname, O_RDWR|O_CREAT, 0666);
  5037. if (f < 0)
  5038. goto ecreate;
  5039. break;
  5040. case NTO:
  5041. #if BASH_REDIR_OUTPUT
  5042. case NTO2:
  5043. #endif
  5044. /* Take care of noclobber mode. */
  5045. if (Cflag) {
  5046. if (stat(fname, &sb) < 0) {
  5047. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  5048. if (f < 0)
  5049. goto ecreate;
  5050. } else if (!S_ISREG(sb.st_mode)) {
  5051. f = open(fname, O_WRONLY, 0666);
  5052. if (f < 0)
  5053. goto ecreate;
  5054. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  5055. close(f);
  5056. errno = EEXIST;
  5057. goto ecreate;
  5058. }
  5059. } else {
  5060. errno = EEXIST;
  5061. goto ecreate;
  5062. }
  5063. break;
  5064. }
  5065. /* FALLTHROUGH */
  5066. case NCLOBBER:
  5067. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  5068. if (f < 0)
  5069. goto ecreate;
  5070. break;
  5071. case NAPPEND:
  5072. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  5073. if (f < 0)
  5074. goto ecreate;
  5075. break;
  5076. }
  5077. return f;
  5078. ecreate:
  5079. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  5080. eopen:
  5081. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  5082. }
  5083. /*
  5084. * Copy a file descriptor to be >= 10. Throws exception on error.
  5085. */
  5086. static int
  5087. savefd(int from)
  5088. {
  5089. int newfd;
  5090. int err;
  5091. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  5092. err = newfd < 0 ? errno : 0;
  5093. if (err != EBADF) {
  5094. if (err)
  5095. ash_msg_and_raise_perror("%d", from);
  5096. close(from);
  5097. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5098. close_on_exec_on(newfd);
  5099. }
  5100. return newfd;
  5101. }
  5102. static int
  5103. dup2_or_raise(int from, int to)
  5104. {
  5105. int newfd;
  5106. newfd = (from != to) ? dup2(from, to) : to;
  5107. if (newfd < 0) {
  5108. /* Happens when source fd is not open: try "echo >&99" */
  5109. ash_msg_and_raise_perror("%d", from);
  5110. }
  5111. return newfd;
  5112. }
  5113. static int
  5114. dup_CLOEXEC(int fd, int avoid_fd)
  5115. {
  5116. int newfd;
  5117. repeat:
  5118. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5119. if (newfd >= 0) {
  5120. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  5121. close_on_exec_on(newfd);
  5122. } else { /* newfd < 0 */
  5123. if (errno == EBUSY)
  5124. goto repeat;
  5125. if (errno == EINTR)
  5126. goto repeat;
  5127. }
  5128. return newfd;
  5129. }
  5130. static int
  5131. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5132. {
  5133. int newfd;
  5134. repeat:
  5135. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5136. if (newfd < 0) {
  5137. if (errno == EBUSY)
  5138. goto repeat;
  5139. if (errno == EINTR)
  5140. goto repeat;
  5141. /* fd was not open? */
  5142. if (errno == EBADF)
  5143. return fd;
  5144. ash_msg_and_raise_perror("%d", newfd);
  5145. }
  5146. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5147. close_on_exec_on(newfd);
  5148. close(fd);
  5149. return newfd;
  5150. }
  5151. /* Struct def and variable are moved down to the first usage site */
  5152. struct squirrel {
  5153. int orig_fd;
  5154. int moved_to;
  5155. };
  5156. struct redirtab {
  5157. struct redirtab *next;
  5158. int pair_count;
  5159. struct squirrel two_fd[];
  5160. };
  5161. #define redirlist (G_var.redirlist)
  5162. static void
  5163. add_squirrel_closed(struct redirtab *sq, int fd)
  5164. {
  5165. int i;
  5166. if (!sq)
  5167. return;
  5168. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5169. /* If we collide with an already moved fd... */
  5170. if (fd == sq->two_fd[i].orig_fd) {
  5171. /* Examples:
  5172. * "echo 3>FILE 3>&- 3>FILE"
  5173. * "echo 3>&- 3>FILE"
  5174. * No need for last redirect to insert
  5175. * another "need to close 3" indicator.
  5176. */
  5177. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5178. return;
  5179. }
  5180. }
  5181. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5182. sq->two_fd[i].orig_fd = fd;
  5183. sq->two_fd[i].moved_to = CLOSED;
  5184. }
  5185. static int
  5186. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5187. {
  5188. int i, new_fd;
  5189. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5190. avoid_fd = 9;
  5191. #if JOBS
  5192. if (fd == ttyfd) {
  5193. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5194. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5195. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5196. return 1; /* "we closed fd" */
  5197. }
  5198. #endif
  5199. /* Are we called from redirect(0)? E.g. redirect
  5200. * in a forked child. No need to save fds,
  5201. * we aren't going to use them anymore, ok to trash.
  5202. */
  5203. if (!sq)
  5204. return 0;
  5205. /* If this one of script's fds? */
  5206. if (fd != 0) {
  5207. struct parsefile *pf = g_parsefile;
  5208. while (pf) {
  5209. /* We skip fd == 0 case because of the following:
  5210. * $ ash # running ash interactively
  5211. * $ . ./script.sh
  5212. * and in script.sh: "exec 9>&0".
  5213. * Even though top-level pf_fd _is_ 0,
  5214. * it's still ok to use it: "read" builtin uses it,
  5215. * why should we cripple "exec" builtin?
  5216. */
  5217. if (fd == pf->pf_fd) {
  5218. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5219. return 1; /* "we closed fd" */
  5220. }
  5221. pf = pf->prev;
  5222. }
  5223. }
  5224. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5225. /* First: do we collide with some already moved fds? */
  5226. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5227. /* If we collide with an already moved fd... */
  5228. if (fd == sq->two_fd[i].moved_to) {
  5229. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5230. sq->two_fd[i].moved_to = new_fd;
  5231. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5232. if (new_fd < 0) /* what? */
  5233. xfunc_die();
  5234. return 0; /* "we did not close fd" */
  5235. }
  5236. if (fd == sq->two_fd[i].orig_fd) {
  5237. /* Example: echo Hello >/dev/null 1>&2 */
  5238. TRACE(("redirect_fd %d: already moved\n", fd));
  5239. return 0; /* "we did not close fd" */
  5240. }
  5241. }
  5242. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5243. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5244. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5245. if (new_fd < 0) {
  5246. if (errno != EBADF)
  5247. xfunc_die();
  5248. /* new_fd = CLOSED; - already is -1 */
  5249. }
  5250. sq->two_fd[i].moved_to = new_fd;
  5251. sq->two_fd[i].orig_fd = fd;
  5252. /* if we move stderr, let "set -x" code know */
  5253. if (fd == preverrout_fd)
  5254. preverrout_fd = new_fd;
  5255. return 0; /* "we did not close fd" */
  5256. }
  5257. static int
  5258. internally_opened_fd(int fd, struct redirtab *sq)
  5259. {
  5260. int i;
  5261. #if JOBS
  5262. if (fd == ttyfd)
  5263. return 1;
  5264. #endif
  5265. /* If this one of script's fds? */
  5266. if (fd != 0) {
  5267. struct parsefile *pf = g_parsefile;
  5268. while (pf) {
  5269. if (fd == pf->pf_fd)
  5270. return 1;
  5271. pf = pf->prev;
  5272. }
  5273. }
  5274. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5275. if (fd == sq->two_fd[i].moved_to)
  5276. return 1;
  5277. }
  5278. return 0;
  5279. }
  5280. /*
  5281. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5282. * old file descriptors are stashed away so that the redirection can be
  5283. * undone by calling popredir.
  5284. */
  5285. /* flags passed to redirect */
  5286. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5287. static void
  5288. redirect(union node *redir, int flags)
  5289. {
  5290. struct redirtab *sv;
  5291. if (!redir)
  5292. return;
  5293. sv = NULL;
  5294. INT_OFF;
  5295. if (flags & REDIR_PUSH)
  5296. sv = redirlist;
  5297. do {
  5298. int fd;
  5299. int newfd;
  5300. int close_fd;
  5301. int closed;
  5302. fd = redir->nfile.fd;
  5303. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5304. //bb_error_msg("doing %d > %d", fd, newfd);
  5305. newfd = redir->ndup.dupfd;
  5306. close_fd = -1;
  5307. } else {
  5308. newfd = openredirect(redir); /* always >= 0 */
  5309. if (fd == newfd) {
  5310. /* open() gave us precisely the fd we wanted.
  5311. * This means that this fd was not busy
  5312. * (not opened to anywhere).
  5313. * Remember to close it on restore:
  5314. */
  5315. add_squirrel_closed(sv, fd);
  5316. continue;
  5317. }
  5318. close_fd = newfd;
  5319. }
  5320. if (fd == newfd)
  5321. continue;
  5322. /* if "N>FILE": move newfd to fd */
  5323. /* if "N>&M": dup newfd to fd */
  5324. /* if "N>&-": close fd (newfd is -1) */
  5325. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5326. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5327. if (newfd == -1) {
  5328. /* "N>&-" means "close me" */
  5329. if (!closed) {
  5330. /* ^^^ optimization: saving may already
  5331. * have closed it. If not... */
  5332. close(fd);
  5333. }
  5334. } else {
  5335. /* if newfd is a script fd or saved fd, simulate EBADF */
  5336. if (internally_opened_fd(newfd, sv)) {
  5337. errno = EBADF;
  5338. ash_msg_and_raise_perror("%d", newfd);
  5339. }
  5340. dup2_or_raise(newfd, fd);
  5341. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5342. close(close_fd);
  5343. #if BASH_REDIR_OUTPUT
  5344. if (redir->nfile.type == NTO2 && fd == 1) {
  5345. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5346. fd = 2;
  5347. newfd = 1;
  5348. close_fd = -1;
  5349. goto redirect_more;
  5350. }
  5351. #endif
  5352. }
  5353. } while ((redir = redir->nfile.next) != NULL);
  5354. INT_ON;
  5355. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5356. #define REDIR_SAVEFD2 0
  5357. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5358. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5359. // not only for calls with flags containing REDIR_SAVEFD2.
  5360. // We do this unconditionally (see save_fd_on_redirect()).
  5361. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5362. // preverrout_fd = copied_fd2;
  5363. }
  5364. static int
  5365. redirectsafe(union node *redir, int flags)
  5366. {
  5367. int err;
  5368. volatile int saveint;
  5369. struct jmploc *volatile savehandler = exception_handler;
  5370. struct jmploc jmploc;
  5371. SAVE_INT(saveint);
  5372. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5373. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5374. if (!err) {
  5375. exception_handler = &jmploc;
  5376. redirect(redir, flags);
  5377. }
  5378. exception_handler = savehandler;
  5379. if (err && exception_type != EXERROR)
  5380. longjmp(exception_handler->loc, 1);
  5381. RESTORE_INT(saveint);
  5382. return err;
  5383. }
  5384. #if BASH_PROCESS_SUBST
  5385. static void
  5386. pushfd(int fd)
  5387. {
  5388. struct redirtab *sv;
  5389. sv = ckzalloc(sizeof(*sv) + sizeof(sv->two_fd[0]));
  5390. sv->pair_count = 1;
  5391. sv->two_fd[0].orig_fd = fd;
  5392. sv->two_fd[0].moved_to = CLOSED;
  5393. sv->next = redirlist;
  5394. redirlist = sv;
  5395. }
  5396. #endif
  5397. static struct redirtab*
  5398. pushredir(union node *redir)
  5399. {
  5400. struct redirtab *sv;
  5401. int i;
  5402. if (!redir)
  5403. return redirlist;
  5404. i = 0;
  5405. do {
  5406. i++;
  5407. #if BASH_REDIR_OUTPUT
  5408. if (redir->nfile.type == NTO2)
  5409. i++;
  5410. #endif
  5411. redir = redir->nfile.next;
  5412. } while (redir);
  5413. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5414. sv->pair_count = i;
  5415. while (--i >= 0)
  5416. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5417. sv->next = redirlist;
  5418. redirlist = sv;
  5419. return sv->next;
  5420. }
  5421. /*
  5422. * Undo the effects of the last redirection.
  5423. */
  5424. static void
  5425. popredir(int drop)
  5426. {
  5427. struct redirtab *rp;
  5428. int i;
  5429. if (redirlist == NULL)
  5430. return;
  5431. INT_OFF;
  5432. rp = redirlist;
  5433. for (i = 0; i < rp->pair_count; i++) {
  5434. int fd = rp->two_fd[i].orig_fd;
  5435. int copy = rp->two_fd[i].moved_to;
  5436. if (copy == CLOSED) {
  5437. if (!drop)
  5438. close(fd);
  5439. continue;
  5440. }
  5441. if (copy != EMPTY) {
  5442. if (!drop) {
  5443. /*close(fd);*/
  5444. dup2_or_raise(copy, fd);
  5445. }
  5446. close(copy);
  5447. }
  5448. }
  5449. redirlist = rp->next;
  5450. free(rp);
  5451. INT_ON;
  5452. }
  5453. static void
  5454. unwindredir(struct redirtab *stop)
  5455. {
  5456. while (redirlist != stop)
  5457. popredir(/*drop:*/ 0);
  5458. }
  5459. /* ============ Routines to expand arguments to commands
  5460. *
  5461. * We have to deal with backquotes, shell variables, and file metacharacters.
  5462. */
  5463. #if ENABLE_FEATURE_SH_MATH
  5464. static arith_t
  5465. ash_arith(const char *s)
  5466. {
  5467. arith_state_t math_state;
  5468. arith_t result;
  5469. math_state.lookupvar = lookupvar;
  5470. math_state.setvar = setvar0;
  5471. //math_state.endofname = endofname;
  5472. INT_OFF;
  5473. result = arith(&math_state, s);
  5474. if (math_state.errmsg)
  5475. ash_msg_and_raise_error(math_state.errmsg);
  5476. INT_ON;
  5477. return result;
  5478. }
  5479. #endif
  5480. #if BASH_SUBSTR
  5481. # if ENABLE_FEATURE_SH_MATH
  5482. static int substr_atoi(const char *s)
  5483. {
  5484. arith_t t = ash_arith(s);
  5485. if (sizeof(t) > sizeof(int)) {
  5486. /* clamp very large or very large negative nums for ${v:N:M}:
  5487. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5488. */
  5489. if (t > INT_MAX)
  5490. t = INT_MAX;
  5491. if (t < INT_MIN)
  5492. t = INT_MIN;
  5493. }
  5494. return t;
  5495. }
  5496. # else
  5497. # define substr_atoi(s) number(s)
  5498. # endif
  5499. #endif
  5500. /*
  5501. * expandarg flags
  5502. */
  5503. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5504. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5505. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5506. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5507. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5508. * POSIX says for this case:
  5509. * Pathname expansion shall not be performed on the word by a
  5510. * non-interactive shell; an interactive shell may perform it, but shall
  5511. * do so only when the expansion would result in one word.
  5512. * Currently, our code complies to the above rule by never globbing
  5513. * redirection filenames.
  5514. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5515. * (this means that on a typical Linux distro, bash almost always
  5516. * performs globbing, and thus diverges from what we do).
  5517. */
  5518. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5519. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5520. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5521. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5522. #define EXP_KEEPNUL 0x200 /* do not skip NUL characters */
  5523. #define EXP_DISCARD 0x400 /* discard result of expansion */
  5524. /*
  5525. * rmescape() flags
  5526. */
  5527. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5528. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5529. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5530. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5531. /* Add CTLESC when necessary. */
  5532. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5533. /*
  5534. * Structure specifying which parts of the string should be searched
  5535. * for IFS characters.
  5536. */
  5537. struct ifsregion {
  5538. struct ifsregion *next; /* next region in list */
  5539. int begoff; /* offset of start of region */
  5540. int endoff; /* offset of end of region */
  5541. int nulonly; /* search for nul bytes only */
  5542. };
  5543. struct arglist {
  5544. struct strlist *list;
  5545. struct strlist **lastp;
  5546. };
  5547. /* output of current string */
  5548. static char *expdest;
  5549. /* list of back quote expressions */
  5550. static struct nodelist *argbackq;
  5551. /* first struct in list of ifs regions */
  5552. static struct ifsregion ifsfirst;
  5553. /* last struct in list */
  5554. static struct ifsregion *ifslastp;
  5555. /* holds expanded arg list */
  5556. static struct arglist exparg;
  5557. /*
  5558. * Break the argument string into pieces based upon IFS and add the
  5559. * strings to the argument list. The regions of the string to be
  5560. * searched for IFS characters have been stored by recordregion.
  5561. */
  5562. static void
  5563. ifsbreakup(char *string, struct arglist *arglist)
  5564. {
  5565. struct ifsregion *ifsp;
  5566. struct strlist *sp;
  5567. char *start;
  5568. char *p;
  5569. char *q;
  5570. const char *ifs, *realifs;
  5571. int ifsspc;
  5572. int nulonly;
  5573. start = string;
  5574. if (ifslastp != NULL) {
  5575. ifsspc = 0;
  5576. nulonly = 0;
  5577. realifs = ifsset() ? ifsval() : defifs;
  5578. ifsp = &ifsfirst;
  5579. do {
  5580. int afternul;
  5581. p = string + ifsp->begoff;
  5582. afternul = nulonly;
  5583. nulonly = ifsp->nulonly;
  5584. ifs = nulonly ? nullstr : realifs;
  5585. ifsspc = 0;
  5586. while (p < string + ifsp->endoff) {
  5587. q = p;
  5588. if ((unsigned char)*p == CTLESC)
  5589. p++;
  5590. if (!strchr(ifs, *p)) {
  5591. p++;
  5592. continue;
  5593. }
  5594. if (!(afternul || nulonly))
  5595. ifsspc = (strchr(defifs, *p) != NULL);
  5596. /* Ignore IFS whitespace at start */
  5597. if (q == start && ifsspc) {
  5598. p++;
  5599. start = p;
  5600. continue;
  5601. }
  5602. *q = '\0';
  5603. sp = stzalloc(sizeof(*sp));
  5604. sp->text = start;
  5605. *arglist->lastp = sp;
  5606. arglist->lastp = &sp->next;
  5607. p++;
  5608. if (!nulonly) {
  5609. for (;;) {
  5610. if (p >= string + ifsp->endoff) {
  5611. break;
  5612. }
  5613. q = p;
  5614. if ((unsigned char)*p == CTLESC)
  5615. p++;
  5616. if (strchr(ifs, *p) == NULL) {
  5617. p = q;
  5618. break;
  5619. }
  5620. if (strchr(defifs, *p) == NULL) {
  5621. if (ifsspc) {
  5622. p++;
  5623. ifsspc = 0;
  5624. } else {
  5625. p = q;
  5626. break;
  5627. }
  5628. } else
  5629. p++;
  5630. }
  5631. }
  5632. start = p;
  5633. } /* while */
  5634. ifsp = ifsp->next;
  5635. } while (ifsp != NULL);
  5636. if (nulonly)
  5637. goto add;
  5638. }
  5639. if (!*start)
  5640. return;
  5641. add:
  5642. sp = stzalloc(sizeof(*sp));
  5643. sp->text = start;
  5644. *arglist->lastp = sp;
  5645. arglist->lastp = &sp->next;
  5646. }
  5647. static void
  5648. ifsfree(void)
  5649. {
  5650. struct ifsregion *p = ifsfirst.next;
  5651. if (!p)
  5652. goto out;
  5653. INT_OFF;
  5654. do {
  5655. struct ifsregion *ifsp;
  5656. ifsp = p->next;
  5657. free(p);
  5658. p = ifsp;
  5659. } while (p);
  5660. ifsfirst.next = NULL;
  5661. INT_ON;
  5662. out:
  5663. ifslastp = NULL;
  5664. }
  5665. static size_t
  5666. esclen(const char *start, const char *p)
  5667. {
  5668. size_t esc = 0;
  5669. while (p > start && (unsigned char)*--p == CTLESC) {
  5670. esc++;
  5671. }
  5672. return esc;
  5673. }
  5674. /*
  5675. * Remove any CTLESC characters from a string.
  5676. */
  5677. #if !BASH_PATTERN_SUBST
  5678. #define rmescapes(str, flag, slash_position) \
  5679. rmescapes(str, flag)
  5680. #endif
  5681. static char *
  5682. rmescapes(char *str, int flag, int *slash_position)
  5683. {
  5684. static const char qchars[] ALIGN1 = {
  5685. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5686. char *p, *q, *r;
  5687. unsigned protect_against_glob;
  5688. unsigned globbing;
  5689. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5690. if (!p)
  5691. return str;
  5692. q = p;
  5693. r = str;
  5694. if (flag & RMESCAPE_ALLOC) {
  5695. size_t len = p - str;
  5696. size_t fulllen = len + strlen(p) + 1;
  5697. if (flag & RMESCAPE_GROW) {
  5698. int strloc = str - (char *)stackblock();
  5699. r = makestrspace(fulllen, expdest);
  5700. /* p and str may be invalidated by makestrspace */
  5701. str = (char *)stackblock() + strloc;
  5702. p = str + len;
  5703. } else if (flag & RMESCAPE_HEAP) {
  5704. r = ckmalloc(fulllen);
  5705. } else {
  5706. r = stalloc(fulllen);
  5707. }
  5708. q = r;
  5709. if (len > 0) {
  5710. q = (char *)mempcpy(q, str, len);
  5711. }
  5712. }
  5713. globbing = flag & RMESCAPE_GLOB;
  5714. protect_against_glob = globbing;
  5715. while (*p) {
  5716. if ((unsigned char)*p == CTLQUOTEMARK) {
  5717. // Note: protect_against_glob only affect whether
  5718. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5719. p++;
  5720. protect_against_glob = globbing;
  5721. continue;
  5722. }
  5723. if (*p == '\\') {
  5724. /* naked back slash */
  5725. protect_against_glob = 0;
  5726. goto copy;
  5727. }
  5728. if ((unsigned char)*p == CTLESC) {
  5729. p++;
  5730. #if DEBUG
  5731. if (*p == '\0')
  5732. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5733. #endif
  5734. if (protect_against_glob) {
  5735. /*
  5736. * We used to trust glob() and fnmatch() to eat
  5737. * superfluous escapes (\z where z has no
  5738. * special meaning anyway). But this causes
  5739. * bugs such as string of one greek letter rho
  5740. * (unicode-encoded as two bytes "cf,81")
  5741. * getting encoded as "cf,CTLESC,81"
  5742. * and here, converted to "cf,\,81" -
  5743. * which does not go well with some flavors
  5744. * of fnmatch() in unicode locales
  5745. * (for example, glibc <= 2.22).
  5746. *
  5747. * Lets add "\" only on the chars which need it.
  5748. * Testcases for less obvious chars are shown.
  5749. */
  5750. if (*p == '*'
  5751. || *p == '?'
  5752. || *p == '['
  5753. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5754. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5755. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5756. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5757. /* Some libc support [^negate], that's why "^" also needs love */
  5758. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5759. ) {
  5760. *q++ = '\\';
  5761. }
  5762. }
  5763. }
  5764. #if BASH_PATTERN_SUBST
  5765. else if (slash_position && p == str + *slash_position) {
  5766. /* stop handling globbing */
  5767. globbing = 0;
  5768. *slash_position = q - r;
  5769. slash_position = NULL;
  5770. }
  5771. #endif
  5772. protect_against_glob = globbing;
  5773. copy:
  5774. *q++ = *p++;
  5775. }
  5776. *q = '\0';
  5777. if (flag & RMESCAPE_GROW) {
  5778. expdest = r;
  5779. STADJUST(q - r + 1, expdest);
  5780. }
  5781. return r;
  5782. }
  5783. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5784. /*
  5785. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5786. *
  5787. * Returns an stalloced string.
  5788. */
  5789. static char *
  5790. preglob(const char *pattern, int flag)
  5791. {
  5792. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5793. }
  5794. /*
  5795. * Put a string on the stack.
  5796. */
  5797. static size_t
  5798. memtodest(const char *p, size_t len, int flags)
  5799. {
  5800. int syntax = flags & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5801. char *q;
  5802. char *s;
  5803. if (!len)
  5804. return 0;
  5805. q = makestrspace(len * 2, expdest);
  5806. s = q;
  5807. do {
  5808. unsigned char c = *p++;
  5809. if (c) {
  5810. if (flags & QUOTES_ESC) {
  5811. int n = SIT(c, syntax);
  5812. if (n == CCTL
  5813. || ((flags & EXP_QUOTED) && n == CBACK)
  5814. ) {
  5815. USTPUTC(CTLESC, q);
  5816. }
  5817. }
  5818. } else if (!(flags & EXP_KEEPNUL))
  5819. continue;
  5820. USTPUTC(c, q);
  5821. } while (--len);
  5822. expdest = q;
  5823. return q - s;
  5824. }
  5825. static size_t
  5826. strtodest(const char *p, int flags)
  5827. {
  5828. size_t len = strlen(p);
  5829. memtodest(p, len, flags);
  5830. return len;
  5831. }
  5832. /*
  5833. * Our own itoa().
  5834. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5835. */
  5836. static int
  5837. cvtnum(arith_t num, int flags)
  5838. {
  5839. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5840. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5841. int len = (sizeof(arith_t) >= 4) ? sizeof(arith_t) * 3 : sizeof(arith_t) * 3 + 2;
  5842. char buf[len];
  5843. len = fmtstr(buf, len, ARITH_FMT, num);
  5844. return memtodest(buf, len, flags);
  5845. }
  5846. /*
  5847. * Record the fact that we have to scan this region of the
  5848. * string for IFS characters.
  5849. */
  5850. static void
  5851. recordregion(int start, int end, int nulonly)
  5852. {
  5853. struct ifsregion *ifsp;
  5854. if (ifslastp == NULL) {
  5855. ifsp = &ifsfirst;
  5856. } else {
  5857. INT_OFF;
  5858. ifsp = ckzalloc(sizeof(*ifsp));
  5859. /*ifsp->next = NULL; - ckzalloc did it */
  5860. ifslastp->next = ifsp;
  5861. INT_ON;
  5862. }
  5863. ifslastp = ifsp;
  5864. ifslastp->begoff = start;
  5865. ifslastp->endoff = end;
  5866. ifslastp->nulonly = nulonly;
  5867. }
  5868. static void
  5869. removerecordregions(int endoff)
  5870. {
  5871. if (ifslastp == NULL)
  5872. return;
  5873. if (ifsfirst.endoff > endoff) {
  5874. while (ifsfirst.next) {
  5875. struct ifsregion *ifsp;
  5876. INT_OFF;
  5877. ifsp = ifsfirst.next->next;
  5878. free(ifsfirst.next);
  5879. ifsfirst.next = ifsp;
  5880. INT_ON;
  5881. }
  5882. if (ifsfirst.begoff > endoff) {
  5883. ifslastp = NULL;
  5884. } else {
  5885. ifslastp = &ifsfirst;
  5886. ifsfirst.endoff = endoff;
  5887. }
  5888. return;
  5889. }
  5890. ifslastp = &ifsfirst;
  5891. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5892. ifslastp = ifslastp->next;
  5893. while (ifslastp->next) {
  5894. struct ifsregion *ifsp;
  5895. INT_OFF;
  5896. ifsp = ifslastp->next->next;
  5897. free(ifslastp->next);
  5898. ifslastp->next = ifsp;
  5899. INT_ON;
  5900. }
  5901. if (ifslastp->endoff > endoff)
  5902. ifslastp->endoff = endoff;
  5903. }
  5904. static char *
  5905. exptilde(char *startp, int flag)
  5906. {
  5907. unsigned char c;
  5908. char *name;
  5909. struct passwd *pw;
  5910. const char *home;
  5911. char *p;
  5912. p = startp;
  5913. name = p + 1;
  5914. while ((c = *++p) != '\0') {
  5915. switch (c) {
  5916. case CTLESC:
  5917. return startp;
  5918. case CTLQUOTEMARK:
  5919. return startp;
  5920. case ':':
  5921. if (flag & EXP_VARTILDE)
  5922. goto done;
  5923. break;
  5924. case '/':
  5925. case CTLENDVAR:
  5926. goto done;
  5927. }
  5928. }
  5929. done:
  5930. if (flag & EXP_DISCARD)
  5931. goto out;
  5932. *p = '\0';
  5933. if (*name == '\0') {
  5934. home = lookupvar("HOME");
  5935. } else {
  5936. pw = getpwnam(name);
  5937. if (pw == NULL)
  5938. goto lose;
  5939. home = pw->pw_dir;
  5940. }
  5941. *p = c;
  5942. if (!home)
  5943. goto lose;
  5944. strtodest(home, flag | EXP_QUOTED);
  5945. out:
  5946. return p;
  5947. lose:
  5948. return startp;
  5949. }
  5950. /*
  5951. * Execute a command inside back quotes. If it's a builtin command, we
  5952. * want to save its output in a block obtained from malloc. Otherwise
  5953. * we fork off a subprocess and get the output of the command via a pipe.
  5954. * Should be called with interrupts off.
  5955. */
  5956. struct backcmd { /* result of evalbackcmd */
  5957. int fd; /* file descriptor to read from */
  5958. int nleft; /* number of chars in buffer */
  5959. char *buf; /* buffer */
  5960. struct job *jp; /* job structure for command */
  5961. };
  5962. /* These forward decls are needed to use "eval" code for backticks handling: */
  5963. /* flags in argument to evaltree */
  5964. #define EV_EXIT 01 /* exit after evaluating tree */
  5965. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5966. static int evaltree(union node *, int);
  5967. /* An evaltree() which is known to never return.
  5968. * Used to use an alias:
  5969. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5970. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5971. */
  5972. static ALWAYS_INLINE NORETURN void
  5973. evaltreenr(union node *n, int flags)
  5974. {
  5975. evaltree(n, flags);
  5976. bb_unreachable(abort());
  5977. /* NOTREACHED */
  5978. }
  5979. static void FAST_FUNC
  5980. evalbackcmd(union node *n, struct backcmd *result
  5981. IF_BASH_PROCESS_SUBST(, int ctl))
  5982. {
  5983. int pip[2];
  5984. struct job *jp;
  5985. #if BASH_PROCESS_SUBST
  5986. /* determine end of pipe used by parent (ip) and child (ic) */
  5987. const int ip = (ctl == CTLTOPROC);
  5988. const int ic = !(ctl == CTLTOPROC);
  5989. #else
  5990. const int ctl = CTLBACKQ;
  5991. const int ip = 0;
  5992. const int ic = 1;
  5993. #endif
  5994. result->fd = -1;
  5995. result->buf = NULL;
  5996. result->nleft = 0;
  5997. result->jp = NULL;
  5998. if (n == NULL) {
  5999. goto out;
  6000. }
  6001. if (pipe(pip) < 0)
  6002. ash_msg_and_raise_perror("can't create pipe");
  6003. /* process substitution uses NULL job/node, like openhere() */
  6004. jp = (ctl == CTLBACKQ) ? makejob(/*n,*/ 1) : NULL;
  6005. if (forkshell(jp, (ctl == CTLBACKQ) ? n : NULL, FORK_NOJOB) == 0) {
  6006. /* child */
  6007. FORCE_INT_ON;
  6008. close(pip[ip]);
  6009. /* ic is index of child end of pipe *and* fd to connect it to */
  6010. if (pip[ic] != ic) {
  6011. /*close(ic);*/
  6012. dup2_or_raise(pip[ic], ic);
  6013. close(pip[ic]);
  6014. }
  6015. /* TODO: eflag clearing makes the following not abort:
  6016. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  6017. * which is what bash does (unless it is in POSIX mode).
  6018. * dash deleted "eflag = 0" line in the commit
  6019. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  6020. * [EVAL] Don't clear eflag in evalbackcmd
  6021. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  6022. */
  6023. eflag = 0;
  6024. ifsfree();
  6025. evaltreenr(n, EV_EXIT);
  6026. /* NOTREACHED */
  6027. }
  6028. /* parent */
  6029. #if BASH_PROCESS_SUBST
  6030. if (ctl != CTLBACKQ) {
  6031. int fd = fcntl(pip[ip], F_DUPFD, 64);
  6032. if (fd > 0) {
  6033. close(pip[ip]);
  6034. pip[ip] = fd;
  6035. }
  6036. pushfd(pip[ip]);
  6037. }
  6038. #endif
  6039. close(pip[ic]);
  6040. result->fd = pip[ip];
  6041. result->jp = jp;
  6042. out:
  6043. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  6044. result->fd, result->buf, result->nleft, result->jp));
  6045. }
  6046. /*
  6047. * Expand stuff in backwards quotes.
  6048. */
  6049. static void
  6050. expbackq(union node *cmd, int flag IF_BASH_PROCESS_SUBST(, int ctl))
  6051. {
  6052. #if !BASH_PROCESS_SUBST
  6053. const int ctl = CTLBACKQ;
  6054. #endif
  6055. struct backcmd in;
  6056. int i;
  6057. char buf[128];
  6058. char *p;
  6059. char *dest;
  6060. int startloc;
  6061. struct stackmark smark;
  6062. if (flag & EXP_DISCARD)
  6063. goto out;
  6064. INT_OFF;
  6065. startloc = expdest - (char *)stackblock();
  6066. pushstackmark(&smark, startloc);
  6067. evalbackcmd(cmd, &in IF_BASH_PROCESS_SUBST(, ctl));
  6068. popstackmark(&smark);
  6069. if (ctl != CTLBACKQ) {
  6070. sprintf(buf, DEV_FD_PREFIX"%d", in.fd);
  6071. strtodest(buf, BASESYNTAX);
  6072. goto done;
  6073. }
  6074. p = in.buf;
  6075. i = in.nleft;
  6076. if (i == 0)
  6077. goto read;
  6078. for (;;) {
  6079. memtodest(p, i, flag);
  6080. read:
  6081. if (in.fd < 0)
  6082. break;
  6083. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  6084. TRACE(("expbackq: read returns %d\n", i));
  6085. if (i <= 0)
  6086. break;
  6087. p = buf;
  6088. }
  6089. free(in.buf);
  6090. if (in.fd >= 0) {
  6091. close(in.fd);
  6092. back_exitstatus = waitforjob(in.jp);
  6093. }
  6094. done:
  6095. INT_ON;
  6096. /* Eat all trailing newlines */
  6097. dest = expdest;
  6098. for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';)
  6099. STUNPUTC(dest);
  6100. expdest = dest;
  6101. if (!(flag & EXP_QUOTED))
  6102. recordregion(startloc, dest - (char *)stackblock(), 0);
  6103. TRACE(("evalbackq: size:%d:'%.*s'\n",
  6104. (int)((dest - (char *)stackblock()) - startloc),
  6105. (int)((dest - (char *)stackblock()) - startloc),
  6106. stackblock() + startloc));
  6107. out:
  6108. argbackq = argbackq->next;
  6109. }
  6110. /* expari needs it */
  6111. static char *argstr(char *p, int flag);
  6112. #if ENABLE_FEATURE_SH_MATH
  6113. /*
  6114. * Expand arithmetic expression. Backup to start of expression,
  6115. * evaluate, place result in (backed up) result, adjust string position.
  6116. */
  6117. static char *
  6118. expari(char *start, int flag)
  6119. {
  6120. struct stackmark sm;
  6121. int begoff;
  6122. int endoff;
  6123. int len;
  6124. arith_t result;
  6125. char *p;
  6126. p = stackblock();
  6127. begoff = expdest - p;
  6128. p = argstr(start, flag & EXP_DISCARD);
  6129. if (flag & EXP_DISCARD)
  6130. goto out;
  6131. start = stackblock();
  6132. endoff = expdest - start;
  6133. start += begoff;
  6134. STADJUST(start - expdest, expdest);
  6135. removerecordregions(begoff);
  6136. if (flag & QUOTES_ESC)
  6137. rmescapes(start, 0, NULL);
  6138. pushstackmark(&sm, endoff);
  6139. result = ash_arith(start);
  6140. popstackmark(&sm);
  6141. len = cvtnum(result, flag);
  6142. if (!(flag & EXP_QUOTED))
  6143. recordregion(begoff, begoff + len, 0);
  6144. out:
  6145. return p;
  6146. }
  6147. #endif
  6148. /* argstr needs it */
  6149. static char *evalvar(char *p, int flags);
  6150. /*
  6151. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  6152. * characters to allow for further processing. Otherwise treat
  6153. * $@ like $* since no splitting will be performed.
  6154. */
  6155. static char *
  6156. argstr(char *p, int flag)
  6157. {
  6158. static const char spclchars[] ALIGN1 = {
  6159. '=',
  6160. ':',
  6161. CTLQUOTEMARK,
  6162. CTLENDVAR,
  6163. CTLESC,
  6164. CTLVAR,
  6165. CTLBACKQ,
  6166. #if BASH_PROCESS_SUBST
  6167. CTLTOPROC,
  6168. CTLFROMPROC,
  6169. #endif
  6170. #if ENABLE_FEATURE_SH_MATH
  6171. CTLARI,
  6172. CTLENDARI,
  6173. #endif
  6174. '\0'
  6175. };
  6176. const char *reject = spclchars;
  6177. int breakall = (flag & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6178. int inquotes;
  6179. size_t length;
  6180. int startloc;
  6181. reject += !!(flag & EXP_VARTILDE2);
  6182. reject += flag & EXP_VARTILDE ? 0 : 2;
  6183. inquotes = 0;
  6184. length = 0;
  6185. if (flag & EXP_TILDE) {
  6186. flag &= ~EXP_TILDE;
  6187. tilde:
  6188. if (*p == '~')
  6189. p = exptilde(p, flag);
  6190. }
  6191. start:
  6192. startloc = expdest - (char *)stackblock();
  6193. for (;;) {
  6194. int end;
  6195. unsigned char c;
  6196. length += strcspn(p + length, reject);
  6197. end = 0;
  6198. c = p[length];
  6199. if (!(c & 0x80)
  6200. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6201. || c == CTLENDVAR
  6202. ) {
  6203. /*
  6204. * c == '=' || c == ':' || c == '\0' ||
  6205. * c == CTLENDARI || c == CTLENDVAR
  6206. */
  6207. length++;
  6208. /* c == '\0' || c == CTLENDARI || c == CTLENDVAR */
  6209. end = !!((c - 1) & 0x80);
  6210. }
  6211. if (length > 0 && !(flag & EXP_DISCARD)) {
  6212. int newloc;
  6213. char *q;
  6214. q = stnputs(p, length, expdest);
  6215. q[-1] &= end - 1;
  6216. expdest = q - (flag & EXP_WORD ? end : 0);
  6217. newloc = q - (char *)stackblock() - end;
  6218. if (breakall && !inquotes && newloc > startloc) {
  6219. recordregion(startloc, newloc, 0);
  6220. }
  6221. startloc = newloc;
  6222. }
  6223. p += length + 1;
  6224. length = 0;
  6225. if (end)
  6226. break;
  6227. switch (c) {
  6228. case '=':
  6229. flag |= EXP_VARTILDE2;
  6230. reject++;
  6231. /* fall through */
  6232. case ':':
  6233. /*
  6234. * sort of a hack - expand tildes in variable
  6235. * assignments (after the first '=' and after ':'s).
  6236. */
  6237. if (*--p == '~') {
  6238. goto tilde;
  6239. }
  6240. continue;
  6241. case CTLQUOTEMARK:
  6242. /* "$@" syntax adherence hack */
  6243. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6244. p = evalvar(p + 1, flag | EXP_QUOTED) + 1;
  6245. goto start;
  6246. }
  6247. inquotes ^= EXP_QUOTED;
  6248. addquote:
  6249. if (flag & QUOTES_ESC) {
  6250. p--;
  6251. length++;
  6252. startloc++;
  6253. }
  6254. break;
  6255. case CTLESC:
  6256. startloc++;
  6257. length++;
  6258. goto addquote;
  6259. case CTLVAR:
  6260. TRACE(("argstr: evalvar('%s')\n", p));
  6261. p = evalvar(p, flag | inquotes);
  6262. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6263. goto start;
  6264. #if BASH_PROCESS_SUBST
  6265. case CTLTOPROC:
  6266. case CTLFROMPROC:
  6267. #endif
  6268. case CTLBACKQ:
  6269. expbackq(argbackq->n, flag | inquotes IF_BASH_PROCESS_SUBST(, c));
  6270. goto start;
  6271. #if ENABLE_FEATURE_SH_MATH
  6272. case CTLARI:
  6273. p = expari(p, flag | inquotes);
  6274. goto start;
  6275. #endif
  6276. }
  6277. }
  6278. return p - 1;
  6279. }
  6280. static char *
  6281. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6282. char *pattern, int quotes, int zero)
  6283. {
  6284. char *loc, *loc2;
  6285. char c;
  6286. loc = startp;
  6287. loc2 = rmesc;
  6288. do {
  6289. int match;
  6290. const char *s = loc2;
  6291. c = *loc2;
  6292. if (zero) {
  6293. *loc2 = '\0';
  6294. s = rmesc;
  6295. }
  6296. match = pmatch(pattern, s);
  6297. *loc2 = c;
  6298. if (match)
  6299. return loc;
  6300. if (quotes && (unsigned char)*loc == CTLESC)
  6301. loc++;
  6302. loc++;
  6303. loc2++;
  6304. } while (c);
  6305. return NULL;
  6306. }
  6307. static char *
  6308. scanright(char *startp, char *rmesc, char *rmescend,
  6309. char *pattern, int quotes, int match_at_start)
  6310. {
  6311. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6312. int try2optimize = match_at_start;
  6313. #endif
  6314. int esc = 0;
  6315. char *loc;
  6316. char *loc2;
  6317. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6318. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6319. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6320. * Logic:
  6321. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6322. * and on each iteration they go back two/one char until they reach the beginning.
  6323. * We try to match "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6324. * If one of these matches, return pointer past last matched char in startp.
  6325. */
  6326. /* TODO: document in what other circumstances we are called. */
  6327. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6328. int match;
  6329. char c = *loc2;
  6330. const char *s = loc2;
  6331. if (match_at_start) {
  6332. *loc2 = '\0';
  6333. s = rmesc;
  6334. }
  6335. match = pmatch(pattern, s);
  6336. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6337. *loc2 = c;
  6338. if (match)
  6339. return loc;
  6340. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6341. if (try2optimize) {
  6342. /* Maybe we can optimize this:
  6343. * if pattern ends with unescaped *, we can avoid checking
  6344. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6345. * it won't match truncated "raw_value_of_" strings too.
  6346. */
  6347. unsigned plen = strlen(pattern);
  6348. /* Does it end with "*"? */
  6349. if (plen != 0 && pattern[--plen] == '*') {
  6350. /* "xxxx*" is not escaped */
  6351. /* "xxx\*" is escaped */
  6352. /* "xx\\*" is not escaped */
  6353. /* "x\\\*" is escaped */
  6354. int slashes = 0;
  6355. while (plen != 0 && pattern[--plen] == '\\')
  6356. slashes++;
  6357. if (!(slashes & 1))
  6358. break; /* ends with unescaped "*" */
  6359. }
  6360. try2optimize = 0;
  6361. }
  6362. #endif
  6363. loc--;
  6364. if (quotes) {
  6365. if (--esc < 0) {
  6366. esc = esclen(startp, loc);
  6367. }
  6368. if (esc % 2) {
  6369. esc--;
  6370. loc--;
  6371. }
  6372. }
  6373. }
  6374. return NULL;
  6375. }
  6376. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6377. static void
  6378. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6379. {
  6380. const char *msg;
  6381. const char *tail;
  6382. tail = nullstr;
  6383. msg = "parameter not set";
  6384. if (umsg) {
  6385. if ((unsigned char)*end == CTLENDVAR) {
  6386. if (varflags & VSNUL)
  6387. tail = " or null";
  6388. } else {
  6389. msg = umsg;
  6390. }
  6391. }
  6392. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6393. }
  6394. static char *
  6395. subevalvar(char *start, char *str, int strloc,
  6396. int startloc, int varflags, int flag)
  6397. {
  6398. int subtype = varflags & VSTYPE;
  6399. int quotes = flag & QUOTES_ESC;
  6400. char *startp;
  6401. char *loc;
  6402. char *rmesc, *rmescend;
  6403. long amount;
  6404. int resetloc;
  6405. int argstr_flags;
  6406. IF_BASH_PATTERN_SUBST(int workloc;)
  6407. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6408. IF_BASH_PATTERN_SUBST(char *repl;)
  6409. int zero;
  6410. char *(*scan)(char*, char*, char*, char*, int, int);
  6411. char *p;
  6412. //bb_error_msg("subevalvar(start:'%s',str:'%s',strloc:%d,startloc:%d,varflags:%x,quotes:%d)",
  6413. // start, str, strloc, startloc, varflags, quotes);
  6414. #if BASH_PATTERN_SUBST
  6415. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6416. * argstr() call expands possible variable references in pattern:
  6417. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6418. */
  6419. repl = NULL;
  6420. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6421. /* Find '/' and replace with NUL */
  6422. repl = start;
  6423. /* The pattern can't be empty.
  6424. * IOW: if the first char after "${v//" is a slash,
  6425. * it does not terminate the pattern - it's the first char of the pattern:
  6426. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6427. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6428. */
  6429. if (*repl == '/')
  6430. repl++;
  6431. for (;;) {
  6432. if (*repl == '\0') {
  6433. repl = NULL;
  6434. break;
  6435. }
  6436. if (*repl == '/') {
  6437. *repl = '\0';
  6438. break;
  6439. }
  6440. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6441. if ((unsigned char)*repl == CTLESC && repl[1])
  6442. repl++;
  6443. repl++;
  6444. }
  6445. }
  6446. #endif
  6447. argstr_flags = (flag & EXP_DISCARD) | EXP_TILDE;
  6448. if (!str
  6449. #if BASH_SUBSTR
  6450. && subtype != VSSUBSTR
  6451. #endif
  6452. ) {
  6453. /* EXP_CASE keeps CTLESC's */
  6454. argstr_flags |= EXP_CASE;
  6455. }
  6456. p = argstr(start, argstr_flags);
  6457. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6458. #if BASH_PATTERN_SUBST
  6459. slash_pos = -1;
  6460. if (repl) {
  6461. slash_pos = expdest - ((char *)stackblock() + strloc);
  6462. if (!(flag & EXP_DISCARD))
  6463. STPUTC('/', expdest);
  6464. //bb_error_msg("repl+1:'%s'", repl + 1);
  6465. p = argstr(repl + 1, (flag & EXP_DISCARD) | EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6466. *repl = '/';
  6467. }
  6468. #endif
  6469. if (flag & EXP_DISCARD)
  6470. return p;
  6471. startp = (char *)stackblock() + startloc;
  6472. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6473. switch (subtype) {
  6474. case VSASSIGN:
  6475. setvar0(str, startp);
  6476. loc = startp;
  6477. goto out;
  6478. case VSQUESTION:
  6479. varunset(start, str, startp, varflags);
  6480. /* NOTREACHED */
  6481. #if BASH_SUBSTR
  6482. case VSSUBSTR: {
  6483. int pos, len, orig_len;
  6484. char *colon;
  6485. char *vstr;
  6486. loc = vstr = stackblock() + strloc;
  6487. /* Read POS in ${var:POS:LEN} */
  6488. colon = strchr(loc, ':');
  6489. if (colon) *colon = '\0';
  6490. pos = substr_atoi(loc);
  6491. if (colon) *colon = ':';
  6492. /* Read LEN in ${var:POS:LEN} */
  6493. len = vstr - startp - 1;
  6494. /* *loc != '\0', guaranteed by parser */
  6495. if (quotes) {
  6496. char *ptr;
  6497. /* Adjust the length by the number of escapes */
  6498. for (ptr = startp; ptr < (vstr - 1); ptr++) {
  6499. if ((unsigned char)*ptr == CTLESC) {
  6500. len--;
  6501. ptr++;
  6502. }
  6503. }
  6504. }
  6505. orig_len = len;
  6506. if (*loc++ == ':') {
  6507. /* ${var::LEN} */
  6508. len = substr_atoi(loc);
  6509. } else {
  6510. /* Skip POS in ${var:POS:LEN} */
  6511. len = orig_len;
  6512. while (*loc && *loc != ':')
  6513. loc++;
  6514. if (*loc++ == ':')
  6515. len = substr_atoi(loc);
  6516. }
  6517. if (pos < 0) {
  6518. /* ${VAR:$((-n)):l} starts n chars from the end */
  6519. pos = orig_len + pos;
  6520. }
  6521. if ((unsigned)pos >= orig_len) {
  6522. /* apart from obvious ${VAR:999999:l},
  6523. * covers ${VAR:$((-9999999)):l} - result is ""
  6524. * (bash compat)
  6525. */
  6526. pos = 0;
  6527. len = 0;
  6528. }
  6529. if (len < 0) {
  6530. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6531. len = (orig_len - pos) + len;
  6532. }
  6533. if ((unsigned)len > (orig_len - pos))
  6534. len = orig_len - pos;
  6535. if (!quotes) {
  6536. loc = mempcpy(startp, startp + pos, len);
  6537. } else {
  6538. for (vstr = startp; pos != 0; pos--) {
  6539. if ((unsigned char)*vstr == CTLESC)
  6540. vstr++;
  6541. vstr++;
  6542. }
  6543. for (loc = startp; len != 0; len--) {
  6544. if ((unsigned char)*vstr == CTLESC)
  6545. *loc++ = *vstr++;
  6546. *loc++ = *vstr++;
  6547. }
  6548. }
  6549. *loc = '\0';
  6550. goto out;
  6551. }
  6552. #endif /* BASH_SUBSTR */
  6553. }
  6554. resetloc = expdest - (char *)stackblock();
  6555. #if BASH_PATTERN_SUBST
  6556. repl = NULL;
  6557. /* We'll comeback here if we grow the stack while handling
  6558. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6559. * stack will need rebasing, and we'll need to remove our work
  6560. * areas each time
  6561. */
  6562. restart:
  6563. #endif
  6564. amount = expdest - ((char *)stackblock() + resetloc);
  6565. STADJUST(-amount, expdest);
  6566. startp = (char *)stackblock() + startloc;
  6567. rmesc = startp;
  6568. rmescend = (char *)stackblock() + strloc;
  6569. //bb_error_msg("str7:'%s'", rmescend);
  6570. if (quotes) {
  6571. //TODO: how to handle slash_pos here if string changes (shortens?)
  6572. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6573. if (rmesc != startp) {
  6574. rmescend = expdest;
  6575. startp = (char *)stackblock() + startloc;
  6576. }
  6577. }
  6578. rmescend--;
  6579. str = (char *)stackblock() + strloc;
  6580. /*
  6581. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6582. * The result is a_\_z_c (not a\_\_z_c)!
  6583. *
  6584. * The search pattern and replace string treat backslashes differently!
  6585. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6586. * and string. It's only used on the first call.
  6587. */
  6588. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6589. rmescapes(str, RMESCAPE_GLOB,
  6590. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6591. );
  6592. #if BASH_PATTERN_SUBST
  6593. workloc = expdest - (char *)stackblock();
  6594. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6595. size_t no_meta_len, first_escaped;
  6596. int len;
  6597. char *idx, *end;
  6598. if (!repl) {
  6599. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6600. repl = nullstr;
  6601. if (slash_pos >= 0) {
  6602. repl = str + slash_pos;
  6603. *repl++ = '\0';
  6604. }
  6605. }
  6606. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6607. /* If there's no pattern to match, return the expansion unmolested */
  6608. if (str[0] == '\0')
  6609. goto out1;
  6610. first_escaped = (str[0] == '\\' && str[1]);
  6611. /* "first_escaped" trick allows to treat e.g. "\*no_glob_chars"
  6612. * as literal too (as it is semi-common, and easy to accomodate
  6613. * by just using str + 1).
  6614. */
  6615. no_meta_len = strpbrk(str + first_escaped * 2, "*?[\\") ? 0 : strlen(str);
  6616. len = 0;
  6617. idx = startp;
  6618. end = str - 1;
  6619. while (idx <= end) {
  6620. try_to_match:
  6621. if (no_meta_len == 0) {
  6622. /* pattern has meta chars, have to glob */
  6623. loc = scanright(idx, rmesc, rmescend, str, quotes, /*match_at_start:*/ 1);
  6624. } else {
  6625. /* Testcase for very slow replace (performs about 22k replaces):
  6626. * x=::::::::::::::::::::::
  6627. * x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;echo ${#x}
  6628. * echo "${x//:/|}"
  6629. * To test "first_escaped" logic, replace : with *.
  6630. */
  6631. if (strncmp(rmesc, str + first_escaped, no_meta_len - first_escaped) != 0)
  6632. goto no_match;
  6633. loc = idx;
  6634. if (!quotes) {
  6635. loc += no_meta_len - first_escaped;
  6636. } else {
  6637. size_t n = no_meta_len - first_escaped;
  6638. do {
  6639. if ((unsigned char)*loc == CTLESC)
  6640. loc++;
  6641. loc++;
  6642. } while (--n != 0);
  6643. }
  6644. }
  6645. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6646. if (!loc) {
  6647. char *restart_detect;
  6648. no_match:
  6649. /* No match, advance */
  6650. restart_detect = stackblock();
  6651. skip_matching:
  6652. if (idx >= end)
  6653. break;
  6654. STPUTC(*idx, expdest);
  6655. if (quotes && (unsigned char)*idx == CTLESC) {
  6656. idx++;
  6657. len++;
  6658. STPUTC(*idx, expdest);
  6659. }
  6660. if (stackblock() != restart_detect)
  6661. goto restart;
  6662. idx++;
  6663. len++;
  6664. rmesc++;
  6665. /* continue; - prone to quadratic behavior, smarter code: */
  6666. if (str[0] == '*') {
  6667. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6668. * it would never match "ong_string" etc, no point in trying.
  6669. */
  6670. goto skip_matching;
  6671. }
  6672. goto try_to_match;
  6673. }
  6674. if (subtype == VSREPLACEALL) {
  6675. while (idx < loc) {
  6676. if (quotes && (unsigned char)*idx == CTLESC)
  6677. idx++;
  6678. idx++;
  6679. rmesc++;
  6680. }
  6681. } else {
  6682. idx = loc;
  6683. }
  6684. //bb_error_msg("repl:'%s'", repl);
  6685. for (loc = (char*)repl; *loc; loc++) {
  6686. char *restart_detect = stackblock();
  6687. if (quotes && *loc == '\\') {
  6688. STPUTC(CTLESC, expdest);
  6689. len++;
  6690. }
  6691. STPUTC(*loc, expdest);
  6692. if (stackblock() != restart_detect)
  6693. goto restart;
  6694. len++;
  6695. }
  6696. if (subtype == VSREPLACE) {
  6697. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6698. while (*idx) {
  6699. char *restart_detect = stackblock();
  6700. STPUTC(*idx, expdest);
  6701. if (stackblock() != restart_detect)
  6702. goto restart;
  6703. len++;
  6704. idx++;
  6705. }
  6706. break;
  6707. }
  6708. }
  6709. /* We've put the replaced text into a buffer at workloc, now
  6710. * move it to the right place and adjust the stack.
  6711. */
  6712. STPUTC('\0', expdest);
  6713. startp = (char *)stackblock() + startloc;
  6714. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6715. //bb_error_msg("startp:'%s'", startp);
  6716. loc = startp + len;
  6717. goto out;
  6718. }
  6719. #endif /* BASH_PATTERN_SUBST */
  6720. subtype -= VSTRIMRIGHT;
  6721. #if DEBUG
  6722. if (subtype < 0 || subtype > 7)
  6723. abort();
  6724. #endif
  6725. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6726. zero = subtype >> 1;
  6727. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6728. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6729. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6730. if (loc) {
  6731. if (zero) {
  6732. memmove(startp, loc, str - loc);
  6733. loc = startp + (str - loc) - 1;
  6734. }
  6735. *loc = '\0';
  6736. } else
  6737. loc = str - 1;
  6738. out:
  6739. amount = loc - expdest;
  6740. STADJUST(amount, expdest);
  6741. #if BASH_PATTERN_SUBST
  6742. out1:
  6743. #endif
  6744. /* Remove any recorded regions beyond start of variable */
  6745. removerecordregions(startloc);
  6746. return p;
  6747. }
  6748. /*
  6749. * Add the value of a specialized variable to the stack string.
  6750. * name parameter (examples):
  6751. * ash -c 'echo $1' name:'1='
  6752. * ash -c 'echo $qwe' name:'qwe='
  6753. * ash -c 'echo $$' name:'$='
  6754. * ash -c 'echo ${$}' name:'$='
  6755. * ash -c 'echo ${$##q}' name:'$=q'
  6756. * ash -c 'echo ${#$}' name:'$='
  6757. * note: examples with bad shell syntax:
  6758. * ash -c 'echo ${#$1}' name:'$=1'
  6759. * ash -c 'echo ${#1#}' name:'1=#'
  6760. */
  6761. static NOINLINE ssize_t
  6762. varvalue(char *name, int varflags, int flags, int quoted)
  6763. {
  6764. const char *p;
  6765. int num;
  6766. int i;
  6767. ssize_t len = 0;
  6768. int sep;
  6769. int subtype = varflags & VSTYPE;
  6770. int discard = (subtype == VSPLUS || subtype == VSLENGTH) | (flags & EXP_DISCARD);
  6771. if (!subtype) {
  6772. if (discard)
  6773. return -1;
  6774. raise_error_syntax("bad substitution");
  6775. }
  6776. flags |= EXP_KEEPNUL;
  6777. flags &= discard ? ~QUOTES_ESC : ~0;
  6778. sep = (flags & EXP_FULL) << CHAR_BIT;
  6779. switch (*name) {
  6780. case '$':
  6781. num = rootpid;
  6782. goto numvar;
  6783. case '?':
  6784. num = exitstatus;
  6785. goto numvar;
  6786. case '#':
  6787. num = shellparam.nparam;
  6788. goto numvar;
  6789. case '!':
  6790. num = backgndpid;
  6791. if (num == 0)
  6792. return -1;
  6793. numvar:
  6794. len = cvtnum(num, flags);
  6795. goto check_1char_name;
  6796. case '-':
  6797. expdest = makestrspace(NOPTS, expdest);
  6798. for (i = NOPTS - 1; i >= 0; i--) {
  6799. if (optlist[i] && optletters(i)) {
  6800. USTPUTC(optletters(i), expdest);
  6801. len++;
  6802. }
  6803. }
  6804. check_1char_name:
  6805. #if 0
  6806. /* handles cases similar to ${#$1} */
  6807. if (name[2] != '\0')
  6808. raise_error_syntax("bad substitution");
  6809. #endif
  6810. break;
  6811. case '@':
  6812. if (quoted && sep)
  6813. goto param;
  6814. /* fall through */
  6815. case '*': {
  6816. char **ap;
  6817. char sepc;
  6818. char c;
  6819. /* We will set c to 0 or ~0 depending on whether
  6820. * we're doing field splitting. We won't do field
  6821. * splitting if either we're quoted or sep is zero.
  6822. *
  6823. * Instead of testing (quoted || !sep) the following
  6824. * trick optimises away any branches by using the
  6825. * fact that EXP_QUOTED (which is the only bit that
  6826. * can be set in quoted) is the same as EXP_FULL <<
  6827. * CHAR_BIT (which is the only bit that can be set
  6828. * in sep).
  6829. */
  6830. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6831. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6832. #endif
  6833. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6834. sep &= ~quoted;
  6835. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6836. param:
  6837. sepc = sep;
  6838. ap = shellparam.p;
  6839. if (!ap)
  6840. return -1;
  6841. while ((p = *ap++) != NULL) {
  6842. len += strtodest(p, flags);
  6843. if (*ap && sep) {
  6844. len++;
  6845. memtodest(&sepc, 1, flags);
  6846. }
  6847. }
  6848. break;
  6849. } /* case '*' */
  6850. case '0':
  6851. case '1':
  6852. case '2':
  6853. case '3':
  6854. case '4':
  6855. case '5':
  6856. case '6':
  6857. case '7':
  6858. case '8':
  6859. case '9':
  6860. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6861. if (num < 0 || num > shellparam.nparam)
  6862. return -1;
  6863. p = num ? shellparam.p[num - 1] : arg0;
  6864. goto value;
  6865. default:
  6866. /* NB: name has form "VAR=..." */
  6867. p = lookupvar(name);
  6868. value:
  6869. if (!p)
  6870. return -1;
  6871. len = strtodest(p, flags);
  6872. #if ENABLE_UNICODE_SUPPORT
  6873. if (subtype == VSLENGTH && len > 0) {
  6874. reinit_unicode_for_ash();
  6875. if (unicode_status == UNICODE_ON) {
  6876. STADJUST(-len, expdest);
  6877. discard = 0;
  6878. len = unicode_strlen(p);
  6879. }
  6880. }
  6881. #endif
  6882. break;
  6883. }
  6884. if (discard)
  6885. STADJUST(-len, expdest);
  6886. return len;
  6887. }
  6888. /*
  6889. * Expand a variable, and return a pointer to the next character in the
  6890. * input string.
  6891. */
  6892. static char *
  6893. evalvar(char *p, int flag)
  6894. {
  6895. char varflags;
  6896. char subtype;
  6897. char *var;
  6898. int patloc;
  6899. int startloc;
  6900. ssize_t varlen;
  6901. int discard;
  6902. int quoted;
  6903. varflags = (unsigned char) *p++;
  6904. subtype = varflags & VSTYPE;
  6905. quoted = flag & EXP_QUOTED;
  6906. var = p;
  6907. startloc = expdest - (char *)stackblock();
  6908. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6909. again:
  6910. varlen = varvalue(var, varflags, flag, quoted);
  6911. if (varflags & VSNUL)
  6912. varlen--;
  6913. discard = varlen < 0 ? EXP_DISCARD : 0;
  6914. switch (subtype) {
  6915. case VSPLUS:
  6916. discard ^= EXP_DISCARD;
  6917. /* fall through */
  6918. case 0:
  6919. case VSMINUS:
  6920. p = argstr(p, flag | EXP_TILDE | EXP_WORD | (discard ^ EXP_DISCARD));
  6921. goto record;
  6922. case VSASSIGN:
  6923. case VSQUESTION:
  6924. p = subevalvar(p, var, 0, startloc, varflags,
  6925. (flag & ~QUOTES_ESC) | (discard ^ EXP_DISCARD));
  6926. if ((flag | ~discard) & EXP_DISCARD)
  6927. goto record;
  6928. varflags &= ~VSNUL;
  6929. subtype = VSNORMAL;
  6930. goto again;
  6931. }
  6932. if ((discard & ~flag) && uflag)
  6933. varunset(p, var, 0, 0);
  6934. if (subtype == VSLENGTH) {
  6935. p++;
  6936. if (flag & EXP_DISCARD)
  6937. return p;
  6938. cvtnum(varlen > 0 ? varlen : 0, flag);
  6939. goto really_record;
  6940. }
  6941. if (subtype == VSNORMAL)
  6942. goto record;
  6943. #if DEBUG
  6944. switch (subtype) {
  6945. case VSTRIMLEFT:
  6946. case VSTRIMLEFTMAX:
  6947. case VSTRIMRIGHT:
  6948. case VSTRIMRIGHTMAX:
  6949. #if BASH_SUBSTR
  6950. case VSSUBSTR:
  6951. #endif
  6952. #if BASH_PATTERN_SUBST
  6953. case VSREPLACE:
  6954. case VSREPLACEALL:
  6955. #endif
  6956. break;
  6957. default:
  6958. abort();
  6959. }
  6960. #endif
  6961. flag |= discard;
  6962. if (!(flag & EXP_DISCARD)) {
  6963. /*
  6964. * Terminate the string and start recording the pattern
  6965. * right after it
  6966. */
  6967. STPUTC('\0', expdest);
  6968. }
  6969. patloc = expdest - (char *)stackblock();
  6970. p = subevalvar(p, NULL, patloc, startloc, varflags, flag);
  6971. record:
  6972. if ((flag | discard) & EXP_DISCARD)
  6973. return p;
  6974. really_record:
  6975. if (quoted) {
  6976. quoted = *var == '@' && shellparam.nparam;
  6977. if (!quoted)
  6978. return p;
  6979. }
  6980. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6981. return p;
  6982. }
  6983. /*
  6984. * Add a file name to the list.
  6985. */
  6986. static void
  6987. addfname(const char *name)
  6988. {
  6989. struct strlist *sp;
  6990. sp = stzalloc(sizeof(*sp));
  6991. sp->text = sstrdup(name);
  6992. *exparg.lastp = sp;
  6993. exparg.lastp = &sp->next;
  6994. }
  6995. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6996. static int
  6997. hasmeta(const char *p)
  6998. {
  6999. static const char chars[] ALIGN1 = {
  7000. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  7001. };
  7002. for (;;) {
  7003. p = strpbrk(p, chars);
  7004. if (!p)
  7005. break;
  7006. switch ((unsigned char)*p) {
  7007. case CTLQUOTEMARK:
  7008. for (;;) {
  7009. p++;
  7010. if ((unsigned char)*p == CTLQUOTEMARK)
  7011. break;
  7012. if ((unsigned char)*p == CTLESC)
  7013. p++;
  7014. if (*p == '\0') /* huh? */
  7015. return 0;
  7016. }
  7017. break;
  7018. case '\\':
  7019. case CTLESC:
  7020. p++;
  7021. if (*p == '\0')
  7022. return 0;
  7023. break;
  7024. case '[':
  7025. if (!strchr(p + 1, ']')) {
  7026. /* It's not a properly closed [] pattern,
  7027. * but other metas may follow. Continue checking.
  7028. * my[file* _is_ globbed by bash
  7029. * and matches filenames like "my[file1".
  7030. */
  7031. break;
  7032. }
  7033. /* fallthrough */
  7034. default:
  7035. /* case '*': */
  7036. /* case '?': */
  7037. return 1;
  7038. }
  7039. p++;
  7040. }
  7041. return 0;
  7042. }
  7043. /* If we want to use glob() from libc... */
  7044. #if !ENABLE_ASH_INTERNAL_GLOB
  7045. /* Add the result of glob() to the list */
  7046. static void
  7047. addglob(const glob_t *pglob)
  7048. {
  7049. char **p = pglob->gl_pathv;
  7050. do {
  7051. addfname(*p);
  7052. } while (*++p);
  7053. }
  7054. static void
  7055. expandmeta(struct strlist *str /*, int flag*/)
  7056. {
  7057. /* TODO - EXP_REDIR */
  7058. while (str) {
  7059. char *p;
  7060. glob_t pglob;
  7061. int i;
  7062. if (fflag)
  7063. goto nometa;
  7064. if (!hasmeta(str->text))
  7065. goto nometa;
  7066. INT_OFF;
  7067. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7068. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  7069. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  7070. //
  7071. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  7072. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  7073. // Which means you need to unescape the string, right? Not so fast:
  7074. // if there _is_ a file named "file\?" (with backslash), it is returned
  7075. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  7076. // You DON'T KNOW by looking at the result whether you need to unescape it.
  7077. //
  7078. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  7079. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  7080. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  7081. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  7082. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  7083. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  7084. i = glob(p, 0, NULL, &pglob);
  7085. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  7086. if (p != str->text)
  7087. free(p);
  7088. switch (i) {
  7089. case 0:
  7090. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  7091. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  7092. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  7093. goto nometa2;
  7094. #endif
  7095. addglob(&pglob);
  7096. globfree(&pglob);
  7097. INT_ON;
  7098. break;
  7099. case GLOB_NOMATCH:
  7100. //nometa2:
  7101. globfree(&pglob);
  7102. INT_ON;
  7103. nometa:
  7104. *exparg.lastp = str;
  7105. rmescapes(str->text, 0, NULL);
  7106. exparg.lastp = &str->next;
  7107. break;
  7108. default: /* GLOB_NOSPACE */
  7109. globfree(&pglob);
  7110. INT_ON;
  7111. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  7112. }
  7113. str = str->next;
  7114. }
  7115. }
  7116. #else
  7117. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  7118. /*
  7119. * Do metacharacter (i.e. *, ?, [...]) expansion.
  7120. */
  7121. typedef struct exp_t {
  7122. char *dir;
  7123. unsigned dir_max;
  7124. } exp_t;
  7125. static void
  7126. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  7127. {
  7128. #define expdir exp->dir
  7129. #define expdir_max exp->dir_max
  7130. char *enddir = expdir + expdir_len;
  7131. char *p;
  7132. const char *cp;
  7133. char *start;
  7134. char *endname;
  7135. int metaflag;
  7136. struct stat statb;
  7137. DIR *dirp;
  7138. struct dirent *dp;
  7139. int atend;
  7140. int matchdot;
  7141. int esc;
  7142. metaflag = 0;
  7143. start = name;
  7144. for (p = name; esc = 0, *p; p += esc + 1) {
  7145. if (*p == '*' || *p == '?')
  7146. metaflag = 1;
  7147. else if (*p == '[') {
  7148. char *q = p + 1;
  7149. if (*q == '!')
  7150. q++;
  7151. for (;;) {
  7152. if (*q == '\\')
  7153. q++;
  7154. if (*q == '/' || *q == '\0')
  7155. break;
  7156. if (*++q == ']') {
  7157. metaflag = 1;
  7158. break;
  7159. }
  7160. }
  7161. } else {
  7162. if (*p == '\\' && p[1])
  7163. esc++;
  7164. if (p[esc] == '/') {
  7165. if (metaflag)
  7166. break;
  7167. start = p + esc + 1;
  7168. }
  7169. }
  7170. }
  7171. if (metaflag == 0) { /* we've reached the end of the file name */
  7172. if (!expdir_len)
  7173. return;
  7174. p = name;
  7175. do {
  7176. if (*p == '\\' && p[1])
  7177. p++;
  7178. *enddir++ = *p;
  7179. } while (*p++);
  7180. if (lstat(expdir, &statb) == 0)
  7181. addfname(expdir);
  7182. return;
  7183. }
  7184. endname = p;
  7185. if (name < start) {
  7186. p = name;
  7187. do {
  7188. if (*p == '\\' && p[1])
  7189. p++;
  7190. *enddir++ = *p++;
  7191. } while (p < start);
  7192. }
  7193. *enddir = '\0';
  7194. cp = expdir;
  7195. expdir_len = enddir - cp;
  7196. if (!expdir_len)
  7197. cp = ".";
  7198. dirp = opendir(cp);
  7199. if (dirp == NULL)
  7200. return;
  7201. if (*endname == 0) {
  7202. atend = 1;
  7203. } else {
  7204. atend = 0;
  7205. *endname = '\0';
  7206. endname += esc + 1;
  7207. }
  7208. name_len -= endname - name;
  7209. matchdot = 0;
  7210. p = start;
  7211. if (*p == '\\')
  7212. p++;
  7213. if (*p == '.')
  7214. matchdot++;
  7215. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7216. if (dp->d_name[0] == '.' && !matchdot)
  7217. continue;
  7218. if (pmatch(start, dp->d_name)) {
  7219. if (atend) {
  7220. strcpy(enddir, dp->d_name);
  7221. addfname(expdir);
  7222. } else {
  7223. unsigned offset;
  7224. unsigned len;
  7225. p = stpcpy(enddir, dp->d_name);
  7226. *p = '/';
  7227. offset = p - expdir + 1;
  7228. len = offset + name_len + NAME_MAX;
  7229. if (len > expdir_max) {
  7230. len += PATH_MAX;
  7231. expdir = ckrealloc(expdir, len);
  7232. expdir_max = len;
  7233. }
  7234. expmeta(exp, endname, name_len, offset);
  7235. enddir = expdir + expdir_len;
  7236. }
  7237. }
  7238. }
  7239. closedir(dirp);
  7240. if (!atend)
  7241. endname[-esc - 1] = esc ? '\\' : '/';
  7242. #undef expdir
  7243. #undef expdir_max
  7244. }
  7245. static struct strlist *
  7246. msort(struct strlist *list, int len)
  7247. {
  7248. struct strlist *p, *q = NULL;
  7249. struct strlist **lpp;
  7250. int half;
  7251. int n;
  7252. if (len <= 1)
  7253. return list;
  7254. half = len >> 1;
  7255. p = list;
  7256. for (n = half; --n >= 0;) {
  7257. q = p;
  7258. p = p->next;
  7259. }
  7260. q->next = NULL; /* terminate first half of list */
  7261. q = msort(list, half); /* sort first half of list */
  7262. p = msort(p, len - half); /* sort second half */
  7263. lpp = &list;
  7264. for (;;) {
  7265. #if ENABLE_LOCALE_SUPPORT
  7266. if (strcoll(p->text, q->text) < 0)
  7267. #else
  7268. if (strcmp(p->text, q->text) < 0)
  7269. #endif
  7270. {
  7271. *lpp = p;
  7272. lpp = &p->next;
  7273. p = *lpp;
  7274. if (p == NULL) {
  7275. *lpp = q;
  7276. break;
  7277. }
  7278. } else {
  7279. *lpp = q;
  7280. lpp = &q->next;
  7281. q = *lpp;
  7282. if (q == NULL) {
  7283. *lpp = p;
  7284. break;
  7285. }
  7286. }
  7287. }
  7288. return list;
  7289. }
  7290. /*
  7291. * Sort the results of file name expansion. It calculates the number of
  7292. * strings to sort and then calls msort (short for merge sort) to do the
  7293. * work.
  7294. */
  7295. static struct strlist *
  7296. expsort(struct strlist *str)
  7297. {
  7298. int len;
  7299. struct strlist *sp;
  7300. len = 0;
  7301. for (sp = str; sp; sp = sp->next)
  7302. len++;
  7303. return msort(str, len);
  7304. }
  7305. static void
  7306. expandmeta(struct strlist *str /*, int flag*/)
  7307. {
  7308. /* TODO - EXP_REDIR */
  7309. while (str) {
  7310. exp_t exp;
  7311. struct strlist **savelastp;
  7312. struct strlist *sp;
  7313. char *p;
  7314. unsigned len;
  7315. if (fflag)
  7316. goto nometa;
  7317. if (!hasmeta(str->text))
  7318. goto nometa;
  7319. savelastp = exparg.lastp;
  7320. INT_OFF;
  7321. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7322. len = strlen(p);
  7323. exp.dir_max = len + PATH_MAX;
  7324. exp.dir = ckmalloc(exp.dir_max);
  7325. expmeta(&exp, p, len, 0);
  7326. free(exp.dir);
  7327. if (p != str->text)
  7328. free(p);
  7329. INT_ON;
  7330. if (exparg.lastp == savelastp) {
  7331. /*
  7332. * no matches
  7333. */
  7334. nometa:
  7335. *exparg.lastp = str;
  7336. rmescapes(str->text, 0, NULL);
  7337. exparg.lastp = &str->next;
  7338. } else {
  7339. *exparg.lastp = NULL;
  7340. *savelastp = sp = expsort(*savelastp);
  7341. while (sp->next != NULL)
  7342. sp = sp->next;
  7343. exparg.lastp = &sp->next;
  7344. }
  7345. str = str->next;
  7346. }
  7347. }
  7348. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7349. /*
  7350. * Perform variable substitution and command substitution on an argument,
  7351. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7352. * perform splitting and file name expansion. When arglist is NULL, perform
  7353. * here document expansion.
  7354. */
  7355. static void
  7356. expandarg(union node *arg, struct arglist *arglist, int flag)
  7357. {
  7358. struct strlist *sp;
  7359. char *p;
  7360. argbackq = arg->narg.backquote;
  7361. STARTSTACKSTR(expdest);
  7362. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7363. argstr(arg->narg.text, flag);
  7364. if (arglist == NULL) {
  7365. /* here document expanded */
  7366. goto out;
  7367. }
  7368. p = grabstackstr(expdest);
  7369. TRACE(("expandarg: p:'%s'\n", p));
  7370. exparg.lastp = &exparg.list;
  7371. /*
  7372. * TODO - EXP_REDIR
  7373. */
  7374. if (flag & EXP_FULL) {
  7375. ifsbreakup(p, &exparg);
  7376. *exparg.lastp = NULL;
  7377. exparg.lastp = &exparg.list;
  7378. expandmeta(exparg.list /*, flag*/);
  7379. } else {
  7380. sp = stzalloc(sizeof(*sp));
  7381. sp->text = p;
  7382. *exparg.lastp = sp;
  7383. exparg.lastp = &sp->next;
  7384. }
  7385. *exparg.lastp = NULL;
  7386. if (exparg.list) {
  7387. *arglist->lastp = exparg.list;
  7388. arglist->lastp = exparg.lastp;
  7389. }
  7390. out:
  7391. ifsfree();
  7392. }
  7393. /*
  7394. * Expand shell variables and backquotes inside a here document.
  7395. */
  7396. static void
  7397. expandhere(union node *arg)
  7398. {
  7399. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7400. }
  7401. /*
  7402. * Returns true if the pattern matches the string.
  7403. */
  7404. static int
  7405. patmatch(char *pattern, const char *string)
  7406. {
  7407. char *p = preglob(pattern, 0);
  7408. int r = pmatch(p, string);
  7409. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7410. return r;
  7411. }
  7412. /*
  7413. * See if a pattern matches in a case statement.
  7414. */
  7415. static int
  7416. casematch(union node *pattern, char *val)
  7417. {
  7418. struct stackmark smark;
  7419. int result;
  7420. setstackmark(&smark);
  7421. argbackq = pattern->narg.backquote;
  7422. STARTSTACKSTR(expdest);
  7423. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7424. ifsfree();
  7425. result = patmatch(stackblock(), val);
  7426. popstackmark(&smark);
  7427. return result;
  7428. }
  7429. /* ============ find_command */
  7430. struct builtincmd {
  7431. const char *name;
  7432. int (*builtin)(int, char **) FAST_FUNC;
  7433. /* unsigned flags; */
  7434. };
  7435. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7436. /* "regular" builtins always take precedence over commands,
  7437. * regardless of PATH=....%builtin... position */
  7438. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7439. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7440. struct cmdentry {
  7441. smallint cmdtype; /* CMDxxx */
  7442. union param {
  7443. int index;
  7444. /* index >= 0 for commands without path (slashes) */
  7445. /* (TODO: what exactly does the value mean? PATH position?) */
  7446. /* index == -1 for commands with slashes */
  7447. /* index == (-2 - applet_no) for NOFORK applets */
  7448. const struct builtincmd *cmd;
  7449. struct funcnode *func;
  7450. } u;
  7451. };
  7452. /* values of cmdtype */
  7453. #define CMDUNKNOWN -1 /* no entry in table for command */
  7454. #define CMDNORMAL 0 /* command is an executable program */
  7455. #define CMDFUNCTION 1 /* command is a shell function */
  7456. #define CMDBUILTIN 2 /* command is a shell builtin */
  7457. /* action to find_command() */
  7458. #define DO_ERR 0x01 /* prints errors */
  7459. #define DO_ABS 0x02 /* checks absolute paths */
  7460. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7461. #define DO_ALTPATH 0x08 /* using alternate path */
  7462. #define DO_REGBLTIN 0x10 /* regular built-ins and functions only */
  7463. static void find_command(char *, struct cmdentry *, int, const char *);
  7464. /* ============ Hashing commands */
  7465. /*
  7466. * When commands are first encountered, they are entered in a hash table.
  7467. * This ensures that a full path search will not have to be done for them
  7468. * on each invocation.
  7469. *
  7470. * We should investigate converting to a linear search, even though that
  7471. * would make the command name "hash" a misnomer.
  7472. */
  7473. struct tblentry {
  7474. struct tblentry *next; /* next entry in hash chain */
  7475. union param param; /* definition of builtin function */
  7476. smallint cmdtype; /* CMDxxx */
  7477. char rehash; /* if set, cd done since entry created */
  7478. char cmdname[1]; /* name of command */
  7479. };
  7480. static struct tblentry **cmdtable;
  7481. #define INIT_G_cmdtable() do { \
  7482. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7483. } while (0)
  7484. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7485. static void
  7486. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7487. {
  7488. #if ENABLE_FEATURE_SH_STANDALONE
  7489. if (applet_no >= 0) {
  7490. if (APPLET_IS_NOEXEC(applet_no)) {
  7491. clearenv();
  7492. while (*envp)
  7493. putenv(*envp++);
  7494. popredir(/*drop:*/ 1);
  7495. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7496. }
  7497. /* re-exec ourselves with the new arguments */
  7498. execve(bb_busybox_exec_path, argv, envp);
  7499. /* If they called chroot or otherwise made the binary no longer
  7500. * executable, fall through */
  7501. }
  7502. #endif
  7503. repeat:
  7504. #ifdef SYSV
  7505. do {
  7506. execve(cmd, argv, envp);
  7507. } while (errno == EINTR);
  7508. #else
  7509. execve(cmd, argv, envp);
  7510. #endif
  7511. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7512. /* Run "cmd" as a shell script:
  7513. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7514. * "If the execve() function fails with ENOEXEC, the shell
  7515. * shall execute a command equivalent to having a shell invoked
  7516. * with the command name as its first operand,
  7517. * with any remaining arguments passed to the new shell"
  7518. *
  7519. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7520. * just call ourselves.
  7521. *
  7522. * Note that bash reads ~80 chars of the file, and if it sees
  7523. * a zero byte before it sees newline, it doesn't try to
  7524. * interpret it, but fails with "cannot execute binary file"
  7525. * message and exit code 126. For one, this prevents attempts
  7526. * to interpret foreign ELF binaries as shell scripts.
  7527. */
  7528. argv[0] = (char*) cmd;
  7529. cmd = bb_busybox_exec_path;
  7530. /* NB: this is only possible because all callers of shellexec()
  7531. * ensure that the argv[-1] slot exists!
  7532. */
  7533. argv--;
  7534. argv[0] = (char*) "ash";
  7535. goto repeat;
  7536. }
  7537. }
  7538. /*
  7539. * Exec a program. Never returns. If you change this routine, you may
  7540. * have to change the find_command routine as well.
  7541. * argv[-1] must exist and be writable! See tryexec() for why.
  7542. */
  7543. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7544. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7545. {
  7546. char *cmdname;
  7547. int e;
  7548. char **envp;
  7549. int exerrno;
  7550. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7551. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7552. if (strchr(prog, '/') != NULL
  7553. #if ENABLE_FEATURE_SH_STANDALONE
  7554. || (applet_no = find_applet_by_name(prog)) >= 0
  7555. #endif
  7556. ) {
  7557. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7558. if (applet_no >= 0) {
  7559. /* We tried execing ourself, but it didn't work.
  7560. * Maybe /proc/self/exe doesn't exist?
  7561. * Try $PATH search.
  7562. */
  7563. goto try_PATH;
  7564. }
  7565. e = errno;
  7566. } else {
  7567. try_PATH:
  7568. e = ENOENT;
  7569. while (padvance(&path, argv[0]) >= 0) {
  7570. cmdname = stackblock();
  7571. if (--idx < 0 && pathopt == NULL) {
  7572. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7573. if (errno != ENOENT && errno != ENOTDIR)
  7574. e = errno;
  7575. }
  7576. }
  7577. }
  7578. /* Map to POSIX errors */
  7579. switch (e) {
  7580. default:
  7581. exerrno = 126;
  7582. break;
  7583. case ELOOP:
  7584. case ENAMETOOLONG:
  7585. case ENOENT:
  7586. case ENOTDIR:
  7587. exerrno = 127;
  7588. break;
  7589. }
  7590. exitstatus = exerrno;
  7591. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7592. prog, e, suppress_int));
  7593. ash_msg_and_raise(EXEND, "%s: %s", prog, errmsg(e, "not found"));
  7594. /* NOTREACHED */
  7595. }
  7596. static void
  7597. printentry(struct tblentry *cmdp)
  7598. {
  7599. int idx;
  7600. const char *path;
  7601. char *name;
  7602. idx = cmdp->param.index;
  7603. path = pathval();
  7604. do {
  7605. padvance(&path, cmdp->cmdname);
  7606. } while (--idx >= 0);
  7607. name = stackblock();
  7608. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7609. }
  7610. /*
  7611. * Clear out command entries.
  7612. */
  7613. static void
  7614. clearcmdentry(void)
  7615. {
  7616. struct tblentry **tblp;
  7617. struct tblentry **pp;
  7618. struct tblentry *cmdp;
  7619. INT_OFF;
  7620. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7621. pp = tblp;
  7622. while ((cmdp = *pp) != NULL) {
  7623. if (cmdp->cmdtype == CMDNORMAL
  7624. || (cmdp->cmdtype == CMDBUILTIN
  7625. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7626. && builtinloc > 0
  7627. )
  7628. ) {
  7629. *pp = cmdp->next;
  7630. free(cmdp);
  7631. } else {
  7632. pp = &cmdp->next;
  7633. }
  7634. }
  7635. }
  7636. INT_ON;
  7637. }
  7638. /*
  7639. * Locate a command in the command hash table. If "add" is nonzero,
  7640. * add the command to the table if it is not already present. The
  7641. * variable "lastcmdentry" is set to point to the address of the link
  7642. * pointing to the entry, so that delete_cmd_entry can delete the
  7643. * entry.
  7644. *
  7645. * Interrupts must be off if called with add != 0.
  7646. */
  7647. static struct tblentry **lastcmdentry;
  7648. static struct tblentry *
  7649. cmdlookup(const char *name, int add)
  7650. {
  7651. unsigned int hashval;
  7652. const char *p;
  7653. struct tblentry *cmdp;
  7654. struct tblentry **pp;
  7655. p = name;
  7656. hashval = (unsigned char)*p << 4;
  7657. while (*p)
  7658. hashval += (unsigned char)*p++;
  7659. hashval &= 0x7FFF;
  7660. pp = &cmdtable[hashval % CMDTABLESIZE];
  7661. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7662. if (strcmp(cmdp->cmdname, name) == 0)
  7663. break;
  7664. pp = &cmdp->next;
  7665. }
  7666. if (add && cmdp == NULL) {
  7667. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7668. + strlen(name)
  7669. /* + 1 - already done because
  7670. * tblentry::cmdname is char[1] */);
  7671. /*cmdp->next = NULL; - ckzalloc did it */
  7672. cmdp->cmdtype = CMDUNKNOWN;
  7673. strcpy(cmdp->cmdname, name);
  7674. }
  7675. lastcmdentry = pp;
  7676. return cmdp;
  7677. }
  7678. /*
  7679. * Delete the command entry returned on the last lookup.
  7680. */
  7681. static void
  7682. delete_cmd_entry(void)
  7683. {
  7684. struct tblentry *cmdp;
  7685. INT_OFF;
  7686. cmdp = *lastcmdentry;
  7687. *lastcmdentry = cmdp->next;
  7688. if (cmdp->cmdtype == CMDFUNCTION)
  7689. freefunc(cmdp->param.func);
  7690. free(cmdp);
  7691. INT_ON;
  7692. }
  7693. /*
  7694. * Add a new command entry, replacing any existing command entry for
  7695. * the same name - except special builtins.
  7696. */
  7697. static void
  7698. addcmdentry(char *name, struct cmdentry *entry)
  7699. {
  7700. struct tblentry *cmdp;
  7701. cmdp = cmdlookup(name, 1);
  7702. if (cmdp->cmdtype == CMDFUNCTION) {
  7703. freefunc(cmdp->param.func);
  7704. }
  7705. cmdp->cmdtype = entry->cmdtype;
  7706. cmdp->param = entry->u;
  7707. cmdp->rehash = 0;
  7708. }
  7709. static int FAST_FUNC
  7710. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7711. {
  7712. struct tblentry **pp;
  7713. struct tblentry *cmdp;
  7714. int c;
  7715. struct cmdentry entry;
  7716. char *name;
  7717. if (nextopt("r") != '\0') {
  7718. clearcmdentry();
  7719. return 0;
  7720. }
  7721. if (*argptr == NULL) {
  7722. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7723. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7724. if (cmdp->cmdtype == CMDNORMAL)
  7725. printentry(cmdp);
  7726. }
  7727. }
  7728. return 0;
  7729. }
  7730. c = 0;
  7731. while ((name = *argptr) != NULL) {
  7732. cmdp = cmdlookup(name, 0);
  7733. if (cmdp != NULL
  7734. && (cmdp->cmdtype == CMDNORMAL
  7735. || (cmdp->cmdtype == CMDBUILTIN
  7736. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7737. && builtinloc > 0
  7738. )
  7739. )
  7740. ) {
  7741. delete_cmd_entry();
  7742. }
  7743. find_command(name, &entry, DO_ERR, pathval());
  7744. if (entry.cmdtype == CMDUNKNOWN)
  7745. c = 1;
  7746. argptr++;
  7747. }
  7748. return c;
  7749. }
  7750. /*
  7751. * Called when a cd is done. Marks all commands so the next time they
  7752. * are executed they will be rehashed.
  7753. */
  7754. static void
  7755. hashcd(void)
  7756. {
  7757. struct tblentry **pp;
  7758. struct tblentry *cmdp;
  7759. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7760. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7761. if (cmdp->cmdtype == CMDNORMAL
  7762. || (cmdp->cmdtype == CMDBUILTIN
  7763. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7764. && builtinloc > 0)
  7765. ) {
  7766. cmdp->rehash = 1;
  7767. }
  7768. }
  7769. }
  7770. }
  7771. /*
  7772. * Fix command hash table when PATH changed.
  7773. * Called before PATH is changed. The argument is the new value of PATH;
  7774. * pathval() still returns the old value at this point.
  7775. * Called with interrupts off.
  7776. */
  7777. static void FAST_FUNC
  7778. changepath(const char *newval)
  7779. {
  7780. const char *new;
  7781. int idx;
  7782. int bltin;
  7783. new = newval;
  7784. idx = 0;
  7785. bltin = -1;
  7786. for (;;) {
  7787. if (*new == '%' && prefix(new + 1, "builtin")) {
  7788. bltin = idx;
  7789. break;
  7790. }
  7791. new = strchr(new, ':');
  7792. if (!new)
  7793. break;
  7794. idx++;
  7795. new++;
  7796. }
  7797. builtinloc = bltin;
  7798. clearcmdentry();
  7799. }
  7800. enum {
  7801. TEOF,
  7802. TNL,
  7803. TREDIR,
  7804. TWORD,
  7805. TSEMI,
  7806. TBACKGND,
  7807. TAND,
  7808. TOR,
  7809. TPIPE,
  7810. TLP,
  7811. TRP,
  7812. TENDCASE,
  7813. TENDBQUOTE,
  7814. TNOT,
  7815. TCASE,
  7816. TDO,
  7817. TDONE,
  7818. TELIF,
  7819. TELSE,
  7820. TESAC,
  7821. TFI,
  7822. TFOR,
  7823. #if BASH_FUNCTION
  7824. TFUNCTION,
  7825. #endif
  7826. TIF,
  7827. TIN,
  7828. TTHEN,
  7829. TUNTIL,
  7830. TWHILE,
  7831. TBEGIN,
  7832. TEND
  7833. };
  7834. typedef smallint token_id_t;
  7835. /* Nth bit indicates if token marks the end of a list */
  7836. enum {
  7837. tokendlist = 0
  7838. /* 0 */ | (1u << TEOF)
  7839. /* 1 */ | (0u << TNL)
  7840. /* 2 */ | (0u << TREDIR)
  7841. /* 3 */ | (0u << TWORD)
  7842. /* 4 */ | (0u << TSEMI)
  7843. /* 5 */ | (0u << TBACKGND)
  7844. /* 6 */ | (0u << TAND)
  7845. /* 7 */ | (0u << TOR)
  7846. /* 8 */ | (0u << TPIPE)
  7847. /* 9 */ | (0u << TLP)
  7848. /* 10 */ | (1u << TRP)
  7849. /* 11 */ | (1u << TENDCASE)
  7850. /* 12 */ | (1u << TENDBQUOTE)
  7851. /* 13 */ | (0u << TNOT)
  7852. /* 14 */ | (0u << TCASE)
  7853. /* 15 */ | (1u << TDO)
  7854. /* 16 */ | (1u << TDONE)
  7855. /* 17 */ | (1u << TELIF)
  7856. /* 18 */ | (1u << TELSE)
  7857. /* 19 */ | (1u << TESAC)
  7858. /* 20 */ | (1u << TFI)
  7859. /* 21 */ | (0u << TFOR)
  7860. #if BASH_FUNCTION
  7861. /* 22 */ | (0u << TFUNCTION)
  7862. #endif
  7863. /* 23 */ | (0u << TIF)
  7864. /* 24 */ | (0u << TIN)
  7865. /* 25 */ | (1u << TTHEN)
  7866. /* 26 */ | (0u << TUNTIL)
  7867. /* 27 */ | (0u << TWHILE)
  7868. /* 28 */ | (0u << TBEGIN)
  7869. /* 29 */ | (1u << TEND)
  7870. , /* thus far 29 bits used */
  7871. };
  7872. static const char *const tokname_array[] ALIGN_PTR = {
  7873. "end of file",
  7874. "newline",
  7875. "redirection",
  7876. "word",
  7877. ";",
  7878. "&",
  7879. "&&",
  7880. "||",
  7881. "|",
  7882. "(",
  7883. ")",
  7884. ";;",
  7885. "`",
  7886. #define KWDOFFSET 13
  7887. /* the following are keywords */
  7888. "!",
  7889. "case",
  7890. "do",
  7891. "done",
  7892. "elif",
  7893. "else",
  7894. "esac",
  7895. "fi",
  7896. "for",
  7897. #if BASH_FUNCTION
  7898. "function",
  7899. #endif
  7900. "if",
  7901. "in",
  7902. "then",
  7903. "until",
  7904. "while",
  7905. "{",
  7906. "}",
  7907. };
  7908. /* Wrapper around strcmp for qsort/bsearch/... */
  7909. static int
  7910. pstrcmp(const void *a, const void *b)
  7911. {
  7912. return strcmp((char*)a, *(char**)b);
  7913. }
  7914. static const char *const *
  7915. findkwd(const char *s)
  7916. {
  7917. return bsearch(s, tokname_array + KWDOFFSET,
  7918. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7919. sizeof(tokname_array[0]), pstrcmp);
  7920. }
  7921. /*
  7922. * Locate and print what a word is...
  7923. */
  7924. static int
  7925. describe_command(char *command, const char *path, int describe_command_verbose)
  7926. {
  7927. struct cmdentry entry;
  7928. #if ENABLE_ASH_ALIAS
  7929. const struct alias *ap;
  7930. #endif
  7931. path = path ? path : pathval();
  7932. if (describe_command_verbose) {
  7933. out1str(command);
  7934. }
  7935. /* First look at the keywords */
  7936. if (findkwd(command)) {
  7937. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7938. goto out;
  7939. }
  7940. #if ENABLE_ASH_ALIAS
  7941. /* Then look at the aliases */
  7942. ap = lookupalias(command, 0);
  7943. if (ap != NULL) {
  7944. if (!describe_command_verbose) {
  7945. out1str("alias ");
  7946. printalias(ap);
  7947. return 0;
  7948. }
  7949. out1fmt(" is an alias for %s", ap->val);
  7950. goto out;
  7951. }
  7952. #endif
  7953. /* Brute force */
  7954. find_command(command, &entry, DO_ABS, path);
  7955. switch (entry.cmdtype) {
  7956. case CMDNORMAL: {
  7957. int j = entry.u.index;
  7958. char *p;
  7959. if (j < 0) {
  7960. p = command;
  7961. } else {
  7962. do {
  7963. padvance(&path, command);
  7964. } while (--j >= 0);
  7965. p = stackblock();
  7966. }
  7967. if (describe_command_verbose) {
  7968. out1fmt(" is %s", p);
  7969. } else {
  7970. out1str(p);
  7971. }
  7972. break;
  7973. }
  7974. case CMDFUNCTION:
  7975. if (describe_command_verbose) {
  7976. /*out1str(" is a shell function");*/
  7977. out1str(" is a function"); /* bash says this */
  7978. } else {
  7979. out1str(command);
  7980. }
  7981. break;
  7982. case CMDBUILTIN:
  7983. if (describe_command_verbose) {
  7984. out1fmt(" is a %sshell builtin",
  7985. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7986. "special " : nullstr
  7987. );
  7988. } else {
  7989. out1str(command);
  7990. }
  7991. break;
  7992. default:
  7993. if (describe_command_verbose) {
  7994. out1str(": not found\n");
  7995. }
  7996. return 127;
  7997. }
  7998. out:
  7999. out1str("\n");
  8000. return 0;
  8001. }
  8002. static int FAST_FUNC
  8003. typecmd(int argc UNUSED_PARAM, char **argv)
  8004. {
  8005. int i = 1;
  8006. int err = 0;
  8007. int verbose = 1;
  8008. /* type -p ... ? (we don't bother checking for 'p') */
  8009. if (argv[1] && argv[1][0] == '-') {
  8010. i++;
  8011. verbose = 0;
  8012. }
  8013. while (argv[i]) {
  8014. err |= describe_command(argv[i++], NULL, verbose);
  8015. }
  8016. return err;
  8017. }
  8018. static struct strlist *
  8019. fill_arglist(struct arglist *arglist, union node **argpp)
  8020. {
  8021. struct strlist **lastp = arglist->lastp;
  8022. union node *argp;
  8023. while ((argp = *argpp) != NULL) {
  8024. expandarg(argp, arglist, EXP_FULL | EXP_TILDE);
  8025. *argpp = argp->narg.next;
  8026. if (*lastp)
  8027. break;
  8028. }
  8029. return *lastp;
  8030. }
  8031. #if ENABLE_ASH_CMDCMD
  8032. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  8033. static int
  8034. parse_command_args(struct arglist *arglist, union node **argpp, const char **path)
  8035. {
  8036. struct strlist *sp = arglist->list;
  8037. char *cp, c;
  8038. for (;;) {
  8039. sp = sp->next ? sp->next : fill_arglist(arglist, argpp);
  8040. if (!sp)
  8041. return 0;
  8042. cp = sp->text;
  8043. if (*cp++ != '-')
  8044. break;
  8045. c = *cp++;
  8046. if (!c)
  8047. break;
  8048. if (c == '-' && !*cp) {
  8049. if (!sp->next && !fill_arglist(arglist, argpp))
  8050. return 0;
  8051. sp = sp->next;
  8052. break;
  8053. }
  8054. do {
  8055. switch (c) {
  8056. case 'p':
  8057. *path = bb_default_path;
  8058. break;
  8059. default:
  8060. /* run 'typecmd' for other options */
  8061. return 0;
  8062. }
  8063. c = *cp++;
  8064. } while (c);
  8065. }
  8066. arglist->list = sp;
  8067. return DO_NOFUNC;
  8068. }
  8069. static int FAST_FUNC
  8070. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8071. {
  8072. char *cmd;
  8073. int c;
  8074. enum {
  8075. VERIFY_BRIEF = 1,
  8076. VERIFY_VERBOSE = 2,
  8077. } verify = 0;
  8078. const char *path = NULL;
  8079. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  8080. * never reaches this function.
  8081. */
  8082. while ((c = nextopt("pvV")) != '\0')
  8083. if (c == 'V')
  8084. verify |= VERIFY_VERBOSE;
  8085. else if (c == 'v')
  8086. /*verify |= VERIFY_BRIEF*/;
  8087. #if DEBUG
  8088. else if (c != 'p')
  8089. abort();
  8090. #endif
  8091. else
  8092. path = bb_default_path;
  8093. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  8094. cmd = *argptr;
  8095. if (/*verify && */ cmd)
  8096. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  8097. return 0;
  8098. }
  8099. #endif
  8100. /*static int funcblocksize; // size of structures in function */
  8101. /*static int funcstringsize; // size of strings in node */
  8102. static void *funcblock; /* block to allocate function from */
  8103. static char *funcstring_end; /* end of block to allocate strings from */
  8104. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  8105. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  8106. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  8107. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  8108. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  8109. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  8110. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8111. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8112. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8113. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  8114. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8115. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8116. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  8117. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  8118. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  8119. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  8120. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  8121. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8122. #if BASH_REDIR_OUTPUT
  8123. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  8124. #endif
  8125. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  8126. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  8127. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8128. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  8129. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8130. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8131. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8132. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8133. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  8134. };
  8135. static int calcsize(int funcblocksize, union node *n);
  8136. static int
  8137. sizenodelist(int funcblocksize, struct nodelist *lp)
  8138. {
  8139. while (lp) {
  8140. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  8141. funcblocksize = calcsize(funcblocksize, lp->n);
  8142. lp = lp->next;
  8143. }
  8144. return funcblocksize;
  8145. }
  8146. static int
  8147. calcsize(int funcblocksize, union node *n)
  8148. {
  8149. if (n == NULL)
  8150. return funcblocksize;
  8151. funcblocksize += nodesize[n->type];
  8152. switch (n->type) {
  8153. case NCMD:
  8154. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  8155. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  8156. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  8157. break;
  8158. case NPIPE:
  8159. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  8160. break;
  8161. case NREDIR:
  8162. case NBACKGND:
  8163. case NSUBSHELL:
  8164. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  8165. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  8166. break;
  8167. case NAND:
  8168. case NOR:
  8169. case NSEMI:
  8170. case NWHILE:
  8171. case NUNTIL:
  8172. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  8173. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  8174. break;
  8175. case NIF:
  8176. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  8177. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  8178. funcblocksize = calcsize(funcblocksize, n->nif.test);
  8179. break;
  8180. case NFOR:
  8181. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  8182. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  8183. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  8184. break;
  8185. case NCASE:
  8186. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  8187. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  8188. break;
  8189. case NCLIST:
  8190. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  8191. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  8192. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  8193. break;
  8194. case NDEFUN:
  8195. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8196. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8197. break;
  8198. case NARG:
  8199. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8200. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8201. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8202. break;
  8203. case NTO:
  8204. #if BASH_REDIR_OUTPUT
  8205. case NTO2:
  8206. #endif
  8207. case NCLOBBER:
  8208. case NFROM:
  8209. case NFROMTO:
  8210. case NAPPEND:
  8211. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8212. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8213. break;
  8214. case NTOFD:
  8215. case NFROMFD:
  8216. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8217. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8218. break;
  8219. case NHERE:
  8220. case NXHERE:
  8221. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8222. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8223. break;
  8224. case NNOT:
  8225. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8226. break;
  8227. };
  8228. return funcblocksize;
  8229. }
  8230. static char *
  8231. nodeckstrdup(char *s)
  8232. {
  8233. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8234. return strcpy(funcstring_end, s);
  8235. }
  8236. static union node *copynode(union node *);
  8237. static struct nodelist *
  8238. copynodelist(struct nodelist *lp)
  8239. {
  8240. struct nodelist *start;
  8241. struct nodelist **lpp;
  8242. lpp = &start;
  8243. while (lp) {
  8244. *lpp = funcblock;
  8245. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8246. (*lpp)->n = copynode(lp->n);
  8247. lp = lp->next;
  8248. lpp = &(*lpp)->next;
  8249. }
  8250. *lpp = NULL;
  8251. return start;
  8252. }
  8253. static union node *
  8254. copynode(union node *n)
  8255. {
  8256. union node *new;
  8257. if (n == NULL)
  8258. return NULL;
  8259. new = funcblock;
  8260. funcblock = (char *) funcblock + nodesize[n->type];
  8261. switch (n->type) {
  8262. case NCMD:
  8263. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8264. new->ncmd.args = copynode(n->ncmd.args);
  8265. new->ncmd.assign = copynode(n->ncmd.assign);
  8266. new->ncmd.linno = n->ncmd.linno;
  8267. break;
  8268. case NPIPE:
  8269. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8270. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8271. break;
  8272. case NREDIR:
  8273. case NBACKGND:
  8274. case NSUBSHELL:
  8275. new->nredir.redirect = copynode(n->nredir.redirect);
  8276. new->nredir.n = copynode(n->nredir.n);
  8277. new->nredir.linno = n->nredir.linno;
  8278. break;
  8279. case NAND:
  8280. case NOR:
  8281. case NSEMI:
  8282. case NWHILE:
  8283. case NUNTIL:
  8284. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8285. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8286. break;
  8287. case NIF:
  8288. new->nif.elsepart = copynode(n->nif.elsepart);
  8289. new->nif.ifpart = copynode(n->nif.ifpart);
  8290. new->nif.test = copynode(n->nif.test);
  8291. break;
  8292. case NFOR:
  8293. new->nfor.var = nodeckstrdup(n->nfor.var);
  8294. new->nfor.body = copynode(n->nfor.body);
  8295. new->nfor.args = copynode(n->nfor.args);
  8296. new->nfor.linno = n->nfor.linno;
  8297. break;
  8298. case NCASE:
  8299. new->ncase.cases = copynode(n->ncase.cases);
  8300. new->ncase.expr = copynode(n->ncase.expr);
  8301. new->ncase.linno = n->ncase.linno;
  8302. break;
  8303. case NCLIST:
  8304. new->nclist.body = copynode(n->nclist.body);
  8305. new->nclist.pattern = copynode(n->nclist.pattern);
  8306. new->nclist.next = copynode(n->nclist.next);
  8307. break;
  8308. case NDEFUN:
  8309. new->ndefun.body = copynode(n->ndefun.body);
  8310. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8311. new->ndefun.linno = n->ndefun.linno;
  8312. break;
  8313. case NARG:
  8314. new->narg.backquote = copynodelist(n->narg.backquote);
  8315. new->narg.text = nodeckstrdup(n->narg.text);
  8316. new->narg.next = copynode(n->narg.next);
  8317. break;
  8318. case NTO:
  8319. #if BASH_REDIR_OUTPUT
  8320. case NTO2:
  8321. #endif
  8322. case NCLOBBER:
  8323. case NFROM:
  8324. case NFROMTO:
  8325. case NAPPEND:
  8326. new->nfile.fname = copynode(n->nfile.fname);
  8327. new->nfile.fd = n->nfile.fd;
  8328. new->nfile.next = copynode(n->nfile.next);
  8329. break;
  8330. case NTOFD:
  8331. case NFROMFD:
  8332. new->ndup.vname = copynode(n->ndup.vname);
  8333. new->ndup.dupfd = n->ndup.dupfd;
  8334. new->ndup.fd = n->ndup.fd;
  8335. new->ndup.next = copynode(n->ndup.next);
  8336. break;
  8337. case NHERE:
  8338. case NXHERE:
  8339. new->nhere.doc = copynode(n->nhere.doc);
  8340. new->nhere.fd = n->nhere.fd;
  8341. new->nhere.next = copynode(n->nhere.next);
  8342. break;
  8343. case NNOT:
  8344. new->nnot.com = copynode(n->nnot.com);
  8345. break;
  8346. };
  8347. new->type = n->type;
  8348. return new;
  8349. }
  8350. /*
  8351. * Make a copy of a parse tree.
  8352. */
  8353. static struct funcnode *
  8354. copyfunc(union node *n)
  8355. {
  8356. struct funcnode *f;
  8357. size_t blocksize;
  8358. /*funcstringsize = 0;*/
  8359. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8360. f = ckzalloc(blocksize /* + funcstringsize */);
  8361. funcblock = (char *) f + offsetof(struct funcnode, n);
  8362. funcstring_end = (char *) f + blocksize;
  8363. copynode(n);
  8364. /* f->count = 0; - ckzalloc did it */
  8365. return f;
  8366. }
  8367. /*
  8368. * Define a shell function.
  8369. */
  8370. static void
  8371. defun(union node *func)
  8372. {
  8373. struct cmdentry entry;
  8374. INT_OFF;
  8375. entry.cmdtype = CMDFUNCTION;
  8376. entry.u.func = copyfunc(func);
  8377. addcmdentry(func->ndefun.text, &entry);
  8378. INT_ON;
  8379. }
  8380. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8381. #define SKIPBREAK (1 << 0)
  8382. #define SKIPCONT (1 << 1)
  8383. #define SKIPFUNC (1 << 2)
  8384. #define SKIPFUNCDEF (1 << 3)
  8385. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8386. static int skipcount; /* number of levels to skip */
  8387. static int loopnest; /* current loop nesting level */
  8388. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8389. /* Forward decl way out to parsing code - dotrap needs it */
  8390. static int evalstring(char *s, int flags);
  8391. /* Called to execute a trap.
  8392. * Single callsite - at the end of evaltree().
  8393. * If we return non-zero, evaltree raises EXEXIT exception.
  8394. *
  8395. * Perhaps we should avoid entering new trap handlers
  8396. * while we are executing a trap handler. [is it a TODO?]
  8397. */
  8398. static void
  8399. dotrap(void)
  8400. {
  8401. uint8_t *g;
  8402. int sig;
  8403. int status, last_status;
  8404. if (!pending_sig)
  8405. return;
  8406. status = savestatus;
  8407. last_status = status;
  8408. if (status < 0) {
  8409. status = exitstatus;
  8410. savestatus = status;
  8411. }
  8412. pending_sig = 0;
  8413. barrier();
  8414. TRACE(("dotrap entered\n"));
  8415. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8416. char *p;
  8417. if (!*g)
  8418. continue;
  8419. if (evalskip) {
  8420. pending_sig = sig;
  8421. break;
  8422. }
  8423. p = trap[sig];
  8424. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8425. * don't upset it by resetting gotsig[SIGINT-1] */
  8426. if (sig == SIGINT && !p)
  8427. continue;
  8428. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8429. *g = 0;
  8430. if (!p)
  8431. continue;
  8432. trap_depth++;
  8433. evalstring(p, 0);
  8434. trap_depth--;
  8435. if (evalskip != SKIPFUNC)
  8436. exitstatus = status;
  8437. }
  8438. savestatus = last_status;
  8439. TRACE(("dotrap returns\n"));
  8440. }
  8441. /* forward declarations - evaluation is fairly recursive business... */
  8442. static int evalloop(union node *, int);
  8443. static int evalfor(union node *, int);
  8444. static int evalcase(union node *, int);
  8445. static int evalsubshell(union node *, int);
  8446. static void expredir(union node *);
  8447. static int evalpipe(union node *, int);
  8448. static int evalcommand(union node *, int);
  8449. static int evalbltin(const struct builtincmd *, int, char **, int);
  8450. static void prehash(union node *);
  8451. /*
  8452. * Evaluate a parse tree. The value is left in the global variable
  8453. * exitstatus.
  8454. */
  8455. static int
  8456. evaltree(union node *n, int flags)
  8457. {
  8458. int checkexit = 0;
  8459. int (*evalfn)(union node *, int);
  8460. struct stackmark smark;
  8461. int status = 0;
  8462. setstackmark(&smark);
  8463. if (nflag)
  8464. goto out;
  8465. if (n == NULL) {
  8466. TRACE(("evaltree(NULL) called\n"));
  8467. goto out;
  8468. }
  8469. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8470. dotrap();
  8471. switch (n->type) {
  8472. default:
  8473. #if DEBUG
  8474. out1fmt("Node type = %d\n", n->type);
  8475. fflush_all();
  8476. break;
  8477. #endif
  8478. case NNOT:
  8479. status = !evaltree(n->nnot.com, EV_TESTED);
  8480. goto setstatus;
  8481. case NREDIR:
  8482. errlinno = lineno = n->nredir.linno;
  8483. expredir(n->nredir.redirect);
  8484. pushredir(n->nredir.redirect);
  8485. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8486. if (!status) {
  8487. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8488. }
  8489. if (n->nredir.redirect)
  8490. popredir(/*drop:*/ 0);
  8491. goto setstatus;
  8492. case NCMD:
  8493. evalfn = evalcommand;
  8494. checkexit:
  8495. checkexit = ~flags & EV_TESTED;
  8496. goto calleval;
  8497. case NFOR:
  8498. evalfn = evalfor;
  8499. goto calleval;
  8500. case NWHILE:
  8501. case NUNTIL:
  8502. evalfn = evalloop;
  8503. goto calleval;
  8504. case NSUBSHELL:
  8505. case NBACKGND:
  8506. evalfn = evalsubshell;
  8507. goto checkexit;
  8508. case NPIPE:
  8509. evalfn = evalpipe;
  8510. goto checkexit;
  8511. case NCASE:
  8512. evalfn = evalcase;
  8513. goto calleval;
  8514. case NAND:
  8515. case NOR:
  8516. case NSEMI: {
  8517. #if NAND + 1 != NOR
  8518. #error NAND + 1 != NOR
  8519. #endif
  8520. #if NOR + 1 != NSEMI
  8521. #error NOR + 1 != NSEMI
  8522. #endif
  8523. unsigned is_or = n->type - NAND;
  8524. status = evaltree(
  8525. n->nbinary.ch1,
  8526. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8527. );
  8528. if ((!status) == is_or || evalskip)
  8529. break;
  8530. n = n->nbinary.ch2;
  8531. evaln:
  8532. evalfn = evaltree;
  8533. calleval:
  8534. status = evalfn(n, flags);
  8535. goto setstatus;
  8536. }
  8537. case NIF:
  8538. status = evaltree(n->nif.test, EV_TESTED);
  8539. if (evalskip)
  8540. break;
  8541. if (!status) {
  8542. n = n->nif.ifpart;
  8543. goto evaln;
  8544. } else if (n->nif.elsepart) {
  8545. n = n->nif.elsepart;
  8546. goto evaln;
  8547. }
  8548. status = 0;
  8549. goto setstatus;
  8550. case NDEFUN:
  8551. defun(n);
  8552. /* Not necessary. To test it:
  8553. * "false; f() { qwerty; }; echo $?" should print 0.
  8554. */
  8555. /* status = 0; */
  8556. setstatus:
  8557. exitstatus = status;
  8558. break;
  8559. }
  8560. out:
  8561. /* Order of checks below is important:
  8562. * signal handlers trigger before exit caused by "set -e".
  8563. */
  8564. dotrap();
  8565. if (checkexit && status) {
  8566. if (trap[NTRAP_ERR] && !in_trap_ERR) {
  8567. int err;
  8568. struct jmploc *volatile savehandler = exception_handler;
  8569. struct jmploc jmploc;
  8570. in_trap_ERR = 1;
  8571. trap_depth++;
  8572. err = setjmp(jmploc.loc);
  8573. if (!err) {
  8574. exception_handler = &jmploc;
  8575. savestatus = exitstatus;
  8576. evalstring(trap[NTRAP_ERR], 0);
  8577. }
  8578. trap_depth--;
  8579. in_trap_ERR = 0;
  8580. exception_handler = savehandler;
  8581. if (err && exception_type != EXERROR)
  8582. longjmp(exception_handler->loc, 1);
  8583. exitstatus = savestatus;
  8584. }
  8585. if (eflag)
  8586. goto exexit;
  8587. }
  8588. if (flags & EV_EXIT) {
  8589. exexit:
  8590. raise_exception(EXEND);
  8591. }
  8592. popstackmark(&smark);
  8593. TRACE(("leaving evaltree (no interrupts)\n"));
  8594. return exitstatus;
  8595. }
  8596. static int
  8597. skiploop(void)
  8598. {
  8599. int skip = evalskip;
  8600. switch (skip) {
  8601. case 0:
  8602. break;
  8603. case SKIPBREAK:
  8604. case SKIPCONT:
  8605. if (--skipcount <= 0) {
  8606. evalskip = 0;
  8607. break;
  8608. }
  8609. skip = SKIPBREAK;
  8610. break;
  8611. }
  8612. return skip;
  8613. }
  8614. static int
  8615. evalloop(union node *n, int flags)
  8616. {
  8617. int skip;
  8618. int status;
  8619. loopnest++;
  8620. status = 0;
  8621. flags &= EV_TESTED;
  8622. do {
  8623. int i;
  8624. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8625. skip = skiploop();
  8626. if (skip == SKIPFUNC)
  8627. status = i;
  8628. if (skip)
  8629. continue;
  8630. if (n->type != NWHILE)
  8631. i = !i;
  8632. if (i != 0)
  8633. break;
  8634. status = evaltree(n->nbinary.ch2, flags);
  8635. skip = skiploop();
  8636. } while (!(skip & ~SKIPCONT));
  8637. loopnest--;
  8638. return status;
  8639. }
  8640. static int
  8641. evalfor(union node *n, int flags)
  8642. {
  8643. struct arglist arglist;
  8644. union node *argp;
  8645. struct strlist *sp;
  8646. int status = 0;
  8647. errlinno = lineno = n->ncase.linno;
  8648. arglist.list = NULL;
  8649. arglist.lastp = &arglist.list;
  8650. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8651. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8652. }
  8653. *arglist.lastp = NULL;
  8654. loopnest++;
  8655. flags &= EV_TESTED;
  8656. for (sp = arglist.list; sp; sp = sp->next) {
  8657. setvar0(n->nfor.var, sp->text);
  8658. status = evaltree(n->nfor.body, flags);
  8659. if (skiploop() & ~SKIPCONT)
  8660. break;
  8661. }
  8662. loopnest--;
  8663. return status;
  8664. }
  8665. static int
  8666. evalcase(union node *n, int flags)
  8667. {
  8668. union node *cp;
  8669. union node *patp;
  8670. struct arglist arglist;
  8671. int status = 0;
  8672. errlinno = lineno = n->ncase.linno;
  8673. arglist.list = NULL;
  8674. arglist.lastp = &arglist.list;
  8675. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8676. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8677. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8678. if (casematch(patp, arglist.list->text)) {
  8679. /* Ensure body is non-empty as otherwise
  8680. * EV_EXIT may prevent us from setting the
  8681. * exit status.
  8682. */
  8683. if (evalskip == 0 && cp->nclist.body) {
  8684. status = evaltree(cp->nclist.body, flags);
  8685. }
  8686. goto out;
  8687. }
  8688. }
  8689. }
  8690. out:
  8691. return status;
  8692. }
  8693. /*
  8694. * Kick off a subshell to evaluate a tree.
  8695. */
  8696. static int
  8697. evalsubshell(union node *n, int flags)
  8698. {
  8699. struct job *jp;
  8700. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8701. int status;
  8702. errlinno = lineno = n->nredir.linno;
  8703. expredir(n->nredir.redirect);
  8704. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8705. goto nofork;
  8706. INT_OFF;
  8707. if (backgnd == FORK_FG)
  8708. get_tty_state();
  8709. jp = makejob(/*n,*/ 1);
  8710. if (forkshell(jp, n, backgnd) == 0) {
  8711. /* child */
  8712. INT_ON;
  8713. flags |= EV_EXIT;
  8714. if (backgnd)
  8715. flags &= ~EV_TESTED;
  8716. nofork:
  8717. redirect(n->nredir.redirect, 0);
  8718. evaltreenr(n->nredir.n, flags);
  8719. /* never returns */
  8720. }
  8721. /* parent */
  8722. status = 0;
  8723. if (backgnd == FORK_FG)
  8724. status = waitforjob(jp);
  8725. INT_ON;
  8726. return status;
  8727. }
  8728. /*
  8729. * Compute the names of the files in a redirection list.
  8730. */
  8731. static void fixredir(union node *, const char *, int);
  8732. static void
  8733. expredir(union node *n)
  8734. {
  8735. union node *redir;
  8736. for (redir = n; redir; redir = redir->nfile.next) {
  8737. struct arglist fn;
  8738. fn.list = NULL;
  8739. fn.lastp = &fn.list;
  8740. switch (redir->type) {
  8741. case NFROMTO:
  8742. case NFROM:
  8743. case NTO:
  8744. #if BASH_REDIR_OUTPUT
  8745. case NTO2:
  8746. #endif
  8747. case NCLOBBER:
  8748. case NAPPEND:
  8749. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8750. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8751. #if BASH_REDIR_OUTPUT
  8752. store_expfname:
  8753. #endif
  8754. #if 0
  8755. // By the design of stack allocator, the loop of this kind:
  8756. // while true; do while true; do break; done </dev/null; done
  8757. // will look like a memory leak: ash plans to free expfname's
  8758. // of "/dev/null" as soon as it finishes running the loop
  8759. // (in this case, never).
  8760. // This "fix" is wrong:
  8761. if (redir->nfile.expfname)
  8762. stunalloc(redir->nfile.expfname);
  8763. // It results in corrupted state of stacked allocations.
  8764. #endif
  8765. redir->nfile.expfname = fn.list->text;
  8766. break;
  8767. case NFROMFD:
  8768. case NTOFD: /* >& */
  8769. if (redir->ndup.vname) {
  8770. expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
  8771. if (fn.list == NULL)
  8772. ash_msg_and_raise_error("redir error");
  8773. #if BASH_REDIR_OUTPUT
  8774. if (!isdigit_str9(fn.list->text)) {
  8775. /* >&file, not >&fd */
  8776. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8777. ash_msg_and_raise_error("redir error");
  8778. redir->type = NTO2;
  8779. goto store_expfname;
  8780. }
  8781. #endif
  8782. fixredir(redir, fn.list->text, 1);
  8783. }
  8784. break;
  8785. }
  8786. }
  8787. }
  8788. /*
  8789. * Evaluate a pipeline. All the processes in the pipeline are children
  8790. * of the process creating the pipeline. (This differs from some versions
  8791. * of the shell, which make the last process in a pipeline the parent
  8792. * of all the rest.)
  8793. */
  8794. static int
  8795. evalpipe(union node *n, int flags)
  8796. {
  8797. struct job *jp;
  8798. struct nodelist *lp;
  8799. int pipelen;
  8800. int prevfd;
  8801. int pip[2];
  8802. int status = 0;
  8803. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8804. pipelen = 0;
  8805. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8806. pipelen++;
  8807. flags |= EV_EXIT;
  8808. INT_OFF;
  8809. if (n->npipe.pipe_backgnd == 0)
  8810. get_tty_state();
  8811. jp = makejob(/*n,*/ pipelen);
  8812. prevfd = -1;
  8813. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8814. prehash(lp->n);
  8815. pip[1] = -1;
  8816. if (lp->next) {
  8817. if (pipe(pip) < 0) {
  8818. close(prevfd);
  8819. ash_msg_and_raise_perror("can't create pipe");
  8820. }
  8821. }
  8822. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8823. /* child */
  8824. INT_ON;
  8825. if (pip[1] >= 0) {
  8826. close(pip[0]);
  8827. }
  8828. if (prevfd > 0) {
  8829. dup2(prevfd, 0);
  8830. close(prevfd);
  8831. }
  8832. if (pip[1] > 1) {
  8833. dup2(pip[1], 1);
  8834. close(pip[1]);
  8835. }
  8836. evaltreenr(lp->n, flags);
  8837. /* never returns */
  8838. }
  8839. /* parent */
  8840. if (prevfd >= 0)
  8841. close(prevfd);
  8842. prevfd = pip[0];
  8843. /* Don't want to trigger debugging */
  8844. if (pip[1] != -1)
  8845. close(pip[1]);
  8846. }
  8847. if (n->npipe.pipe_backgnd == 0) {
  8848. status = waitforjob(jp);
  8849. TRACE(("evalpipe: job done exit status %d\n", status));
  8850. }
  8851. INT_ON;
  8852. return status;
  8853. }
  8854. /* setinteractive needs this forward reference */
  8855. #if EDITING_HAS_get_exe_name
  8856. static const char *get_builtin_name(int i) FAST_FUNC;
  8857. #endif
  8858. /*
  8859. * Controls whether the shell is interactive or not.
  8860. */
  8861. static void
  8862. setinteractive(int on)
  8863. {
  8864. static smallint is_interactive;
  8865. if (++on == is_interactive)
  8866. return;
  8867. is_interactive = on;
  8868. setsignal(SIGINT);
  8869. setsignal(SIGQUIT);
  8870. setsignal(SIGTERM);
  8871. if (is_interactive > 1) {
  8872. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8873. /* Looks like they want an interactive shell */
  8874. static smallint did_banner;
  8875. if (!did_banner) {
  8876. /* note: ash and hush share this string */
  8877. out1fmt("\n\n%s %s\n"
  8878. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8879. "\n",
  8880. bb_banner,
  8881. "built-in shell (ash)"
  8882. );
  8883. did_banner = 1;
  8884. }
  8885. #endif
  8886. #if ENABLE_FEATURE_EDITING
  8887. if (!line_input_state) {
  8888. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  8889. # if EDITING_HAS_get_exe_name
  8890. line_input_state->get_exe_name = get_builtin_name;
  8891. # endif
  8892. }
  8893. #endif
  8894. }
  8895. }
  8896. static void
  8897. optschanged(void)
  8898. {
  8899. #if DEBUG
  8900. opentrace();
  8901. #endif
  8902. setinteractive(iflag);
  8903. setjobctl(mflag);
  8904. #if ENABLE_FEATURE_EDITING_VI
  8905. if (line_input_state) {
  8906. if (viflag)
  8907. line_input_state->flags |= VI_MODE;
  8908. else
  8909. line_input_state->flags &= ~VI_MODE;
  8910. }
  8911. #else
  8912. viflag = 0; /* forcibly keep the option off */
  8913. #endif
  8914. }
  8915. struct localvar_list {
  8916. struct localvar_list *next;
  8917. struct localvar *lv;
  8918. };
  8919. static struct localvar_list *localvar_stack;
  8920. /*
  8921. * Called after a function returns.
  8922. * Interrupts must be off.
  8923. */
  8924. static void
  8925. poplocalvars(int keep)
  8926. {
  8927. struct localvar_list *ll;
  8928. struct localvar *lvp, *next;
  8929. struct var *vp;
  8930. INT_OFF;
  8931. ll = localvar_stack;
  8932. localvar_stack = ll->next;
  8933. next = ll->lv;
  8934. free(ll);
  8935. while ((lvp = next) != NULL) {
  8936. next = lvp->next;
  8937. vp = lvp->vp;
  8938. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8939. if (keep) {
  8940. int bits = VSTRFIXED;
  8941. if (lvp->flags != VUNSET) {
  8942. if (vp->var_text == lvp->text)
  8943. bits |= VTEXTFIXED;
  8944. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8945. free((char*)lvp->text);
  8946. }
  8947. vp->flags &= ~bits;
  8948. vp->flags |= (lvp->flags & bits);
  8949. if ((vp->flags &
  8950. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8951. unsetvar(vp->var_text);
  8952. } else if (vp == NULL) { /* $- saved */
  8953. memcpy(optlist, lvp->text, sizeof(optlist));
  8954. free((char*)lvp->text);
  8955. optschanged();
  8956. } else if (lvp->flags == VUNSET) {
  8957. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8958. unsetvar(vp->var_text);
  8959. } else {
  8960. if (vp->var_func)
  8961. vp->var_func(var_end(lvp->text));
  8962. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8963. free((char*)vp->var_text);
  8964. vp->flags = lvp->flags;
  8965. vp->var_text = lvp->text;
  8966. }
  8967. free(lvp);
  8968. }
  8969. INT_ON;
  8970. }
  8971. /*
  8972. * Create a new localvar environment.
  8973. */
  8974. static struct localvar_list *
  8975. pushlocalvars(int push)
  8976. {
  8977. struct localvar_list *ll;
  8978. struct localvar_list *top;
  8979. top = localvar_stack;
  8980. if (!push)
  8981. goto out;
  8982. INT_OFF;
  8983. ll = ckzalloc(sizeof(*ll));
  8984. /*ll->lv = NULL; - zalloc did it */
  8985. ll->next = top;
  8986. localvar_stack = ll;
  8987. INT_ON;
  8988. out:
  8989. return top;
  8990. }
  8991. static void
  8992. unwindlocalvars(struct localvar_list *stop)
  8993. {
  8994. while (localvar_stack != stop)
  8995. poplocalvars(0);
  8996. }
  8997. static int
  8998. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8999. {
  9000. volatile struct shparam saveparam;
  9001. struct jmploc *volatile savehandler;
  9002. struct jmploc jmploc;
  9003. int e;
  9004. int savelineno;
  9005. int savefuncline;
  9006. char *savefuncname;
  9007. char *savetrap = NULL;
  9008. if (!Eflag) {
  9009. savetrap = trap[NTRAP_ERR];
  9010. trap[NTRAP_ERR] = NULL;
  9011. }
  9012. savelineno = lineno;
  9013. saveparam = shellparam;
  9014. savefuncline = funcline;
  9015. savefuncname = funcname;
  9016. savehandler = exception_handler;
  9017. e = setjmp(jmploc.loc);
  9018. if (e) {
  9019. goto funcdone;
  9020. }
  9021. INT_OFF;
  9022. exception_handler = &jmploc;
  9023. shellparam.malloced = 0;
  9024. func->count++;
  9025. funcname = func->n.ndefun.text;
  9026. funcline = func->n.ndefun.linno;
  9027. INT_ON;
  9028. shellparam.nparam = argc - 1;
  9029. shellparam.p = argv + 1;
  9030. #if ENABLE_ASH_GETOPTS
  9031. shellparam.optind = 1;
  9032. shellparam.optoff = -1;
  9033. #endif
  9034. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  9035. funcdone:
  9036. INT_OFF;
  9037. funcname = savefuncname;
  9038. if (savetrap) {
  9039. if (!trap[NTRAP_ERR])
  9040. trap[NTRAP_ERR] = savetrap;
  9041. else
  9042. free(savetrap);
  9043. }
  9044. funcline = savefuncline;
  9045. lineno = savelineno;
  9046. freefunc(func);
  9047. freeparam(&shellparam);
  9048. shellparam = saveparam;
  9049. exception_handler = savehandler;
  9050. INT_ON;
  9051. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  9052. return e;
  9053. }
  9054. /*
  9055. * Make a variable a local variable. When a variable is made local, it's
  9056. * value and flags are saved in a localvar structure. The saved values
  9057. * will be restored when the shell function returns. We handle the name
  9058. * "-" as a special case: it makes changes to "set +-options" local
  9059. * (options will be restored on return from the function).
  9060. */
  9061. static void
  9062. mklocal(char *name, int flags)
  9063. {
  9064. struct localvar *lvp;
  9065. struct var **vpp;
  9066. struct var *vp;
  9067. char *eq = strchr(name, '=');
  9068. INT_OFF;
  9069. /* Cater for duplicate "local". Examples:
  9070. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  9071. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  9072. */
  9073. lvp = localvar_stack->lv;
  9074. while (lvp) {
  9075. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  9076. if (eq)
  9077. setvareq(name, 0);
  9078. /* else:
  9079. * it's a duplicate "local VAR" declaration, do nothing
  9080. */
  9081. goto ret;
  9082. }
  9083. lvp = lvp->next;
  9084. }
  9085. lvp = ckzalloc(sizeof(*lvp));
  9086. if (LONE_DASH(name)) {
  9087. char *p;
  9088. p = ckmalloc(sizeof(optlist));
  9089. lvp->text = memcpy(p, optlist, sizeof(optlist));
  9090. vp = NULL;
  9091. } else {
  9092. vpp = hashvar(name);
  9093. vp = *findvar(vpp, name);
  9094. if (vp == NULL) {
  9095. /* variable did not exist yet */
  9096. if (eq)
  9097. vp = setvareq(name, VSTRFIXED | flags);
  9098. else
  9099. vp = setvar(name, NULL, VSTRFIXED | flags);
  9100. lvp->flags = VUNSET;
  9101. } else {
  9102. lvp->text = vp->var_text;
  9103. lvp->flags = vp->flags;
  9104. /* make sure neither "struct var" nor string gets freed
  9105. * during (un)setting:
  9106. */
  9107. vp->flags |= VSTRFIXED|VTEXTFIXED;
  9108. if (eq)
  9109. setvareq(name, flags);
  9110. else
  9111. /* "local VAR" unsets VAR: */
  9112. setvar0(name, NULL);
  9113. }
  9114. }
  9115. lvp->vp = vp;
  9116. lvp->next = localvar_stack->lv;
  9117. localvar_stack->lv = lvp;
  9118. ret:
  9119. INT_ON;
  9120. }
  9121. /*
  9122. * The "local" command.
  9123. */
  9124. static int FAST_FUNC
  9125. localcmd(int argc UNUSED_PARAM, char **argv)
  9126. {
  9127. char *name;
  9128. if (!localvar_stack)
  9129. ash_msg_and_raise_error("not in a function");
  9130. argv = argptr;
  9131. while ((name = *argv++) != NULL) {
  9132. mklocal(name, 0);
  9133. }
  9134. return 0;
  9135. }
  9136. static int FAST_FUNC
  9137. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9138. {
  9139. return 1;
  9140. }
  9141. static int FAST_FUNC
  9142. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9143. {
  9144. return 0;
  9145. }
  9146. static int FAST_FUNC
  9147. execcmd(int argc UNUSED_PARAM, char **argv)
  9148. {
  9149. optionarg = NULL;
  9150. while (nextopt("a:") != '\0')
  9151. /* nextopt() sets optionarg to "-a ARGV0" */;
  9152. argv = argptr;
  9153. if (argv[0]) {
  9154. char *prog;
  9155. iflag = 0; /* exit on error */
  9156. mflag = 0;
  9157. optschanged();
  9158. /* We should set up signals for "exec CMD"
  9159. * the same way as for "CMD" without "exec".
  9160. * But optschanged->setinteractive->setsignal
  9161. * still thought we are a root shell. Therefore, for example,
  9162. * SIGQUIT is still set to IGN. Fix it:
  9163. */
  9164. shlvl++;
  9165. setsignal(SIGQUIT);
  9166. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  9167. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  9168. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  9169. prog = argv[0];
  9170. if (optionarg)
  9171. argv[0] = optionarg;
  9172. shellexec(prog, argv, pathval(), 0);
  9173. /* NOTREACHED */
  9174. }
  9175. return 0;
  9176. }
  9177. /*
  9178. * The return command.
  9179. */
  9180. static int FAST_FUNC
  9181. returncmd(int argc UNUSED_PARAM, char **argv)
  9182. {
  9183. int skip;
  9184. int status;
  9185. /*
  9186. * If called outside a function, do what ksh does;
  9187. * skip the rest of the file.
  9188. */
  9189. if (argv[1]) {
  9190. skip = SKIPFUNC;
  9191. status = number(argv[1]);
  9192. } else {
  9193. skip = SKIPFUNCDEF;
  9194. status = exitstatus;
  9195. }
  9196. evalskip = skip;
  9197. return status;
  9198. }
  9199. /* Forward declarations for builtintab[] */
  9200. static int breakcmd(int, char **) FAST_FUNC;
  9201. static int dotcmd(int, char **) FAST_FUNC;
  9202. static int evalcmd(int, char **, int) FAST_FUNC;
  9203. static int exitcmd(int, char **) FAST_FUNC;
  9204. static int exportcmd(int, char **) FAST_FUNC;
  9205. #if ENABLE_ASH_GETOPTS
  9206. static int getoptscmd(int, char **) FAST_FUNC;
  9207. #endif
  9208. #if ENABLE_ASH_HELP
  9209. static int helpcmd(int, char **) FAST_FUNC;
  9210. #endif
  9211. #if MAX_HISTORY
  9212. static int historycmd(int, char **) FAST_FUNC;
  9213. #endif
  9214. #if ENABLE_FEATURE_SH_MATH
  9215. static int letcmd(int, char **) FAST_FUNC;
  9216. #endif
  9217. static int readcmd(int, char **) FAST_FUNC;
  9218. static int setcmd(int, char **) FAST_FUNC;
  9219. static int shiftcmd(int, char **) FAST_FUNC;
  9220. static int timescmd(int, char **) FAST_FUNC;
  9221. static int trapcmd(int, char **) FAST_FUNC;
  9222. static int umaskcmd(int, char **) FAST_FUNC;
  9223. static int unsetcmd(int, char **) FAST_FUNC;
  9224. static int ulimitcmd(int, char **) FAST_FUNC;
  9225. #define BUILTIN_NOSPEC "0"
  9226. #define BUILTIN_SPECIAL "1"
  9227. #define BUILTIN_REGULAR "2"
  9228. #define BUILTIN_SPEC_REG "3"
  9229. #define BUILTIN_ASSIGN "4"
  9230. #define BUILTIN_SPEC_ASSG "5"
  9231. #define BUILTIN_REG_ASSG "6"
  9232. #define BUILTIN_SPEC_REG_ASSG "7"
  9233. /* Stubs for calling non-FAST_FUNC's */
  9234. #if ENABLE_ASH_ECHO
  9235. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  9236. #endif
  9237. #if ENABLE_ASH_PRINTF
  9238. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  9239. #endif
  9240. #if ENABLE_ASH_TEST || BASH_TEST2
  9241. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  9242. #endif
  9243. /* Keep these in proper order since it is searched via bsearch() */
  9244. static const struct builtincmd builtintab[] = {
  9245. { BUILTIN_SPEC_REG "." , dotcmd },
  9246. { BUILTIN_SPEC_REG ":" , truecmd },
  9247. #if ENABLE_ASH_TEST
  9248. { BUILTIN_REGULAR "[" , testcmd },
  9249. #endif
  9250. #if BASH_TEST2
  9251. { BUILTIN_REGULAR "[[" , testcmd },
  9252. #endif
  9253. #if ENABLE_ASH_ALIAS
  9254. { BUILTIN_REG_ASSG "alias" , aliascmd },
  9255. #endif
  9256. #if JOBS
  9257. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  9258. #endif
  9259. { BUILTIN_SPEC_REG "break" , breakcmd },
  9260. { BUILTIN_REGULAR "cd" , cdcmd },
  9261. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9262. #if ENABLE_ASH_CMDCMD
  9263. { BUILTIN_REGULAR "command" , commandcmd },
  9264. #endif
  9265. { BUILTIN_SPEC_REG "continue", breakcmd },
  9266. #if ENABLE_ASH_ECHO
  9267. { BUILTIN_REGULAR "echo" , echocmd },
  9268. #endif
  9269. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9270. { BUILTIN_SPEC_REG "exec" , execcmd },
  9271. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9272. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9273. { BUILTIN_REGULAR "false" , falsecmd },
  9274. #if JOBS
  9275. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9276. #endif
  9277. #if ENABLE_ASH_GETOPTS
  9278. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9279. #endif
  9280. { BUILTIN_REGULAR "hash" , hashcmd },
  9281. #if ENABLE_ASH_HELP
  9282. { BUILTIN_NOSPEC "help" , helpcmd },
  9283. #endif
  9284. #if MAX_HISTORY
  9285. { BUILTIN_NOSPEC "history" , historycmd },
  9286. #endif
  9287. #if JOBS
  9288. { BUILTIN_REGULAR "jobs" , jobscmd },
  9289. { BUILTIN_REGULAR "kill" , killcmd },
  9290. #endif
  9291. #if ENABLE_FEATURE_SH_MATH
  9292. { BUILTIN_NOSPEC "let" , letcmd },
  9293. #endif
  9294. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9295. #if ENABLE_ASH_PRINTF
  9296. { BUILTIN_REGULAR "printf" , printfcmd },
  9297. #endif
  9298. { BUILTIN_REGULAR "pwd" , pwdcmd },
  9299. { BUILTIN_REGULAR "read" , readcmd },
  9300. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9301. { BUILTIN_SPEC_REG "return" , returncmd },
  9302. { BUILTIN_SPEC_REG "set" , setcmd },
  9303. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9304. #if BASH_SOURCE
  9305. { BUILTIN_SPEC_REG "source" , dotcmd },
  9306. #endif
  9307. #if ENABLE_ASH_TEST
  9308. { BUILTIN_REGULAR "test" , testcmd },
  9309. #endif
  9310. { BUILTIN_SPEC_REG "times" , timescmd },
  9311. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9312. { BUILTIN_REGULAR "true" , truecmd },
  9313. { BUILTIN_REGULAR "type" , typecmd },
  9314. { BUILTIN_REGULAR "ulimit" , ulimitcmd },
  9315. { BUILTIN_REGULAR "umask" , umaskcmd },
  9316. #if ENABLE_ASH_ALIAS
  9317. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9318. #endif
  9319. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9320. { BUILTIN_REGULAR "wait" , waitcmd },
  9321. };
  9322. /* Should match the above table! */
  9323. #define COMMANDCMD (builtintab + \
  9324. /* . : */ 2 + \
  9325. /* [ */ 1 * ENABLE_ASH_TEST + \
  9326. /* [[ */ 1 * BASH_TEST2 + \
  9327. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9328. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9329. /* break cd cddir */ 3)
  9330. #define EVALCMD (COMMANDCMD + \
  9331. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9332. /* continue */ 1 + \
  9333. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9334. 0)
  9335. #define EXECCMD (EVALCMD + \
  9336. /* eval */ 1)
  9337. /*
  9338. * Search the table of builtin commands.
  9339. */
  9340. static int
  9341. pstrcmp1(const void *a, const void *b)
  9342. {
  9343. return strcmp((char*)a, *(char**)b + 1);
  9344. }
  9345. static struct builtincmd *
  9346. find_builtin(const char *name)
  9347. {
  9348. struct builtincmd *bp;
  9349. bp = bsearch(
  9350. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9351. pstrcmp1
  9352. );
  9353. return bp;
  9354. }
  9355. #if EDITING_HAS_get_exe_name
  9356. static const char * FAST_FUNC
  9357. get_builtin_name(int i)
  9358. {
  9359. return /*i >= 0 &&*/ i < ARRAY_SIZE(builtintab) ? builtintab[i].name + 1 : NULL;
  9360. }
  9361. #endif
  9362. /*
  9363. * Execute a simple command.
  9364. */
  9365. static void unwindfiles(struct parsefile *stop);
  9366. static int
  9367. isassignment(const char *p)
  9368. {
  9369. const char *q = endofname(p);
  9370. if (p == q)
  9371. return 0;
  9372. return *q == '=';
  9373. }
  9374. static int FAST_FUNC
  9375. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9376. {
  9377. /* Preserve exitstatus of a previous possible redirection
  9378. * as POSIX mandates */
  9379. return back_exitstatus;
  9380. }
  9381. static int
  9382. evalcommand(union node *cmd, int flags)
  9383. {
  9384. static const struct builtincmd null_bltin = {
  9385. BUILTIN_REGULAR "", bltincmd
  9386. };
  9387. struct localvar_list *localvar_stop;
  9388. struct parsefile *file_stop;
  9389. struct redirtab *redir_stop;
  9390. union node *argp;
  9391. struct arglist arglist;
  9392. struct arglist varlist;
  9393. char **argv;
  9394. int argc;
  9395. struct strlist *osp;
  9396. const struct strlist *sp;
  9397. struct cmdentry cmdentry;
  9398. struct job *jp;
  9399. char *lastarg;
  9400. const char *path;
  9401. int spclbltin;
  9402. int cmd_flag;
  9403. int status;
  9404. char **nargv;
  9405. smallint cmd_is_exec;
  9406. int vflags;
  9407. int vlocal;
  9408. errlinno = lineno = cmd->ncmd.linno;
  9409. /* First expand the arguments. */
  9410. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9411. #if BASH_PROCESS_SUBST
  9412. redir_stop = redirlist;
  9413. #endif
  9414. file_stop = g_parsefile;
  9415. back_exitstatus = 0;
  9416. cmdentry.cmdtype = CMDBUILTIN;
  9417. cmdentry.u.cmd = &null_bltin;
  9418. varlist.lastp = &varlist.list;
  9419. *varlist.lastp = NULL;
  9420. arglist.lastp = &arglist.list;
  9421. *arglist.lastp = NULL;
  9422. cmd_flag = 0;
  9423. cmd_is_exec = 0;
  9424. spclbltin = -1;
  9425. vflags = 0;
  9426. vlocal = 0;
  9427. path = NULL;
  9428. argc = 0;
  9429. argp = cmd->ncmd.args;
  9430. osp = fill_arglist(&arglist, &argp);
  9431. if (osp) {
  9432. int pseudovarflag = 0;
  9433. for (;;) {
  9434. find_command(arglist.list->text, &cmdentry,
  9435. cmd_flag | DO_REGBLTIN, pathval());
  9436. vlocal++;
  9437. /* implement bltin and command here */
  9438. if (cmdentry.cmdtype != CMDBUILTIN)
  9439. break;
  9440. pseudovarflag = IS_BUILTIN_ASSIGN(cmdentry.u.cmd);
  9441. if (spclbltin < 0) {
  9442. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9443. vlocal = !spclbltin;
  9444. }
  9445. cmd_is_exec = cmdentry.u.cmd == EXECCMD;
  9446. #if ENABLE_ASH_CMDCMD
  9447. if (cmdentry.u.cmd != COMMANDCMD)
  9448. break;
  9449. cmd_flag = parse_command_args(&arglist, &argp, &path);
  9450. if (!cmd_flag)
  9451. #endif
  9452. break;
  9453. }
  9454. for (; argp; argp = argp->narg.next)
  9455. expandarg(argp, &arglist,
  9456. pseudovarflag &&
  9457. isassignment(argp->narg.text) ?
  9458. EXP_VARTILDE : EXP_FULL | EXP_TILDE);
  9459. for (sp = arglist.list; sp; sp = sp->next)
  9460. argc++;
  9461. if (cmd_is_exec && argc > 1)
  9462. vflags = VEXPORT;
  9463. }
  9464. localvar_stop = pushlocalvars(vlocal);
  9465. /* Reserve one extra spot at the front for shellexec. */
  9466. nargv = stalloc(sizeof(char *) * (argc + 2));
  9467. argv = ++nargv;
  9468. for (sp = arglist.list; sp; sp = sp->next) {
  9469. TRACE(("evalcommand arg: %s\n", sp->text));
  9470. *nargv++ = sp->text;
  9471. }
  9472. *nargv = NULL;
  9473. lastarg = NULL;
  9474. if (iflag && funcline == 0 && argc > 0)
  9475. lastarg = nargv[-1];
  9476. expredir(cmd->ncmd.redirect);
  9477. #if !BASH_PROCESS_SUBST
  9478. redir_stop = pushredir(cmd->ncmd.redirect);
  9479. #else
  9480. pushredir(cmd->ncmd.redirect);
  9481. #endif
  9482. preverrout_fd = 2;
  9483. if (BASH_XTRACEFD && xflag) {
  9484. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9485. * we do not emulate this. We only use its value.
  9486. */
  9487. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9488. if (xtracefd && is_number(xtracefd))
  9489. preverrout_fd = atoi(xtracefd);
  9490. }
  9491. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9492. if (status) {
  9493. bail:
  9494. exitstatus = status;
  9495. /* We have a redirection error. */
  9496. if (spclbltin > 0)
  9497. raise_exception(EXERROR);
  9498. goto out;
  9499. }
  9500. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9501. struct strlist **spp;
  9502. spp = varlist.lastp;
  9503. expandarg(argp, &varlist, EXP_VARTILDE);
  9504. if (vlocal)
  9505. mklocal((*spp)->text, VEXPORT);
  9506. else
  9507. setvareq((*spp)->text, vflags);
  9508. }
  9509. /* Print the command if xflag is set. */
  9510. if (xflag && !inps4) {
  9511. const char *pfx = "";
  9512. inps4 = 1;
  9513. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9514. inps4 = 0;
  9515. sp = varlist.list;
  9516. while (sp) {
  9517. char *varval = sp->text;
  9518. char *eq = strchrnul(varval, '=');
  9519. if (*eq)
  9520. eq++;
  9521. fdprintf(preverrout_fd, "%s%.*s%s",
  9522. pfx,
  9523. (int)(eq - varval), varval,
  9524. maybe_single_quote(eq)
  9525. );
  9526. sp = sp->next;
  9527. pfx = " ";
  9528. }
  9529. sp = arglist.list;
  9530. while (sp) {
  9531. fdprintf(preverrout_fd, "%s%s",
  9532. pfx,
  9533. /* always quote if matches reserved word: */
  9534. findkwd(sp->text)
  9535. ? single_quote(sp->text)
  9536. : maybe_single_quote(sp->text)
  9537. );
  9538. sp = sp->next;
  9539. pfx = " ";
  9540. }
  9541. safe_write(preverrout_fd, "\n", 1);
  9542. }
  9543. /* Now locate the command. */
  9544. if (cmdentry.cmdtype != CMDBUILTIN
  9545. || !(IS_BUILTIN_REGULAR(cmdentry.u.cmd))
  9546. ) {
  9547. path = path ? path : pathval();
  9548. find_command(argv[0], &cmdentry, cmd_flag | DO_ERR, path);
  9549. }
  9550. jp = NULL;
  9551. /* Execute the command. */
  9552. switch (cmdentry.cmdtype) {
  9553. case CMDUNKNOWN:
  9554. status = 127;
  9555. flush_stdout_stderr();
  9556. goto bail;
  9557. default: {
  9558. #if ENABLE_FEATURE_SH_STANDALONE \
  9559. && ENABLE_FEATURE_SH_NOFORK \
  9560. && NUM_APPLETS > 1
  9561. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9562. * around run_nofork_applet() call.
  9563. * (2) Should this check also be done in forkshell()?
  9564. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9565. */
  9566. /* find_command() encodes applet_no as (-2 - applet_no) */
  9567. int applet_no = (- cmdentry.u.index - 2);
  9568. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9569. char **sv_environ;
  9570. INT_OFF;
  9571. sv_environ = environ;
  9572. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9573. /*
  9574. * Run <applet>_main().
  9575. * Signals (^C) can't interrupt here.
  9576. * Otherwise we can mangle stdio or malloc internal state.
  9577. * This makes applets which can run for a long time
  9578. * and/or wait for user input ineligible for NOFORK:
  9579. * for example, "yes" or "rm" (rm -i waits for input).
  9580. */
  9581. exitstatus = run_nofork_applet(applet_no, argv);
  9582. environ = sv_environ;
  9583. /*
  9584. * Try enabling NOFORK for "yes" applet.
  9585. * ^C _will_ stop it (write returns EINTR),
  9586. * but this causes stdout FILE to be stuck
  9587. * and needing clearerr(). What if other applets
  9588. * also can get EINTRs? Do we need to switch
  9589. * our signals to SA_RESTART?
  9590. */
  9591. /*clearerr(stdout);*/
  9592. INT_ON;
  9593. break;
  9594. }
  9595. #endif
  9596. /* Can we avoid forking? For example, very last command
  9597. * in a script or a subshell does not need forking,
  9598. * we can just exec it.
  9599. */
  9600. if (!(flags & EV_EXIT) || may_have_traps) {
  9601. /* No, forking off a child is necessary */
  9602. INT_OFF;
  9603. get_tty_state();
  9604. jp = makejob(/*cmd,*/ 1);
  9605. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9606. /* parent */
  9607. break;
  9608. }
  9609. /* child */
  9610. FORCE_INT_ON;
  9611. /* fall through to exec'ing external program */
  9612. }
  9613. shellexec(argv[0], argv, path, cmdentry.u.index);
  9614. /* NOTREACHED */
  9615. } /* default */
  9616. case CMDBUILTIN:
  9617. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)
  9618. && !(exception_type == EXERROR && spclbltin <= 0)
  9619. ) {
  9620. raise:
  9621. longjmp(exception_handler->loc, 1);
  9622. }
  9623. break;
  9624. case CMDFUNCTION:
  9625. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9626. goto raise;
  9627. break;
  9628. } /* switch */
  9629. status = waitforjob(jp);
  9630. if (jp)
  9631. TRACE(("forked child exited with %d\n", status));
  9632. FORCE_INT_ON;
  9633. out:
  9634. if (cmd->ncmd.redirect)
  9635. popredir(/*drop:*/ cmd_is_exec);
  9636. unwindredir(redir_stop);
  9637. unwindfiles(file_stop);
  9638. unwindlocalvars(localvar_stop);
  9639. if (lastarg) {
  9640. /* dsl: I think this is intended to be used to support
  9641. * '_' in 'vi' command mode during line editing...
  9642. * However I implemented that within libedit itself.
  9643. */
  9644. setvar0("_", lastarg);
  9645. }
  9646. return status;
  9647. }
  9648. static int
  9649. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9650. {
  9651. char *volatile savecmdname;
  9652. struct jmploc *volatile savehandler;
  9653. struct jmploc jmploc;
  9654. int status;
  9655. int i;
  9656. savecmdname = commandname;
  9657. savehandler = exception_handler;
  9658. i = setjmp(jmploc.loc);
  9659. if (i)
  9660. goto cmddone;
  9661. exception_handler = &jmploc;
  9662. commandname = argv[0];
  9663. argptr = argv + 1;
  9664. optptr = NULL; /* initialize nextopt */
  9665. if (cmd == EVALCMD)
  9666. status = evalcmd(argc, argv, flags);
  9667. else
  9668. status = (*cmd->builtin)(argc, argv);
  9669. flush_stdout_stderr();
  9670. status |= ferror(stdout);
  9671. exitstatus = status;
  9672. cmddone:
  9673. clearerr(stdout);
  9674. commandname = savecmdname;
  9675. exception_handler = savehandler;
  9676. return i;
  9677. }
  9678. static int
  9679. goodname(const char *p)
  9680. {
  9681. return endofname(p)[0] == '\0';
  9682. }
  9683. /*
  9684. * Search for a command. This is called before we fork so that the
  9685. * location of the command will be available in the parent as well as
  9686. * the child. The check for "goodname" is an overly conservative
  9687. * check that the name will not be subject to expansion.
  9688. */
  9689. static void
  9690. prehash(union node *n)
  9691. {
  9692. struct cmdentry entry;
  9693. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9694. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9695. }
  9696. /* ============ Builtin commands
  9697. *
  9698. * Builtin commands whose functions are closely tied to evaluation
  9699. * are implemented here.
  9700. */
  9701. /*
  9702. * Handle break and continue commands. Break, continue, and return are
  9703. * all handled by setting the evalskip flag. The evaluation routines
  9704. * above all check this flag, and if it is set they start skipping
  9705. * commands rather than executing them. The variable skipcount is
  9706. * the number of loops to break/continue, or the number of function
  9707. * levels to return. (The latter is always 1.) It should probably
  9708. * be an error to break out of more loops than exist, but it isn't
  9709. * in the standard shell so we don't make it one here.
  9710. */
  9711. static int FAST_FUNC
  9712. breakcmd(int argc UNUSED_PARAM, char **argv)
  9713. {
  9714. int n = argv[1] ? number(argv[1]) : 1;
  9715. if (n <= 0)
  9716. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9717. if (n > loopnest)
  9718. n = loopnest;
  9719. if (n > 0) {
  9720. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9721. skipcount = n;
  9722. }
  9723. return 0;
  9724. }
  9725. /*
  9726. * This implements the input routines used by the parser.
  9727. */
  9728. enum {
  9729. INPUT_PUSH_FILE = 1,
  9730. INPUT_NOFILE_OK = 2,
  9731. };
  9732. static smallint checkkwd;
  9733. /* values of checkkwd variable */
  9734. #define CHKALIAS 0x1
  9735. #define CHKKWD 0x2
  9736. #define CHKNL 0x4
  9737. #define CHKEOFMARK 0x8
  9738. /*
  9739. * Push a string back onto the input at this current parsefile level.
  9740. * We handle aliases this way.
  9741. */
  9742. #if !ENABLE_ASH_ALIAS
  9743. #define pushstring(s, ap) pushstring(s)
  9744. #endif
  9745. static void
  9746. pushstring(char *s, struct alias *ap)
  9747. {
  9748. struct strpush *sp;
  9749. int len;
  9750. len = strlen(s);
  9751. INT_OFF;
  9752. if (g_parsefile->strpush || g_parsefile->spfree) {
  9753. sp = ckzalloc(sizeof(*sp));
  9754. sp->prev = g_parsefile->strpush;
  9755. } else {
  9756. sp = &(g_parsefile->basestrpush);
  9757. }
  9758. g_parsefile->strpush = sp;
  9759. sp->prev_string = g_parsefile->next_to_pgetc;
  9760. sp->prev_left_in_line = g_parsefile->left_in_line;
  9761. sp->unget = g_parsefile->unget;
  9762. sp->spfree = g_parsefile->spfree;
  9763. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9764. #if ENABLE_ASH_ALIAS
  9765. sp->ap = ap;
  9766. if (ap) {
  9767. ap->flag |= ALIASINUSE;
  9768. sp->string = s;
  9769. }
  9770. #endif
  9771. g_parsefile->next_to_pgetc = s;
  9772. g_parsefile->left_in_line = len;
  9773. g_parsefile->unget = 0;
  9774. g_parsefile->spfree = NULL;
  9775. INT_ON;
  9776. }
  9777. static void popstring(void)
  9778. {
  9779. struct strpush *sp = g_parsefile->strpush;
  9780. INT_OFF;
  9781. #if ENABLE_ASH_ALIAS
  9782. if (sp->ap) {
  9783. if (g_parsefile->next_to_pgetc[-1] == ' '
  9784. || g_parsefile->next_to_pgetc[-1] == '\t'
  9785. ) {
  9786. checkkwd |= CHKALIAS;
  9787. }
  9788. if (sp->string != sp->ap->val) {
  9789. free(sp->string);
  9790. }
  9791. }
  9792. #endif
  9793. g_parsefile->next_to_pgetc = sp->prev_string;
  9794. g_parsefile->left_in_line = sp->prev_left_in_line;
  9795. g_parsefile->unget = sp->unget;
  9796. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9797. g_parsefile->strpush = sp->prev;
  9798. g_parsefile->spfree = sp;
  9799. INT_ON;
  9800. }
  9801. static int
  9802. preadfd(void)
  9803. {
  9804. int nr;
  9805. char *buf = g_parsefile->buf;
  9806. g_parsefile->next_to_pgetc = buf;
  9807. #if ENABLE_FEATURE_EDITING
  9808. /* retry: */
  9809. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9810. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9811. else {
  9812. # if ENABLE_ASH_IDLE_TIMEOUT
  9813. int timeout = -1;
  9814. const char *tmout_var = lookupvar("TMOUT");
  9815. if (tmout_var) {
  9816. timeout = atoi(tmout_var) * 1000;
  9817. if (timeout <= 0)
  9818. timeout = -1;
  9819. }
  9820. line_input_state->timeout = timeout;
  9821. # endif
  9822. # if ENABLE_FEATURE_TAB_COMPLETION
  9823. line_input_state->path_lookup = pathval();
  9824. # endif
  9825. reinit_unicode_for_ash();
  9826. again:
  9827. /* For shell, LI_INTERRUPTIBLE is set:
  9828. * read_line_input will abort on either
  9829. * getting EINTR in poll(), or if it sees bb_got_signal != 0
  9830. * (IOW: if signal arrives before poll() is reached).
  9831. * Interactive testcases:
  9832. * (while kill -INT $$; do sleep 1; done) &
  9833. * #^^^ prints ^C, prints prompt, repeats
  9834. * trap 'echo I' int; (while kill -INT $$; do sleep 1; done) &
  9835. * #^^^ prints ^C, prints "I", prints prompt, repeats
  9836. * trap 'echo T' term; (while kill $$; do sleep 1; done) &
  9837. * #^^^ prints "T", prints prompt, repeats
  9838. * #(bash 5.0.17 exits after first "T", looks like a bug)
  9839. */
  9840. bb_got_signal = 0;
  9841. INT_OFF; /* no longjmp'ing out of read_line_input please */
  9842. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9843. if (bb_got_signal == SIGINT)
  9844. write(STDOUT_FILENO, "^C\n", 3);
  9845. INT_ON; /* here non-blocked SIGINT will longjmp */
  9846. if (nr == 0) {
  9847. /* ^C pressed, "convert" to SIGINT */
  9848. write(STDOUT_FILENO, "^C\n", 3);
  9849. raise(SIGINT); /* here non-blocked SIGINT will longjmp */
  9850. /* raise(SIGINT) did not work! (e.g. if SIGINT
  9851. * is SIG_IGNed on startup, it stays SIG_IGNed)
  9852. */
  9853. if (trap[SIGINT]) {
  9854. empty_line_input:
  9855. buf[0] = '\n';
  9856. buf[1] = '\0';
  9857. return 1;
  9858. }
  9859. exitstatus = 128 + SIGINT;
  9860. /* bash behavior on ^C + ignored SIGINT: */
  9861. goto again;
  9862. }
  9863. if (nr < 0) {
  9864. if (errno == 0) {
  9865. /* ^D pressed */
  9866. nr = 0;
  9867. }
  9868. else if (errno == EINTR) { /* got signal? */
  9869. if (bb_got_signal != SIGINT)
  9870. write(STDOUT_FILENO, "\n", 1);
  9871. goto empty_line_input;
  9872. }
  9873. # if ENABLE_ASH_IDLE_TIMEOUT
  9874. else if (errno == EAGAIN && timeout > 0) {
  9875. puts("\007timed out waiting for input: auto-logout");
  9876. exitshell();
  9877. }
  9878. # endif
  9879. }
  9880. }
  9881. #else
  9882. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9883. #endif
  9884. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9885. if (nr < 0) {
  9886. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9887. int flags = fcntl(0, F_GETFL);
  9888. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9889. flags &= ~O_NONBLOCK;
  9890. if (fcntl(0, F_SETFL, flags) >= 0) {
  9891. out2str("sh: turning off NDELAY mode\n");
  9892. goto retry;
  9893. }
  9894. }
  9895. }
  9896. }
  9897. #endif
  9898. return nr;
  9899. }
  9900. /*
  9901. * Refill the input buffer and return the next input character:
  9902. *
  9903. * 1) If a string was pushed back on the input, pop it;
  9904. * 2) If we are reading from a string we can't refill the buffer, return EOF.
  9905. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9906. * 4) Process input up to the next newline, deleting nul characters.
  9907. */
  9908. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9909. #define pgetc_debug(...) ((void)0)
  9910. static int __pgetc(void);
  9911. static int
  9912. preadbuffer(void)
  9913. {
  9914. char *q;
  9915. int more;
  9916. if (unlikely(g_parsefile->strpush)) {
  9917. popstring();
  9918. return __pgetc();
  9919. }
  9920. if (g_parsefile->buf == NULL) {
  9921. pgetc_debug("preadbuffer PEOF1");
  9922. return PEOF;
  9923. }
  9924. more = g_parsefile->left_in_buffer;
  9925. if (more <= 0) {
  9926. flush_stdout_stderr();
  9927. again:
  9928. more = preadfd();
  9929. if (more <= 0) {
  9930. g_parsefile->left_in_buffer = g_parsefile->left_in_line = 0;
  9931. pgetc_debug("preadbuffer PEOF2");
  9932. return PEOF;
  9933. }
  9934. }
  9935. /* Find out where's the end of line.
  9936. * Set g_parsefile->left_in_line
  9937. * and g_parsefile->left_in_buffer acordingly.
  9938. * NUL chars are deleted.
  9939. */
  9940. q = g_parsefile->next_to_pgetc;
  9941. for (;;) {
  9942. char c;
  9943. more--;
  9944. c = *q;
  9945. if (c == '\0') {
  9946. memmove(q, q + 1, more);
  9947. } else {
  9948. q++;
  9949. if (c == '\n') {
  9950. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9951. break;
  9952. }
  9953. }
  9954. if (more <= 0) {
  9955. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9956. if (g_parsefile->left_in_line < 0)
  9957. goto again;
  9958. break;
  9959. }
  9960. }
  9961. g_parsefile->left_in_buffer = more;
  9962. if (vflag) {
  9963. char save = *q;
  9964. *q = '\0';
  9965. out2str(g_parsefile->next_to_pgetc);
  9966. *q = save;
  9967. }
  9968. pgetc_debug("preadbuffer at %d:%p'%s'",
  9969. g_parsefile->left_in_line,
  9970. g_parsefile->next_to_pgetc,
  9971. g_parsefile->next_to_pgetc);
  9972. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9973. }
  9974. static void
  9975. nlprompt(void)
  9976. {
  9977. if (trap_depth == 0)
  9978. g_parsefile->linno++;
  9979. setprompt_if(doprompt, 2);
  9980. }
  9981. static void
  9982. nlnoprompt(void)
  9983. {
  9984. if (trap_depth == 0)
  9985. g_parsefile->linno++;
  9986. needprompt = doprompt;
  9987. }
  9988. static void freestrings(struct strpush *sp)
  9989. {
  9990. INT_OFF;
  9991. do {
  9992. struct strpush *psp;
  9993. #if ENABLE_ASH_ALIAS
  9994. if (sp->ap) {
  9995. sp->ap->flag &= ~ALIASINUSE;
  9996. if (sp->ap->flag & ALIASDEAD) {
  9997. unalias(sp->ap->name);
  9998. }
  9999. }
  10000. #endif
  10001. psp = sp;
  10002. sp = sp->spfree;
  10003. if (psp != &(g_parsefile->basestrpush))
  10004. free(psp);
  10005. } while (sp);
  10006. g_parsefile->spfree = NULL;
  10007. INT_ON;
  10008. }
  10009. static int __pgetc(void)
  10010. {
  10011. int c;
  10012. pgetc_debug("pgetc at %d:%p'%s'",
  10013. g_parsefile->left_in_line,
  10014. g_parsefile->next_to_pgetc,
  10015. g_parsefile->next_to_pgetc);
  10016. if (g_parsefile->unget)
  10017. return g_parsefile->lastc[--g_parsefile->unget];
  10018. if (--g_parsefile->left_in_line >= 0)
  10019. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  10020. else
  10021. c = preadbuffer();
  10022. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  10023. g_parsefile->lastc[0] = c;
  10024. return c;
  10025. }
  10026. /*
  10027. * Read a character from the script, returning PEOF on end of file.
  10028. * Nul characters in the input are silently discarded.
  10029. */
  10030. static int pgetc(void)
  10031. {
  10032. struct strpush *sp = g_parsefile->spfree;
  10033. if (unlikely(sp))
  10034. freestrings(sp);
  10035. return __pgetc();
  10036. }
  10037. /*
  10038. * Undo a call to pgetc. Only two characters may be pushed back.
  10039. * PEOF may be pushed back.
  10040. */
  10041. static void
  10042. pungetc(void)
  10043. {
  10044. g_parsefile->unget++;
  10045. }
  10046. /* This one eats backslash+newline */
  10047. static int
  10048. pgetc_eatbnl(void)
  10049. {
  10050. int c;
  10051. while ((c = pgetc()) == '\\') {
  10052. if (pgetc() != '\n') {
  10053. pungetc();
  10054. break;
  10055. }
  10056. nlprompt();
  10057. }
  10058. return c;
  10059. }
  10060. struct synstack {
  10061. smalluint syntax;
  10062. uint8_t innerdq :1;
  10063. uint8_t varpushed :1;
  10064. uint8_t dblquote :1;
  10065. int varnest; /* levels of variables expansion */
  10066. int dqvarnest; /* levels of variables expansion within double quotes */
  10067. int parenlevel; /* levels of parens in arithmetic */
  10068. struct synstack *prev;
  10069. struct synstack *next;
  10070. };
  10071. static int
  10072. pgetc_top(struct synstack *stack)
  10073. {
  10074. return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
  10075. }
  10076. static void
  10077. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  10078. {
  10079. memset(next, 0, sizeof(*next));
  10080. next->syntax = syntax;
  10081. next->next = *stack;
  10082. (*stack)->prev = next;
  10083. *stack = next;
  10084. }
  10085. static ALWAYS_INLINE void
  10086. synstack_pop(struct synstack **stack)
  10087. {
  10088. *stack = (*stack)->next;
  10089. }
  10090. /*
  10091. * To handle the "." command, a stack of input files is used. Pushfile
  10092. * adds a new entry to the stack and popfile restores the previous level.
  10093. */
  10094. static void
  10095. pushfile(void)
  10096. {
  10097. struct parsefile *pf;
  10098. pf = ckzalloc(sizeof(*pf));
  10099. pf->prev = g_parsefile;
  10100. pf->pf_fd = -1;
  10101. /*pf->strpush = NULL; - ckzalloc did it */
  10102. /*pf->spfree = NULL;*/
  10103. /*pf->basestrpush.prev = NULL;*/
  10104. /*pf->unget = 0;*/
  10105. g_parsefile = pf;
  10106. }
  10107. static void
  10108. popfile(void)
  10109. {
  10110. struct parsefile *pf = g_parsefile;
  10111. if (pf == &basepf)
  10112. return;
  10113. INT_OFF;
  10114. if (pf->pf_fd >= 0)
  10115. close(pf->pf_fd);
  10116. free(pf->buf);
  10117. if (g_parsefile->spfree)
  10118. freestrings(g_parsefile->spfree);
  10119. while (pf->strpush) {
  10120. popstring();
  10121. freestrings(g_parsefile->spfree);
  10122. }
  10123. g_parsefile = pf->prev;
  10124. free(pf);
  10125. INT_ON;
  10126. }
  10127. static void
  10128. unwindfiles(struct parsefile *stop)
  10129. {
  10130. while (g_parsefile != stop)
  10131. popfile();
  10132. }
  10133. /*
  10134. * Return to top level.
  10135. */
  10136. static void
  10137. popallfiles(void)
  10138. {
  10139. unwindfiles(&basepf);
  10140. }
  10141. /*
  10142. * Close the file(s) that the shell is reading commands from. Called
  10143. * after a fork is done.
  10144. */
  10145. static void
  10146. closescript(void)
  10147. {
  10148. popallfiles();
  10149. if (g_parsefile->pf_fd > 0) {
  10150. close(g_parsefile->pf_fd);
  10151. g_parsefile->pf_fd = 0;
  10152. }
  10153. }
  10154. /*
  10155. * Like setinputfile, but takes an open file descriptor. Call this with
  10156. * interrupts off.
  10157. */
  10158. static void
  10159. setinputfd(int fd, int push)
  10160. {
  10161. if (push) {
  10162. pushfile();
  10163. g_parsefile->buf = NULL;
  10164. }
  10165. g_parsefile->pf_fd = fd;
  10166. if (g_parsefile->buf == NULL)
  10167. g_parsefile->buf = ckmalloc(IBUFSIZ);
  10168. g_parsefile->left_in_buffer = 0;
  10169. g_parsefile->left_in_line = 0;
  10170. g_parsefile->linno = 1;
  10171. }
  10172. /*
  10173. * Set the input to take input from a file. If push is set, push the
  10174. * old input onto the stack first.
  10175. */
  10176. static int
  10177. setinputfile(const char *fname, int flags)
  10178. {
  10179. int fd;
  10180. INT_OFF;
  10181. fd = open(fname, O_RDONLY | O_CLOEXEC);
  10182. if (fd < 0) {
  10183. if (flags & INPUT_NOFILE_OK)
  10184. goto out;
  10185. exitstatus = 127;
  10186. ash_msg_and_raise_perror("can't open '%s'", fname);
  10187. }
  10188. if (fd < 10)
  10189. fd = savefd(fd);
  10190. else if (O_CLOEXEC == 0) /* old libc */
  10191. close_on_exec_on(fd);
  10192. setinputfd(fd, flags & INPUT_PUSH_FILE);
  10193. out:
  10194. INT_ON;
  10195. return fd;
  10196. }
  10197. /*
  10198. * Like setinputfile, but takes input from a string.
  10199. */
  10200. static void
  10201. setinputstring(char *string)
  10202. {
  10203. INT_OFF;
  10204. pushfile();
  10205. g_parsefile->next_to_pgetc = string;
  10206. g_parsefile->left_in_line = strlen(string);
  10207. g_parsefile->buf = NULL;
  10208. g_parsefile->linno = lineno;
  10209. INT_ON;
  10210. }
  10211. /*
  10212. * Routines to check for mail.
  10213. */
  10214. #if ENABLE_ASH_MAIL
  10215. /* Hash of mtimes of mailboxes */
  10216. static unsigned mailtime_hash;
  10217. /* Set if MAIL or MAILPATH is changed. */
  10218. static smallint mail_var_path_changed;
  10219. /*
  10220. * Print appropriate message(s) if mail has arrived.
  10221. * If mail_var_path_changed is set,
  10222. * then the value of MAIL has mail_var_path_changed,
  10223. * so we just update the values.
  10224. */
  10225. static void
  10226. chkmail(void)
  10227. {
  10228. const char *mpath;
  10229. char *p;
  10230. char *q;
  10231. unsigned new_hash;
  10232. struct stackmark smark;
  10233. struct stat statb;
  10234. setstackmark(&smark);
  10235. mpath = mpathset() ? mpathval() : mailval();
  10236. new_hash = 0;
  10237. for (;;) {
  10238. int len;
  10239. len = padvance_magic(&mpath, nullstr, 2);
  10240. if (!len)
  10241. break;
  10242. p = stackblock();
  10243. break;
  10244. if (*p == '\0')
  10245. continue;
  10246. for (q = p; *q; q++)
  10247. continue;
  10248. #if DEBUG
  10249. if (q[-1] != '/')
  10250. abort();
  10251. #endif
  10252. q[-1] = '\0'; /* delete trailing '/' */
  10253. if (stat(p, &statb) < 0) {
  10254. continue;
  10255. }
  10256. /* Very simplistic "hash": just a sum of all mtimes */
  10257. new_hash += (unsigned)statb.st_mtime;
  10258. }
  10259. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  10260. if (mailtime_hash != 0)
  10261. out2str("you have mail\n");
  10262. mailtime_hash = new_hash;
  10263. }
  10264. mail_var_path_changed = 0;
  10265. popstackmark(&smark);
  10266. }
  10267. static void FAST_FUNC
  10268. changemail(const char *val UNUSED_PARAM)
  10269. {
  10270. mail_var_path_changed = 1;
  10271. }
  10272. #endif /* ASH_MAIL */
  10273. /* ============ ??? */
  10274. /*
  10275. * Set the shell parameters.
  10276. */
  10277. static void
  10278. setparam(char **argv)
  10279. {
  10280. char **newparam;
  10281. char **ap;
  10282. int nparam;
  10283. for (nparam = 0; argv[nparam]; nparam++)
  10284. continue;
  10285. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10286. while (*argv) {
  10287. *ap++ = ckstrdup(*argv++);
  10288. }
  10289. *ap = NULL;
  10290. freeparam(&shellparam);
  10291. shellparam.malloced = 1;
  10292. shellparam.nparam = nparam;
  10293. shellparam.p = newparam;
  10294. #if ENABLE_ASH_GETOPTS
  10295. shellparam.optind = 1;
  10296. shellparam.optoff = -1;
  10297. #endif
  10298. }
  10299. /*
  10300. * Process shell options. The global variable argptr contains a pointer
  10301. * to the argument list; we advance it past the options.
  10302. *
  10303. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10304. * For a non-interactive shell, an error condition encountered
  10305. * by a special built-in ... shall cause the shell to write a diagnostic message
  10306. * to standard error and exit as shown in the following table:
  10307. * Error Special Built-In
  10308. * ...
  10309. * Utility syntax error (option or operand error) Shall exit
  10310. * ...
  10311. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10312. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10313. * and shell continues), and people rely on this behavior!
  10314. * Testcase:
  10315. * set -o barfoo 2>/dev/null
  10316. * echo $?
  10317. *
  10318. * Oh well. Let's mimic that.
  10319. */
  10320. static int
  10321. plus_minus_o(char *name, int val)
  10322. {
  10323. int i;
  10324. if (name) {
  10325. for (i = 0; i < NOPTS; i++) {
  10326. if (strcmp(name, optnames(i)) == 0) {
  10327. optlist[i] = val;
  10328. return 0;
  10329. }
  10330. }
  10331. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10332. return 1;
  10333. }
  10334. for (i = 0; i < NOPTS; i++) {
  10335. if (optnames(i)[0] == '\0')
  10336. continue;
  10337. if (val) {
  10338. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10339. } else {
  10340. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10341. }
  10342. }
  10343. return 0;
  10344. }
  10345. static void
  10346. setoption(int flag, int val)
  10347. {
  10348. int i;
  10349. for (i = 0; i < NOPTS; i++) {
  10350. if (optletters(i) == flag && optnames(i)[0] != '\0') {
  10351. optlist[i] = val;
  10352. return;
  10353. }
  10354. }
  10355. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10356. /* NOTREACHED */
  10357. }
  10358. /* If login_sh is not NULL, we are called to parse command line opts,
  10359. * not "set -opts"
  10360. */
  10361. static int
  10362. options(int *login_sh)
  10363. {
  10364. char *p;
  10365. int val;
  10366. int c;
  10367. if (login_sh != NULL) /* if we came from startup code */
  10368. minusc = NULL;
  10369. while ((p = *argptr) != NULL) {
  10370. c = *p++;
  10371. if (c != '-' && c != '+')
  10372. break;
  10373. argptr++;
  10374. val = 0; /* val = 0 if c == '+' */
  10375. if (c == '-') {
  10376. val = 1;
  10377. if (p[0] == '\0' || LONE_DASH(p)) {
  10378. if (login_sh == NULL) { /* we came from setcmd() */
  10379. /* "-" means turn off -x and -v */
  10380. if (p[0] == '\0')
  10381. xflag = vflag = 0;
  10382. /* "--" means reset params */
  10383. else if (*argptr == NULL)
  10384. setparam(argptr);
  10385. }
  10386. break; /* "-" or "--" terminates options */
  10387. }
  10388. }
  10389. /* first char was + or - */
  10390. while ((c = *p++) != '\0') {
  10391. if (login_sh != NULL) { /* if we came from startup code */
  10392. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10393. if (c == 'c') {
  10394. minusc = p; /* command is after shell args */
  10395. cflag = 1;
  10396. continue;
  10397. }
  10398. if (c == 's') { /* -s, +s */
  10399. sflag = 1;
  10400. continue;
  10401. }
  10402. if (c == 'i') { /* -i, +i */
  10403. iflag = 1;
  10404. continue;
  10405. }
  10406. if (c == 'l') {
  10407. *login_sh = 1; /* -l or +l == --login */
  10408. continue;
  10409. }
  10410. /* bash does not accept +-login, we also won't */
  10411. if (val && (c == '-')) { /* long options */
  10412. if (strcmp(p, "login") == 0) {
  10413. *login_sh = 1;
  10414. }
  10415. /* TODO: --noprofile: e.g. if I want to run emergency shell from sulogin,
  10416. * I want minimal/no shell init scripts - but it insists on running it as "-ash"...
  10417. */
  10418. break;
  10419. }
  10420. }
  10421. if (c == 'o') {
  10422. if (plus_minus_o(*argptr, val)) {
  10423. /* it already printed err message */
  10424. return 1; /* error */
  10425. }
  10426. if (*argptr)
  10427. argptr++;
  10428. } else {
  10429. setoption(c, val);
  10430. }
  10431. }
  10432. }
  10433. return 0;
  10434. }
  10435. /*
  10436. * The shift builtin command.
  10437. */
  10438. static int FAST_FUNC
  10439. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10440. {
  10441. int n;
  10442. char **ap1, **ap2;
  10443. n = 1;
  10444. if (argv[1])
  10445. n = number(argv[1]);
  10446. if (n > shellparam.nparam)
  10447. return 1;
  10448. INT_OFF;
  10449. shellparam.nparam -= n;
  10450. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10451. if (shellparam.malloced)
  10452. free(*ap1);
  10453. }
  10454. ap2 = shellparam.p;
  10455. while ((*ap2++ = *ap1++) != NULL)
  10456. continue;
  10457. #if ENABLE_ASH_GETOPTS
  10458. shellparam.optind = 1;
  10459. shellparam.optoff = -1;
  10460. #endif
  10461. INT_ON;
  10462. return 0;
  10463. }
  10464. /*
  10465. * POSIX requires that 'set' (but not export or readonly) output the
  10466. * variables in lexicographic order - by the locale's collating order (sigh).
  10467. * Maybe we could keep them in an ordered balanced binary tree
  10468. * instead of hashed lists.
  10469. * For now just roll 'em through qsort for printing...
  10470. */
  10471. static int
  10472. showvars(const char *sep_prefix, int on, int off)
  10473. {
  10474. const char *sep;
  10475. char **ep, **epend;
  10476. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10477. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10478. sep = *sep_prefix ? " " : sep_prefix;
  10479. for (; ep < epend; ep++) {
  10480. const char *p;
  10481. const char *q;
  10482. p = endofname(*ep);
  10483. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10484. * makes "export -p" to have output not suitable for "eval":
  10485. * import os
  10486. * os.environ["test-test"]="test"
  10487. * if os.fork() == 0:
  10488. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10489. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10490. */
  10491. q = nullstr;
  10492. if (*p == '=')
  10493. q = single_quote(++p);
  10494. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10495. }
  10496. return 0;
  10497. }
  10498. /*
  10499. * The set command builtin.
  10500. */
  10501. static int FAST_FUNC
  10502. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10503. {
  10504. int retval;
  10505. if (!argv[1])
  10506. return showvars(nullstr, 0, VUNSET);
  10507. INT_OFF;
  10508. retval = options(/*login_sh:*/ NULL);
  10509. if (retval == 0) { /* if no parse error... */
  10510. optschanged();
  10511. if (*argptr != NULL) {
  10512. setparam(argptr);
  10513. }
  10514. }
  10515. INT_ON;
  10516. return retval;
  10517. }
  10518. #if ENABLE_ASH_RANDOM_SUPPORT
  10519. static void FAST_FUNC
  10520. change_random(const char *value)
  10521. {
  10522. uint32_t t;
  10523. if (value == NULL) {
  10524. /* "get", generate */
  10525. t = next_random(&random_gen);
  10526. /* set without recursion */
  10527. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10528. vrandom.flags &= ~VNOFUNC;
  10529. } else {
  10530. /* set/reset */
  10531. t = strtoul(value, NULL, 10);
  10532. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10533. }
  10534. }
  10535. #endif
  10536. #if BASH_EPOCH_VARS
  10537. static void FAST_FUNC
  10538. change_epoch(struct var *vepoch, const char *fmt)
  10539. {
  10540. struct timeval tv;
  10541. char buffer[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
  10542. xgettimeofday(&tv);
  10543. sprintf(buffer, fmt, (unsigned long long)tv.tv_sec, (unsigned)tv.tv_usec);
  10544. setvar(vepoch->var_text, buffer, VNOFUNC);
  10545. vepoch->flags &= ~VNOFUNC;
  10546. }
  10547. static void FAST_FUNC
  10548. change_seconds(const char *value UNUSED_PARAM)
  10549. {
  10550. change_epoch(&vepochs, "%llu");
  10551. }
  10552. static void FAST_FUNC
  10553. change_realtime(const char *value UNUSED_PARAM)
  10554. {
  10555. change_epoch(&vepochr, "%llu.%06u");
  10556. }
  10557. #endif
  10558. #if ENABLE_ASH_GETOPTS
  10559. static int
  10560. getopts(char *optstr, char *optvar, char **optfirst)
  10561. {
  10562. char *p, *q;
  10563. char c = '?';
  10564. int done = 0;
  10565. char sbuf[2];
  10566. char **optnext;
  10567. int ind = shellparam.optind;
  10568. int off = shellparam.optoff;
  10569. sbuf[1] = '\0';
  10570. shellparam.optind = -1;
  10571. optnext = optfirst + ind - 1;
  10572. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10573. p = NULL;
  10574. else
  10575. p = optnext[-1] + off;
  10576. if (p == NULL || *p == '\0') {
  10577. /* Current word is done, advance */
  10578. p = *optnext;
  10579. if (p == NULL || *p != '-' || *++p == '\0') {
  10580. atend:
  10581. unsetvar("OPTARG");
  10582. p = NULL;
  10583. done = 1;
  10584. goto out;
  10585. }
  10586. optnext++;
  10587. if (LONE_DASH(p)) /* check for "--" */
  10588. goto atend;
  10589. }
  10590. c = *p++;
  10591. for (q = optstr; *q != c;) {
  10592. if (*q == '\0') {
  10593. /* OPTERR is a bashism */
  10594. const char *cp = lookupvar("OPTERR");
  10595. if ((cp && LONE_CHAR(cp, '0'))
  10596. || (optstr[0] == ':')
  10597. ) {
  10598. sbuf[0] = c;
  10599. /*sbuf[1] = '\0'; - already is */
  10600. setvar0("OPTARG", sbuf);
  10601. } else {
  10602. fprintf(stderr, "Illegal option -%c\n", c);
  10603. unsetvar("OPTARG");
  10604. }
  10605. c = '?';
  10606. goto out;
  10607. }
  10608. if (*++q == ':')
  10609. q++;
  10610. }
  10611. if (*++q == ':') {
  10612. if (*p == '\0' && (p = *optnext) == NULL) {
  10613. /* OPTERR is a bashism */
  10614. const char *cp = lookupvar("OPTERR");
  10615. if ((cp && LONE_CHAR(cp, '0'))
  10616. || (optstr[0] == ':')
  10617. ) {
  10618. sbuf[0] = c;
  10619. /*sbuf[1] = '\0'; - already is */
  10620. setvar0("OPTARG", sbuf);
  10621. c = ':';
  10622. } else {
  10623. fprintf(stderr, "No arg for -%c option\n", c);
  10624. unsetvar("OPTARG");
  10625. c = '?';
  10626. }
  10627. goto out;
  10628. }
  10629. if (p == *optnext)
  10630. optnext++;
  10631. setvar0("OPTARG", p);
  10632. p = NULL;
  10633. } else
  10634. setvar0("OPTARG", nullstr);
  10635. out:
  10636. ind = optnext - optfirst + 1;
  10637. setvar("OPTIND", itoa(ind), VNOFUNC);
  10638. sbuf[0] = c;
  10639. /*sbuf[1] = '\0'; - already is */
  10640. setvar0(optvar, sbuf);
  10641. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10642. shellparam.optind = ind;
  10643. return done;
  10644. }
  10645. /*
  10646. * The getopts builtin. Shellparam.optnext points to the next argument
  10647. * to be processed. Shellparam.optptr points to the next character to
  10648. * be processed in the current argument. If shellparam.optnext is NULL,
  10649. * then it's the first time getopts has been called.
  10650. */
  10651. static int FAST_FUNC
  10652. getoptscmd(int argc, char **argv)
  10653. {
  10654. char **optbase;
  10655. if (argc < 3)
  10656. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10657. if (argc == 3) {
  10658. optbase = shellparam.p;
  10659. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10660. shellparam.optind = 1;
  10661. shellparam.optoff = -1;
  10662. }
  10663. } else {
  10664. optbase = &argv[3];
  10665. if ((unsigned)shellparam.optind > argc - 2) {
  10666. shellparam.optind = 1;
  10667. shellparam.optoff = -1;
  10668. }
  10669. }
  10670. return getopts(argv[1], argv[2], optbase);
  10671. }
  10672. #endif /* ASH_GETOPTS */
  10673. /* ============ Shell parser */
  10674. struct heredoc {
  10675. struct heredoc *next; /* next here document in list */
  10676. union node *here; /* redirection node */
  10677. char *eofmark; /* string indicating end of input */
  10678. smallint striptabs; /* if set, strip leading tabs */
  10679. };
  10680. static smallint tokpushback; /* last token pushed back */
  10681. static smallint quoteflag; /* set if (part of) last token was quoted */
  10682. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10683. static struct heredoc *heredoclist; /* list of here documents to read */
  10684. static char *wordtext; /* text of last word returned by readtoken */
  10685. static struct nodelist *backquotelist;
  10686. static union node *redirnode;
  10687. static struct heredoc *heredoc;
  10688. static const char *
  10689. tokname(char *buf, int tok)
  10690. {
  10691. if (tok < TSEMI)
  10692. return tokname_array[tok];
  10693. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10694. return buf;
  10695. }
  10696. /* raise_error_unexpected_syntax:
  10697. * Called when an unexpected token is read during the parse. The argument
  10698. * is the token that is expected, or -1 if more than one type of token can
  10699. * occur at this point.
  10700. */
  10701. static void raise_error_unexpected_syntax(int) NORETURN;
  10702. static void
  10703. raise_error_unexpected_syntax(int token)
  10704. {
  10705. char msg[64];
  10706. char buf[16];
  10707. int l;
  10708. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10709. if (token >= 0)
  10710. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10711. raise_error_syntax(msg);
  10712. /* NOTREACHED */
  10713. }
  10714. /* parsing is heavily cross-recursive, need these forward decls */
  10715. static union node *andor(void);
  10716. static union node *pipeline(void);
  10717. static union node *parse_command(void);
  10718. static void parseheredoc(void);
  10719. static int readtoken(void);
  10720. static union node *
  10721. list(int nlflag)
  10722. {
  10723. int chknl = nlflag & 1 ? 0 : CHKNL;
  10724. union node *n1, *n2, *n3;
  10725. int tok;
  10726. n1 = NULL;
  10727. for (;;) {
  10728. checkkwd = chknl | CHKKWD | CHKALIAS;
  10729. tok = readtoken();
  10730. switch (tok) {
  10731. case TNL:
  10732. parseheredoc();
  10733. return n1;
  10734. case TEOF:
  10735. if (!n1 && !chknl)
  10736. n1 = NODE_EOF;
  10737. out_eof:
  10738. parseheredoc();
  10739. tokpushback++;
  10740. lasttoken = TEOF;
  10741. return n1;
  10742. }
  10743. tokpushback++;
  10744. if (nlflag == 2 && ((1 << tok) & tokendlist))
  10745. return n1;
  10746. nlflag |= 2;
  10747. n2 = andor();
  10748. tok = readtoken();
  10749. if (tok == TBACKGND) {
  10750. if (n2->type == NPIPE) {
  10751. n2->npipe.pipe_backgnd = 1;
  10752. } else {
  10753. if (n2->type != NREDIR) {
  10754. n3 = stzalloc(sizeof(struct nredir));
  10755. n3->nredir.n = n2;
  10756. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10757. n2 = n3;
  10758. }
  10759. n2->type = NBACKGND;
  10760. }
  10761. }
  10762. if (n1 == NULL) {
  10763. n1 = n2;
  10764. } else {
  10765. n3 = stzalloc(sizeof(struct nbinary));
  10766. n3->type = NSEMI;
  10767. n3->nbinary.ch1 = n1;
  10768. n3->nbinary.ch2 = n2;
  10769. n1 = n3;
  10770. }
  10771. switch (tok) {
  10772. case TEOF:
  10773. goto out_eof;
  10774. case TNL:
  10775. tokpushback = 1;
  10776. /* fall through */
  10777. case TBACKGND:
  10778. case TSEMI:
  10779. break;
  10780. default:
  10781. if (!chknl)
  10782. raise_error_unexpected_syntax(-1);
  10783. tokpushback = 1;
  10784. return n1;
  10785. }
  10786. }
  10787. }
  10788. static union node *
  10789. andor(void)
  10790. {
  10791. union node *n1, *n2, *n3;
  10792. int t;
  10793. n1 = pipeline();
  10794. for (;;) {
  10795. t = readtoken();
  10796. if (t == TAND) {
  10797. t = NAND;
  10798. } else if (t == TOR) {
  10799. t = NOR;
  10800. } else {
  10801. tokpushback = 1;
  10802. return n1;
  10803. }
  10804. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10805. n2 = pipeline();
  10806. n3 = stzalloc(sizeof(struct nbinary));
  10807. n3->type = t;
  10808. n3->nbinary.ch1 = n1;
  10809. n3->nbinary.ch2 = n2;
  10810. n1 = n3;
  10811. }
  10812. }
  10813. static union node *
  10814. pipeline(void)
  10815. {
  10816. union node *n1, *n2, *pipenode;
  10817. struct nodelist *lp, *prev;
  10818. int negate;
  10819. negate = 0;
  10820. TRACE(("pipeline: entered\n"));
  10821. if (readtoken() == TNOT) {
  10822. negate = !negate;
  10823. checkkwd = CHKKWD | CHKALIAS;
  10824. } else
  10825. tokpushback = 1;
  10826. n1 = parse_command();
  10827. if (readtoken() == TPIPE) {
  10828. pipenode = stzalloc(sizeof(struct npipe));
  10829. pipenode->type = NPIPE;
  10830. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10831. lp = stzalloc(sizeof(struct nodelist));
  10832. pipenode->npipe.cmdlist = lp;
  10833. lp->n = n1;
  10834. do {
  10835. prev = lp;
  10836. lp = stzalloc(sizeof(struct nodelist));
  10837. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10838. lp->n = parse_command();
  10839. prev->next = lp;
  10840. } while (readtoken() == TPIPE);
  10841. lp->next = NULL;
  10842. n1 = pipenode;
  10843. }
  10844. tokpushback = 1;
  10845. if (negate) {
  10846. n2 = stzalloc(sizeof(struct nnot));
  10847. n2->type = NNOT;
  10848. n2->nnot.com = n1;
  10849. return n2;
  10850. }
  10851. return n1;
  10852. }
  10853. static union node *
  10854. makename(void)
  10855. {
  10856. union node *n;
  10857. n = stzalloc(sizeof(struct narg));
  10858. n->type = NARG;
  10859. /*n->narg.next = NULL; - stzalloc did it */
  10860. n->narg.text = wordtext;
  10861. n->narg.backquote = backquotelist;
  10862. return n;
  10863. }
  10864. static void
  10865. fixredir(union node *n, const char *text, int err)
  10866. {
  10867. int fd;
  10868. TRACE(("Fix redir %s %d\n", text, err));
  10869. if (!err)
  10870. n->ndup.vname = NULL;
  10871. fd = bb_strtou(text, NULL, 10);
  10872. if (!errno && fd >= 0)
  10873. n->ndup.dupfd = fd;
  10874. else if (LONE_DASH(text))
  10875. n->ndup.dupfd = -1;
  10876. else {
  10877. if (err)
  10878. raise_error_syntax("bad fd number");
  10879. n->ndup.vname = makename();
  10880. }
  10881. }
  10882. static void
  10883. parsefname(void)
  10884. {
  10885. union node *n = redirnode;
  10886. if (n->type == NHERE)
  10887. checkkwd = CHKEOFMARK;
  10888. if (readtoken() != TWORD)
  10889. raise_error_unexpected_syntax(-1);
  10890. if (n->type == NHERE) {
  10891. struct heredoc *here = heredoc;
  10892. struct heredoc *p;
  10893. if (quoteflag == 0)
  10894. n->type = NXHERE;
  10895. TRACE(("Here document %d\n", n->type));
  10896. rmescapes(wordtext, 0, NULL);
  10897. here->eofmark = wordtext;
  10898. here->next = NULL;
  10899. if (heredoclist == NULL)
  10900. heredoclist = here;
  10901. else {
  10902. for (p = heredoclist; p->next; p = p->next)
  10903. continue;
  10904. p->next = here;
  10905. }
  10906. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10907. fixredir(n, wordtext, 0);
  10908. } else {
  10909. n->nfile.fname = makename();
  10910. }
  10911. }
  10912. static union node *
  10913. simplecmd(void)
  10914. {
  10915. union node *args, **app;
  10916. union node *n = NULL;
  10917. union node *vars, **vpp;
  10918. union node **rpp, *redir;
  10919. int savecheckkwd;
  10920. int savelinno;
  10921. #if BASH_TEST2
  10922. smallint double_brackets_flag = 0;
  10923. #endif
  10924. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10925. args = NULL;
  10926. app = &args;
  10927. vars = NULL;
  10928. vpp = &vars;
  10929. redir = NULL;
  10930. rpp = &redir;
  10931. savecheckkwd = CHKALIAS;
  10932. savelinno = g_parsefile->linno;
  10933. for (;;) {
  10934. int t;
  10935. checkkwd = savecheckkwd;
  10936. t = readtoken();
  10937. switch (t) {
  10938. #if BASH_FUNCTION
  10939. case TFUNCTION:
  10940. if (readtoken() != TWORD)
  10941. raise_error_unexpected_syntax(TWORD);
  10942. tokpushback = 1;
  10943. function_flag = 1;
  10944. break;
  10945. #endif
  10946. #if BASH_TEST2
  10947. case TAND: /* "&&" */
  10948. case TOR: /* "||" */
  10949. if (!double_brackets_flag) {
  10950. tokpushback = 1;
  10951. goto out;
  10952. }
  10953. /* pass "&&" or "||" to [[ ]] as literal args */
  10954. wordtext = (char *) (t == TAND ? "&&" : "||");
  10955. #endif
  10956. case TWORD:
  10957. n = stzalloc(sizeof(struct narg));
  10958. n->type = NARG;
  10959. /*n->narg.next = NULL; - stzalloc did it */
  10960. n->narg.text = wordtext;
  10961. #if BASH_TEST2
  10962. if (strcmp("[[", wordtext) == 0)
  10963. double_brackets_flag = 1;
  10964. else if (strcmp("]]", wordtext) == 0)
  10965. double_brackets_flag = 0;
  10966. #endif
  10967. n->narg.backquote = backquotelist;
  10968. if (savecheckkwd && isassignment(wordtext)) {
  10969. *vpp = n;
  10970. vpp = &n->narg.next;
  10971. } else {
  10972. *app = n;
  10973. app = &n->narg.next;
  10974. savecheckkwd = 0;
  10975. }
  10976. #if BASH_FUNCTION
  10977. if (function_flag) {
  10978. checkkwd = CHKNL | CHKKWD;
  10979. t = readtoken();
  10980. tokpushback = 1;
  10981. switch (t) {
  10982. case TBEGIN:
  10983. case TIF:
  10984. case TCASE:
  10985. case TUNTIL:
  10986. case TWHILE:
  10987. case TFOR:
  10988. goto do_func;
  10989. case TLP:
  10990. function_flag = 0;
  10991. break;
  10992. # if BASH_TEST2
  10993. case TWORD:
  10994. if (strcmp("[[", wordtext) == 0)
  10995. goto do_func;
  10996. /* fall through */
  10997. # endif
  10998. default:
  10999. raise_error_unexpected_syntax(-1);
  11000. }
  11001. }
  11002. #endif
  11003. break;
  11004. case TREDIR:
  11005. *rpp = n = redirnode;
  11006. rpp = &n->nfile.next;
  11007. parsefname(); /* read name of redirection file */
  11008. break;
  11009. case TLP:
  11010. IF_BASH_FUNCTION(do_func:)
  11011. if (args && app == &args->narg.next
  11012. && !vars && !redir
  11013. ) {
  11014. struct builtincmd *bcmd;
  11015. const char *name;
  11016. /* We have a function */
  11017. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  11018. raise_error_unexpected_syntax(TRP);
  11019. name = n->narg.text;
  11020. if (!goodname(name)
  11021. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  11022. ) {
  11023. raise_error_syntax("bad function name");
  11024. }
  11025. n->type = NDEFUN;
  11026. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11027. n->ndefun.text = n->narg.text;
  11028. n->ndefun.linno = g_parsefile->linno;
  11029. n->ndefun.body = parse_command();
  11030. return n;
  11031. }
  11032. IF_BASH_FUNCTION(function_flag = 0;)
  11033. /* fall through */
  11034. default:
  11035. tokpushback = 1;
  11036. goto out;
  11037. }
  11038. }
  11039. out:
  11040. *app = NULL;
  11041. *vpp = NULL;
  11042. *rpp = NULL;
  11043. n = stzalloc(sizeof(struct ncmd));
  11044. if (NCMD != 0)
  11045. n->type = NCMD;
  11046. n->ncmd.linno = savelinno;
  11047. n->ncmd.args = args;
  11048. n->ncmd.assign = vars;
  11049. n->ncmd.redirect = redir;
  11050. return n;
  11051. }
  11052. static union node *
  11053. parse_command(void)
  11054. {
  11055. union node *n1, *n2;
  11056. union node *ap, **app;
  11057. union node *cp, **cpp;
  11058. union node *redir, **rpp;
  11059. union node **rpp2;
  11060. int t;
  11061. int savelinno;
  11062. redir = NULL;
  11063. rpp2 = &redir;
  11064. savelinno = g_parsefile->linno;
  11065. switch (readtoken()) {
  11066. default:
  11067. raise_error_unexpected_syntax(-1);
  11068. /* NOTREACHED */
  11069. case TIF:
  11070. n1 = stzalloc(sizeof(struct nif));
  11071. n1->type = NIF;
  11072. n1->nif.test = list(0);
  11073. if (readtoken() != TTHEN)
  11074. raise_error_unexpected_syntax(TTHEN);
  11075. n1->nif.ifpart = list(0);
  11076. n2 = n1;
  11077. while (readtoken() == TELIF) {
  11078. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  11079. n2 = n2->nif.elsepart;
  11080. n2->type = NIF;
  11081. n2->nif.test = list(0);
  11082. if (readtoken() != TTHEN)
  11083. raise_error_unexpected_syntax(TTHEN);
  11084. n2->nif.ifpart = list(0);
  11085. }
  11086. if (lasttoken == TELSE)
  11087. n2->nif.elsepart = list(0);
  11088. else {
  11089. n2->nif.elsepart = NULL;
  11090. tokpushback = 1;
  11091. }
  11092. t = TFI;
  11093. break;
  11094. case TWHILE:
  11095. case TUNTIL: {
  11096. int got;
  11097. n1 = stzalloc(sizeof(struct nbinary));
  11098. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  11099. n1->nbinary.ch1 = list(0);
  11100. got = readtoken();
  11101. if (got != TDO) {
  11102. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  11103. got == TWORD ? wordtext : ""));
  11104. raise_error_unexpected_syntax(TDO);
  11105. }
  11106. n1->nbinary.ch2 = list(0);
  11107. t = TDONE;
  11108. break;
  11109. }
  11110. case TFOR:
  11111. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  11112. raise_error_syntax("bad for loop variable");
  11113. n1 = stzalloc(sizeof(struct nfor));
  11114. n1->type = NFOR;
  11115. n1->nfor.linno = savelinno;
  11116. n1->nfor.var = wordtext;
  11117. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11118. if (readtoken() == TIN) {
  11119. app = &ap;
  11120. while (readtoken() == TWORD) {
  11121. n2 = stzalloc(sizeof(struct narg));
  11122. n2->type = NARG;
  11123. /*n2->narg.next = NULL; - stzalloc did it */
  11124. n2->narg.text = wordtext;
  11125. n2->narg.backquote = backquotelist;
  11126. *app = n2;
  11127. app = &n2->narg.next;
  11128. }
  11129. *app = NULL;
  11130. n1->nfor.args = ap;
  11131. if (lasttoken != TNL && lasttoken != TSEMI)
  11132. raise_error_unexpected_syntax(-1);
  11133. } else {
  11134. n2 = stzalloc(sizeof(struct narg));
  11135. n2->type = NARG;
  11136. /*n2->narg.next = NULL; - stzalloc did it */
  11137. n2->narg.text = (char *)dolatstr;
  11138. /*n2->narg.backquote = NULL;*/
  11139. n1->nfor.args = n2;
  11140. /*
  11141. * Newline or semicolon here is optional (but note
  11142. * that the original Bourne shell only allowed NL).
  11143. */
  11144. if (lasttoken != TSEMI)
  11145. tokpushback = 1;
  11146. }
  11147. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11148. if (readtoken() != TDO)
  11149. raise_error_unexpected_syntax(TDO);
  11150. n1->nfor.body = list(0);
  11151. t = TDONE;
  11152. break;
  11153. case TCASE:
  11154. n1 = stzalloc(sizeof(struct ncase));
  11155. n1->type = NCASE;
  11156. n1->ncase.linno = savelinno;
  11157. if (readtoken() != TWORD)
  11158. raise_error_unexpected_syntax(TWORD);
  11159. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  11160. n2->type = NARG;
  11161. /*n2->narg.next = NULL; - stzalloc did it */
  11162. n2->narg.text = wordtext;
  11163. n2->narg.backquote = backquotelist;
  11164. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11165. if (readtoken() != TIN)
  11166. raise_error_unexpected_syntax(TIN);
  11167. cpp = &n1->ncase.cases;
  11168. next_case:
  11169. checkkwd = CHKNL | CHKKWD;
  11170. t = readtoken();
  11171. while (t != TESAC) {
  11172. if (lasttoken == TLP)
  11173. readtoken();
  11174. *cpp = cp = stzalloc(sizeof(struct nclist));
  11175. cp->type = NCLIST;
  11176. app = &cp->nclist.pattern;
  11177. for (;;) {
  11178. *app = ap = stzalloc(sizeof(struct narg));
  11179. ap->type = NARG;
  11180. /*ap->narg.next = NULL; - stzalloc did it */
  11181. ap->narg.text = wordtext;
  11182. ap->narg.backquote = backquotelist;
  11183. if (readtoken() != TPIPE)
  11184. break;
  11185. app = &ap->narg.next;
  11186. readtoken();
  11187. }
  11188. //ap->narg.next = NULL;
  11189. if (lasttoken != TRP)
  11190. raise_error_unexpected_syntax(TRP);
  11191. cp->nclist.body = list(2);
  11192. cpp = &cp->nclist.next;
  11193. checkkwd = CHKNL | CHKKWD;
  11194. t = readtoken();
  11195. if (t != TESAC) {
  11196. if (t != TENDCASE)
  11197. raise_error_unexpected_syntax(TENDCASE);
  11198. goto next_case;
  11199. }
  11200. }
  11201. *cpp = NULL;
  11202. goto redir;
  11203. case TLP:
  11204. n1 = stzalloc(sizeof(struct nredir));
  11205. n1->type = NSUBSHELL;
  11206. n1->nredir.linno = savelinno;
  11207. n1->nredir.n = list(0);
  11208. /*n1->nredir.redirect = NULL; - stzalloc did it */
  11209. t = TRP;
  11210. break;
  11211. case TBEGIN:
  11212. n1 = list(0);
  11213. t = TEND;
  11214. break;
  11215. IF_BASH_FUNCTION(case TFUNCTION:)
  11216. case TWORD:
  11217. case TREDIR:
  11218. tokpushback = 1;
  11219. return simplecmd();
  11220. }
  11221. if (readtoken() != t)
  11222. raise_error_unexpected_syntax(t);
  11223. redir:
  11224. /* Now check for redirection which may follow command */
  11225. checkkwd = CHKKWD | CHKALIAS;
  11226. rpp = rpp2;
  11227. while (readtoken() == TREDIR) {
  11228. *rpp = n2 = redirnode;
  11229. rpp = &n2->nfile.next;
  11230. parsefname();
  11231. }
  11232. tokpushback = 1;
  11233. *rpp = NULL;
  11234. if (redir) {
  11235. if (n1->type != NSUBSHELL) {
  11236. n2 = stzalloc(sizeof(struct nredir));
  11237. n2->type = NREDIR;
  11238. n2->nredir.linno = savelinno;
  11239. n2->nredir.n = n1;
  11240. n1 = n2;
  11241. }
  11242. n1->nredir.redirect = redir;
  11243. }
  11244. return n1;
  11245. }
  11246. #if BASH_DOLLAR_SQUOTE
  11247. static int
  11248. decode_dollar_squote(void)
  11249. {
  11250. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  11251. int c, cnt;
  11252. char *p;
  11253. char buf[4];
  11254. c = pgetc();
  11255. p = strchr(C_escapes, c);
  11256. if (p) {
  11257. buf[0] = c;
  11258. p = buf;
  11259. cnt = 3;
  11260. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  11261. do {
  11262. c = pgetc();
  11263. *++p = c;
  11264. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  11265. pungetc();
  11266. } else if (c == 'x') { /* \xHH */
  11267. do {
  11268. c = pgetc();
  11269. *++p = c;
  11270. } while (isxdigit(c) && --cnt);
  11271. pungetc();
  11272. if (cnt == 3) { /* \x but next char is "bad" */
  11273. c = 'x';
  11274. goto unrecognized;
  11275. }
  11276. } else { /* simple seq like \\ or \t */
  11277. p++;
  11278. }
  11279. *p = '\0';
  11280. p = buf;
  11281. c = bb_process_escape_sequence((void*)&p);
  11282. } else { /* unrecognized "\z": print both chars unless ' or " */
  11283. if (c != '\'' && c != '"') {
  11284. unrecognized:
  11285. c |= 0x100; /* "please encode \, then me" */
  11286. }
  11287. }
  11288. return c;
  11289. }
  11290. #endif
  11291. /* Used by expandstr to get here-doc like behaviour. */
  11292. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  11293. static ALWAYS_INLINE int
  11294. realeofmark(const char *eofmark)
  11295. {
  11296. return eofmark && eofmark != FAKEEOFMARK;
  11297. }
  11298. /*
  11299. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  11300. * is not NULL, read a here document. In the latter case, eofmark is the
  11301. * word which marks the end of the document and striptabs is true if
  11302. * leading tabs should be stripped from the document. The argument c
  11303. * is the first character of the input token or document.
  11304. *
  11305. * Because C does not have internal subroutines, I have simulated them
  11306. * using goto's to implement the subroutine linkage. The following macros
  11307. * will run code that appears at the end of readtoken1.
  11308. */
  11309. #define CHECKEND() {goto checkend; checkend_return:;}
  11310. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  11311. #define PARSESUB() {goto parsesub; parsesub_return:;}
  11312. #define PARSEBACKQOLD() {style = OLD; goto parsebackq; parsebackq_oldreturn:;}
  11313. #define PARSEBACKQNEW() {style = NEW; goto parsebackq; parsebackq_newreturn:;}
  11314. #define PARSEPROCSUB() {style = PSUB; goto parsebackq; parsebackq_psreturn:;}
  11315. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  11316. static int
  11317. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  11318. {
  11319. /* NB: syntax parameter fits into smallint */
  11320. /* c parameter is an unsigned char or PEOF */
  11321. char *out;
  11322. size_t len;
  11323. struct nodelist *bqlist;
  11324. smallint quotef;
  11325. smallint style;
  11326. enum { OLD, NEW, PSUB };
  11327. #define oldstyle (style == OLD)
  11328. smallint pssyntax; /* we are expanding a prompt string */
  11329. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  11330. /* syntax stack */
  11331. struct synstack synbase = { };
  11332. struct synstack *synstack = &synbase;
  11333. #if ENABLE_ASH_EXPAND_PRMT
  11334. pssyntax = (syntax == PSSYNTAX);
  11335. if (pssyntax)
  11336. syntax = DQSYNTAX;
  11337. #else
  11338. pssyntax = 0; /* constant */
  11339. #endif
  11340. synstack->syntax = syntax;
  11341. if (syntax == DQSYNTAX)
  11342. synstack->dblquote = 1;
  11343. quotef = 0;
  11344. bqlist = NULL;
  11345. STARTSTACKSTR(out);
  11346. loop:
  11347. /* For each line, until end of word */
  11348. CHECKEND(); /* set c to PEOF if at end of here document */
  11349. for (;;) { /* until end of line or end of word */
  11350. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11351. switch (SIT(c, synstack->syntax)) {
  11352. case CNL: /* '\n' */
  11353. if (synstack->syntax == BASESYNTAX
  11354. && !synstack->varnest
  11355. ) {
  11356. goto endword; /* exit outer loop */
  11357. }
  11358. USTPUTC(c, out);
  11359. nlprompt();
  11360. c = pgetc_top(synstack);
  11361. goto loop; /* continue outer loop */
  11362. case CWORD:
  11363. USTPUTC(c, out);
  11364. break;
  11365. case CCTL:
  11366. #if BASH_DOLLAR_SQUOTE
  11367. if (c == '\\' && bash_dollar_squote) {
  11368. c = decode_dollar_squote();
  11369. if (c == '\0') {
  11370. /* skip $'\000', $'\x00' (like bash) */
  11371. break;
  11372. }
  11373. if (c & 0x100) {
  11374. /* Unknown escape. Encode as '\z' */
  11375. c = (unsigned char)c;
  11376. if (eofmark == NULL || synstack->dblquote)
  11377. USTPUTC(CTLESC, out);
  11378. USTPUTC('\\', out);
  11379. }
  11380. }
  11381. #endif
  11382. if (!eofmark || synstack->dblquote || synstack->varnest)
  11383. USTPUTC(CTLESC, out);
  11384. USTPUTC(c, out);
  11385. break;
  11386. case CBACK: /* backslash */
  11387. c = pgetc();
  11388. if (c == PEOF) {
  11389. USTPUTC(CTLESC, out);
  11390. USTPUTC('\\', out);
  11391. pungetc();
  11392. } else {
  11393. if (pssyntax && c == '$') {
  11394. USTPUTC(CTLESC, out);
  11395. USTPUTC('\\', out);
  11396. }
  11397. /* Backslash is retained if we are in "str"
  11398. * and next char isn't dquote-special.
  11399. */
  11400. if (synstack->dblquote
  11401. && c != '\\'
  11402. && c != '`'
  11403. && c != '$'
  11404. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11405. && (c != '}' || !synstack->varnest)
  11406. ) {
  11407. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11408. USTPUTC('\\', out);
  11409. }
  11410. USTPUTC(CTLESC, out);
  11411. USTPUTC(c, out);
  11412. quotef = 1;
  11413. }
  11414. break;
  11415. case CSQUOTE:
  11416. synstack->syntax = SQSYNTAX;
  11417. quotemark:
  11418. if (eofmark == NULL) {
  11419. USTPUTC(CTLQUOTEMARK, out);
  11420. }
  11421. break;
  11422. case CDQUOTE:
  11423. synstack->syntax = DQSYNTAX;
  11424. synstack->dblquote = 1;
  11425. toggledq:
  11426. if (synstack->varnest)
  11427. synstack->innerdq ^= 1;
  11428. goto quotemark;
  11429. case CENDQUOTE:
  11430. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11431. if (eofmark != NULL && synstack->varnest == 0) {
  11432. USTPUTC(c, out);
  11433. break;
  11434. }
  11435. if (synstack->dqvarnest == 0) {
  11436. synstack->syntax = BASESYNTAX;
  11437. synstack->dblquote = 0;
  11438. }
  11439. quotef = 1;
  11440. if (c == '"')
  11441. goto toggledq;
  11442. goto quotemark;
  11443. case CVAR: /* '$' */
  11444. PARSESUB(); /* parse substitution */
  11445. break;
  11446. case CENDVAR: /* '}' */
  11447. if (!synstack->innerdq && synstack->varnest > 0) {
  11448. if (!--synstack->varnest && synstack->varpushed)
  11449. synstack_pop(&synstack);
  11450. else if (synstack->dqvarnest > 0)
  11451. synstack->dqvarnest--;
  11452. c = CTLENDVAR;
  11453. }
  11454. USTPUTC(c, out);
  11455. break;
  11456. #if ENABLE_FEATURE_SH_MATH
  11457. case CLP: /* '(' in arithmetic */
  11458. synstack->parenlevel++;
  11459. USTPUTC(c, out);
  11460. break;
  11461. case CRP: /* ')' in arithmetic */
  11462. if (synstack->parenlevel > 0) {
  11463. synstack->parenlevel--;
  11464. } else {
  11465. if (pgetc_eatbnl() == ')') {
  11466. c = CTLENDARI;
  11467. synstack_pop(&synstack);
  11468. } else {
  11469. /*
  11470. * unbalanced parens
  11471. * (don't 2nd guess - no error)
  11472. */
  11473. pungetc();
  11474. }
  11475. }
  11476. USTPUTC(c, out);
  11477. break;
  11478. #endif
  11479. case CBQUOTE: /* '`' */
  11480. if (checkkwd & CHKEOFMARK) {
  11481. quotef = 1;
  11482. USTPUTC('`', out);
  11483. break;
  11484. }
  11485. PARSEBACKQOLD();
  11486. break;
  11487. case CENDFILE:
  11488. goto endword; /* exit outer loop */
  11489. default:
  11490. if (synstack->varnest == 0) {
  11491. #if BASH_REDIR_OUTPUT
  11492. if (c == '&') {
  11493. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11494. if (pgetc() == '>')
  11495. c = 0x100 + '>'; /* flag &> */
  11496. pungetc();
  11497. }
  11498. #endif
  11499. #if BASH_PROCESS_SUBST
  11500. if (c == '<' || c == '>') {
  11501. if (pgetc() == '(') {
  11502. PARSEPROCSUB();
  11503. break;
  11504. }
  11505. pungetc();
  11506. }
  11507. #endif
  11508. goto endword; /* exit outer loop */
  11509. }
  11510. USTPUTC(c, out);
  11511. }
  11512. c = pgetc_top(synstack);
  11513. } /* for (;;) */
  11514. endword:
  11515. #if ENABLE_FEATURE_SH_MATH
  11516. if (synstack->syntax == ARISYNTAX)
  11517. raise_error_syntax("missing '))'");
  11518. #endif
  11519. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11520. raise_error_syntax("unterminated quoted string");
  11521. if (synstack->varnest != 0) {
  11522. /* { */
  11523. raise_error_syntax("missing '}'");
  11524. }
  11525. USTPUTC('\0', out);
  11526. len = out - (char *)stackblock();
  11527. out = stackblock();
  11528. if (eofmark == NULL) {
  11529. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11530. && quotef == 0
  11531. ) {
  11532. if (isdigit_str9(out)) {
  11533. PARSEREDIR(); /* passed as params: out, c */
  11534. lasttoken = TREDIR;
  11535. return lasttoken;
  11536. }
  11537. /* else: non-number X seen, interpret it
  11538. * as "NNNX>file" = "NNNX >file" */
  11539. }
  11540. pungetc();
  11541. }
  11542. quoteflag = quotef;
  11543. backquotelist = bqlist;
  11544. grabstackblock(len);
  11545. wordtext = out;
  11546. lasttoken = TWORD;
  11547. return lasttoken;
  11548. /* end of readtoken routine */
  11549. /*
  11550. * Check to see whether we are at the end of the here document. When this
  11551. * is called, c is set to the first character of the next input line. If
  11552. * we are at the end of the here document, this routine sets the c to PEOF.
  11553. */
  11554. checkend: {
  11555. if (realeofmark(eofmark)) {
  11556. int markloc;
  11557. char *p;
  11558. if (striptabs) {
  11559. while (c == '\t')
  11560. c = pgetc();
  11561. }
  11562. markloc = out - (char *)stackblock();
  11563. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11564. if (c != *p)
  11565. goto more_heredoc;
  11566. /* FIXME: fails for backslash-newlined terminator:
  11567. * cat <<EOF
  11568. * ...
  11569. * EO\
  11570. * F
  11571. * (see heredoc_bkslash_newline2.tests)
  11572. */
  11573. c = pgetc();
  11574. }
  11575. if (c == '\n' || c == PEOF) {
  11576. c = PEOF;
  11577. if (trap_depth == 0)
  11578. g_parsefile->linno++;
  11579. needprompt = doprompt;
  11580. } else {
  11581. int len_here;
  11582. more_heredoc:
  11583. p = (char *)stackblock() + markloc + 1;
  11584. len_here = out - p;
  11585. if (len_here) {
  11586. len_here -= (c >= PEOF);
  11587. c = p[-1];
  11588. if (len_here) {
  11589. char *str;
  11590. str = alloca(len_here + 1);
  11591. *(char *)mempcpy(str, p, len_here) = '\0';
  11592. pushstring(str, NULL);
  11593. }
  11594. }
  11595. }
  11596. STADJUST((char *)stackblock() + markloc - out, out);
  11597. }
  11598. goto checkend_return;
  11599. }
  11600. /*
  11601. * Parse a redirection operator. The variable "out" points to a string
  11602. * specifying the fd to be redirected. The variable "c" contains the
  11603. * first character of the redirection operator.
  11604. */
  11605. parseredir: {
  11606. /* out is already checked to be a valid number or "" */
  11607. int fd = (*out == '\0' ? -1 : atoi(out));
  11608. union node *np;
  11609. np = stzalloc(sizeof(struct nfile));
  11610. if (c == '>') {
  11611. np->nfile.fd = 1;
  11612. c = pgetc_eatbnl();
  11613. if (c == '>')
  11614. np->type = NAPPEND;
  11615. else if (c == '|')
  11616. np->type = NCLOBBER;
  11617. else if (c == '&')
  11618. np->type = NTOFD;
  11619. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11620. else {
  11621. np->type = NTO;
  11622. pungetc();
  11623. }
  11624. }
  11625. #if BASH_REDIR_OUTPUT
  11626. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11627. np->nfile.fd = 1;
  11628. pgetc(); /* this is '>', no need to check */
  11629. np->type = NTO2;
  11630. }
  11631. #endif
  11632. else { /* c == '<' */
  11633. /*np->nfile.fd = 0; - stzalloc did it */
  11634. c = pgetc_eatbnl();
  11635. switch (c) {
  11636. case '<':
  11637. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11638. np = stzalloc(sizeof(struct nhere));
  11639. /*np->nfile.fd = 0; - stzalloc did it */
  11640. }
  11641. np->type = NHERE;
  11642. heredoc = stzalloc(sizeof(struct heredoc));
  11643. heredoc->here = np;
  11644. c = pgetc_eatbnl();
  11645. if (c == '-') {
  11646. heredoc->striptabs = 1;
  11647. } else {
  11648. /*heredoc->striptabs = 0; - stzalloc did it */
  11649. pungetc();
  11650. }
  11651. break;
  11652. case '&':
  11653. np->type = NFROMFD;
  11654. break;
  11655. case '>':
  11656. np->type = NFROMTO;
  11657. break;
  11658. default:
  11659. np->type = NFROM;
  11660. pungetc();
  11661. break;
  11662. }
  11663. }
  11664. if (fd >= 0)
  11665. np->nfile.fd = fd;
  11666. redirnode = np;
  11667. goto parseredir_return;
  11668. }
  11669. /*
  11670. * Parse a substitution. At this point, we have read the dollar sign
  11671. * and nothing else.
  11672. */
  11673. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11674. * (assuming ascii char codes, as the original implementation did) */
  11675. #define is_special(c) \
  11676. (((unsigned)(c) - 33 < 32) \
  11677. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11678. parsesub: {
  11679. unsigned char subtype;
  11680. int typeloc;
  11681. c = pgetc_eatbnl();
  11682. if ((checkkwd & CHKEOFMARK)
  11683. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11684. ) {
  11685. #if BASH_DOLLAR_SQUOTE
  11686. if (synstack->syntax != DQSYNTAX && c == '\'')
  11687. bash_dollar_squote = 1;
  11688. else
  11689. #endif
  11690. USTPUTC('$', out);
  11691. pungetc();
  11692. } else if (c == '(') {
  11693. /* $(command) or $((arith)) */
  11694. if (pgetc_eatbnl() == '(') {
  11695. #if ENABLE_FEATURE_SH_MATH
  11696. PARSEARITH();
  11697. #else
  11698. raise_error_syntax("support for $((arith)) is disabled");
  11699. #endif
  11700. } else {
  11701. pungetc();
  11702. PARSEBACKQNEW();
  11703. }
  11704. } else {
  11705. /* $VAR, $<specialchar>, ${...}, or PEOF */
  11706. smalluint newsyn = synstack->syntax;
  11707. USTPUTC(CTLVAR, out);
  11708. typeloc = out - (char *)stackblock();
  11709. STADJUST(1, out);
  11710. subtype = VSNORMAL;
  11711. if (c == '{') {
  11712. c = pgetc_eatbnl();
  11713. subtype = 0;
  11714. }
  11715. varname:
  11716. if (is_name(c)) {
  11717. /* $[{[#]]NAME[}] */
  11718. do {
  11719. STPUTC(c, out);
  11720. c = pgetc_eatbnl();
  11721. } while (is_in_name(c));
  11722. } else if (isdigit(c)) {
  11723. /* $[{[#]]NUM[}] */
  11724. do {
  11725. STPUTC(c, out);
  11726. c = pgetc_eatbnl();
  11727. } while ((subtype == 0 || subtype == VSLENGTH) && isdigit(c));
  11728. } else if (c != '}') {
  11729. /* $[{[#]]<specialchar>[}] */
  11730. int cc = c;
  11731. c = pgetc_eatbnl();
  11732. if (!subtype && cc == '#') {
  11733. subtype = VSLENGTH;
  11734. if (c == '_' || isalnum(c))
  11735. goto varname;
  11736. cc = c;
  11737. c = pgetc_eatbnl();
  11738. if (cc == '}' || c != '}') {
  11739. pungetc();
  11740. subtype = 0;
  11741. c = cc;
  11742. cc = '#';
  11743. }
  11744. }
  11745. if (!is_special(cc)) {
  11746. if (subtype == VSLENGTH)
  11747. subtype = 0;
  11748. goto badsub;
  11749. }
  11750. USTPUTC(cc, out);
  11751. } else
  11752. goto badsub;
  11753. if (subtype == 0) {
  11754. static const char types[] ALIGN1 = "}-+?=";
  11755. /* ${VAR...} but not $VAR or ${#VAR} */
  11756. /* c == first char after VAR */
  11757. int cc = c;
  11758. switch (c) {
  11759. case ':':
  11760. c = pgetc_eatbnl();
  11761. #if BASH_SUBSTR
  11762. /* This check is only needed to not misinterpret
  11763. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11764. * constructs.
  11765. */
  11766. if (!strchr(types, c)) {
  11767. subtype = VSSUBSTR;
  11768. pungetc();
  11769. break; /* "goto badsub" is bigger (!) */
  11770. }
  11771. #endif
  11772. subtype = VSNUL;
  11773. /*FALLTHROUGH*/
  11774. default: {
  11775. const char *p = strchr(types, c);
  11776. if (p == NULL)
  11777. break;
  11778. subtype |= p - types + VSNORMAL;
  11779. break;
  11780. }
  11781. case '%':
  11782. case '#':
  11783. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11784. c = pgetc_eatbnl();
  11785. if (c == cc)
  11786. subtype++;
  11787. else
  11788. pungetc();
  11789. newsyn = BASESYNTAX;
  11790. break;
  11791. #if BASH_PATTERN_SUBST
  11792. case '/':
  11793. /* ${v/[/]pattern/repl} */
  11794. //TODO: encode pattern and repl separately.
  11795. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11796. // are broken (should print "ONE")
  11797. subtype = VSREPLACE;
  11798. newsyn = BASESYNTAX;
  11799. c = pgetc_eatbnl();
  11800. if (c != '/')
  11801. goto badsub;
  11802. subtype++; /* VSREPLACEALL */
  11803. break;
  11804. #endif
  11805. }
  11806. } else {
  11807. if (subtype == VSLENGTH && c != '}')
  11808. subtype = 0;
  11809. badsub:
  11810. pungetc();
  11811. }
  11812. if (newsyn == ARISYNTAX)
  11813. newsyn = DQSYNTAX;
  11814. if ((newsyn != synstack->syntax || synstack->innerdq)
  11815. && subtype != VSNORMAL
  11816. ) {
  11817. synstack_push(&synstack,
  11818. synstack->prev ?: alloca(sizeof(*synstack)),
  11819. newsyn);
  11820. synstack->varpushed = 1;
  11821. synstack->dblquote = newsyn != BASESYNTAX;
  11822. }
  11823. ((unsigned char *)stackblock())[typeloc] = subtype;
  11824. if (subtype != VSNORMAL) {
  11825. synstack->varnest++;
  11826. if (synstack->dblquote)
  11827. synstack->dqvarnest++;
  11828. }
  11829. STPUTC('=', out);
  11830. }
  11831. goto parsesub_return;
  11832. }
  11833. /*
  11834. * Called to parse command substitutions. Newstyle is set if the command
  11835. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11836. * list of commands (passed by reference), and savelen is the number of
  11837. * characters on the top of the stack which must be preserved.
  11838. */
  11839. parsebackq: {
  11840. struct nodelist **nlpp;
  11841. union node *n;
  11842. char *str;
  11843. size_t savelen;
  11844. struct heredoc *saveheredoclist;
  11845. smallint saveprompt = 0;
  11846. str = NULL;
  11847. savelen = out - (char *)stackblock();
  11848. if (savelen > 0) {
  11849. /*
  11850. * FIXME: this can allocate very large block on stack and SEGV.
  11851. * Example:
  11852. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11853. * allocates 100kb for every command subst. With about
  11854. * a hundred command substitutions stack overflows.
  11855. * With larger prepended string, SEGV happens sooner.
  11856. */
  11857. str = alloca(savelen);
  11858. memcpy(str, stackblock(), savelen);
  11859. }
  11860. if (oldstyle) {
  11861. /* We must read until the closing backquote, giving special
  11862. * treatment to some slashes, and then push the string and
  11863. * reread it as input, interpreting it normally.
  11864. */
  11865. char *pout;
  11866. size_t psavelen;
  11867. char *pstr;
  11868. STARTSTACKSTR(pout);
  11869. for (;;) {
  11870. int pc;
  11871. setprompt_if(needprompt, 2);
  11872. pc = pgetc_eatbnl();
  11873. switch (pc) {
  11874. case '`':
  11875. goto done;
  11876. case '\\':
  11877. pc = pgetc(); /* not pgetc_eatbnl! */
  11878. if (pc != '\\' && pc != '`' && pc != '$'
  11879. && (!synstack->dblquote || pc != '"')
  11880. ) {
  11881. STPUTC('\\', pout);
  11882. }
  11883. break;
  11884. case PEOF:
  11885. raise_error_syntax("EOF in backquote substitution");
  11886. case '\n':
  11887. nlnoprompt();
  11888. break;
  11889. default:
  11890. break;
  11891. }
  11892. STPUTC(pc, pout);
  11893. }
  11894. done:
  11895. STPUTC('\0', pout);
  11896. psavelen = pout - (char *)stackblock();
  11897. if (psavelen > 0) {
  11898. pstr = grabstackstr(pout);
  11899. setinputstring(pstr);
  11900. }
  11901. }
  11902. nlpp = &bqlist;
  11903. while (*nlpp)
  11904. nlpp = &(*nlpp)->next;
  11905. *nlpp = stzalloc(sizeof(**nlpp));
  11906. /* (*nlpp)->next = NULL; - stzalloc did it */
  11907. saveheredoclist = heredoclist;
  11908. heredoclist = NULL;
  11909. if (oldstyle) {
  11910. saveprompt = doprompt;
  11911. doprompt = 0;
  11912. }
  11913. n = list(2);
  11914. if (oldstyle)
  11915. doprompt = saveprompt;
  11916. else {
  11917. if (readtoken() != TRP)
  11918. raise_error_unexpected_syntax(TRP);
  11919. setinputstring(nullstr);
  11920. }
  11921. parseheredoc();
  11922. heredoclist = saveheredoclist;
  11923. (*nlpp)->n = n;
  11924. /* Start reading from old file again. */
  11925. popfile();
  11926. /* Ignore any pushed back tokens left from the backquote parsing. */
  11927. if (oldstyle)
  11928. tokpushback = 0;
  11929. out = growstackto(savelen + 1);
  11930. if (str) {
  11931. memcpy(out, str, savelen);
  11932. STADJUST(savelen, out);
  11933. }
  11934. #if BASH_PROCESS_SUBST
  11935. if (style == PSUB)
  11936. USTPUTC(c == '<' ? CTLFROMPROC : CTLTOPROC, out);
  11937. else
  11938. #endif
  11939. USTPUTC(CTLBACKQ, out);
  11940. if (oldstyle)
  11941. goto parsebackq_oldreturn;
  11942. #if BASH_PROCESS_SUBST
  11943. else if (style == PSUB)
  11944. goto parsebackq_psreturn;
  11945. #endif
  11946. goto parsebackq_newreturn;
  11947. }
  11948. #if ENABLE_FEATURE_SH_MATH
  11949. /*
  11950. * Parse an arithmetic expansion (indicate start of one and set state)
  11951. */
  11952. parsearith: {
  11953. synstack_push(&synstack,
  11954. synstack->prev ?: alloca(sizeof(*synstack)),
  11955. ARISYNTAX);
  11956. synstack->dblquote = 1;
  11957. USTPUTC(CTLARI, out);
  11958. goto parsearith_return;
  11959. }
  11960. #endif
  11961. } /* end of readtoken */
  11962. /*
  11963. * Read the next input token.
  11964. * If the token is a word, we set backquotelist to the list of cmds in
  11965. * backquotes. We set quoteflag to true if any part of the word was
  11966. * quoted.
  11967. * If the token is TREDIR, then we set redirnode to a structure containing
  11968. * the redirection.
  11969. *
  11970. * [Change comment: here documents and internal procedures]
  11971. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11972. * word parsing code into a separate routine. In this case, readtoken
  11973. * doesn't need to have any internal procedures, but parseword does.
  11974. * We could also make parseoperator in essence the main routine, and
  11975. * have parseword (readtoken1?) handle both words and redirection.]
  11976. */
  11977. #define NEW_xxreadtoken
  11978. #ifdef NEW_xxreadtoken
  11979. /* singles must be first! */
  11980. static const char xxreadtoken_chars[7] ALIGN1 = {
  11981. '\n', '(', ')', /* singles */
  11982. '&', '|', ';', /* doubles */
  11983. 0
  11984. };
  11985. #define xxreadtoken_singles 3
  11986. #define xxreadtoken_doubles 3
  11987. static const char xxreadtoken_tokens[] ALIGN1 = {
  11988. TNL, TLP, TRP, /* only single occurrence allowed */
  11989. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11990. TEOF, /* corresponds to trailing nul */
  11991. TAND, TOR, TENDCASE /* if double occurrence */
  11992. };
  11993. static int
  11994. xxreadtoken(void)
  11995. {
  11996. int c;
  11997. if (tokpushback) {
  11998. tokpushback = 0;
  11999. return lasttoken;
  12000. }
  12001. setprompt_if(needprompt, 2);
  12002. for (;;) { /* until token or start of word found */
  12003. c = pgetc_eatbnl();
  12004. if (c == ' ' || c == '\t')
  12005. continue;
  12006. if (c == '#') {
  12007. while ((c = pgetc()) != '\n' && c != PEOF)
  12008. continue;
  12009. pungetc();
  12010. } else if (c == '\\') {
  12011. break; /* return readtoken1(...) */
  12012. } else {
  12013. const char *p;
  12014. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  12015. if (c != PEOF) {
  12016. if (c == '\n') {
  12017. nlnoprompt();
  12018. }
  12019. p = strchr(xxreadtoken_chars, c);
  12020. if (p == NULL)
  12021. break; /* return readtoken1(...) */
  12022. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  12023. int cc = pgetc_eatbnl();
  12024. if (cc == c) { /* double occurrence? */
  12025. p += xxreadtoken_doubles + 1;
  12026. } else {
  12027. pungetc();
  12028. #if BASH_REDIR_OUTPUT
  12029. if (c == '&' && cc == '>') /* &> */
  12030. break; /* return readtoken1(...) */
  12031. #endif
  12032. }
  12033. }
  12034. }
  12035. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  12036. return lasttoken;
  12037. }
  12038. } /* for (;;) */
  12039. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  12040. }
  12041. #else /* old xxreadtoken */
  12042. #define RETURN(token) return lasttoken = token
  12043. static int
  12044. xxreadtoken(void)
  12045. {
  12046. int c;
  12047. if (tokpushback) {
  12048. tokpushback = 0;
  12049. return lasttoken;
  12050. }
  12051. setprompt_if(needprompt, 2);
  12052. for (;;) { /* until token or start of word found */
  12053. c = pgetc_eatbnl();
  12054. switch (c) {
  12055. case ' ': case '\t':
  12056. continue;
  12057. case '#':
  12058. while ((c = pgetc()) != '\n' && c != PEOF)
  12059. continue;
  12060. pungetc();
  12061. continue;
  12062. case '\n':
  12063. nlnoprompt();
  12064. RETURN(TNL);
  12065. case PEOF:
  12066. RETURN(TEOF);
  12067. case '&':
  12068. if (pgetc_eatbnl() == '&')
  12069. RETURN(TAND);
  12070. pungetc();
  12071. RETURN(TBACKGND);
  12072. case '|':
  12073. if (pgetc_eatbnl() == '|')
  12074. RETURN(TOR);
  12075. pungetc();
  12076. RETURN(TPIPE);
  12077. case ';':
  12078. if (pgetc_eatbnl() == ';')
  12079. RETURN(TENDCASE);
  12080. pungetc();
  12081. RETURN(TSEMI);
  12082. case '(':
  12083. RETURN(TLP);
  12084. case ')':
  12085. RETURN(TRP);
  12086. }
  12087. break;
  12088. }
  12089. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  12090. #undef RETURN
  12091. }
  12092. #endif /* old xxreadtoken */
  12093. static int
  12094. readtoken(void)
  12095. {
  12096. int t;
  12097. int kwd = checkkwd;
  12098. #if DEBUG
  12099. smallint alreadyseen = tokpushback;
  12100. #endif
  12101. #if ENABLE_ASH_ALIAS
  12102. top:
  12103. #endif
  12104. t = xxreadtoken();
  12105. /*
  12106. * eat newlines
  12107. */
  12108. if (kwd & CHKNL) {
  12109. while (t == TNL) {
  12110. parseheredoc();
  12111. checkkwd = 0;
  12112. t = xxreadtoken();
  12113. }
  12114. }
  12115. kwd |= checkkwd;
  12116. checkkwd = 0;
  12117. if (t != TWORD || quoteflag) {
  12118. goto out;
  12119. }
  12120. /*
  12121. * check for keywords
  12122. */
  12123. if (kwd & CHKKWD) {
  12124. const char *const *pp;
  12125. pp = findkwd(wordtext);
  12126. if (pp) {
  12127. lasttoken = t = pp - tokname_array;
  12128. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  12129. goto out;
  12130. }
  12131. }
  12132. if (kwd & CHKALIAS) {
  12133. #if ENABLE_ASH_ALIAS
  12134. struct alias *ap;
  12135. ap = lookupalias(wordtext, 1);
  12136. if (ap != NULL) {
  12137. if (*ap->val) {
  12138. pushstring(ap->val, ap);
  12139. }
  12140. goto top;
  12141. }
  12142. #endif
  12143. }
  12144. out:
  12145. #if DEBUG
  12146. if (!alreadyseen)
  12147. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  12148. else
  12149. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  12150. #endif
  12151. return t;
  12152. }
  12153. /*
  12154. * Read and parse a command. Returns NODE_EOF on end of file.
  12155. * (NULL is a valid parse tree indicating a blank line.)
  12156. */
  12157. static union node *
  12158. parsecmd(int interact)
  12159. {
  12160. tokpushback = 0;
  12161. checkkwd = 0;
  12162. heredoclist = 0;
  12163. doprompt = interact;
  12164. setprompt_if(doprompt, doprompt);
  12165. needprompt = 0;
  12166. return list(1);
  12167. }
  12168. /*
  12169. * Input any here documents.
  12170. */
  12171. static void
  12172. parseheredoc(void)
  12173. {
  12174. struct heredoc *here;
  12175. union node *n;
  12176. here = heredoclist;
  12177. heredoclist = NULL;
  12178. while (here) {
  12179. tokpushback = 0;
  12180. setprompt_if(needprompt, 2);
  12181. if (here->here->type == NHERE)
  12182. readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
  12183. else
  12184. readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
  12185. n = stzalloc(sizeof(struct narg));
  12186. n->narg.type = NARG;
  12187. /*n->narg.next = NULL; - stzalloc did it */
  12188. n->narg.text = wordtext;
  12189. n->narg.backquote = backquotelist;
  12190. here->here->nhere.doc = n;
  12191. here = here->next;
  12192. }
  12193. }
  12194. static const char *
  12195. expandstr(const char *ps, int syntax_type)
  12196. {
  12197. struct parsefile *file_stop;
  12198. struct jmploc *volatile savehandler;
  12199. struct heredoc *saveheredoclist;
  12200. const char *result;
  12201. int saveprompt;
  12202. struct jmploc jmploc;
  12203. union node n;
  12204. int err;
  12205. file_stop = g_parsefile;
  12206. /* XXX Fix (char *) cast. */
  12207. setinputstring((char *)ps);
  12208. saveheredoclist = heredoclist;
  12209. heredoclist = NULL;
  12210. saveprompt = doprompt;
  12211. doprompt = 0;
  12212. result = ps;
  12213. savehandler = exception_handler;
  12214. err = setjmp(jmploc.loc);
  12215. if (err)
  12216. goto out;
  12217. /* readtoken1() might die horribly.
  12218. * Try a prompt with syntactically wrong command:
  12219. * PS1='$(date "+%H:%M:%S) > '
  12220. */
  12221. exception_handler = &jmploc;
  12222. readtoken1(pgetc_eatbnl(), syntax_type, FAKEEOFMARK, 0);
  12223. n.narg.type = NARG;
  12224. n.narg.next = NULL;
  12225. n.narg.text = wordtext;
  12226. n.narg.backquote = backquotelist;
  12227. /* expandarg() might fail too:
  12228. * PS1='$((123+))'
  12229. */
  12230. expandarg(&n, NULL, EXP_QUOTED);
  12231. result = stackblock();
  12232. out:
  12233. exception_handler = savehandler;
  12234. if (err && exception_type != EXERROR)
  12235. longjmp(exception_handler->loc, 1);
  12236. doprompt = saveprompt;
  12237. /* Try: PS1='`xxx(`' */
  12238. unwindfiles(file_stop);
  12239. heredoclist = saveheredoclist;
  12240. return result;
  12241. }
  12242. static inline int
  12243. parser_eof(void)
  12244. {
  12245. return tokpushback && lasttoken == TEOF;
  12246. }
  12247. /*
  12248. * Execute a command or commands contained in a string.
  12249. */
  12250. static int
  12251. evalstring(char *s, int flags)
  12252. {
  12253. struct jmploc *volatile savehandler;
  12254. struct jmploc jmploc;
  12255. int ex;
  12256. union node *n;
  12257. struct stackmark smark;
  12258. int status;
  12259. s = sstrdup(s);
  12260. setinputstring(s);
  12261. setstackmark(&smark);
  12262. status = 0;
  12263. /* On exception inside execution loop, we must popfile().
  12264. * Try interactively:
  12265. * readonly a=a
  12266. * command eval "a=b" # throws "is read only" error
  12267. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  12268. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  12269. */
  12270. savehandler = exception_handler;
  12271. ex = setjmp(jmploc.loc);
  12272. if (ex)
  12273. goto out;
  12274. exception_handler = &jmploc;
  12275. while ((n = parsecmd(0)) != NODE_EOF) {
  12276. int i;
  12277. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  12278. if (n)
  12279. status = i;
  12280. popstackmark(&smark);
  12281. if (evalskip)
  12282. break;
  12283. }
  12284. out:
  12285. popstackmark(&smark);
  12286. popfile();
  12287. stunalloc(s);
  12288. exception_handler = savehandler;
  12289. if (ex)
  12290. longjmp(exception_handler->loc, ex);
  12291. return status;
  12292. }
  12293. /*
  12294. * The eval command.
  12295. */
  12296. static int FAST_FUNC
  12297. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  12298. {
  12299. char *p;
  12300. char *concat;
  12301. if (argv[1]) {
  12302. p = argv[1];
  12303. argv += 2;
  12304. if (argv[0]) {
  12305. STARTSTACKSTR(concat);
  12306. for (;;) {
  12307. concat = stack_putstr(p, concat);
  12308. p = *argv++;
  12309. if (p == NULL)
  12310. break;
  12311. STPUTC(' ', concat);
  12312. }
  12313. STPUTC('\0', concat);
  12314. p = grabstackstr(concat);
  12315. }
  12316. return evalstring(p, flags & EV_TESTED);
  12317. }
  12318. return 0;
  12319. }
  12320. /*
  12321. * Read and execute commands.
  12322. * "Top" is nonzero for the top level command loop;
  12323. * it turns on prompting if the shell is interactive.
  12324. */
  12325. static int
  12326. cmdloop(int top)
  12327. {
  12328. union node *n;
  12329. struct stackmark smark;
  12330. int inter;
  12331. int status = 0;
  12332. int numeof = 0;
  12333. TRACE(("cmdloop(%d) called\n", top));
  12334. for (;;) {
  12335. int skip;
  12336. setstackmark(&smark);
  12337. #if JOBS
  12338. if (doing_jobctl)
  12339. showjobs(SHOW_CHANGED|SHOW_STDERR);
  12340. #endif
  12341. inter = 0;
  12342. if (iflag && top) {
  12343. inter++;
  12344. chkmail();
  12345. }
  12346. n = parsecmd(inter);
  12347. #if DEBUG
  12348. if (DEBUG > 2 && debug && (n != NODE_EOF))
  12349. showtree(n);
  12350. #endif
  12351. if (n == NODE_EOF) {
  12352. if (!top || numeof >= 50)
  12353. break;
  12354. if (!stoppedjobs()) {
  12355. if (!iflag)
  12356. break;
  12357. if (!Iflag) {
  12358. newline_and_flush(stderr);
  12359. break;
  12360. }
  12361. /* "set -o ignoreeof" active, do not exit command loop on ^D */
  12362. out2str("\nUse \"exit\" to leave shell.\n");
  12363. }
  12364. numeof++;
  12365. } else {
  12366. int i;
  12367. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12368. job_warning >>= 1;
  12369. numeof = 0;
  12370. i = evaltree(n, 0);
  12371. if (n)
  12372. status = i;
  12373. }
  12374. popstackmark(&smark);
  12375. skip = evalskip;
  12376. if (skip) {
  12377. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  12378. break;
  12379. }
  12380. }
  12381. return status;
  12382. }
  12383. /*
  12384. * Take commands from a file. To be compatible we should do a path
  12385. * search for the file, which is necessary to find sub-commands.
  12386. */
  12387. static char *
  12388. find_dot_file(char *basename)
  12389. {
  12390. char *fullname;
  12391. const char *path = pathval();
  12392. struct stat statb;
  12393. int len;
  12394. /* don't try this for absolute or relative paths */
  12395. if (strchr(basename, '/'))
  12396. return basename;
  12397. while ((len = padvance(&path, basename)) >= 0) {
  12398. fullname = stackblock();
  12399. if ((!pathopt || *pathopt == 'f')
  12400. && !stat(fullname, &statb) && S_ISREG(statb.st_mode)
  12401. ) {
  12402. /* This will be freed by the caller. */
  12403. return stalloc(len);
  12404. }
  12405. }
  12406. /* not found in PATH */
  12407. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12408. return basename;
  12409. #else
  12410. ash_msg_and_raise_error("%s: not found", basename);
  12411. /* NOTREACHED */
  12412. #endif
  12413. }
  12414. static int FAST_FUNC
  12415. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12416. {
  12417. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12418. int status = 0;
  12419. char *fullname;
  12420. char **argv;
  12421. char *args_need_save;
  12422. volatile struct shparam saveparam;
  12423. //???
  12424. // struct strlist *sp;
  12425. // for (sp = cmdenviron; sp; sp = sp->next)
  12426. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12427. nextopt(nullstr); /* handle possible "--" */
  12428. argv = argptr;
  12429. if (!argv[0]) {
  12430. /* bash says: "bash: .: filename argument required" */
  12431. return 2; /* bash compat */
  12432. }
  12433. /* This aborts if file isn't found, which is POSIXly correct.
  12434. * bash returns exitcode 1 instead.
  12435. */
  12436. fullname = find_dot_file(argv[0]);
  12437. argv++;
  12438. args_need_save = argv[0];
  12439. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12440. int argc;
  12441. saveparam = shellparam;
  12442. shellparam.malloced = 0;
  12443. argc = 1;
  12444. while (argv[argc])
  12445. argc++;
  12446. shellparam.nparam = argc;
  12447. shellparam.p = argv;
  12448. };
  12449. /* This aborts if file can't be opened, which is POSIXly correct.
  12450. * bash returns exitcode 1 instead.
  12451. */
  12452. setinputfile(fullname, INPUT_PUSH_FILE);
  12453. commandname = fullname;
  12454. status = cmdloop(0);
  12455. popfile();
  12456. if (args_need_save) {
  12457. freeparam(&shellparam);
  12458. shellparam = saveparam;
  12459. };
  12460. return status;
  12461. }
  12462. static int FAST_FUNC
  12463. exitcmd(int argc UNUSED_PARAM, char **argv)
  12464. {
  12465. if (stoppedjobs())
  12466. return 0;
  12467. if (argv[1])
  12468. savestatus = number(argv[1]);
  12469. //TODO: this script
  12470. // trap 'echo trap:$FUNCNAME' EXIT
  12471. // f() { exit; }
  12472. // f
  12473. //prints "trap:f" in bash. We can call exitshell() here to achieve this.
  12474. //For now, keeping dash code:
  12475. raise_exception(EXEXIT);
  12476. /* NOTREACHED */
  12477. }
  12478. /*
  12479. * Read a file containing shell functions.
  12480. */
  12481. static void
  12482. readcmdfile(char *name)
  12483. {
  12484. setinputfile(name, INPUT_PUSH_FILE);
  12485. cmdloop(0);
  12486. popfile();
  12487. }
  12488. /* ============ find_command inplementation */
  12489. /*
  12490. * Resolve a command name. If you change this routine, you may have to
  12491. * change the shellexec routine as well.
  12492. */
  12493. static void
  12494. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12495. {
  12496. struct tblentry *cmdp;
  12497. int idx;
  12498. int prev;
  12499. char *fullname;
  12500. struct stat statb;
  12501. int e;
  12502. int updatetbl;
  12503. struct builtincmd *bcmd;
  12504. int len;
  12505. /* If name contains a slash, don't use PATH or hash table */
  12506. if (strchr(name, '/') != NULL) {
  12507. entry->u.index = -1;
  12508. if (act & DO_ABS) {
  12509. while (stat(name, &statb) < 0) {
  12510. #ifdef SYSV
  12511. if (errno == EINTR)
  12512. continue;
  12513. #endif
  12514. entry->cmdtype = CMDUNKNOWN;
  12515. return;
  12516. }
  12517. }
  12518. entry->cmdtype = CMDNORMAL;
  12519. return;
  12520. }
  12521. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12522. updatetbl = (path == pathval());
  12523. if (!updatetbl)
  12524. act |= DO_ALTPATH;
  12525. /* If name is in the table, check answer will be ok */
  12526. cmdp = cmdlookup(name, 0);
  12527. if (cmdp != NULL) {
  12528. int bit;
  12529. switch (cmdp->cmdtype) {
  12530. default:
  12531. #if DEBUG
  12532. abort();
  12533. #endif
  12534. case CMDNORMAL:
  12535. bit = DO_ALTPATH | DO_REGBLTIN;
  12536. break;
  12537. case CMDFUNCTION:
  12538. bit = DO_NOFUNC;
  12539. break;
  12540. case CMDBUILTIN:
  12541. bit = IS_BUILTIN_REGULAR(cmdp->param.cmd) ? 0 : DO_REGBLTIN;
  12542. break;
  12543. }
  12544. if (act & bit) {
  12545. if (act & bit & DO_REGBLTIN)
  12546. goto fail;
  12547. updatetbl = 0;
  12548. cmdp = NULL;
  12549. } else if (cmdp->rehash == 0)
  12550. /* if not invalidated by cd, we're done */
  12551. goto success;
  12552. }
  12553. /* If %builtin not in path, check for builtin next */
  12554. bcmd = find_builtin(name);
  12555. if (bcmd) {
  12556. if (IS_BUILTIN_REGULAR(bcmd))
  12557. goto builtin_success;
  12558. if (act & DO_ALTPATH)
  12559. goto builtin_success;
  12560. if (builtinloc <= 0)
  12561. goto builtin_success;
  12562. }
  12563. if (act & DO_REGBLTIN)
  12564. goto fail;
  12565. #if ENABLE_FEATURE_SH_STANDALONE
  12566. {
  12567. int applet_no = find_applet_by_name(name);
  12568. if (applet_no >= 0) {
  12569. entry->cmdtype = CMDNORMAL;
  12570. entry->u.index = -2 - applet_no;
  12571. return;
  12572. }
  12573. }
  12574. #endif
  12575. /* We have to search path. */
  12576. prev = -1; /* where to start */
  12577. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12578. if (cmdp->cmdtype == CMDBUILTIN)
  12579. prev = builtinloc;
  12580. else
  12581. prev = cmdp->param.index;
  12582. }
  12583. e = ENOENT;
  12584. idx = -1;
  12585. loop:
  12586. while ((len = padvance(&path, name)) >= 0) {
  12587. const char *lpathopt = pathopt;
  12588. fullname = stackblock();
  12589. idx++;
  12590. if (lpathopt) {
  12591. if (*lpathopt == 'b') {
  12592. if (bcmd)
  12593. goto builtin_success;
  12594. continue;
  12595. } else if (!(act & DO_NOFUNC)) {
  12596. /* handled below */
  12597. } else {
  12598. /* ignore unimplemented options */
  12599. continue;
  12600. }
  12601. }
  12602. /* if rehash, don't redo absolute path names */
  12603. if (fullname[0] == '/' && idx <= prev) {
  12604. if (idx < prev)
  12605. continue;
  12606. TRACE(("searchexec \"%s\": no change\n", name));
  12607. goto success;
  12608. }
  12609. while (stat(fullname, &statb) < 0) {
  12610. #ifdef SYSV
  12611. if (errno == EINTR)
  12612. continue;
  12613. #endif
  12614. if (errno != ENOENT && errno != ENOTDIR)
  12615. e = errno;
  12616. goto loop;
  12617. }
  12618. e = EACCES; /* if we fail, this will be the error */
  12619. if (!S_ISREG(statb.st_mode))
  12620. continue;
  12621. if (lpathopt) { /* this is a %func directory */
  12622. stalloc(len);
  12623. /* NB: stalloc will return space pointed by fullname
  12624. * (because we don't have any intervening allocations
  12625. * between stunalloc above and this stalloc) */
  12626. readcmdfile(fullname);
  12627. cmdp = cmdlookup(name, 0);
  12628. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12629. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12630. stunalloc(fullname);
  12631. goto success;
  12632. }
  12633. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12634. if (!updatetbl) {
  12635. entry->cmdtype = CMDNORMAL;
  12636. entry->u.index = idx;
  12637. return;
  12638. }
  12639. INT_OFF;
  12640. cmdp = cmdlookup(name, 1);
  12641. cmdp->cmdtype = CMDNORMAL;
  12642. cmdp->param.index = idx;
  12643. INT_ON;
  12644. goto success;
  12645. }
  12646. /* We failed. If there was an entry for this command, delete it */
  12647. if (cmdp && updatetbl)
  12648. delete_cmd_entry();
  12649. if (act & DO_ERR) {
  12650. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12651. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12652. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12653. char *argv[3];
  12654. argv[0] = (char*) "command_not_found_handle";
  12655. argv[1] = name;
  12656. argv[2] = NULL;
  12657. evalfun(hookp->param.func, 2, argv, 0);
  12658. entry->cmdtype = CMDUNKNOWN;
  12659. return;
  12660. }
  12661. #endif
  12662. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12663. }
  12664. fail:
  12665. entry->cmdtype = CMDUNKNOWN;
  12666. return;
  12667. builtin_success:
  12668. if (!updatetbl) {
  12669. entry->cmdtype = CMDBUILTIN;
  12670. entry->u.cmd = bcmd;
  12671. return;
  12672. }
  12673. INT_OFF;
  12674. cmdp = cmdlookup(name, 1);
  12675. cmdp->cmdtype = CMDBUILTIN;
  12676. cmdp->param.cmd = bcmd;
  12677. INT_ON;
  12678. success:
  12679. cmdp->rehash = 0;
  12680. entry->cmdtype = cmdp->cmdtype;
  12681. entry->u = cmdp->param;
  12682. }
  12683. /*
  12684. * The trap builtin.
  12685. */
  12686. static int FAST_FUNC
  12687. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12688. {
  12689. char *action;
  12690. char **ap;
  12691. int signo, exitcode;
  12692. nextopt(nullstr);
  12693. ap = argptr;
  12694. if (!*ap) {
  12695. for (signo = 0; signo <= NTRAP_LAST; signo++) {
  12696. char *tr = trap_ptr[signo];
  12697. if (tr) {
  12698. /* note: bash adds "SIG", but only if invoked
  12699. * as "bash". If called as "sh", or if set -o posix,
  12700. * then it prints short signal names.
  12701. * We are printing short names: */
  12702. out1fmt("trap -- %s %s\n",
  12703. single_quote(tr),
  12704. (signo == NTRAP_ERR) ? "ERR" : get_signame(signo));
  12705. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12706. * In this case, we will exit very soon, no need to free(). */
  12707. /* if (trap_ptr != trap && tp[0]) */
  12708. /* free(tr); */
  12709. }
  12710. }
  12711. /*
  12712. if (trap_ptr != trap) {
  12713. free(trap_ptr);
  12714. trap_ptr = trap;
  12715. }
  12716. */
  12717. return 0;
  12718. }
  12719. /* Why the second check?
  12720. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12721. * In this case, NUM is signal no, not an action.
  12722. */
  12723. action = NULL;
  12724. if (ap[1] && !is_number(ap[0]))
  12725. action = *ap++;
  12726. exitcode = 0;
  12727. while (*ap) {
  12728. signo = strcmp(*ap, "ERR") == 0 ? NTRAP_ERR : get_signum(*ap);
  12729. if (signo < 0) {
  12730. /* Mimic bash message exactly */
  12731. ash_msg("%s: invalid signal specification", *ap);
  12732. exitcode = 1;
  12733. goto next;
  12734. }
  12735. INT_OFF;
  12736. if (action) {
  12737. if (LONE_DASH(action))
  12738. action = NULL;
  12739. else {
  12740. if (action[0]) /* not NULL and not "" and not "-" */
  12741. may_have_traps = 1;
  12742. action = ckstrdup(action);
  12743. }
  12744. }
  12745. free(trap[signo]);
  12746. trap[signo] = action;
  12747. if (signo != 0 && signo < NSIG)
  12748. setsignal(signo);
  12749. INT_ON;
  12750. next:
  12751. ap++;
  12752. }
  12753. return exitcode;
  12754. }
  12755. /* ============ Builtins */
  12756. #if ENABLE_ASH_HELP
  12757. static int FAST_FUNC
  12758. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12759. {
  12760. unsigned col;
  12761. unsigned i;
  12762. out1fmt(
  12763. "Built-in commands:\n"
  12764. "------------------\n");
  12765. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12766. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12767. builtintab[i].name + 1);
  12768. if (col > 60) {
  12769. out1fmt("\n");
  12770. col = 0;
  12771. }
  12772. }
  12773. # if ENABLE_FEATURE_SH_STANDALONE
  12774. {
  12775. const char *a = applet_names;
  12776. while (*a) {
  12777. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12778. if (col > 60) {
  12779. out1fmt("\n");
  12780. col = 0;
  12781. }
  12782. while (*a++ != '\0')
  12783. continue;
  12784. }
  12785. }
  12786. # endif
  12787. newline_and_flush(stdout);
  12788. return EXIT_SUCCESS;
  12789. }
  12790. #endif
  12791. #if MAX_HISTORY
  12792. static int FAST_FUNC
  12793. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12794. {
  12795. show_history(line_input_state);
  12796. return EXIT_SUCCESS;
  12797. }
  12798. #endif
  12799. /*
  12800. * The export and readonly commands.
  12801. */
  12802. static int FAST_FUNC
  12803. exportcmd(int argc UNUSED_PARAM, char **argv)
  12804. {
  12805. struct var *vp;
  12806. char *name;
  12807. const char *p;
  12808. char **aptr;
  12809. char opt;
  12810. int flag;
  12811. int flag_off;
  12812. /* "readonly" in bash accepts, but ignores -n.
  12813. * We do the same: it saves a conditional in nextopt's param.
  12814. */
  12815. flag_off = 0;
  12816. while ((opt = nextopt("np")) != '\0') {
  12817. if (opt == 'n')
  12818. flag_off = VEXPORT;
  12819. }
  12820. flag = VEXPORT;
  12821. if (argv[0][0] == 'r') {
  12822. flag = VREADONLY;
  12823. flag_off = 0; /* readonly ignores -n */
  12824. }
  12825. flag_off = ~flag_off;
  12826. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12827. {
  12828. aptr = argptr;
  12829. name = *aptr;
  12830. if (name) {
  12831. do {
  12832. p = strchr(name, '=');
  12833. if (p != NULL) {
  12834. p++;
  12835. } else {
  12836. vp = *findvar(hashvar(name), name);
  12837. if (vp) {
  12838. vp->flags = ((vp->flags | flag) & flag_off);
  12839. continue;
  12840. }
  12841. }
  12842. setvar(name, p, (flag & flag_off));
  12843. } while ((name = *++aptr) != NULL);
  12844. return 0;
  12845. }
  12846. }
  12847. /* No arguments. Show the list of exported or readonly vars.
  12848. * -n is ignored.
  12849. */
  12850. showvars(argv[0], flag, 0);
  12851. return 0;
  12852. }
  12853. /*
  12854. * Delete a function if it exists.
  12855. */
  12856. static void
  12857. unsetfunc(const char *name)
  12858. {
  12859. struct tblentry *cmdp;
  12860. cmdp = cmdlookup(name, 0);
  12861. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12862. delete_cmd_entry();
  12863. }
  12864. /*
  12865. * The unset builtin command. We unset the function before we unset the
  12866. * variable to allow a function to be unset when there is a readonly variable
  12867. * with the same name.
  12868. */
  12869. static int FAST_FUNC
  12870. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12871. {
  12872. char **ap;
  12873. int i;
  12874. int flag = 0;
  12875. while ((i = nextopt("vf")) != 0) {
  12876. flag = i;
  12877. }
  12878. for (ap = argptr; *ap; ap++) {
  12879. if (flag != 'f') {
  12880. unsetvar(*ap);
  12881. continue;
  12882. }
  12883. if (flag != 'v')
  12884. unsetfunc(*ap);
  12885. }
  12886. return 0;
  12887. }
  12888. static const unsigned char timescmd_str[] ALIGN1 = {
  12889. ' ', offsetof(struct tms, tms_utime),
  12890. '\n', offsetof(struct tms, tms_stime),
  12891. ' ', offsetof(struct tms, tms_cutime),
  12892. '\n', offsetof(struct tms, tms_cstime),
  12893. 0
  12894. };
  12895. static int FAST_FUNC
  12896. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12897. {
  12898. unsigned clk_tck;
  12899. const unsigned char *p;
  12900. struct tms buf;
  12901. clk_tck = bb_clk_tck();
  12902. times(&buf);
  12903. p = timescmd_str;
  12904. do {
  12905. unsigned sec, frac;
  12906. unsigned long t;
  12907. t = *(clock_t *)(((char *) &buf) + p[1]);
  12908. sec = t / clk_tck;
  12909. frac = t % clk_tck;
  12910. out1fmt("%um%u.%03us%c",
  12911. sec / 60, sec % 60,
  12912. (frac * 1000) / clk_tck,
  12913. p[0]);
  12914. p += 2;
  12915. } while (*p);
  12916. return 0;
  12917. }
  12918. #if ENABLE_FEATURE_SH_MATH
  12919. /*
  12920. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12921. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12922. *
  12923. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12924. */
  12925. static int FAST_FUNC
  12926. letcmd(int argc UNUSED_PARAM, char **argv)
  12927. {
  12928. arith_t i;
  12929. argv++;
  12930. if (!*argv)
  12931. ash_msg_and_raise_error("expression expected");
  12932. do {
  12933. i = ash_arith(*argv);
  12934. } while (*++argv);
  12935. return !i;
  12936. }
  12937. #endif
  12938. /*
  12939. * The read builtin. Options:
  12940. * -r Do not interpret '\' specially
  12941. * -s Turn off echo (tty only)
  12942. * -n NCHARS Read NCHARS max
  12943. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12944. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12945. * -u FD Read from given FD instead of fd 0
  12946. * -d DELIM End on DELIM char, not newline
  12947. * This uses unbuffered input, which may be avoidable in some cases.
  12948. * TODO: bash also has:
  12949. * -a ARRAY Read into array[0],[1],etc
  12950. * -e Use line editing (tty only)
  12951. */
  12952. static int FAST_FUNC
  12953. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12954. {
  12955. struct builtin_read_params params;
  12956. const char *r;
  12957. int i;
  12958. memset(&params, 0, sizeof(params));
  12959. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12960. switch (i) {
  12961. case 'p':
  12962. params.opt_p = optionarg;
  12963. break;
  12964. case 'n':
  12965. params.opt_n = optionarg;
  12966. break;
  12967. case 's':
  12968. params.read_flags |= BUILTIN_READ_SILENT;
  12969. break;
  12970. case 't':
  12971. params.opt_t = optionarg;
  12972. break;
  12973. case 'r':
  12974. params.read_flags |= BUILTIN_READ_RAW;
  12975. break;
  12976. case 'u':
  12977. params.opt_u = optionarg;
  12978. break;
  12979. #if BASH_READ_D
  12980. case 'd':
  12981. params.opt_d = optionarg;
  12982. break;
  12983. #endif
  12984. default:
  12985. break;
  12986. }
  12987. }
  12988. if (!ENABLE_ASH_BASH_COMPAT && !argptr) {
  12989. bb_simple_error_msg("read: need variable name");
  12990. return 1;
  12991. }
  12992. params.argv = argptr;
  12993. params.setvar = setvar0;
  12994. params.ifs = bltinlookup("IFS"); /* can be NULL */
  12995. /* "read -s" needs to save/restore termios, can't allow ^C
  12996. * to jump out of it.
  12997. */
  12998. again:
  12999. INT_OFF;
  13000. r = shell_builtin_read(&params);
  13001. INT_ON;
  13002. if ((uintptr_t)r == 1 && errno == EINTR) {
  13003. /* To get SIGCHLD: sleep 1 & read x; echo $x
  13004. * Correct behavior is to not exit "read"
  13005. */
  13006. if (pending_sig == 0)
  13007. goto again;
  13008. }
  13009. if ((uintptr_t)r > 1)
  13010. ash_msg_and_raise_error(r);
  13011. return (uintptr_t)r;
  13012. }
  13013. static int FAST_FUNC
  13014. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  13015. {
  13016. static const char permuser[3] ALIGN1 = "ogu";
  13017. mode_t mask;
  13018. int symbolic_mode = 0;
  13019. while (nextopt("S") != '\0') {
  13020. symbolic_mode = 1;
  13021. }
  13022. INT_OFF;
  13023. mask = umask(0);
  13024. umask(mask);
  13025. INT_ON;
  13026. if (*argptr == NULL) {
  13027. if (symbolic_mode) {
  13028. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  13029. char *p = buf;
  13030. int i;
  13031. i = 2;
  13032. for (;;) {
  13033. *p++ = ',';
  13034. *p++ = permuser[i];
  13035. *p++ = '=';
  13036. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  13037. if (!(mask & 0400)) *p++ = 'r';
  13038. if (!(mask & 0200)) *p++ = 'w';
  13039. if (!(mask & 0100)) *p++ = 'x';
  13040. mask <<= 3;
  13041. if (--i < 0)
  13042. break;
  13043. }
  13044. *p = '\0';
  13045. puts(buf + 1);
  13046. } else {
  13047. out1fmt("%04o\n", mask);
  13048. }
  13049. } else {
  13050. char *modestr = *argptr;
  13051. /* numeric umasks are taken as-is */
  13052. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  13053. if (!isdigit(modestr[0]))
  13054. mask ^= 0777;
  13055. mask = bb_parse_mode(modestr, mask);
  13056. if ((unsigned)mask > 0777) {
  13057. ash_msg_and_raise_error("illegal mode: %s", modestr);
  13058. }
  13059. if (!isdigit(modestr[0]))
  13060. mask ^= 0777;
  13061. umask(mask);
  13062. }
  13063. return 0;
  13064. }
  13065. static int FAST_FUNC
  13066. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  13067. {
  13068. return shell_builtin_ulimit(argv);
  13069. }
  13070. /* ============ main() and helpers */
  13071. /*
  13072. * This routine is called when an error or an interrupt occurs in an
  13073. * interactive shell and control is returned to the main command loop
  13074. * but prior to exitshell.
  13075. */
  13076. static void
  13077. exitreset(void)
  13078. {
  13079. /* from eval.c: */
  13080. if (savestatus >= 0) {
  13081. if (exception_type == EXEXIT || evalskip == SKIPFUNCDEF)
  13082. exitstatus = savestatus;
  13083. savestatus = -1;
  13084. }
  13085. evalskip = 0;
  13086. loopnest = 0;
  13087. inps4 = 0;
  13088. /* from expand.c: */
  13089. ifsfree();
  13090. /* from redir.c: */
  13091. unwindredir(NULL);
  13092. }
  13093. /*
  13094. * This routine is called when an error or an interrupt occurs in an
  13095. * interactive shell and control is returned to the main command loop.
  13096. * (In dash, this function is auto-generated by build machinery).
  13097. */
  13098. static void
  13099. reset(void)
  13100. {
  13101. /* from input.c: */
  13102. g_parsefile->left_in_buffer = 0;
  13103. g_parsefile->left_in_line = 0; /* clear input buffer */
  13104. g_parsefile->unget = 0;
  13105. popallfiles();
  13106. /* from var.c: */
  13107. unwindlocalvars(NULL);
  13108. }
  13109. /*
  13110. * Called to exit the shell.
  13111. */
  13112. static void
  13113. exitshell(void)
  13114. {
  13115. struct jmploc loc;
  13116. char *p;
  13117. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  13118. save_history(line_input_state); /* may be NULL */
  13119. #endif
  13120. savestatus = exitstatus;
  13121. TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
  13122. if (setjmp(loc.loc))
  13123. goto out;
  13124. exception_handler = &loc;
  13125. p = trap[0];
  13126. if (p) {
  13127. trap[0] = NULL;
  13128. evalskip = 0;
  13129. trap_depth++;
  13130. evalstring(p, 0);
  13131. trap_depth--;
  13132. evalskip = SKIPFUNCDEF;
  13133. /*free(p); - we'll exit soon */
  13134. }
  13135. out:
  13136. exitreset();
  13137. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  13138. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  13139. */
  13140. setjobctl(0);
  13141. flush_stdout_stderr();
  13142. _exit(exitstatus);
  13143. /* NOTREACHED */
  13144. }
  13145. /* Don't inline: conserve stack of caller from having our locals too */
  13146. static NOINLINE void
  13147. init(void)
  13148. {
  13149. /* we will never free this */
  13150. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  13151. basepf.linno = 1;
  13152. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  13153. setsignal(SIGCHLD);
  13154. {
  13155. char **envp;
  13156. const char *p;
  13157. initvar();
  13158. for (envp = environ; envp && *envp; envp++) {
  13159. /* Used to have
  13160. * p = endofname(*envp);
  13161. * if (p != *envp && *p == '=') {
  13162. * here to weed out badly-named variables, but this breaks
  13163. * scenarios where people do want them passed to children:
  13164. * import os
  13165. * os.environ["test-test"]="test"
  13166. * if os.fork() == 0:
  13167. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  13168. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  13169. */
  13170. if (strchr(*envp, '=')) {
  13171. setvareq(*envp, VEXPORT|VTEXTFIXED);
  13172. }
  13173. }
  13174. setvareq((char*)defifsvar, VTEXTFIXED);
  13175. setvareq((char*)defoptindvar, VTEXTFIXED);
  13176. setvar0("PPID", utoa(getppid()));
  13177. #if BASH_SHLVL_VAR
  13178. p = lookupvar("SHLVL");
  13179. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  13180. #endif
  13181. #if BASH_HOSTNAME_VAR
  13182. if (!lookupvar("HOSTNAME")) {
  13183. struct utsname uts;
  13184. uname(&uts);
  13185. setvar0("HOSTNAME", uts.nodename);
  13186. }
  13187. #endif
  13188. p = lookupvar("PWD");
  13189. if (p) {
  13190. struct stat st1, st2;
  13191. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  13192. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  13193. ) {
  13194. p = NULL;
  13195. }
  13196. }
  13197. setpwd(p, 0);
  13198. }
  13199. }
  13200. //usage:#define ash_trivial_usage
  13201. //usage: "[-il] [-|+Cabefmnuvx] [-|+o OPT]... [-c 'SCRIPT' [ARG0 ARGS] | FILE ARGS | -s ARGS]"
  13202. //////// comes from ^^^^^^^^^^optletters
  13203. //usage:#define ash_full_usage "\n\n"
  13204. //usage: "Unix shell interpreter"
  13205. /*
  13206. * Process the shell command line arguments.
  13207. */
  13208. static int
  13209. procargs(char **argv)
  13210. {
  13211. int i;
  13212. const char *xminusc;
  13213. char **xargv;
  13214. int login_sh;
  13215. xargv = argv;
  13216. login_sh = xargv[0] && xargv[0][0] == '-';
  13217. #if NUM_SCRIPTS > 0
  13218. if (minusc)
  13219. goto setarg0;
  13220. #endif
  13221. arg0 = xargv[0];
  13222. /* if (xargv[0]) - mmm, this is always true! */
  13223. xargv++;
  13224. argptr = xargv;
  13225. for (i = 0; i < NOPTS; i++)
  13226. optlist[i] = 2;
  13227. if (options(&login_sh)) {
  13228. /* it already printed err message */
  13229. raise_exception(EXERROR);
  13230. }
  13231. xargv = argptr;
  13232. xminusc = minusc;
  13233. if (*xargv == NULL) {
  13234. if (xminusc)
  13235. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  13236. sflag = 1;
  13237. }
  13238. if (iflag == 2 /* no explicit -i given */
  13239. && sflag == 1 /* -s given (or implied) */
  13240. && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
  13241. && isatty(0) && isatty(1) /* we are on tty */
  13242. ) {
  13243. iflag = 1;
  13244. }
  13245. if (mflag == 2)
  13246. mflag = iflag;
  13247. /* Unset options which weren't explicitly set or unset */
  13248. for (i = 0; i < NOPTS; i++)
  13249. optlist[i] &= 1; /* same effect as "if (optlist[i] == 2) optlist[i] = 0;" */
  13250. #if DEBUG == 2
  13251. debug = 1;
  13252. #endif
  13253. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  13254. if (xminusc) {
  13255. minusc = *xargv++;
  13256. if (*xargv)
  13257. goto setarg0;
  13258. } else if (!sflag) {
  13259. setinputfile(*xargv, 0);
  13260. setarg0:
  13261. arg0 = *xargv++;
  13262. commandname = arg0;
  13263. }
  13264. shellparam.p = xargv;
  13265. #if ENABLE_ASH_GETOPTS
  13266. shellparam.optind = 1;
  13267. shellparam.optoff = -1;
  13268. #endif
  13269. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  13270. while (*xargv) {
  13271. shellparam.nparam++;
  13272. xargv++;
  13273. }
  13274. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  13275. * Try:
  13276. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  13277. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  13278. * NB: must do it before setting up signals (in optschanged())
  13279. * and reading .profile etc (after we return from here):
  13280. */
  13281. if (iflag)
  13282. signal(SIGHUP, SIG_DFL);
  13283. optschanged();
  13284. return login_sh;
  13285. }
  13286. /*
  13287. * Read /etc/profile, ~/.profile, $ENV.
  13288. */
  13289. static void
  13290. read_profile(const char *name)
  13291. {
  13292. name = expandstr(name, DQSYNTAX);
  13293. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  13294. return;
  13295. cmdloop(0);
  13296. popfile();
  13297. }
  13298. #if PROFILE
  13299. static short profile_buf[16384];
  13300. extern int etext();
  13301. #endif
  13302. /*
  13303. * Main routine. We initialize things, parse the arguments, execute
  13304. * profiles if we're a login shell, and then call cmdloop to execute
  13305. * commands. The setjmp call sets up the location to jump to when an
  13306. * exception occurs. When an exception occurs the variable "state"
  13307. * is used to figure out how far we had gotten.
  13308. */
  13309. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13310. #if NUM_SCRIPTS > 0
  13311. int ash_main(int argc, char **argv)
  13312. #else
  13313. int ash_main(int argc UNUSED_PARAM, char **argv)
  13314. #endif
  13315. /* note: 'argc' is used only if embedded scripts are enabled */
  13316. {
  13317. volatile smallint state;
  13318. struct jmploc jmploc;
  13319. struct stackmark smark;
  13320. int login_sh;
  13321. /* Initialize global data */
  13322. INIT_G_misc();
  13323. INIT_G_memstack();
  13324. INIT_G_var();
  13325. #if ENABLE_ASH_ALIAS
  13326. INIT_G_alias();
  13327. #endif
  13328. INIT_G_cmdtable();
  13329. #if PROFILE
  13330. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  13331. #endif
  13332. state = 0;
  13333. if (setjmp(jmploc.loc)) {
  13334. smallint e;
  13335. smallint s;
  13336. exitreset();
  13337. e = exception_type;
  13338. s = state;
  13339. if (e == EXEND || e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  13340. exitshell();
  13341. }
  13342. reset();
  13343. if (e == EXINT) {
  13344. newline_and_flush(stderr);
  13345. }
  13346. popstackmark(&smark);
  13347. FORCE_INT_ON; /* enable interrupts */
  13348. if (s == 1)
  13349. goto state1;
  13350. if (s == 2)
  13351. goto state2;
  13352. if (s == 3)
  13353. goto state3;
  13354. goto state4;
  13355. }
  13356. exception_handler = &jmploc;
  13357. rootpid = getpid();
  13358. init();
  13359. setstackmark(&smark);
  13360. #if NUM_SCRIPTS > 0
  13361. if (argc < 0)
  13362. /* Non-NULL minusc tells procargs that an embedded script is being run */
  13363. minusc = get_script_content(-argc - 1);
  13364. #endif
  13365. login_sh = procargs(argv);
  13366. #if DEBUG
  13367. TRACE(("Shell args: "));
  13368. trace_puts_args(argv);
  13369. #endif
  13370. if (login_sh) {
  13371. const char *hp;
  13372. state = 1;
  13373. read_profile("/etc/profile");
  13374. state1:
  13375. state = 2;
  13376. hp = lookupvar("HOME");
  13377. if (hp)
  13378. read_profile("$HOME/.profile");
  13379. }
  13380. state2:
  13381. state = 3;
  13382. if (iflag
  13383. #ifndef linux
  13384. && getuid() == geteuid() && getgid() == getegid()
  13385. #endif
  13386. ) {
  13387. const char *shinit = lookupvar("ENV");
  13388. if (shinit != NULL && *shinit != '\0')
  13389. read_profile(shinit);
  13390. }
  13391. popstackmark(&smark);
  13392. state3:
  13393. state = 4;
  13394. if (minusc) {
  13395. /* evalstring pushes parsefile stack.
  13396. * Ensure we don't falsely claim that 0 (stdin)
  13397. * is one of stacked source fds.
  13398. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13399. // if (!sflag) g_parsefile->pf_fd = -1;
  13400. // ^^ not necessary since now we special-case fd 0
  13401. // in save_fd_on_redirect()
  13402. lineno = 0; // bash compat
  13403. // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
  13404. // The above makes
  13405. // ash -sc 'echo $-'
  13406. // continue reading input from stdin after running 'echo'.
  13407. // bash does not do this: it prints "hBcs" and exits.
  13408. evalstring(minusc, EV_EXIT);
  13409. }
  13410. if (sflag || minusc == NULL) {
  13411. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13412. if (line_input_state) {
  13413. const char *hp = lookupvar("HISTFILE");
  13414. if (!hp) {
  13415. hp = lookupvar("HOME");
  13416. if (hp) {
  13417. INT_OFF;
  13418. hp = concat_path_file(hp, ".ash_history");
  13419. setvar0("HISTFILE", hp);
  13420. free((char*)hp);
  13421. INT_ON;
  13422. hp = lookupvar("HISTFILE");
  13423. }
  13424. }
  13425. if (hp)
  13426. line_input_state->hist_file = xstrdup(hp);
  13427. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13428. hp = lookupvar("HISTFILESIZE");
  13429. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13430. # endif
  13431. }
  13432. #endif
  13433. state4: /* XXX ??? - why isn't this before the "if" statement */
  13434. cmdloop(1);
  13435. }
  13436. #if PROFILE
  13437. monitor(0);
  13438. #endif
  13439. #ifdef GPROF
  13440. {
  13441. extern void _mcleanup(void);
  13442. _mcleanup();
  13443. }
  13444. #endif
  13445. TRACE(("End of main reached\n"));
  13446. exitshell();
  13447. /* NOTREACHED */
  13448. }
  13449. /*-
  13450. * Copyright (c) 1989, 1991, 1993, 1994
  13451. * The Regents of the University of California. All rights reserved.
  13452. *
  13453. * This code is derived from software contributed to Berkeley by
  13454. * Kenneth Almquist.
  13455. *
  13456. * Redistribution and use in source and binary forms, with or without
  13457. * modification, are permitted provided that the following conditions
  13458. * are met:
  13459. * 1. Redistributions of source code must retain the above copyright
  13460. * notice, this list of conditions and the following disclaimer.
  13461. * 2. Redistributions in binary form must reproduce the above copyright
  13462. * notice, this list of conditions and the following disclaimer in the
  13463. * documentation and/or other materials provided with the distribution.
  13464. * 3. Neither the name of the University nor the names of its contributors
  13465. * may be used to endorse or promote products derived from this software
  13466. * without specific prior written permission.
  13467. *
  13468. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13469. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13470. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13471. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13472. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13473. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13474. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13475. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13476. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13477. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13478. * SUCH DAMAGE.
  13479. */