ash.c 336 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918
  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 (80 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. //
  138. ////config:config ASH_SLEEP
  139. ////config: bool "sleep builtin"
  140. ////config: default y
  141. ////config: depends on SHELL_ASH
  142. ////config:
  143. //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  144. //Disabled for now. Has a few annoying problems:
  145. // * sleepcmd() -> sleep_main(), the parsing of bad arguments exits the shell.
  146. // * sleep_for_duration() in sleep_main() has to be interruptible for
  147. // ^C traps to work, which may be a problem for other users
  148. // of sleep_for_duration().
  149. // * BUT, if sleep_for_duration() is interruptible, then SIGCHLD interrupts it
  150. // as well (try "/bin/sleep 1 & sleep 10").
  151. // * sleep_main() must not allocate anything as ^C in ash longjmp's.
  152. // (currently, allocations are only on error paths, in message printing).
  153. //
  154. //config:config ASH_HELP
  155. //config: bool "help builtin"
  156. //config: default y
  157. //config: depends on SHELL_ASH
  158. //config:
  159. //config:config ASH_GETOPTS
  160. //config: bool "getopts builtin"
  161. //config: default y
  162. //config: depends on SHELL_ASH
  163. //config:
  164. //config:config ASH_CMDCMD
  165. //config: bool "command builtin"
  166. //config: default y
  167. //config: depends on SHELL_ASH
  168. //config: help
  169. //config: Enable support for the 'command' builtin, which allows
  170. //config: you to run the specified command or builtin,
  171. //config: even when there is a function with the same name.
  172. //config:
  173. //config:endif # ash options
  174. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  175. // APPLET_ODDNAME:name main location suid_type help
  176. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  177. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  178. //kbuild:lib-$(CONFIG_SHELL_ASH) += ash.o ash_ptr_hack.o shell_common.o
  179. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  180. /*
  181. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  182. * DEBUG=2 to compile in and turn on debugging.
  183. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  184. * debugging info is written to ./trace, quit signal generates core dump.
  185. */
  186. #define DEBUG 0
  187. /* Tweak debug output verbosity here */
  188. #define DEBUG_TIME 0
  189. #define DEBUG_PID 1
  190. #define DEBUG_SIG 1
  191. #define DEBUG_INTONOFF 0
  192. #define PROFILE 0
  193. #define JOBS ENABLE_ASH_JOB_CONTROL
  194. #include <fnmatch.h>
  195. #include <sys/times.h>
  196. #include <sys/utsname.h> /* for setting $HOSTNAME */
  197. #include "busybox.h" /* for applet_names */
  198. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
  199. # include "embedded_scripts.h"
  200. #else
  201. # define NUM_SCRIPTS 0
  202. #endif
  203. /* So far, all bash compat is controlled by one config option */
  204. /* Separate defines document which part of code implements what */
  205. /* function keyword */
  206. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  207. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  208. /* &>file */
  209. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  210. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  211. /* $'...' */
  212. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  213. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  214. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  215. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  216. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  217. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  218. /* BASH_TEST2: [[ EXPR ]]
  219. * Status of [[ support:
  220. * && and || work as they should
  221. * = is glob match operator, not equality operator: STR = GLOB
  222. * == same as =
  223. * =~ is regex match operator: STR =~ REGEX
  224. * TODO:
  225. * singleword+noglob expansion:
  226. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  227. * [[ /bin/n* ]]; echo 0:$?
  228. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  229. * ( ) < > should not have special meaning (IOW: should not require quoting)
  230. * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
  231. */
  232. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  233. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  234. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  235. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  236. #define BASH_EPOCH_VARS ENABLE_ASH_BASH_COMPAT
  237. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  238. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  239. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  240. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  241. #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
  242. /* <(...) and >(...) */
  243. #if HAVE_DEV_FD
  244. # define BASH_PROCESS_SUBST ENABLE_ASH_BASH_COMPAT
  245. # define IF_BASH_PROCESS_SUBST IF_ASH_BASH_COMPAT
  246. #else
  247. # define BASH_PROCESS_SUBST 0
  248. # define IF_BASH_PROCESS_SUBST(...)
  249. #endif
  250. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  251. /* Bionic at least up to version 24 has no glob() */
  252. # undef ENABLE_ASH_INTERNAL_GLOB
  253. # define ENABLE_ASH_INTERNAL_GLOB 1
  254. #endif
  255. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  256. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  257. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  258. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  259. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  260. # error fails to match dirname, subsequently not expanding <pattern> in it.
  261. // Testcase:
  262. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  263. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  264. #endif
  265. #if !ENABLE_ASH_INTERNAL_GLOB
  266. # include <glob.h>
  267. #endif
  268. #include "unicode.h"
  269. #include "shell_common.h"
  270. #if ENABLE_FEATURE_SH_MATH
  271. # include "math.h"
  272. #else
  273. typedef long arith_t;
  274. # define ARITH_FMT "%ld"
  275. #endif
  276. #if ENABLE_ASH_RANDOM_SUPPORT
  277. # include "random.h"
  278. #else
  279. # define CLEAR_RANDOM_T(rnd) ((void)0)
  280. #endif
  281. #include "NUM_APPLETS.h"
  282. #if NUM_APPLETS == 1
  283. /* STANDALONE does not make sense, and won't compile */
  284. # undef CONFIG_FEATURE_SH_STANDALONE
  285. # undef ENABLE_FEATURE_SH_STANDALONE
  286. # undef IF_FEATURE_SH_STANDALONE
  287. # undef IF_NOT_FEATURE_SH_STANDALONE
  288. # define ENABLE_FEATURE_SH_STANDALONE 0
  289. # define IF_FEATURE_SH_STANDALONE(...)
  290. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  291. #endif
  292. #ifndef F_DUPFD_CLOEXEC
  293. # define F_DUPFD_CLOEXEC F_DUPFD
  294. #endif
  295. #ifndef O_CLOEXEC
  296. # define O_CLOEXEC 0
  297. #endif
  298. #ifndef PIPE_BUF
  299. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  300. #endif
  301. #ifndef unlikely
  302. # define unlikely(cond) (cond)
  303. #endif
  304. #if !BB_MMU
  305. # error "Do not even bother, ash will not run on NOMMU machine"
  306. #endif
  307. /* ============ Hash table sizes. Configurable. */
  308. #define VTABSIZE 39
  309. #define ATABSIZE 39
  310. #define CMDTABLESIZE 31 /* should be prime */
  311. /* ============ Shell options */
  312. /* If you add/change options hare, update --help text too */
  313. static const char *const optletters_optnames[] ALIGN_PTR = {
  314. "e" "errexit",
  315. "f" "noglob",
  316. /* bash has '-o ignoreeof', but no short synonym -I for it */
  317. /* (in bash, set -I disables invisible variables (what's that?)) */
  318. "I" "ignoreeof",
  319. /* The below allowed this invocation:
  320. * ash -c 'set -i; echo $-; sleep 5; echo $-'
  321. * to be ^C-ed and get to interactive ash prompt.
  322. * bash does not support such "set -i".
  323. * In our code, this is denoted by empty long name:
  324. */
  325. "i" "",
  326. /* (removing "i" altogether would remove it from "$-", not good) */
  327. "m" "monitor",
  328. "n" "noexec",
  329. /* Ditto: bash has no "set -s", "set -c" */
  330. "s" "",
  331. "c" "",
  332. "x" "xtrace",
  333. "v" "verbose",
  334. "C" "noclobber",
  335. "a" "allexport",
  336. "b" "notify",
  337. "u" "nounset",
  338. "E" "errtrace",
  339. "\0" "vi"
  340. #if BASH_PIPEFAIL
  341. ,"\0" "pipefail"
  342. #endif
  343. #if DEBUG
  344. ,"\0" "nolog"
  345. ,"\0" "debug"
  346. #endif
  347. };
  348. //bash 4.4.23 also has these opts (with these defaults):
  349. //braceexpand on
  350. //emacs on
  351. //errtrace off
  352. //functrace off
  353. //hashall on
  354. //histexpand off
  355. //history on
  356. //interactive-comments on
  357. //keyword off
  358. //onecmd off
  359. //physical off
  360. //posix off
  361. //privileged off
  362. #define optletters(n) optletters_optnames[n][0]
  363. #define optnames(n) (optletters_optnames[n] + 1)
  364. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  365. /* ============ Misc data */
  366. #define msg_illnum "Illegal number: %s"
  367. /*
  368. * We enclose jmp_buf in a structure so that we can declare pointers to
  369. * jump locations. The global variable handler contains the location to
  370. * jump to when an exception occurs, and the global variable exception_type
  371. * contains a code identifying the exception. To implement nested
  372. * exception handlers, the user should save the value of handler on entry
  373. * to an inner scope, set handler to point to a jmploc structure for the
  374. * inner scope, and restore handler on exit from the scope.
  375. */
  376. struct jmploc {
  377. jmp_buf loc;
  378. };
  379. struct globals_misc {
  380. uint8_t exitstatus; /* exit status of last command */
  381. uint8_t back_exitstatus;/* exit status of backquoted command */
  382. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  383. smallint inps4; /* Prevent PS4 nesting. */
  384. int savestatus; /* exit status of last command outside traps */
  385. int rootpid; /* pid of main shell */
  386. /* shell level: 0 for the main shell, 1 for its children, and so on */
  387. int shlvl;
  388. #define rootshell (!shlvl)
  389. int errlinno;
  390. char *minusc; /* argument to -c option */
  391. char *curdir; // = nullstr; /* current working directory */
  392. char *physdir; // = nullstr; /* physical working directory */
  393. char *arg0; /* value of $0 */
  394. struct jmploc *exception_handler;
  395. /*volatile*/ int suppress_int; /* counter */
  396. /* ^^^^^^^ removed "volatile" since on x86, gcc turns suppress_int++
  397. * into ridiculous 3-insn sequence otherwise.
  398. * We don't change suppress_int asyncronously (in a signal handler),
  399. * but we do read it async.
  400. */
  401. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  402. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  403. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  404. smallint exception_type; /* kind of exception: */
  405. #define EXINT 0 /* SIGINT received */
  406. #define EXERROR 1 /* a generic error */
  407. #define EXEND 3 /* exit the shell */
  408. #define EXEXIT 4 /* exit the shell via exitcmd */
  409. char nullstr[1]; /* zero length string */
  410. char optlist[NOPTS];
  411. #define eflag optlist[0]
  412. #define fflag optlist[1]
  413. #define Iflag optlist[2]
  414. #define iflag optlist[3]
  415. #define mflag optlist[4]
  416. #define nflag optlist[5]
  417. #define sflag optlist[6]
  418. #define cflag optlist[7]
  419. #define xflag optlist[8]
  420. #define vflag optlist[9]
  421. #define Cflag optlist[10]
  422. #define aflag optlist[11]
  423. #define bflag optlist[12]
  424. #define uflag optlist[13]
  425. #define Eflag optlist[14]
  426. #define viflag optlist[15]
  427. #if BASH_PIPEFAIL
  428. # define pipefail optlist[16]
  429. #else
  430. # define pipefail 0
  431. #endif
  432. #if DEBUG
  433. # define nolog optlist[16 + BASH_PIPEFAIL]
  434. # define debug optlist[17 + BASH_PIPEFAIL]
  435. #endif
  436. /* trap handler commands */
  437. /*
  438. * Sigmode records the current value of the signal handlers for the various
  439. * modes. A value of zero means that the current handler is not known.
  440. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  441. */
  442. char sigmode[NSIG - 1];
  443. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  444. #define S_CATCH 2 /* signal is caught */
  445. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  446. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  447. /* indicates specified signal received */
  448. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  449. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  450. char *trap[NSIG + 1];
  451. /* trap[0] is EXIT trap, trap[NTRAP_ERR] is ERR trap, other trap[i] are signal traps */
  452. #define NTRAP_ERR NSIG
  453. #define NTRAP_LAST NSIG
  454. char **trap_ptr; /* used only by "trap hack" */
  455. /* Rarely referenced stuff */
  456. /* Cached supplementary group array (for testing executable'ity of files) */
  457. struct cached_groupinfo groupinfo;
  458. #if ENABLE_ASH_RANDOM_SUPPORT
  459. random_t random_gen;
  460. #endif
  461. pid_t backgndpid; /* pid of last background process */
  462. };
  463. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  464. #define G_misc (*ash_ptr_to_globals_misc)
  465. #define exitstatus (G_misc.exitstatus )
  466. #define back_exitstatus (G_misc.back_exitstatus )
  467. #define job_warning (G_misc.job_warning)
  468. #define inps4 (G_misc.inps4 )
  469. #define savestatus (G_misc.savestatus )
  470. #define rootpid (G_misc.rootpid )
  471. #define shlvl (G_misc.shlvl )
  472. #define errlinno (G_misc.errlinno )
  473. #define minusc (G_misc.minusc )
  474. #define curdir (G_misc.curdir )
  475. #define physdir (G_misc.physdir )
  476. #define arg0 (G_misc.arg0 )
  477. #define exception_handler (G_misc.exception_handler)
  478. #define exception_type (G_misc.exception_type )
  479. #define suppress_int (G_misc.suppress_int )
  480. #define pending_int (G_misc.pending_int )
  481. #define got_sigchld (G_misc.got_sigchld )
  482. #define pending_sig (G_misc.pending_sig )
  483. #define nullstr (G_misc.nullstr )
  484. #define optlist (G_misc.optlist )
  485. #define sigmode (G_misc.sigmode )
  486. #define gotsig (G_misc.gotsig )
  487. #define may_have_traps (G_misc.may_have_traps )
  488. #define trap (G_misc.trap )
  489. #define trap_ptr (G_misc.trap_ptr )
  490. #define groupinfo (G_misc.groupinfo )
  491. #define random_gen (G_misc.random_gen )
  492. #define backgndpid (G_misc.backgndpid )
  493. #define INIT_G_misc() do { \
  494. XZALLOC_CONST_PTR(&ash_ptr_to_globals_misc, sizeof(G_misc)); \
  495. savestatus = -1; \
  496. curdir = nullstr; \
  497. physdir = nullstr; \
  498. trap_ptr = trap; \
  499. groupinfo.euid = -1; \
  500. groupinfo.egid = -1; \
  501. } while (0)
  502. /* ============ DEBUG */
  503. #if DEBUG
  504. static void trace_printf(const char *fmt, ...);
  505. static void trace_vprintf(const char *fmt, va_list va);
  506. # define TRACE(param) trace_printf param
  507. # define TRACEV(param) trace_vprintf param
  508. # define close(fd) do { \
  509. int dfd = (fd); \
  510. if (close(dfd) < 0) \
  511. bb_error_msg("bug on %d: closing %d(0x%x)", \
  512. __LINE__, dfd, dfd); \
  513. } while (0)
  514. #else
  515. # define TRACE(param)
  516. # define TRACEV(param)
  517. #endif
  518. /* ============ Utility functions */
  519. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  520. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  521. static int
  522. isdigit_str(const char *str)
  523. {
  524. while (isdigit(*str))
  525. str++;
  526. return (*str == '\0');
  527. }
  528. static const char *
  529. var_end(const char *var)
  530. {
  531. while (*var)
  532. if (*var++ == '=')
  533. break;
  534. return var;
  535. }
  536. /* ============ Parser data */
  537. /*
  538. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  539. */
  540. struct strlist {
  541. struct strlist *next;
  542. char *text;
  543. };
  544. struct alias;
  545. struct strpush {
  546. struct strpush *prev; /* preceding string on stack */
  547. char *prev_string;
  548. int prev_left_in_line;
  549. #if ENABLE_ASH_ALIAS
  550. struct alias *ap; /* if push was associated with an alias */
  551. #endif
  552. char *string; /* remember the string since it may change */
  553. /* Delay freeing so we can stop nested aliases. */
  554. struct strpush *spfree;
  555. /* Remember last two characters for pungetc. */
  556. int lastc[2];
  557. /* Number of outstanding calls to pungetc. */
  558. int unget;
  559. };
  560. /*
  561. * The parsefile structure pointed to by the global variable parsefile
  562. * contains information about the current file being read.
  563. */
  564. struct parsefile {
  565. struct parsefile *prev; /* preceding file on stack */
  566. int linno; /* current line */
  567. int pf_fd; /* file descriptor (or -1 if string) */
  568. int left_in_line; /* number of chars left in this line */
  569. int left_in_buffer; /* number of chars left in this buffer past the line */
  570. char *next_to_pgetc; /* next char in buffer */
  571. char *buf; /* input buffer */
  572. struct strpush *strpush; /* for pushing strings at this level */
  573. struct strpush basestrpush; /* so pushing one is fast */
  574. /* Delay freeing so we can stop nested aliases. */
  575. struct strpush *spfree;
  576. /* Remember last two characters for pungetc. */
  577. int lastc[2];
  578. /* Number of outstanding calls to pungetc. */
  579. int unget;
  580. };
  581. static struct parsefile basepf; /* top level input file */
  582. static struct parsefile *g_parsefile = &basepf; /* current input file */
  583. static char *commandname; /* currently executing command */
  584. /* ============ Interrupts / exceptions */
  585. static void exitshell(void) NORETURN;
  586. /*
  587. * These macros allow the user to suspend the handling of interrupt signals
  588. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  589. * much more efficient and portable. (But hacking the kernel is so much
  590. * more fun than worrying about efficiency and portability. :-))
  591. */
  592. #if DEBUG_INTONOFF
  593. # define INT_OFF do { \
  594. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  595. suppress_int++; \
  596. barrier(); \
  597. } while (0)
  598. #else
  599. # define INT_OFF do { \
  600. suppress_int++; \
  601. barrier(); \
  602. } while (0)
  603. #endif
  604. /*
  605. * Called to raise an exception. Since C doesn't include exceptions, we
  606. * just do a longjmp to the exception handler. The type of exception is
  607. * stored in the global variable "exception_type".
  608. */
  609. static void raise_exception(int) NORETURN;
  610. static void
  611. raise_exception(int e)
  612. {
  613. #if DEBUG
  614. if (exception_handler == NULL)
  615. abort();
  616. #endif
  617. INT_OFF;
  618. exception_type = e;
  619. longjmp(exception_handler->loc, 1);
  620. }
  621. #if DEBUG
  622. #define raise_exception(e) do { \
  623. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  624. raise_exception(e); \
  625. } while (0)
  626. #endif
  627. /*
  628. * Called when a SIGINT is received. (If the user specifies
  629. * that SIGINT is to be trapped or ignored using the trap builtin, then
  630. * this routine is not called.) suppress_int is nonzero when interrupts
  631. * are held using the INT_OFF macro. (The test for iflag is just
  632. * defensive programming.)
  633. */
  634. static void raise_interrupt(void) NORETURN;
  635. static void
  636. raise_interrupt(void)
  637. {
  638. pending_int = 0;
  639. /* Signal is not automatically unmasked after it is raised,
  640. * do it ourself - unmask all signals */
  641. sigprocmask_allsigs(SIG_UNBLOCK);
  642. /* pending_sig = 0; - now done in signal_handler() */
  643. if (!(rootshell && iflag)) {
  644. /* Kill ourself with SIGINT */
  645. signal(SIGINT, SIG_DFL);
  646. raise(SIGINT);
  647. }
  648. /* bash: ^C even on empty command line sets $? */
  649. exitstatus = SIGINT + 128;
  650. raise_exception(EXINT);
  651. /* NOTREACHED */
  652. }
  653. #if DEBUG
  654. #define raise_interrupt() do { \
  655. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  656. raise_interrupt(); \
  657. } while (0)
  658. #endif
  659. static IF_NOT_ASH_OPTIMIZE_FOR_SIZE(inline) void
  660. int_on(void)
  661. {
  662. barrier();
  663. if (--suppress_int == 0 && pending_int)
  664. raise_interrupt(); /* does not return */
  665. barrier();
  666. }
  667. #if DEBUG_INTONOFF
  668. # define INT_ON do { \
  669. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  670. int_on(); \
  671. } while (0)
  672. #else
  673. # define INT_ON int_on()
  674. #endif
  675. static IF_NOT_ASH_OPTIMIZE_FOR_SIZE(inline) void
  676. force_int_on(void)
  677. {
  678. barrier();
  679. suppress_int = 0;
  680. if (pending_int)
  681. raise_interrupt(); /* does not return */
  682. barrier();
  683. }
  684. #define FORCE_INT_ON force_int_on()
  685. #define SAVE_INT(v) ((v) = suppress_int)
  686. #define RESTORE_INT(v) do { \
  687. barrier(); \
  688. suppress_int = (v); \
  689. if (suppress_int == 0 && pending_int) \
  690. raise_interrupt(); /* does not return */ \
  691. barrier(); \
  692. } while (0)
  693. /* ============ Stdout/stderr output */
  694. static void
  695. outstr(const char *p, FILE *file)
  696. {
  697. INT_OFF;
  698. fputs(p, file);
  699. INT_ON;
  700. }
  701. static void
  702. flush_stdout_stderr(void)
  703. {
  704. INT_OFF;
  705. fflush_all();
  706. INT_ON;
  707. }
  708. /* Was called outcslow(c,FILE*), but c was always '\n' */
  709. static void
  710. newline_and_flush(FILE *dest)
  711. {
  712. INT_OFF;
  713. putc('\n', dest);
  714. fflush(dest);
  715. INT_ON;
  716. }
  717. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  718. static int
  719. out1fmt(const char *fmt, ...)
  720. {
  721. va_list ap;
  722. int r;
  723. INT_OFF;
  724. va_start(ap, fmt);
  725. r = vprintf(fmt, ap);
  726. va_end(ap);
  727. INT_ON;
  728. return r;
  729. }
  730. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  731. static int
  732. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  733. {
  734. va_list ap;
  735. int ret;
  736. INT_OFF;
  737. va_start(ap, fmt);
  738. ret = vsnprintf(outbuf, length, fmt, ap);
  739. va_end(ap);
  740. INT_ON;
  741. return ret > (int)length ? length : ret;
  742. }
  743. static void
  744. out1str(const char *p)
  745. {
  746. outstr(p, stdout);
  747. }
  748. static void
  749. out2str(const char *p)
  750. {
  751. outstr(p, stderr);
  752. flush_stdout_stderr();
  753. }
  754. /* ============ Parser structures */
  755. /* control characters in argument strings */
  756. #define CTL_FIRST CTLESC
  757. #define CTLESC ((unsigned char)'\201') /* escape next character */
  758. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  759. #define CTLENDVAR ((unsigned char)'\203')
  760. #define CTLBACKQ ((unsigned char)'\204')
  761. #define CTLARI ((unsigned char)'\205') /* arithmetic expression */
  762. #define CTLENDARI ((unsigned char)'\206')
  763. #define CTLQUOTEMARK ((unsigned char)'\207')
  764. #define CTL_LAST CTLQUOTEMARK
  765. #if BASH_PROCESS_SUBST
  766. # define CTLTOPROC ((unsigned char)'\210')
  767. # define CTLFROMPROC ((unsigned char)'\211')
  768. # undef CTL_LAST
  769. # define CTL_LAST CTLFROMPROC
  770. #endif
  771. /* variable substitution byte (follows CTLVAR) */
  772. #define VSTYPE 0x0f /* type of variable substitution */
  773. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  774. /* values of VSTYPE field */
  775. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  776. #define VSMINUS 0x2 /* ${var-text} */
  777. #define VSPLUS 0x3 /* ${var+text} */
  778. #define VSQUESTION 0x4 /* ${var?message} */
  779. #define VSASSIGN 0x5 /* ${var=text} */
  780. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  781. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  782. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  783. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  784. #define VSLENGTH 0xa /* ${#var} */
  785. #if BASH_SUBSTR
  786. #define VSSUBSTR 0xc /* ${var:position:length} */
  787. #endif
  788. #if BASH_PATTERN_SUBST
  789. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  790. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  791. #endif
  792. static const char dolatstr[] ALIGN1 = {
  793. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  794. };
  795. #define DOLATSTRLEN 6
  796. #define NCMD 0
  797. #define NPIPE 1
  798. #define NREDIR 2
  799. #define NBACKGND 3
  800. #define NSUBSHELL 4
  801. #define NAND 5
  802. #define NOR 6
  803. #define NSEMI 7
  804. #define NIF 8
  805. #define NWHILE 9
  806. #define NUNTIL 10
  807. #define NFOR 11
  808. #define NCASE 12
  809. #define NCLIST 13
  810. #define NDEFUN 14
  811. #define NARG 15
  812. #define NTO 16
  813. #if BASH_REDIR_OUTPUT
  814. #define NTO2 17
  815. #endif
  816. #define NCLOBBER 18
  817. #define NFROM 19
  818. #define NFROMTO 20
  819. #define NAPPEND 21
  820. #define NTOFD 22
  821. #define NFROMFD 23
  822. #define NHERE 24
  823. #define NXHERE 25
  824. #define NNOT 26
  825. #define N_NUMBER 27
  826. union node;
  827. struct ncmd {
  828. smallint type; /* Nxxxx */
  829. int linno;
  830. union node *assign;
  831. union node *args;
  832. union node *redirect;
  833. };
  834. struct npipe {
  835. smallint type;
  836. smallint pipe_backgnd;
  837. struct nodelist *cmdlist;
  838. };
  839. struct nredir {
  840. smallint type;
  841. int linno;
  842. union node *n;
  843. union node *redirect;
  844. };
  845. struct nbinary {
  846. smallint type;
  847. union node *ch1;
  848. union node *ch2;
  849. };
  850. struct nif {
  851. smallint type;
  852. union node *test;
  853. union node *ifpart;
  854. union node *elsepart;
  855. };
  856. struct nfor {
  857. smallint type;
  858. int linno;
  859. union node *args;
  860. union node *body;
  861. char *var;
  862. };
  863. struct ncase {
  864. smallint type;
  865. int linno;
  866. union node *expr;
  867. union node *cases;
  868. };
  869. struct nclist {
  870. smallint type;
  871. union node *next;
  872. union node *pattern;
  873. union node *body;
  874. };
  875. struct ndefun {
  876. smallint type;
  877. int linno;
  878. char *text;
  879. union node *body;
  880. };
  881. struct narg {
  882. smallint type;
  883. union node *next;
  884. char *text;
  885. struct nodelist *backquote;
  886. };
  887. /* nfile and ndup layout must match!
  888. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  889. * that it is actually NTO2 (>&file), and change its type.
  890. */
  891. struct nfile {
  892. smallint type;
  893. union node *next;
  894. int fd;
  895. int _unused_dupfd;
  896. union node *fname;
  897. char *expfname;
  898. };
  899. struct ndup {
  900. smallint type;
  901. union node *next;
  902. int fd;
  903. int dupfd;
  904. union node *vname;
  905. char *_unused_expfname;
  906. };
  907. struct nhere {
  908. smallint type;
  909. union node *next;
  910. int fd;
  911. union node *doc;
  912. };
  913. struct nnot {
  914. smallint type;
  915. union node *com;
  916. };
  917. union node {
  918. smallint type;
  919. struct ncmd ncmd;
  920. struct npipe npipe;
  921. struct nredir nredir;
  922. struct nbinary nbinary;
  923. struct nif nif;
  924. struct nfor nfor;
  925. struct ncase ncase;
  926. struct nclist nclist;
  927. struct ndefun ndefun;
  928. struct narg narg;
  929. struct nfile nfile;
  930. struct ndup ndup;
  931. struct nhere nhere;
  932. struct nnot nnot;
  933. };
  934. /*
  935. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  936. * It must be distinct from NULL.
  937. */
  938. #define NODE_EOF ((union node *) -1L)
  939. struct nodelist {
  940. struct nodelist *next;
  941. union node *n;
  942. };
  943. struct funcnode {
  944. int count;
  945. union node n;
  946. };
  947. /*
  948. * Free a parse tree.
  949. */
  950. static void
  951. freefunc(struct funcnode *f)
  952. {
  953. if (f && --f->count < 0)
  954. free(f);
  955. }
  956. /* ============ Debugging output */
  957. #if DEBUG
  958. static FILE *tracefile;
  959. static void
  960. trace_printf(const char *fmt, ...)
  961. {
  962. va_list va;
  963. if (debug != 1)
  964. return;
  965. if (DEBUG_TIME)
  966. fprintf(tracefile, "%u ", (int) time(NULL));
  967. if (DEBUG_PID)
  968. fprintf(tracefile, "[%u] ", (int) getpid());
  969. if (DEBUG_SIG)
  970. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  971. va_start(va, fmt);
  972. vfprintf(tracefile, fmt, va);
  973. va_end(va);
  974. }
  975. static void
  976. trace_vprintf(const char *fmt, va_list va)
  977. {
  978. if (debug != 1)
  979. return;
  980. vfprintf(tracefile, fmt, va);
  981. fprintf(tracefile, "\n");
  982. }
  983. static void
  984. trace_puts(const char *s)
  985. {
  986. if (debug != 1)
  987. return;
  988. fputs(s, tracefile);
  989. }
  990. static void
  991. trace_puts_quoted(char *s)
  992. {
  993. char *p;
  994. char c;
  995. if (debug != 1)
  996. return;
  997. putc('"', tracefile);
  998. for (p = s; *p; p++) {
  999. switch ((unsigned char)*p) {
  1000. case '\n': c = 'n'; goto backslash;
  1001. case '\t': c = 't'; goto backslash;
  1002. case '\r': c = 'r'; goto backslash;
  1003. case '\"': c = '\"'; goto backslash;
  1004. case '\\': c = '\\'; goto backslash;
  1005. case CTLESC: c = 'e'; goto backslash;
  1006. case CTLVAR: c = 'v'; goto backslash;
  1007. case CTLBACKQ: c = 'q'; goto backslash;
  1008. #if BASH_PROCESS_SUBST
  1009. case CTLTOPROC: c = 'p'; goto backslash;
  1010. case CTLFROMPROC: c = 'P'; goto backslash;
  1011. #endif
  1012. backslash:
  1013. putc('\\', tracefile);
  1014. putc(c, tracefile);
  1015. break;
  1016. default:
  1017. if (*p >= ' ' && *p <= '~')
  1018. putc(*p, tracefile);
  1019. else {
  1020. putc('\\', tracefile);
  1021. putc((*p >> 6) & 03, tracefile);
  1022. putc((*p >> 3) & 07, tracefile);
  1023. putc(*p & 07, tracefile);
  1024. }
  1025. break;
  1026. }
  1027. }
  1028. putc('"', tracefile);
  1029. }
  1030. static void
  1031. trace_puts_args(char **ap)
  1032. {
  1033. if (debug != 1)
  1034. return;
  1035. if (!*ap)
  1036. return;
  1037. while (1) {
  1038. trace_puts_quoted(*ap);
  1039. if (!*++ap) {
  1040. putc('\n', tracefile);
  1041. break;
  1042. }
  1043. putc(' ', tracefile);
  1044. }
  1045. }
  1046. static void
  1047. opentrace(void)
  1048. {
  1049. char s[100];
  1050. #ifdef O_APPEND
  1051. int flags;
  1052. #endif
  1053. if (debug != 1) {
  1054. if (tracefile)
  1055. fflush(tracefile);
  1056. /* leave open because libedit might be using it */
  1057. return;
  1058. }
  1059. strcpy(s, "./trace");
  1060. if (tracefile) {
  1061. if (!freopen(s, "a", tracefile)) {
  1062. fprintf(stderr, "Can't re-open %s\n", s);
  1063. debug = 0;
  1064. return;
  1065. }
  1066. } else {
  1067. tracefile = fopen(s, "a");
  1068. if (tracefile == NULL) {
  1069. fprintf(stderr, "Can't open %s\n", s);
  1070. debug = 0;
  1071. return;
  1072. }
  1073. }
  1074. #ifdef O_APPEND
  1075. flags = fcntl(fileno(tracefile), F_GETFL);
  1076. if (flags >= 0)
  1077. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  1078. #endif
  1079. setlinebuf(tracefile);
  1080. fputs("\nTracing started.\n", tracefile);
  1081. }
  1082. static void
  1083. indent(int amount, char *pfx, FILE *fp)
  1084. {
  1085. int i;
  1086. for (i = 0; i < amount; i++) {
  1087. if (pfx && i == amount - 1)
  1088. fputs(pfx, fp);
  1089. putc('\t', fp);
  1090. }
  1091. }
  1092. /* little circular references here... */
  1093. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  1094. static void
  1095. sharg(union node *arg, FILE *fp)
  1096. {
  1097. char *p;
  1098. struct nodelist *bqlist;
  1099. unsigned char subtype;
  1100. if (arg->type != NARG) {
  1101. out1fmt("<node type %d>\n", arg->type);
  1102. abort();
  1103. }
  1104. bqlist = arg->narg.backquote;
  1105. for (p = arg->narg.text; *p; p++) {
  1106. switch ((unsigned char)*p) {
  1107. case CTLESC:
  1108. p++;
  1109. putc(*p, fp);
  1110. break;
  1111. case CTLVAR:
  1112. putc('$', fp);
  1113. putc('{', fp);
  1114. subtype = *++p;
  1115. if (subtype == VSLENGTH)
  1116. putc('#', fp);
  1117. while (*p != '=') {
  1118. putc(*p, fp);
  1119. p++;
  1120. }
  1121. if (subtype & VSNUL)
  1122. putc(':', fp);
  1123. switch (subtype & VSTYPE) {
  1124. case VSNORMAL:
  1125. putc('}', fp);
  1126. break;
  1127. case VSMINUS:
  1128. putc('-', fp);
  1129. break;
  1130. case VSPLUS:
  1131. putc('+', fp);
  1132. break;
  1133. case VSQUESTION:
  1134. putc('?', fp);
  1135. break;
  1136. case VSASSIGN:
  1137. putc('=', fp);
  1138. break;
  1139. case VSTRIMLEFT:
  1140. putc('#', fp);
  1141. break;
  1142. case VSTRIMLEFTMAX:
  1143. putc('#', fp);
  1144. putc('#', fp);
  1145. break;
  1146. case VSTRIMRIGHT:
  1147. putc('%', fp);
  1148. break;
  1149. case VSTRIMRIGHTMAX:
  1150. putc('%', fp);
  1151. putc('%', fp);
  1152. break;
  1153. case VSLENGTH:
  1154. break;
  1155. default:
  1156. out1fmt("<subtype %d>", subtype);
  1157. }
  1158. break;
  1159. case CTLENDVAR:
  1160. putc('}', fp);
  1161. break;
  1162. #if BASH_PROCESS_SUBST
  1163. case CTLTOPROC:
  1164. putc('>', fp);
  1165. goto backq;
  1166. case CTLFROMPROC:
  1167. putc('<', fp);
  1168. goto backq;
  1169. #endif
  1170. case CTLBACKQ:
  1171. putc('$', fp);
  1172. IF_BASH_PROCESS_SUBST(backq:)
  1173. putc('(', fp);
  1174. shtree(bqlist->n, -1, NULL, fp);
  1175. putc(')', fp);
  1176. break;
  1177. default:
  1178. putc(*p, fp);
  1179. break;
  1180. }
  1181. }
  1182. }
  1183. static void
  1184. shcmd(union node *cmd, FILE *fp)
  1185. {
  1186. union node *np;
  1187. int first;
  1188. const char *s;
  1189. int dftfd;
  1190. first = 1;
  1191. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1192. if (!first)
  1193. putc(' ', fp);
  1194. sharg(np, fp);
  1195. first = 0;
  1196. }
  1197. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1198. if (!first)
  1199. putc(' ', fp);
  1200. dftfd = 0;
  1201. switch (np->nfile.type) {
  1202. case NTO: s = ">>"+1; dftfd = 1; break;
  1203. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1204. case NAPPEND: s = ">>"; dftfd = 1; break;
  1205. #if BASH_REDIR_OUTPUT
  1206. case NTO2:
  1207. #endif
  1208. case NTOFD: s = ">&"; dftfd = 1; break;
  1209. case NFROM: s = "<"; break;
  1210. case NFROMFD: s = "<&"; break;
  1211. case NFROMTO: s = "<>"; break;
  1212. default: s = "*error*"; break;
  1213. }
  1214. if (np->nfile.fd != dftfd)
  1215. fprintf(fp, "%d", np->nfile.fd);
  1216. fputs(s, fp);
  1217. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1218. fprintf(fp, "%d", np->ndup.dupfd);
  1219. } else {
  1220. sharg(np->nfile.fname, fp);
  1221. }
  1222. first = 0;
  1223. }
  1224. }
  1225. static void
  1226. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1227. {
  1228. struct nodelist *lp;
  1229. const char *s;
  1230. if (n == NULL)
  1231. return;
  1232. indent(ind, pfx, fp);
  1233. if (n == NODE_EOF) {
  1234. fputs("<EOF>", fp);
  1235. return;
  1236. }
  1237. switch (n->type) {
  1238. case NSEMI:
  1239. s = "; ";
  1240. goto binop;
  1241. case NAND:
  1242. s = " && ";
  1243. goto binop;
  1244. case NOR:
  1245. s = " || ";
  1246. binop:
  1247. shtree(n->nbinary.ch1, ind, NULL, fp);
  1248. /* if (ind < 0) */
  1249. fputs(s, fp);
  1250. shtree(n->nbinary.ch2, ind, NULL, fp);
  1251. break;
  1252. case NCMD:
  1253. shcmd(n, fp);
  1254. if (ind >= 0)
  1255. putc('\n', fp);
  1256. break;
  1257. case NPIPE:
  1258. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1259. shtree(lp->n, 0, NULL, fp);
  1260. if (lp->next)
  1261. fputs(" | ", fp);
  1262. }
  1263. if (n->npipe.pipe_backgnd)
  1264. fputs(" &", fp);
  1265. if (ind >= 0)
  1266. putc('\n', fp);
  1267. break;
  1268. default:
  1269. fprintf(fp, "<node type %d>", n->type);
  1270. if (ind >= 0)
  1271. putc('\n', fp);
  1272. break;
  1273. }
  1274. }
  1275. static void
  1276. showtree(union node *n)
  1277. {
  1278. trace_puts("showtree called\n");
  1279. shtree(n, 1, NULL, stderr);
  1280. }
  1281. #endif /* DEBUG */
  1282. /* ============ Message printing */
  1283. static void
  1284. ash_vmsg(const char *msg, va_list ap)
  1285. {
  1286. fprintf(stderr, "%s: ", arg0);
  1287. if (commandname) {
  1288. if (strcmp(arg0, commandname))
  1289. fprintf(stderr, "%s: ", commandname);
  1290. if (!iflag || g_parsefile->pf_fd > 0)
  1291. fprintf(stderr, "line %d: ", errlinno);
  1292. }
  1293. vfprintf(stderr, msg, ap);
  1294. newline_and_flush(stderr);
  1295. }
  1296. /*
  1297. * Exverror is called to raise the error exception. If the second argument
  1298. * is not NULL then error prints an error message using printf style
  1299. * formatting. It then raises the error exception.
  1300. */
  1301. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1302. static void
  1303. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1304. {
  1305. #if DEBUG
  1306. if (msg) {
  1307. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1308. TRACEV((msg, ap));
  1309. } else
  1310. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1311. if (msg)
  1312. #endif
  1313. ash_vmsg(msg, ap);
  1314. flush_stdout_stderr();
  1315. raise_exception(cond);
  1316. /* NOTREACHED */
  1317. }
  1318. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1319. static void
  1320. ash_msg_and_raise_error(const char *msg, ...)
  1321. {
  1322. va_list ap;
  1323. exitstatus = 2;
  1324. va_start(ap, msg);
  1325. ash_vmsg_and_raise(EXERROR, msg, ap);
  1326. /* NOTREACHED */
  1327. va_end(ap);
  1328. }
  1329. /*
  1330. * 'fmt' must be a string literal.
  1331. */
  1332. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1333. static void raise_error_syntax(const char *) NORETURN;
  1334. static void
  1335. raise_error_syntax(const char *msg)
  1336. {
  1337. errlinno = g_parsefile->linno;
  1338. ash_msg_and_raise_error("syntax error: %s", msg);
  1339. /* NOTREACHED */
  1340. }
  1341. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1342. static void
  1343. ash_msg_and_raise(int cond, const char *msg, ...)
  1344. {
  1345. va_list ap;
  1346. va_start(ap, msg);
  1347. ash_vmsg_and_raise(cond, msg, ap);
  1348. /* NOTREACHED */
  1349. va_end(ap);
  1350. }
  1351. /*
  1352. * error/warning routines for external builtins
  1353. */
  1354. static void
  1355. ash_msg(const char *fmt, ...)
  1356. {
  1357. va_list ap;
  1358. va_start(ap, fmt);
  1359. ash_vmsg(fmt, ap);
  1360. va_end(ap);
  1361. }
  1362. /*
  1363. * Return a string describing an error. The returned string may be a
  1364. * pointer to a static buffer that will be overwritten on the next call.
  1365. * Action describes the operation that got the error.
  1366. */
  1367. static const char *
  1368. errmsg(int e, const char *em)
  1369. {
  1370. if (e == ENOENT || e == ENOTDIR) {
  1371. return em;
  1372. }
  1373. return strerror(e);
  1374. }
  1375. /* ============ Memory allocation */
  1376. #if 0
  1377. /* I consider these wrappers nearly useless:
  1378. * ok, they return you to nearest exception handler, but
  1379. * how much memory do you leak in the process, making
  1380. * memory starvation worse?
  1381. */
  1382. static void *
  1383. ckrealloc(void * p, size_t nbytes)
  1384. {
  1385. p = realloc(p, nbytes);
  1386. if (!p)
  1387. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1388. return p;
  1389. }
  1390. static void *
  1391. ckmalloc(size_t nbytes)
  1392. {
  1393. return ckrealloc(NULL, nbytes);
  1394. }
  1395. static void *
  1396. ckzalloc(size_t nbytes)
  1397. {
  1398. return memset(ckmalloc(nbytes), 0, nbytes);
  1399. }
  1400. static char *
  1401. ckstrdup(const char *s)
  1402. {
  1403. char *p = strdup(s);
  1404. if (!p)
  1405. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1406. return p;
  1407. }
  1408. #else
  1409. /* Using bbox equivalents. They exit if out of memory */
  1410. # define ckrealloc xrealloc
  1411. # define ckmalloc xmalloc
  1412. # define ckzalloc xzalloc
  1413. # define ckstrdup xstrdup
  1414. #endif
  1415. /*
  1416. * It appears that grabstackstr() will barf with such alignments
  1417. * because stalloc() will return a string allocated in a new stackblock.
  1418. */
  1419. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1420. enum {
  1421. /* Most machines require the value returned from malloc to be aligned
  1422. * in some way. The following macro will get this right
  1423. * on many machines. */
  1424. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1425. /* Minimum size of a block */
  1426. MINSIZE = SHELL_ALIGN(504),
  1427. };
  1428. struct stack_block {
  1429. struct stack_block *prev;
  1430. char space[MINSIZE];
  1431. };
  1432. struct stackmark {
  1433. struct stack_block *stackp;
  1434. char *stacknxt;
  1435. size_t stacknleft;
  1436. };
  1437. struct globals_memstack {
  1438. struct stack_block *g_stackp; // = &stackbase;
  1439. char *g_stacknxt; // = stackbase.space;
  1440. char *sstrend; // = stackbase.space + MINSIZE;
  1441. size_t g_stacknleft; // = MINSIZE;
  1442. struct stack_block stackbase;
  1443. };
  1444. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1445. #define G_memstack (*ash_ptr_to_globals_memstack)
  1446. #define g_stackp (G_memstack.g_stackp )
  1447. #define g_stacknxt (G_memstack.g_stacknxt )
  1448. #define sstrend (G_memstack.sstrend )
  1449. #define g_stacknleft (G_memstack.g_stacknleft)
  1450. #define stackbase (G_memstack.stackbase )
  1451. #define INIT_G_memstack() do { \
  1452. XZALLOC_CONST_PTR(&ash_ptr_to_globals_memstack, sizeof(G_memstack)); \
  1453. g_stackp = &stackbase; \
  1454. g_stacknxt = stackbase.space; \
  1455. g_stacknleft = MINSIZE; \
  1456. sstrend = stackbase.space + MINSIZE; \
  1457. } while (0)
  1458. #define stackblock() ((void *)g_stacknxt)
  1459. #define stackblocksize() g_stacknleft
  1460. /*
  1461. * Parse trees for commands are allocated in lifo order, so we use a stack
  1462. * to make this more efficient, and also to avoid all sorts of exception
  1463. * handling code to handle interrupts in the middle of a parse.
  1464. *
  1465. * The size 504 was chosen because the Ultrix malloc handles that size
  1466. * well.
  1467. */
  1468. static void *
  1469. stalloc(size_t nbytes)
  1470. {
  1471. char *p;
  1472. size_t aligned;
  1473. aligned = SHELL_ALIGN(nbytes);
  1474. if (aligned > g_stacknleft) {
  1475. size_t len;
  1476. size_t blocksize;
  1477. struct stack_block *sp;
  1478. blocksize = aligned;
  1479. if (blocksize < MINSIZE)
  1480. blocksize = MINSIZE;
  1481. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1482. if (len < blocksize)
  1483. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1484. INT_OFF;
  1485. sp = ckmalloc(len);
  1486. sp->prev = g_stackp;
  1487. g_stacknxt = sp->space;
  1488. g_stacknleft = blocksize;
  1489. sstrend = g_stacknxt + blocksize;
  1490. g_stackp = sp;
  1491. INT_ON;
  1492. }
  1493. p = g_stacknxt;
  1494. g_stacknxt += aligned;
  1495. g_stacknleft -= aligned;
  1496. return p;
  1497. }
  1498. static void *
  1499. stzalloc(size_t nbytes)
  1500. {
  1501. return memset(stalloc(nbytes), 0, nbytes);
  1502. }
  1503. static void
  1504. stunalloc(void *p)
  1505. {
  1506. #if DEBUG
  1507. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1508. write(STDERR_FILENO, "stunalloc\n", 10);
  1509. abort();
  1510. }
  1511. #endif
  1512. g_stacknleft += g_stacknxt - (char *)p;
  1513. g_stacknxt = p;
  1514. }
  1515. /*
  1516. * Like strdup but works with the ash stack.
  1517. */
  1518. static char *
  1519. sstrdup(const char *p)
  1520. {
  1521. size_t len = strlen(p) + 1;
  1522. return memcpy(stalloc(len), p, len);
  1523. }
  1524. static ALWAYS_INLINE void
  1525. grabstackblock(size_t len)
  1526. {
  1527. stalloc(len);
  1528. }
  1529. static void
  1530. pushstackmark(struct stackmark *mark, size_t len)
  1531. {
  1532. mark->stackp = g_stackp;
  1533. mark->stacknxt = g_stacknxt;
  1534. mark->stacknleft = g_stacknleft;
  1535. grabstackblock(len);
  1536. }
  1537. static void
  1538. setstackmark(struct stackmark *mark)
  1539. {
  1540. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1541. }
  1542. static void
  1543. popstackmark(struct stackmark *mark)
  1544. {
  1545. struct stack_block *sp;
  1546. if (!mark->stackp)
  1547. return;
  1548. INT_OFF;
  1549. while (g_stackp != mark->stackp) {
  1550. sp = g_stackp;
  1551. g_stackp = sp->prev;
  1552. free(sp);
  1553. }
  1554. g_stacknxt = mark->stacknxt;
  1555. g_stacknleft = mark->stacknleft;
  1556. sstrend = mark->stacknxt + mark->stacknleft;
  1557. INT_ON;
  1558. }
  1559. /*
  1560. * When the parser reads in a string, it wants to stick the string on the
  1561. * stack and only adjust the stack pointer when it knows how big the
  1562. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1563. * of space on top of the stack and stackblocklen returns the length of
  1564. * this block. Growstackblock will grow this space by at least one byte,
  1565. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1566. * part of the block that has been used.
  1567. */
  1568. static void
  1569. growstackblock(size_t min)
  1570. {
  1571. size_t newlen;
  1572. newlen = g_stacknleft * 2;
  1573. if (newlen < g_stacknleft)
  1574. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1575. min = SHELL_ALIGN(min | 128);
  1576. if (newlen < min)
  1577. newlen += min;
  1578. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1579. struct stack_block *sp;
  1580. struct stack_block *prevstackp;
  1581. size_t grosslen;
  1582. INT_OFF;
  1583. sp = g_stackp;
  1584. prevstackp = sp->prev;
  1585. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1586. sp = ckrealloc(sp, grosslen);
  1587. sp->prev = prevstackp;
  1588. g_stackp = sp;
  1589. g_stacknxt = sp->space;
  1590. g_stacknleft = newlen;
  1591. sstrend = sp->space + newlen;
  1592. INT_ON;
  1593. } else {
  1594. char *oldspace = g_stacknxt;
  1595. size_t oldlen = g_stacknleft;
  1596. char *p = stalloc(newlen);
  1597. /* free the space we just allocated */
  1598. g_stacknxt = memcpy(p, oldspace, oldlen);
  1599. g_stacknleft += newlen;
  1600. }
  1601. }
  1602. /*
  1603. * The following routines are somewhat easier to use than the above.
  1604. * The user declares a variable of type STACKSTR, which may be declared
  1605. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1606. * the user uses the macro STPUTC to add characters to the string. In
  1607. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1608. * grown as necessary. When the user is done, she can just leave the
  1609. * string there and refer to it using stackblock(). Or she can allocate
  1610. * the space for it using grabstackstr(). If it is necessary to allow
  1611. * someone else to use the stack temporarily and then continue to grow
  1612. * the string, the user should use grabstack to allocate the space, and
  1613. * then call ungrabstr(p) to return to the previous mode of operation.
  1614. *
  1615. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1616. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1617. * is space for at least one character.
  1618. */
  1619. static void *
  1620. growstackstr(void)
  1621. {
  1622. size_t len = stackblocksize();
  1623. growstackblock(0);
  1624. return (char *)stackblock() + len;
  1625. }
  1626. static char *
  1627. growstackto(size_t len)
  1628. {
  1629. if (stackblocksize() < len)
  1630. growstackblock(len);
  1631. return stackblock();
  1632. }
  1633. /*
  1634. * Called from CHECKSTRSPACE.
  1635. */
  1636. static char *
  1637. makestrspace(size_t newlen, char *p)
  1638. {
  1639. size_t len = p - g_stacknxt;
  1640. return growstackto(len + newlen) + len;
  1641. }
  1642. static char *
  1643. stnputs(const char *s, size_t n, char *p)
  1644. {
  1645. p = makestrspace(n, p);
  1646. p = (char *)mempcpy(p, s, n);
  1647. return p;
  1648. }
  1649. static char *
  1650. stack_putstr(const char *s, char *p)
  1651. {
  1652. return stnputs(s, strlen(s), p);
  1653. }
  1654. static char *
  1655. _STPUTC(int c, char *p)
  1656. {
  1657. if (p == sstrend)
  1658. p = growstackstr();
  1659. *p++ = c;
  1660. return p;
  1661. }
  1662. #define STARTSTACKSTR(p) ((p) = stackblock())
  1663. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1664. #define CHECKSTRSPACE(n, p) do { \
  1665. char *q = (p); \
  1666. size_t l = (n); \
  1667. size_t m = sstrend - q; \
  1668. if (l > m) \
  1669. (p) = makestrspace(l, q); \
  1670. } while (0)
  1671. #define USTPUTC(c, p) (*(p)++ = (c))
  1672. #define STACKSTRNUL(p) do { \
  1673. if ((p) == sstrend) \
  1674. (p) = growstackstr(); \
  1675. *(p) = '\0'; \
  1676. } while (0)
  1677. #define STUNPUTC(p) (--(p))
  1678. #define STTOPC(p) ((p)[-1])
  1679. #define STADJUST(amount, p) ((p) += (amount))
  1680. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1681. #define ungrabstackstr(s, p) stunalloc(s)
  1682. #define stackstrend() ((void *)sstrend)
  1683. /* ============ String helpers */
  1684. /*
  1685. * prefix -- see if pfx is a prefix of string.
  1686. */
  1687. static ALWAYS_INLINE char *
  1688. prefix(const char *string, const char *pfx)
  1689. {
  1690. return is_prefixed_with(string, pfx);
  1691. #if 0 /* dash implementation: */
  1692. while (*pfx) {
  1693. if (*pfx++ != *string++)
  1694. return NULL;
  1695. }
  1696. return (char *) string;
  1697. #endif
  1698. }
  1699. /*
  1700. * Check for a valid number. This should be elsewhere.
  1701. */
  1702. static int
  1703. is_number(const char *p)
  1704. {
  1705. do {
  1706. if (!isdigit(*p))
  1707. return 0;
  1708. } while (*++p != '\0');
  1709. return 1;
  1710. }
  1711. /*
  1712. * Convert a string of digits to an integer, printing an error message on
  1713. * failure.
  1714. */
  1715. static int
  1716. number(const char *s)
  1717. {
  1718. if (!is_number(s))
  1719. ash_msg_and_raise_error(msg_illnum, s);
  1720. return atoi(s);
  1721. }
  1722. /*
  1723. * Produce a single quoted string suitable as input to the shell.
  1724. * The return string is allocated on the stack.
  1725. */
  1726. static char *
  1727. single_quote(const char *s)
  1728. {
  1729. char *p;
  1730. STARTSTACKSTR(p);
  1731. do {
  1732. char *q;
  1733. size_t len;
  1734. len = strchrnul(s, '\'') - s;
  1735. q = p = makestrspace(len + 3, p);
  1736. *q++ = '\'';
  1737. q = (char *)mempcpy(q, s, len);
  1738. *q++ = '\'';
  1739. s += len;
  1740. STADJUST(q - p, p);
  1741. if (*s != '\'')
  1742. break;
  1743. len = 0;
  1744. do len++; while (*++s == '\'');
  1745. q = p = makestrspace(len + 3, p);
  1746. *q++ = '"';
  1747. q = (char *)mempcpy(q, s - len, len);
  1748. *q++ = '"';
  1749. STADJUST(q - p, p);
  1750. } while (*s);
  1751. USTPUTC('\0', p);
  1752. return stackblock();
  1753. }
  1754. /*
  1755. * Produce a possibly single quoted string suitable as input to the shell.
  1756. * If quoting was done, the return string is allocated on the stack,
  1757. * otherwise a pointer to the original string is returned.
  1758. */
  1759. static const char *
  1760. maybe_single_quote(const char *s)
  1761. {
  1762. const char *p = s;
  1763. while (*p) {
  1764. /* Assuming ACSII */
  1765. /* quote ctrl_chars space !"#$%&'()* */
  1766. if (*p < '+')
  1767. goto need_quoting;
  1768. /* quote ;<=>? */
  1769. if (*p >= ';' && *p <= '?')
  1770. goto need_quoting;
  1771. /* quote `[\ */
  1772. if (*p == '`')
  1773. goto need_quoting;
  1774. if (*p == '[')
  1775. goto need_quoting;
  1776. if (*p == '\\')
  1777. goto need_quoting;
  1778. /* quote {|}~ DEL and high bytes */
  1779. if (*p > 'z')
  1780. goto need_quoting;
  1781. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1782. /* TODO: maybe avoid quoting % */
  1783. p++;
  1784. }
  1785. return s;
  1786. need_quoting:
  1787. return single_quote(s);
  1788. }
  1789. /* ============ nextopt */
  1790. static char **argptr; /* argument list for builtin commands */
  1791. static char *optionarg; /* set by nextopt (like getopt) */
  1792. static char *optptr; /* used by nextopt */
  1793. /*
  1794. * XXX - should get rid of. Have all builtins use getopt(3).
  1795. * The library getopt must have the BSD extension static variable
  1796. * "optreset", otherwise it can't be used within the shell safely.
  1797. *
  1798. * Standard option processing (a la getopt) for builtin routines.
  1799. * The only argument that is passed to nextopt is the option string;
  1800. * the other arguments are unnecessary. It returns the character,
  1801. * or '\0' on end of input.
  1802. */
  1803. static int
  1804. nextopt(const char *optstring)
  1805. {
  1806. char *p;
  1807. const char *q;
  1808. char c;
  1809. p = optptr;
  1810. if (p == NULL || *p == '\0') {
  1811. /* We ate entire "-param", take next one */
  1812. p = *argptr;
  1813. if (p == NULL)
  1814. return '\0';
  1815. if (*p != '-')
  1816. return '\0';
  1817. if (*++p == '\0') /* just "-" ? */
  1818. return '\0';
  1819. argptr++;
  1820. if (LONE_DASH(p)) /* "--" ? */
  1821. return '\0';
  1822. /* p => next "-param" */
  1823. }
  1824. /* p => some option char in the middle of a "-param" */
  1825. c = *p++;
  1826. for (q = optstring; *q != c;) {
  1827. if (*q == '\0')
  1828. ash_msg_and_raise_error("illegal option -%c", c);
  1829. if (*++q == ':')
  1830. q++;
  1831. }
  1832. if (*++q == ':') {
  1833. if (*p == '\0') {
  1834. p = *argptr++;
  1835. if (p == NULL)
  1836. ash_msg_and_raise_error("no arg for -%c option", c);
  1837. }
  1838. optionarg = p;
  1839. p = NULL;
  1840. }
  1841. optptr = p;
  1842. return c;
  1843. }
  1844. /* ============ Shell variables */
  1845. struct shparam {
  1846. int nparam; /* # of positional parameters (without $0) */
  1847. #if ENABLE_ASH_GETOPTS
  1848. int optind; /* next parameter to be processed by getopts */
  1849. int optoff; /* used by getopts */
  1850. #endif
  1851. unsigned char malloced; /* if parameter list dynamically allocated */
  1852. char **p; /* parameter list */
  1853. };
  1854. /*
  1855. * Free the list of positional parameters.
  1856. */
  1857. static void
  1858. freeparam(volatile struct shparam *param)
  1859. {
  1860. if (param->malloced) {
  1861. char **ap, **ap1;
  1862. ap = ap1 = param->p;
  1863. while (*ap)
  1864. free(*ap++);
  1865. free(ap1);
  1866. }
  1867. }
  1868. #if ENABLE_ASH_GETOPTS
  1869. static void FAST_FUNC getoptsreset(const char *value);
  1870. #endif
  1871. struct var {
  1872. struct var *next; /* next entry in hash list */
  1873. int flags; /* flags are defined above */
  1874. const char *var_text; /* name=value */
  1875. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1876. /* the variable gets set/unset */
  1877. };
  1878. struct localvar {
  1879. struct localvar *next; /* next local variable in list */
  1880. struct var *vp; /* the variable that was made local */
  1881. int flags; /* saved flags */
  1882. const char *text; /* saved text */
  1883. };
  1884. /* flags */
  1885. #define VEXPORT 0x01 /* variable is exported */
  1886. #define VREADONLY 0x02 /* variable cannot be modified */
  1887. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1888. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1889. #define VSTACK 0x10 /* text is allocated on the stack */
  1890. #define VUNSET 0x20 /* the variable is not set */
  1891. #define VNOFUNC 0x40 /* don't call the callback function */
  1892. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1893. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1894. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  1895. # define VDYNAMIC 0x200 /* dynamic variable */
  1896. #else
  1897. # define VDYNAMIC 0
  1898. #endif
  1899. /* Need to be before varinit_data[] */
  1900. #if ENABLE_LOCALE_SUPPORT
  1901. static void FAST_FUNC
  1902. change_lc_all(const char *value)
  1903. {
  1904. if (value && *value != '\0')
  1905. setlocale(LC_ALL, value);
  1906. }
  1907. static void FAST_FUNC
  1908. change_lc_ctype(const char *value)
  1909. {
  1910. if (value && *value != '\0')
  1911. setlocale(LC_CTYPE, value);
  1912. }
  1913. #endif
  1914. #if ENABLE_ASH_MAIL
  1915. static void changemail(const char *var_value) FAST_FUNC;
  1916. #endif
  1917. static void changepath(const char *) FAST_FUNC;
  1918. #if ENABLE_ASH_RANDOM_SUPPORT
  1919. static void change_random(const char *) FAST_FUNC;
  1920. #endif
  1921. #if BASH_EPOCH_VARS
  1922. static void change_seconds(const char *) FAST_FUNC;
  1923. static void change_realtime(const char *) FAST_FUNC;
  1924. #endif
  1925. static const struct {
  1926. int flags;
  1927. const char *var_text;
  1928. void (*var_func)(const char *) FAST_FUNC;
  1929. } varinit_data[] ALIGN_PTR = {
  1930. /*
  1931. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1932. * some environment strings may be constant.
  1933. */
  1934. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1935. #if ENABLE_ASH_MAIL
  1936. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1937. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1938. #endif
  1939. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1940. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1941. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1942. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1943. #if ENABLE_ASH_GETOPTS
  1944. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1945. #endif
  1946. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1947. { VSTRFIXED|VTEXTFIXED , NULL /* inited to funcnamevar */, NULL },
  1948. #if ENABLE_ASH_RANDOM_SUPPORT
  1949. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1950. #endif
  1951. #if BASH_EPOCH_VARS
  1952. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
  1953. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
  1954. #endif
  1955. #if ENABLE_LOCALE_SUPPORT
  1956. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1957. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1958. #endif
  1959. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1960. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1961. #endif
  1962. };
  1963. struct redirtab;
  1964. struct globals_var {
  1965. struct shparam shellparam; /* $@ current positional parameters */
  1966. struct redirtab *redirlist;
  1967. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1968. struct var *vartab[VTABSIZE];
  1969. struct var varinit[ARRAY_SIZE(varinit_data)];
  1970. int lineno;
  1971. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1972. char funcnamevar[sizeof("FUNCNAME=") + 64];
  1973. char *funcname;
  1974. unsigned trap_depth;
  1975. bool in_trap_ERR; /* ERR cannot recurse, no need to be a counter */
  1976. };
  1977. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1978. #define G_var (*ash_ptr_to_globals_var)
  1979. #define shellparam (G_var.shellparam )
  1980. //#define redirlist (G_var.redirlist )
  1981. #define preverrout_fd (G_var.preverrout_fd)
  1982. #define vartab (G_var.vartab )
  1983. #define varinit (G_var.varinit )
  1984. #define lineno (G_var.lineno )
  1985. #define linenovar (G_var.linenovar )
  1986. #define funcnamevar (G_var.funcnamevar )
  1987. #define funcname (G_var.funcname )
  1988. #define trap_depth (G_var.trap_depth )
  1989. #define in_trap_ERR (G_var.in_trap_ERR )
  1990. #define vifs varinit[0]
  1991. #if ENABLE_ASH_MAIL
  1992. # define vmail varinit[1]
  1993. # define vmpath varinit[2]
  1994. #endif
  1995. #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
  1996. #define vpath varinit[VAR_OFFSET1 + 1]
  1997. #define vps1 varinit[VAR_OFFSET1 + 2]
  1998. #define vps2 varinit[VAR_OFFSET1 + 3]
  1999. #define vps4 varinit[VAR_OFFSET1 + 4]
  2000. #if ENABLE_ASH_GETOPTS
  2001. # define voptind varinit[VAR_OFFSET1 + 5]
  2002. #endif
  2003. #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
  2004. #define vlineno varinit[VAR_OFFSET2 + 5]
  2005. #define vfuncname varinit[VAR_OFFSET2 + 6]
  2006. #if ENABLE_ASH_RANDOM_SUPPORT
  2007. # define vrandom varinit[VAR_OFFSET2 + 7]
  2008. #endif
  2009. #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
  2010. #if BASH_EPOCH_VARS
  2011. # define vepochs varinit[VAR_OFFSET3 + 7]
  2012. # define vepochr varinit[VAR_OFFSET3 + 8]
  2013. #endif
  2014. #define INIT_G_var() do { \
  2015. unsigned i; \
  2016. XZALLOC_CONST_PTR(&ash_ptr_to_globals_var, sizeof(G_var)); \
  2017. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  2018. varinit[i].flags = varinit_data[i].flags; \
  2019. varinit[i].var_text = varinit_data[i].var_text; \
  2020. varinit[i].var_func = varinit_data[i].var_func; \
  2021. } \
  2022. strcpy(linenovar, "LINENO="); \
  2023. vlineno.var_text = linenovar; \
  2024. strcpy(funcnamevar, "FUNCNAME="); \
  2025. vfuncname.var_text = funcnamevar; \
  2026. } while (0)
  2027. /*
  2028. * The following macros access the values of the above variables.
  2029. * They have to skip over the name. They return the null string
  2030. * for unset variables.
  2031. */
  2032. #define ifsval() (vifs.var_text + 4)
  2033. #define ifsset() ((vifs.flags & VUNSET) == 0)
  2034. #if ENABLE_ASH_MAIL
  2035. # define mailval() (vmail.var_text + 5)
  2036. # define mpathval() (vmpath.var_text + 9)
  2037. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  2038. #endif
  2039. #define pathval() (vpath.var_text + 5)
  2040. #define ps1val() (vps1.var_text + 4)
  2041. #define ps2val() (vps2.var_text + 4)
  2042. #define ps4val() (vps4.var_text + 4)
  2043. #if ENABLE_ASH_GETOPTS
  2044. # define optindval() (voptind.var_text + 7)
  2045. #endif
  2046. #if ENABLE_ASH_GETOPTS
  2047. static void FAST_FUNC
  2048. getoptsreset(const char *value)
  2049. {
  2050. shellparam.optind = 1;
  2051. if (is_number(value))
  2052. shellparam.optind = number(value) ?: 1;
  2053. shellparam.optoff = -1;
  2054. }
  2055. #endif
  2056. /*
  2057. * Find the appropriate entry in the hash table from the name.
  2058. */
  2059. static struct var **
  2060. hashvar(const char *p)
  2061. {
  2062. unsigned hashval;
  2063. hashval = ((unsigned char) *p) << 4;
  2064. while (*p && *p != '=')
  2065. hashval += (unsigned char) *p++;
  2066. return &vartab[hashval % VTABSIZE];
  2067. }
  2068. static int
  2069. vpcmp(const void *a, const void *b)
  2070. {
  2071. return varcmp(*(const char **)a, *(const char **)b);
  2072. }
  2073. /*
  2074. * This routine initializes the builtin variables.
  2075. */
  2076. static void
  2077. initvar(void)
  2078. {
  2079. struct var *vp;
  2080. struct var *end;
  2081. struct var **vpp;
  2082. /*
  2083. * PS1 depends on uid
  2084. */
  2085. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2086. vps1.var_text = "PS1=\\w \\$ ";
  2087. #else
  2088. if (!get_cached_euid(&groupinfo.euid));
  2089. vps1.var_text = "PS1=# ";
  2090. #endif
  2091. vp = varinit;
  2092. end = vp + ARRAY_SIZE(varinit);
  2093. do {
  2094. vpp = hashvar(vp->var_text);
  2095. vp->next = *vpp;
  2096. *vpp = vp;
  2097. } while (++vp < end);
  2098. }
  2099. static struct var **
  2100. findvar(const char *name)
  2101. {
  2102. struct var **vpp;
  2103. for (vpp = hashvar(name); *vpp; vpp = &(*vpp)->next) {
  2104. if (varcmp((*vpp)->var_text, name) == 0) {
  2105. break;
  2106. }
  2107. }
  2108. return vpp;
  2109. }
  2110. /*
  2111. * Find the value of a variable. Returns NULL if not set.
  2112. */
  2113. static const char* FAST_FUNC
  2114. lookupvar(const char *name)
  2115. {
  2116. struct var *v;
  2117. v = *findvar(name);
  2118. if (v) {
  2119. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2120. /*
  2121. * Dynamic variables are implemented roughly the same way they are
  2122. * in bash. Namely, they're "special" so long as they aren't unset.
  2123. * As soon as they're unset, they're no longer dynamic, and dynamic
  2124. * lookup will no longer happen at that point. -- PFM.
  2125. */
  2126. if (v->flags & VDYNAMIC)
  2127. v->var_func(NULL);
  2128. #endif
  2129. if (!(v->flags & VUNSET)) {
  2130. if (v->var_text == linenovar) {
  2131. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2132. } else
  2133. if (v->var_text == funcnamevar) {
  2134. safe_strncpy(funcnamevar+9, funcname ? funcname : "", sizeof(funcnamevar)-9);
  2135. }
  2136. return var_end(v->var_text);
  2137. }
  2138. }
  2139. return NULL;
  2140. }
  2141. #if ENABLE_UNICODE_SUPPORT
  2142. static void
  2143. reinit_unicode_for_ash(void)
  2144. {
  2145. /* Unicode support should be activated even if LANG is set
  2146. * _during_ shell execution, not only if it was set when
  2147. * shell was started. Therefore, re-check LANG every time:
  2148. */
  2149. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2150. || ENABLE_UNICODE_USING_LOCALE
  2151. ) {
  2152. const char *s = lookupvar("LC_ALL");
  2153. if (!s) s = lookupvar("LC_CTYPE");
  2154. if (!s) s = lookupvar("LANG");
  2155. reinit_unicode(s);
  2156. }
  2157. }
  2158. #else
  2159. # define reinit_unicode_for_ash() ((void)0)
  2160. #endif
  2161. /*
  2162. * Search the environment of a builtin command.
  2163. */
  2164. static ALWAYS_INLINE const char *
  2165. bltinlookup(const char *name)
  2166. {
  2167. return lookupvar(name);
  2168. }
  2169. /*
  2170. * Same as setvar except that the variable and value are passed in
  2171. * the first argument as name=value. Since the first argument will
  2172. * be actually stored in the table, it should not be a string that
  2173. * will go away.
  2174. * Called with interrupts off.
  2175. */
  2176. static struct var *
  2177. setvareq(char *s, int flags)
  2178. {
  2179. struct var *vp, **vpp;
  2180. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2181. vpp = findvar(s);
  2182. vp = *vpp;
  2183. if (vp) {
  2184. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2185. const char *n;
  2186. if (flags & VNOSAVE)
  2187. free(s);
  2188. n = vp->var_text;
  2189. exitstatus = 1;
  2190. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2191. }
  2192. if (flags & VNOSET)
  2193. goto out;
  2194. if (vp->var_func && !(flags & VNOFUNC))
  2195. vp->var_func(var_end(s));
  2196. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2197. free((char*)vp->var_text);
  2198. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2199. *vpp = vp->next;
  2200. free(vp);
  2201. out_free:
  2202. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2203. free(s);
  2204. goto out;
  2205. }
  2206. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2207. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2208. if (flags & VUNSET)
  2209. flags &= ~VDYNAMIC;
  2210. #endif
  2211. } else {
  2212. /* variable s is not found */
  2213. if (flags & VNOSET)
  2214. goto out;
  2215. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2216. goto out_free;
  2217. vp = ckzalloc(sizeof(*vp));
  2218. vp->next = *vpp;
  2219. /*vp->func = NULL; - ckzalloc did it */
  2220. *vpp = vp;
  2221. }
  2222. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2223. s = ckstrdup(s);
  2224. vp->var_text = s;
  2225. vp->flags = flags;
  2226. out:
  2227. return vp;
  2228. }
  2229. /*
  2230. * Set the value of a variable. The flags argument is ored with the
  2231. * flags of the variable. If val is NULL, the variable is unset.
  2232. */
  2233. static struct var *
  2234. setvar(const char *name, const char *val, int flags)
  2235. {
  2236. const char *q;
  2237. char *p;
  2238. char *nameeq;
  2239. size_t namelen;
  2240. size_t vallen;
  2241. struct var *vp;
  2242. q = endofname(name);
  2243. p = strchrnul(q, '=');
  2244. namelen = p - name;
  2245. if (!namelen || p != q)
  2246. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2247. vallen = 0;
  2248. if (val == NULL) {
  2249. flags |= VUNSET;
  2250. } else {
  2251. vallen = strlen(val);
  2252. }
  2253. INT_OFF;
  2254. nameeq = ckzalloc(namelen + vallen + 2);
  2255. p = mempcpy(nameeq, name, namelen);
  2256. if (val) {
  2257. *p++ = '=';
  2258. strcpy(p, val);
  2259. }
  2260. vp = setvareq(nameeq, flags | VNOSAVE);
  2261. INT_ON;
  2262. return vp;
  2263. }
  2264. static void FAST_FUNC
  2265. setvar0(const char *name, const char *val)
  2266. {
  2267. setvar(name, val, 0);
  2268. }
  2269. /*
  2270. * Unset the specified variable.
  2271. */
  2272. static void
  2273. unsetvar(const char *s)
  2274. {
  2275. setvar(s, NULL, 0);
  2276. }
  2277. /*
  2278. * Generate a list of variables satisfying the given conditions.
  2279. */
  2280. #if !ENABLE_FEATURE_SH_NOFORK
  2281. # define listvars(on, off, lp, end) listvars(on, off, end)
  2282. #endif
  2283. static char **
  2284. listvars(int on, int off, struct strlist *lp, char ***end)
  2285. {
  2286. struct var **vpp;
  2287. struct var *vp;
  2288. char **ep;
  2289. int mask;
  2290. STARTSTACKSTR(ep);
  2291. vpp = vartab;
  2292. mask = on | off;
  2293. do {
  2294. for (vp = *vpp; vp; vp = vp->next) {
  2295. if ((vp->flags & mask) == on) {
  2296. #if ENABLE_FEATURE_SH_NOFORK
  2297. /* If variable with the same name is both
  2298. * exported and temporarily set for a command:
  2299. * export ZVAR=5
  2300. * ZVAR=6 printenv
  2301. * then "ZVAR=6" will be both in vartab and
  2302. * lp lists. Do not pass it twice to printenv.
  2303. */
  2304. struct strlist *lp1 = lp;
  2305. while (lp1) {
  2306. if (strcmp(lp1->text, vp->var_text) == 0)
  2307. goto skip;
  2308. lp1 = lp1->next;
  2309. }
  2310. #endif
  2311. if (ep == stackstrend())
  2312. ep = growstackstr();
  2313. *ep++ = (char*)vp->var_text;
  2314. #if ENABLE_FEATURE_SH_NOFORK
  2315. skip: ;
  2316. #endif
  2317. }
  2318. }
  2319. } while (++vpp < vartab + VTABSIZE);
  2320. #if ENABLE_FEATURE_SH_NOFORK
  2321. while (lp) {
  2322. if (ep == stackstrend())
  2323. ep = growstackstr();
  2324. *ep++ = lp->text;
  2325. lp = lp->next;
  2326. }
  2327. #endif
  2328. if (ep == stackstrend())
  2329. ep = growstackstr();
  2330. if (end)
  2331. *end = ep;
  2332. *ep++ = NULL;
  2333. return grabstackstr(ep);
  2334. }
  2335. /* ============ Path search helper */
  2336. static const char *
  2337. legal_pathopt(const char *opt, const char *term, int magic)
  2338. {
  2339. switch (magic) {
  2340. case 0:
  2341. opt = NULL;
  2342. break;
  2343. case 1:
  2344. opt = prefix(opt, "builtin") ?: prefix(opt, "func");
  2345. break;
  2346. default:
  2347. opt += strcspn(opt, term);
  2348. break;
  2349. }
  2350. if (opt && *opt == '%')
  2351. opt++;
  2352. return opt;
  2353. }
  2354. /*
  2355. * The variable path (passed by reference) should be set to the start
  2356. * of the path before the first call; padvance will update
  2357. * this value as it proceeds. Successive calls to padvance will return
  2358. * the possible path expansions in sequence. If an option (indicated by
  2359. * a percent sign) appears in the path entry then the global variable
  2360. * pathopt will be set to point to it; otherwise pathopt will be set to
  2361. * NULL.
  2362. *
  2363. * If magic is 0 then pathopt recognition will be disabled. If magic is
  2364. * 1 we shall recognise %builtin/%func. Otherwise we shall accept any
  2365. * pathopt.
  2366. */
  2367. static const char *pathopt; /* set by padvance */
  2368. static int
  2369. padvance_magic(const char **path, const char *name, int magic)
  2370. {
  2371. const char *term = "%:";
  2372. const char *lpathopt;
  2373. const char *p;
  2374. char *q;
  2375. const char *start;
  2376. size_t qlen;
  2377. size_t len;
  2378. if (*path == NULL)
  2379. return -1;
  2380. lpathopt = NULL;
  2381. start = *path;
  2382. if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) {
  2383. lpathopt = start + 1;
  2384. start = p;
  2385. term = ":";
  2386. }
  2387. len = strcspn(start, term);
  2388. p = start + len;
  2389. if (*p == '%') {
  2390. size_t extra = strchrnul(p, ':') - p;
  2391. if (legal_pathopt(p + 1, term, magic))
  2392. lpathopt = p + 1;
  2393. else
  2394. len += extra;
  2395. p += extra;
  2396. }
  2397. pathopt = lpathopt;
  2398. *path = *p == ':' ? p + 1 : NULL;
  2399. /* "2" is for '/' and '\0' */
  2400. qlen = len + strlen(name) + 2;
  2401. q = growstackto(qlen);
  2402. if (len) {
  2403. q = mempcpy(q, start, len);
  2404. *q++ = '/';
  2405. }
  2406. strcpy(q, name);
  2407. return qlen;
  2408. }
  2409. static int
  2410. padvance(const char **path, const char *name)
  2411. {
  2412. return padvance_magic(path, name, 1);
  2413. }
  2414. /* ============ Prompt */
  2415. static smallint doprompt; /* if set, prompt the user */
  2416. static smallint needprompt; /* true if interactive and at start of line */
  2417. #if ENABLE_FEATURE_EDITING
  2418. static line_input_t *line_input_state;
  2419. static const char *cmdedit_prompt;
  2420. static void
  2421. putprompt(const char *s)
  2422. {
  2423. if (ENABLE_ASH_EXPAND_PRMT) {
  2424. free((char*)cmdedit_prompt);
  2425. cmdedit_prompt = ckstrdup(s);
  2426. return;
  2427. }
  2428. cmdedit_prompt = s;
  2429. }
  2430. #else
  2431. static void
  2432. putprompt(const char *s)
  2433. {
  2434. out2str(s);
  2435. }
  2436. #endif
  2437. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2438. static const char *expandstr(const char *ps, int syntax_type);
  2439. /* Values for syntax param */
  2440. #define BASESYNTAX 0 /* not in quotes */
  2441. #define DQSYNTAX 1 /* in double quotes */
  2442. #define SQSYNTAX 2 /* in single quotes */
  2443. #define ARISYNTAX 3 /* in arithmetic */
  2444. #if ENABLE_ASH_EXPAND_PRMT
  2445. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2446. #endif
  2447. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2448. /*
  2449. * called by editline -- any expansions to the prompt should be added here.
  2450. */
  2451. static void
  2452. setprompt_if(smallint do_set, int whichprompt)
  2453. {
  2454. const char *prompt;
  2455. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2456. if (!do_set)
  2457. return;
  2458. needprompt = 0;
  2459. switch (whichprompt) {
  2460. case 1:
  2461. prompt = ps1val();
  2462. break;
  2463. case 2:
  2464. prompt = ps2val();
  2465. break;
  2466. default: /* 0 */
  2467. prompt = nullstr;
  2468. }
  2469. #if ENABLE_ASH_EXPAND_PRMT
  2470. pushstackmark(&smark, stackblocksize());
  2471. putprompt(expandstr(prompt, PSSYNTAX));
  2472. popstackmark(&smark);
  2473. #else
  2474. putprompt(prompt);
  2475. #endif
  2476. }
  2477. /* ============ The cd and pwd commands */
  2478. #define CD_PHYSICAL 1
  2479. #define CD_PRINT 2
  2480. static int
  2481. cdopt(void)
  2482. {
  2483. int flags = 0;
  2484. int i, j;
  2485. j = 'L';
  2486. while ((i = nextopt("LP")) != '\0') {
  2487. if (i != j) {
  2488. flags ^= CD_PHYSICAL;
  2489. j = i;
  2490. }
  2491. }
  2492. return flags;
  2493. }
  2494. /*
  2495. * Update curdir (the name of the current directory) in response to a
  2496. * cd command.
  2497. */
  2498. static const char *
  2499. updatepwd(const char *dir)
  2500. {
  2501. char *new;
  2502. char *p;
  2503. char *cdcomppath;
  2504. const char *lim;
  2505. cdcomppath = sstrdup(dir);
  2506. STARTSTACKSTR(new);
  2507. if (*dir != '/') {
  2508. if (curdir == nullstr)
  2509. return 0;
  2510. new = stack_putstr(curdir, new);
  2511. }
  2512. new = makestrspace(strlen(dir) + 2, new);
  2513. lim = (char *)stackblock() + 1;
  2514. if (*dir != '/') {
  2515. if (new[-1] != '/')
  2516. USTPUTC('/', new);
  2517. if (new > lim && *lim == '/')
  2518. lim++;
  2519. } else {
  2520. USTPUTC('/', new);
  2521. cdcomppath++;
  2522. if (dir[1] == '/' && dir[2] != '/') {
  2523. USTPUTC('/', new);
  2524. cdcomppath++;
  2525. lim++;
  2526. }
  2527. }
  2528. p = strtok_r(cdcomppath, "/", &cdcomppath);
  2529. while (p) {
  2530. switch (*p) {
  2531. case '.':
  2532. if (p[1] == '.' && p[2] == '\0') {
  2533. while (new > lim) {
  2534. STUNPUTC(new);
  2535. if (new[-1] == '/')
  2536. break;
  2537. }
  2538. break;
  2539. }
  2540. if (p[1] == '\0')
  2541. break;
  2542. /* fall through */
  2543. default:
  2544. new = stack_putstr(p, new);
  2545. USTPUTC('/', new);
  2546. }
  2547. p = strtok_r(NULL, "/", &cdcomppath);
  2548. }
  2549. if (new > lim)
  2550. STUNPUTC(new);
  2551. *new = 0;
  2552. return stackblock();
  2553. }
  2554. /*
  2555. * Find out what the current directory is. If we already know the current
  2556. * directory, this routine returns immediately.
  2557. */
  2558. static char *
  2559. getpwd(void)
  2560. {
  2561. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2562. return dir ? dir : nullstr;
  2563. }
  2564. static void
  2565. setpwd(const char *val, int setold)
  2566. {
  2567. char *oldcur, *dir;
  2568. oldcur = dir = curdir;
  2569. if (setold) {
  2570. setvar("OLDPWD", oldcur, VEXPORT);
  2571. }
  2572. INT_OFF;
  2573. if (physdir != nullstr) {
  2574. if (physdir != oldcur)
  2575. free(physdir);
  2576. physdir = nullstr;
  2577. }
  2578. if (oldcur == val || !val) {
  2579. char *s = getpwd();
  2580. physdir = s;
  2581. if (!val)
  2582. dir = s;
  2583. } else
  2584. dir = ckstrdup(val);
  2585. if (oldcur != dir && oldcur != nullstr) {
  2586. free(oldcur);
  2587. }
  2588. curdir = dir;
  2589. INT_ON;
  2590. setvar("PWD", dir, VEXPORT);
  2591. }
  2592. static void hashcd(void);
  2593. /*
  2594. * Actually do the chdir. We also call hashcd to let other routines
  2595. * know that the current directory has changed.
  2596. */
  2597. static int
  2598. docd(const char *dest, int flags)
  2599. {
  2600. const char *dir = NULL;
  2601. int err;
  2602. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2603. INT_OFF;
  2604. if (!(flags & CD_PHYSICAL)) {
  2605. dir = updatepwd(dest);
  2606. if (dir)
  2607. dest = dir;
  2608. }
  2609. err = chdir(dest);
  2610. if (err)
  2611. goto out;
  2612. setpwd(dir, 1);
  2613. hashcd();
  2614. out:
  2615. INT_ON;
  2616. return err;
  2617. }
  2618. static int FAST_FUNC
  2619. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2620. {
  2621. const char *dest;
  2622. const char *path;
  2623. const char *p;
  2624. char c;
  2625. struct stat statb;
  2626. int flags;
  2627. int len;
  2628. flags = cdopt();
  2629. dest = *argptr;
  2630. if (!dest)
  2631. dest = bltinlookup("HOME");
  2632. else if (LONE_DASH(dest)) {
  2633. dest = bltinlookup("OLDPWD");
  2634. flags |= CD_PRINT;
  2635. }
  2636. if (!dest)
  2637. dest = nullstr;
  2638. if (*dest == '/')
  2639. goto step6;
  2640. if (*dest == '.') {
  2641. c = dest[1];
  2642. dotdot:
  2643. switch (c) {
  2644. case '\0':
  2645. case '/':
  2646. goto step6;
  2647. case '.':
  2648. c = dest[2];
  2649. if (c != '.')
  2650. goto dotdot;
  2651. }
  2652. }
  2653. if (!*dest)
  2654. dest = ".";
  2655. path = bltinlookup("CDPATH");
  2656. while (p = path, (len = padvance_magic(&path, dest, 0)) >= 0) {
  2657. c = *p;
  2658. p = stalloc(len);
  2659. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2660. if (c && c != ':')
  2661. flags |= CD_PRINT;
  2662. docd:
  2663. if (!docd(p, flags))
  2664. goto out;
  2665. goto err;
  2666. }
  2667. }
  2668. step6:
  2669. p = dest;
  2670. goto docd;
  2671. err:
  2672. ash_msg_and_raise_perror("can't cd to %s", dest);
  2673. /* NOTREACHED */
  2674. out:
  2675. if (flags & CD_PRINT)
  2676. out1fmt("%s\n", curdir);
  2677. return 0;
  2678. }
  2679. static int FAST_FUNC
  2680. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2681. {
  2682. int flags;
  2683. const char *dir = curdir;
  2684. flags = cdopt();
  2685. if (flags) {
  2686. if (physdir == nullstr)
  2687. setpwd(dir, 0);
  2688. dir = physdir;
  2689. }
  2690. out1fmt("%s\n", dir);
  2691. return 0;
  2692. }
  2693. /* ============ ... */
  2694. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2695. /* Syntax classes */
  2696. #define CWORD 0 /* character is nothing special */
  2697. #define CNL 1 /* newline character */
  2698. #define CBACK 2 /* a backslash character */
  2699. #define CSQUOTE 3 /* single quote */
  2700. #define CDQUOTE 4 /* double quote */
  2701. #define CENDQUOTE 5 /* a terminating quote */
  2702. #define CBQUOTE 6 /* backwards single quote */
  2703. #define CVAR 7 /* a dollar sign */
  2704. #define CENDVAR 8 /* a '}' character */
  2705. #define CLP 9 /* a left paren in arithmetic */
  2706. #define CRP 10 /* a right paren in arithmetic */
  2707. #define CENDFILE 11 /* end of file */
  2708. #define CCTL 12 /* like CWORD, except it must be escaped */
  2709. #define CSPCL 13 /* these terminate a word */
  2710. #define PEOF 256
  2711. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2712. #if ENABLE_FEATURE_SH_MATH
  2713. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2714. #else
  2715. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2716. #endif
  2717. static const uint16_t S_I_T[] ALIGN2 = {
  2718. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 0, ' ' */
  2719. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 1, \n */
  2720. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 2, !*-/:=?[]~ */
  2721. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 3, '"' */
  2722. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 4, $ */
  2723. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 5, "'" */
  2724. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 6, ( */
  2725. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 7, ) */
  2726. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 8, \ */
  2727. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 9, ` */
  2728. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 10, } */
  2729. #if !USE_SIT_FUNCTION
  2730. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 11, PEOF */
  2731. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 12, 0-9A-Za-z */
  2732. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 13, CTLESC ... */
  2733. #endif
  2734. #undef SIT_ITEM
  2735. };
  2736. /* Constants below must match table above */
  2737. enum {
  2738. CSPCL_CWORD_CWORD_CWORD , /* 0 */
  2739. CNL_CNL_CNL_CNL , /* 1 */
  2740. CWORD_CCTL_CCTL_CWORD , /* 2 */
  2741. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 3 */
  2742. CVAR_CVAR_CWORD_CVAR , /* 4 */
  2743. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 5 */
  2744. CSPCL_CWORD_CWORD_CLP , /* 6 */
  2745. CSPCL_CWORD_CWORD_CRP , /* 7 */
  2746. CBACK_CBACK_CCTL_CBACK , /* 8 */
  2747. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 9 */
  2748. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 10 */
  2749. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 11 */
  2750. CWORD_CWORD_CWORD_CWORD , /* 12 */
  2751. CCTL_CCTL_CCTL_CCTL , /* 13 */
  2752. };
  2753. /* c in SIT(c, syntax) must be an *unsigned char* or PEOF,
  2754. * caller must ensure proper cast on it if c is *char_ptr!
  2755. */
  2756. #if USE_SIT_FUNCTION
  2757. static int
  2758. SIT(int c, int syntax)
  2759. {
  2760. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2761. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2762. /*
  2763. * This causes '/' to be prepended with CTLESC in dquoted string,
  2764. * making "./file"* treated incorrectly because we feed
  2765. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2766. * The "homegrown" glob implementation is okay with that,
  2767. * but glibc one isn't. With '/' always treated as CWORD,
  2768. * both work fine.
  2769. */
  2770. static const uint8_t syntax_index_table[] ALIGN1 = {
  2771. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2772. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2773. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2774. 10, 2 /* "}~" */
  2775. };
  2776. const char *s;
  2777. int indx;
  2778. if (c == PEOF)
  2779. return CENDFILE;
  2780. /* Cast is purely for paranoia here,
  2781. * just in case someone passed signed char to us */
  2782. if ((unsigned char)c >= CTL_FIRST
  2783. && (unsigned char)c <= CTL_LAST
  2784. ) {
  2785. return CCTL;
  2786. }
  2787. s = strchrnul(spec_symbls, c);
  2788. if (*s == '\0')
  2789. return CWORD;
  2790. indx = syntax_index_table[s - spec_symbls];
  2791. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2792. }
  2793. #else /* !USE_SIT_FUNCTION */
  2794. static const uint8_t syntax_index_table[] ALIGN1 = {
  2795. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2796. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2806. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2807. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2829. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2830. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2831. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2832. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2833. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2835. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2836. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2837. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2838. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2839. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2840. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2841. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2842. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2843. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2844. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2856. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2857. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2858. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2859. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2860. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2861. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2889. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2890. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2891. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2894. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2897. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2899. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2902. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2903. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2904. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2905. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2906. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2922. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2923. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2924. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2925. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2926. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2927. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2928. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2929. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2930. /* 133 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2931. /* 134 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2932. /* 135 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2933. #if BASH_PROCESS_SUBST
  2934. /* 136 CTLTOPROC */ CCTL_CCTL_CCTL_CCTL,
  2935. /* 137 CTLFROMPROC */ CCTL_CCTL_CCTL_CCTL,
  2936. #else
  2937. /* 136 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2939. #endif
  2940. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2967. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2968. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2969. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2970. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2971. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2972. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2973. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2974. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2975. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2976. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2977. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2978. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2979. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2980. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2981. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2982. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2983. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2984. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2985. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2986. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2987. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2988. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2989. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2990. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2991. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2992. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2993. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2994. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2995. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2996. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2997. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2998. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2999. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  3000. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  3001. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  3002. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  3003. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  3004. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  3005. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  3006. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  3007. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  3008. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  3009. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  3010. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  3011. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  3012. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  3013. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  3014. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  3015. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  3016. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  3017. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  3018. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  3019. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  3020. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  3021. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  3022. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  3023. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  3024. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  3025. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  3026. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  3027. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  3028. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  3029. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  3030. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  3031. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  3032. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3033. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  3034. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  3035. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  3036. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  3037. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  3038. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  3039. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  3040. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  3041. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  3042. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3043. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  3044. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  3045. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  3046. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  3047. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  3048. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  3049. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  3050. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  3051. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  3052. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  3053. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  3054. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  3055. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  3056. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  3057. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  3058. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  3059. };
  3060. #if 1
  3061. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  3062. #else /* debug version, caught one signed char bug */
  3063. # define SIT(c, syntax) \
  3064. ({ \
  3065. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  3066. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3067. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  3068. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3069. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  3070. })
  3071. #endif
  3072. #endif /* !USE_SIT_FUNCTION */
  3073. /* ============ Alias handling */
  3074. #if ENABLE_ASH_ALIAS
  3075. #define ALIASINUSE 1
  3076. #define ALIASDEAD 2
  3077. struct alias {
  3078. struct alias *next;
  3079. char *name;
  3080. char *val;
  3081. int flag;
  3082. };
  3083. static struct alias **atab; // [ATABSIZE];
  3084. #define INIT_G_alias() do { \
  3085. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  3086. } while (0)
  3087. static struct alias **
  3088. __lookupalias(const char *name)
  3089. {
  3090. unsigned int hashval;
  3091. struct alias **app;
  3092. const char *p;
  3093. unsigned int ch;
  3094. p = name;
  3095. ch = (unsigned char)*p;
  3096. hashval = ch << 4;
  3097. while (ch) {
  3098. hashval += ch;
  3099. ch = (unsigned char)*++p;
  3100. }
  3101. app = &atab[hashval % ATABSIZE];
  3102. for (; *app; app = &(*app)->next) {
  3103. if (strcmp(name, (*app)->name) == 0) {
  3104. break;
  3105. }
  3106. }
  3107. return app;
  3108. }
  3109. static struct alias *
  3110. lookupalias(const char *name, int check)
  3111. {
  3112. struct alias *ap = *__lookupalias(name);
  3113. if (check && ap && (ap->flag & ALIASINUSE))
  3114. return NULL;
  3115. return ap;
  3116. }
  3117. static struct alias *
  3118. freealias(struct alias *ap)
  3119. {
  3120. struct alias *next;
  3121. if (ap->flag & ALIASINUSE) {
  3122. ap->flag |= ALIASDEAD;
  3123. return ap;
  3124. }
  3125. next = ap->next;
  3126. free(ap->name);
  3127. free(ap->val);
  3128. free(ap);
  3129. return next;
  3130. }
  3131. static void
  3132. setalias(const char *name, const char *val)
  3133. {
  3134. struct alias *ap, **app;
  3135. app = __lookupalias(name);
  3136. ap = *app;
  3137. INT_OFF;
  3138. if (ap) {
  3139. if (!(ap->flag & ALIASINUSE)) {
  3140. free(ap->val);
  3141. }
  3142. ap->val = ckstrdup(val);
  3143. ap->flag &= ~ALIASDEAD;
  3144. } else {
  3145. /* not found */
  3146. ap = ckzalloc(sizeof(struct alias));
  3147. ap->name = ckstrdup(name);
  3148. ap->val = ckstrdup(val);
  3149. /*ap->flag = 0; - ckzalloc did it */
  3150. /*ap->next = NULL;*/
  3151. *app = ap;
  3152. }
  3153. INT_ON;
  3154. }
  3155. static int
  3156. unalias(const char *name)
  3157. {
  3158. struct alias **app;
  3159. app = __lookupalias(name);
  3160. if (*app) {
  3161. INT_OFF;
  3162. *app = freealias(*app);
  3163. INT_ON;
  3164. return 0;
  3165. }
  3166. return 1;
  3167. }
  3168. static void
  3169. rmaliases(void)
  3170. {
  3171. struct alias *ap, **app;
  3172. int i;
  3173. INT_OFF;
  3174. for (i = 0; i < ATABSIZE; i++) {
  3175. app = &atab[i];
  3176. for (ap = *app; ap; ap = *app) {
  3177. *app = freealias(*app);
  3178. if (ap == *app) {
  3179. app = &ap->next;
  3180. }
  3181. }
  3182. }
  3183. INT_ON;
  3184. }
  3185. static void
  3186. printalias(const struct alias *ap)
  3187. {
  3188. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3189. }
  3190. /*
  3191. * TODO - sort output
  3192. */
  3193. static int FAST_FUNC
  3194. aliascmd(int argc UNUSED_PARAM, char **argv)
  3195. {
  3196. char *n, *v;
  3197. int ret = 0;
  3198. struct alias *ap;
  3199. if (!argv[1]) {
  3200. int i;
  3201. for (i = 0; i < ATABSIZE; i++) {
  3202. for (ap = atab[i]; ap; ap = ap->next) {
  3203. printalias(ap);
  3204. }
  3205. }
  3206. return 0;
  3207. }
  3208. while ((n = *++argv) != NULL) {
  3209. v = strchr(n+1, '=');
  3210. if (v == NULL) { /* n+1: funny ksh stuff */
  3211. ap = *__lookupalias(n);
  3212. if (ap == NULL) {
  3213. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3214. ret = 1;
  3215. } else
  3216. printalias(ap);
  3217. } else {
  3218. *v++ = '\0';
  3219. setalias(n, v);
  3220. }
  3221. }
  3222. return ret;
  3223. }
  3224. static int FAST_FUNC
  3225. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3226. {
  3227. int i;
  3228. while (nextopt("a") != '\0') {
  3229. rmaliases();
  3230. return 0;
  3231. }
  3232. for (i = 0; *argptr; argptr++) {
  3233. if (unalias(*argptr)) {
  3234. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3235. i = 1;
  3236. }
  3237. }
  3238. return i;
  3239. }
  3240. #endif /* ASH_ALIAS */
  3241. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3242. #define FORK_FG 0
  3243. #define FORK_BG 1
  3244. #define FORK_NOJOB 2
  3245. /* mode flags for showjob(s) */
  3246. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3247. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3248. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3249. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3250. /*
  3251. * A job structure contains information about a job. A job is either a
  3252. * single process or a set of processes contained in a pipeline. In the
  3253. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3254. * array of pids.
  3255. */
  3256. struct procstat {
  3257. pid_t ps_pid; /* process id */
  3258. int ps_status; /* last process status from wait() */
  3259. char *ps_cmd; /* text of command being run */
  3260. };
  3261. struct job {
  3262. struct procstat ps0; /* status of process */
  3263. struct procstat *ps; /* status of processes when more than one */
  3264. #if JOBS
  3265. int stopstatus; /* status of a stopped job */
  3266. #endif
  3267. unsigned nprocs; /* number of processes */
  3268. #define JOBRUNNING 0 /* at least one proc running */
  3269. #define JOBSTOPPED 1 /* all procs are stopped */
  3270. #define JOBDONE 2 /* all procs are completed */
  3271. unsigned
  3272. state: 8,
  3273. #if JOBS
  3274. sigint: 1, /* job was killed by SIGINT */
  3275. jobctl: 1, /* job running under job control */
  3276. #endif
  3277. waited: 1, /* true if this entry has been waited for */
  3278. used: 1, /* true if this entry is in used */
  3279. changed: 1; /* true if status has changed */
  3280. struct job *prev_job; /* previous job */
  3281. };
  3282. static struct job *makejob(/*union node *,*/ int);
  3283. static int forkshell(struct job *, union node *, int);
  3284. static int waitforjob(struct job *);
  3285. #if !JOBS
  3286. enum { doing_jobctl = 0 };
  3287. #define setjobctl(on) do {} while (0)
  3288. #else
  3289. static smallint doing_jobctl; //references:8
  3290. static void setjobctl(int);
  3291. #endif
  3292. /*
  3293. * Ignore a signal.
  3294. */
  3295. static void
  3296. ignoresig(int signo)
  3297. {
  3298. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3299. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3300. /* No, need to do it */
  3301. signal(signo, SIG_IGN);
  3302. }
  3303. sigmode[signo - 1] = S_HARD_IGN;
  3304. }
  3305. /*
  3306. * Only one usage site - in setsignal()
  3307. */
  3308. static void
  3309. signal_handler(int signo)
  3310. {
  3311. if (signo == SIGCHLD) {
  3312. got_sigchld = 1;
  3313. if (!trap[SIGCHLD])
  3314. return;
  3315. }
  3316. #if ENABLE_FEATURE_EDITING
  3317. bb_got_signal = signo; /* for read_line_input: "we got a signal" */
  3318. #endif
  3319. gotsig[signo - 1] = 1;
  3320. pending_sig = signo;
  3321. if (signo == SIGINT && !trap[SIGINT]) {
  3322. if (!suppress_int) {
  3323. pending_sig = 0;
  3324. raise_interrupt(); /* does not return */
  3325. }
  3326. pending_int = 1;
  3327. }
  3328. }
  3329. /*
  3330. * Set the signal handler for the specified signal. The routine figures
  3331. * out what it should be set to.
  3332. */
  3333. static void
  3334. setsignal(int signo)
  3335. {
  3336. char *t;
  3337. char cur_act, new_act;
  3338. struct sigaction act;
  3339. t = trap[signo];
  3340. new_act = S_DFL;
  3341. if (t != NULL) { /* trap for this sig is set */
  3342. new_act = S_CATCH;
  3343. if (t[0] == '\0') /* trap is "": ignore this sig */
  3344. new_act = S_IGN;
  3345. }
  3346. if (rootshell && new_act == S_DFL) {
  3347. switch (signo) {
  3348. case SIGINT:
  3349. if (iflag || minusc || sflag == 0)
  3350. new_act = S_CATCH;
  3351. break;
  3352. case SIGQUIT:
  3353. #if DEBUG
  3354. if (debug)
  3355. break;
  3356. #endif
  3357. /* man bash:
  3358. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3359. * commands run by bash have signal handlers
  3360. * set to the values inherited by the shell
  3361. * from its parent". */
  3362. new_act = S_IGN;
  3363. break;
  3364. case SIGTERM:
  3365. if (iflag)
  3366. new_act = S_IGN;
  3367. break;
  3368. #if JOBS
  3369. case SIGTSTP:
  3370. case SIGTTOU:
  3371. if (mflag)
  3372. new_act = S_IGN;
  3373. break;
  3374. #endif
  3375. }
  3376. }
  3377. /* if !rootshell, we reset SIGQUIT to DFL,
  3378. * whereas we have to restore it to what shell got on entry.
  3379. * This is handled by the fact that if signal was IGNored on entry,
  3380. * then cur_act is S_HARD_IGN and we never change its sigaction
  3381. * (see code below).
  3382. */
  3383. if (signo == SIGCHLD)
  3384. new_act = S_CATCH;
  3385. t = &sigmode[signo - 1];
  3386. cur_act = *t;
  3387. if (cur_act == 0) {
  3388. /* current setting is not yet known */
  3389. if (sigaction(signo, NULL, &act)) {
  3390. /* pretend it worked; maybe we should give a warning,
  3391. * but other shells don't. We don't alter sigmode,
  3392. * so we retry every time.
  3393. * btw, in Linux it never fails. --vda */
  3394. return;
  3395. }
  3396. if (act.sa_handler == SIG_IGN) {
  3397. cur_act = S_HARD_IGN;
  3398. if (mflag
  3399. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3400. ) {
  3401. cur_act = S_IGN; /* don't hard ignore these */
  3402. }
  3403. }
  3404. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3405. /* installing SIG_DFL over SIG_DFL is a no-op */
  3406. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3407. *t = S_DFL;
  3408. return;
  3409. }
  3410. }
  3411. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3412. return;
  3413. *t = new_act;
  3414. act.sa_handler = SIG_DFL;
  3415. switch (new_act) {
  3416. case S_CATCH:
  3417. act.sa_handler = signal_handler;
  3418. break;
  3419. case S_IGN:
  3420. act.sa_handler = SIG_IGN;
  3421. break;
  3422. }
  3423. /* flags and mask matter only if !DFL and !IGN, but we do it
  3424. * for all cases for more deterministic behavior:
  3425. */
  3426. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3427. sigfillset(&act.sa_mask);
  3428. sigaction_set(signo, &act);
  3429. }
  3430. /* mode flags for set_curjob */
  3431. #define CUR_DELETE 2
  3432. #define CUR_RUNNING 1
  3433. #define CUR_STOPPED 0
  3434. #if JOBS
  3435. /* pgrp of shell on invocation */
  3436. static int initialpgrp; //references:2
  3437. static int ttyfd = -1; //5
  3438. #endif
  3439. /* array of jobs */
  3440. static struct job *jobtab; //5
  3441. /* size of array */
  3442. static unsigned njobs; //4
  3443. /* current job */
  3444. static struct job *curjob; //lots
  3445. #if 0
  3446. /* Bash has a feature: it restores termios after a successful wait for
  3447. * a foreground job which had at least one stopped or sigkilled member.
  3448. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3449. * properly restoring tty state. Should we do this too?
  3450. * A reproducer: ^Z an interactive python:
  3451. *
  3452. * # python
  3453. * Python 2.7.12 (...)
  3454. * >>> ^Z
  3455. * { python leaves tty in -icanon -echo state. We do survive that... }
  3456. * [1]+ Stopped python
  3457. * { ...however, next program (python #2) does not survive it well: }
  3458. * # python
  3459. * Python 2.7.12 (...)
  3460. * >>> Traceback (most recent call last):
  3461. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3462. * File "<stdin>", line 1, in <module>
  3463. * NameError: name 'qwerty' is not defined
  3464. *
  3465. * The implementation below is modeled on bash code and seems to work.
  3466. * However, I'm not sure we should do this. For one: what if I'd fg
  3467. * the stopped python instead? It'll be confused by "restored" tty state.
  3468. */
  3469. static struct termios shell_tty_info;
  3470. static void
  3471. get_tty_state(void)
  3472. {
  3473. if (rootshell && ttyfd >= 0)
  3474. tcgetattr(ttyfd, &shell_tty_info);
  3475. }
  3476. static void
  3477. set_tty_state(void)
  3478. {
  3479. /* if (rootshell) - caller ensures this */
  3480. if (ttyfd >= 0)
  3481. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3482. }
  3483. static int
  3484. job_signal_status(struct job *jp)
  3485. {
  3486. int status;
  3487. unsigned i;
  3488. struct procstat *ps = jp->ps;
  3489. for (i = 0; i < jp->nprocs; i++) {
  3490. status = ps[i].ps_status;
  3491. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3492. return status;
  3493. }
  3494. return 0;
  3495. }
  3496. static void
  3497. restore_tty_if_stopped_or_signaled(struct job *jp)
  3498. {
  3499. //TODO: check what happens if we come from waitforjob() in expbackq()
  3500. if (rootshell) {
  3501. int s = job_signal_status(jp);
  3502. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3503. set_tty_state();
  3504. }
  3505. }
  3506. #else
  3507. # define get_tty_state() ((void)0)
  3508. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3509. #endif
  3510. static void
  3511. set_curjob(struct job *jp, unsigned mode)
  3512. {
  3513. struct job *jp1;
  3514. struct job **jpp, **curp;
  3515. /* first remove from list */
  3516. jpp = curp = &curjob;
  3517. while (1) {
  3518. jp1 = *jpp;
  3519. if (jp1 == jp)
  3520. break;
  3521. jpp = &jp1->prev_job;
  3522. }
  3523. *jpp = jp1->prev_job;
  3524. /* Then re-insert in correct position */
  3525. jpp = curp;
  3526. switch (mode) {
  3527. default:
  3528. #if DEBUG
  3529. abort();
  3530. #endif
  3531. case CUR_DELETE:
  3532. /* job being deleted */
  3533. break;
  3534. case CUR_RUNNING:
  3535. /* newly created job or backgrounded job,
  3536. * put after all stopped jobs.
  3537. */
  3538. while (1) {
  3539. jp1 = *jpp;
  3540. #if JOBS
  3541. if (!jp1 || jp1->state != JOBSTOPPED)
  3542. #endif
  3543. break;
  3544. jpp = &jp1->prev_job;
  3545. }
  3546. /* FALLTHROUGH */
  3547. #if JOBS
  3548. case CUR_STOPPED:
  3549. #endif
  3550. /* newly stopped job - becomes curjob */
  3551. jp->prev_job = *jpp;
  3552. *jpp = jp;
  3553. break;
  3554. }
  3555. }
  3556. #if JOBS || DEBUG
  3557. static int
  3558. jobno(const struct job *jp)
  3559. {
  3560. return jp - jobtab + 1;
  3561. }
  3562. #endif
  3563. /*
  3564. * Convert a job name to a job structure.
  3565. */
  3566. #if !JOBS
  3567. #define getjob(name, getctl) getjob(name)
  3568. #endif
  3569. static struct job *
  3570. getjob(const char *name, int getctl)
  3571. {
  3572. struct job *jp;
  3573. struct job *found;
  3574. const char *err_msg = "%s: no such job";
  3575. unsigned num;
  3576. int c;
  3577. const char *p;
  3578. jp = curjob;
  3579. p = name;
  3580. if (!p)
  3581. goto currentjob;
  3582. if (*p != '%')
  3583. goto err;
  3584. c = *++p;
  3585. if (!c)
  3586. goto currentjob;
  3587. if (!p[1]) {
  3588. if (c == '+' || c == '%') {
  3589. currentjob:
  3590. err_msg = "No current job";
  3591. goto check;
  3592. }
  3593. if (c == '-') {
  3594. if (jp)
  3595. jp = jp->prev_job;
  3596. err_msg = "No previous job";
  3597. check:
  3598. if (!jp)
  3599. goto err;
  3600. goto gotit;
  3601. }
  3602. }
  3603. if (is_number(p)) {
  3604. num = atoi(p);
  3605. if (num > 0 && num <= njobs) {
  3606. jp = jobtab + num - 1;
  3607. if (jp->used)
  3608. goto gotit;
  3609. goto err;
  3610. }
  3611. }
  3612. found = NULL;
  3613. while (jp) {
  3614. if (*p == '?'
  3615. ? strstr(jp->ps[0].ps_cmd, p + 1)
  3616. : prefix(jp->ps[0].ps_cmd, p)
  3617. ) {
  3618. if (found)
  3619. goto err;
  3620. found = jp;
  3621. err_msg = "%s: ambiguous";
  3622. }
  3623. jp = jp->prev_job;
  3624. }
  3625. if (!found)
  3626. goto err;
  3627. jp = found;
  3628. gotit:
  3629. #if JOBS
  3630. err_msg = "job %s not created under job control";
  3631. if (getctl && jp->jobctl == 0)
  3632. goto err;
  3633. #endif
  3634. return jp;
  3635. err:
  3636. ash_msg_and_raise_error(err_msg, name);
  3637. }
  3638. /*
  3639. * Mark a job structure as unused.
  3640. */
  3641. static void
  3642. freejob(struct job *jp)
  3643. {
  3644. struct procstat *ps;
  3645. int i;
  3646. INT_OFF;
  3647. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3648. if (ps->ps_cmd != nullstr)
  3649. free(ps->ps_cmd);
  3650. }
  3651. if (jp->ps != &jp->ps0)
  3652. free(jp->ps);
  3653. jp->used = 0;
  3654. set_curjob(jp, CUR_DELETE);
  3655. INT_ON;
  3656. }
  3657. #if JOBS
  3658. static void
  3659. xtcsetpgrp(int fd, pid_t pgrp)
  3660. {
  3661. if (tcsetpgrp(fd, pgrp))
  3662. ash_msg_and_raise_perror("can't set tty process group");
  3663. }
  3664. /*
  3665. * Turn job control on and off.
  3666. *
  3667. * Note: This code assumes that the third arg to ioctl is a character
  3668. * pointer, which is true on Berkeley systems but not System V. Since
  3669. * System V doesn't have job control yet, this isn't a problem now.
  3670. *
  3671. * Called with interrupts off.
  3672. */
  3673. static void
  3674. setjobctl(int on)
  3675. {
  3676. int fd;
  3677. int pgrp;
  3678. if (on == doing_jobctl || rootshell == 0)
  3679. return;
  3680. if (on) {
  3681. int ofd;
  3682. ofd = fd = open(_PATH_TTY, O_RDWR);
  3683. if (fd < 0) {
  3684. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3685. * That sometimes helps to acquire controlling tty.
  3686. * Obviously, a workaround for bugs when someone
  3687. * failed to provide a controlling tty to bash! :) */
  3688. fd = 2;
  3689. while (!isatty(fd))
  3690. if (--fd < 0)
  3691. goto out;
  3692. }
  3693. /* fd is a tty at this point */
  3694. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3695. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3696. close(ofd);
  3697. if (fd < 0)
  3698. goto out; /* F_DUPFD failed */
  3699. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3700. close_on_exec_on(fd);
  3701. while (1) { /* while we are in the background */
  3702. pgrp = tcgetpgrp(fd);
  3703. if (pgrp < 0) {
  3704. out:
  3705. ash_msg("can't access tty; job control turned off");
  3706. mflag = on = 0;
  3707. goto close;
  3708. }
  3709. if (pgrp == getpgrp())
  3710. break;
  3711. killpg(0, SIGTTIN);
  3712. }
  3713. initialpgrp = pgrp;
  3714. setsignal(SIGTSTP);
  3715. setsignal(SIGTTOU);
  3716. setsignal(SIGTTIN);
  3717. pgrp = rootpid;
  3718. setpgid(0, pgrp);
  3719. xtcsetpgrp(fd, pgrp);
  3720. } else {
  3721. /* turning job control off */
  3722. fd = ttyfd;
  3723. pgrp = initialpgrp;
  3724. /* was xtcsetpgrp, but this can make exiting ash
  3725. * loop forever if pty is already deleted */
  3726. tcsetpgrp(fd, pgrp);
  3727. setpgid(0, pgrp);
  3728. setsignal(SIGTSTP);
  3729. setsignal(SIGTTOU);
  3730. setsignal(SIGTTIN);
  3731. close:
  3732. if (fd >= 0)
  3733. close(fd);
  3734. fd = -1;
  3735. }
  3736. ttyfd = fd;
  3737. doing_jobctl = on;
  3738. }
  3739. static int FAST_FUNC
  3740. killcmd(int argc, char **argv)
  3741. {
  3742. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3743. int i = 1;
  3744. do {
  3745. if (argv[i][0] == '%') {
  3746. /*
  3747. * "kill %N" - job kill
  3748. * Converting to pgrp / pid kill
  3749. */
  3750. struct job *jp;
  3751. char *dst;
  3752. int j, n;
  3753. jp = getjob(argv[i], 0);
  3754. /*
  3755. * In jobs started under job control, we signal
  3756. * entire process group by kill -PGRP_ID.
  3757. * This happens, f.e., in interactive shell.
  3758. *
  3759. * Otherwise, we signal each child via
  3760. * kill PID1 PID2 PID3.
  3761. * Testcases:
  3762. * sh -c 'sleep 1|sleep 1 & kill %1'
  3763. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3764. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3765. */
  3766. n = jp->nprocs; /* can't be 0 (I hope) */
  3767. if (jp->jobctl)
  3768. n = 1;
  3769. dst = alloca(n * sizeof(int)*4);
  3770. argv[i] = dst;
  3771. for (j = 0; j < n; j++) {
  3772. struct procstat *ps = &jp->ps[j];
  3773. /* Skip non-running and not-stopped members
  3774. * (i.e. dead members) of the job
  3775. */
  3776. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3777. continue;
  3778. /*
  3779. * kill_main has matching code to expect
  3780. * leading space. Needed to not confuse
  3781. * negative pids with "kill -SIGNAL_NO" syntax
  3782. */
  3783. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3784. }
  3785. *dst = '\0';
  3786. }
  3787. } while (argv[++i]);
  3788. }
  3789. return kill_main(argc, argv);
  3790. }
  3791. static void
  3792. showpipe(struct job *jp /*, FILE *out*/)
  3793. {
  3794. struct procstat *ps;
  3795. struct procstat *psend;
  3796. psend = jp->ps + jp->nprocs;
  3797. for (ps = jp->ps + 1; ps < psend; ps++)
  3798. printf(" | %s", ps->ps_cmd);
  3799. newline_and_flush(stdout);
  3800. flush_stdout_stderr();
  3801. }
  3802. static int
  3803. restartjob(struct job *jp, int mode)
  3804. {
  3805. struct procstat *ps;
  3806. int i;
  3807. int status;
  3808. pid_t pgid;
  3809. INT_OFF;
  3810. if (jp->state == JOBDONE)
  3811. goto out;
  3812. jp->state = JOBRUNNING;
  3813. pgid = jp->ps[0].ps_pid;
  3814. if (mode == FORK_FG) {
  3815. get_tty_state();
  3816. xtcsetpgrp(ttyfd, pgid);
  3817. }
  3818. killpg(pgid, SIGCONT);
  3819. ps = jp->ps;
  3820. i = jp->nprocs;
  3821. do {
  3822. if (WIFSTOPPED(ps->ps_status)) {
  3823. ps->ps_status = -1;
  3824. }
  3825. ps++;
  3826. } while (--i);
  3827. out:
  3828. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3829. INT_ON;
  3830. return status;
  3831. }
  3832. static int FAST_FUNC
  3833. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3834. {
  3835. struct job *jp;
  3836. int mode;
  3837. int retval;
  3838. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3839. nextopt(nullstr);
  3840. argv = argptr;
  3841. do {
  3842. jp = getjob(*argv, 1);
  3843. if (mode == FORK_BG) {
  3844. set_curjob(jp, CUR_RUNNING);
  3845. printf("[%d] ", jobno(jp));
  3846. }
  3847. out1str(jp->ps[0].ps_cmd);
  3848. showpipe(jp /*, stdout*/);
  3849. retval = restartjob(jp, mode);
  3850. } while (*argv && *++argv);
  3851. return retval;
  3852. }
  3853. #endif
  3854. static int
  3855. sprint_status48(char *os, int status, int sigonly)
  3856. {
  3857. char *s = os;
  3858. int st;
  3859. if (!WIFEXITED(status)) {
  3860. #if JOBS
  3861. if (WIFSTOPPED(status))
  3862. st = WSTOPSIG(status);
  3863. else
  3864. #endif
  3865. st = WTERMSIG(status);
  3866. if (sigonly) {
  3867. if (st == SIGINT || st == SIGPIPE)
  3868. goto out;
  3869. #if JOBS
  3870. if (WIFSTOPPED(status))
  3871. goto out;
  3872. #endif
  3873. }
  3874. st &= 0x7f;
  3875. s = stpncpy(s, strsignal(st), 32);
  3876. if (WCOREDUMP(status)) {
  3877. s = stpcpy(s, " (core dumped)");
  3878. }
  3879. } else if (!sigonly) {
  3880. st = WEXITSTATUS(status);
  3881. s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3882. }
  3883. out:
  3884. return s - os;
  3885. }
  3886. #define DOWAIT_NONBLOCK 0
  3887. #define DOWAIT_BLOCK 1
  3888. #define DOWAIT_BLOCK_OR_SIG 2
  3889. #if BASH_WAIT_N
  3890. # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
  3891. #endif
  3892. static int
  3893. waitproc(int block, int *status)
  3894. {
  3895. sigset_t oldmask;
  3896. int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG;
  3897. int err;
  3898. #if JOBS
  3899. if (doing_jobctl)
  3900. flags |= WUNTRACED;
  3901. #endif
  3902. do {
  3903. got_sigchld = 0;
  3904. do
  3905. err = waitpid(-1, status, flags);
  3906. while (err < 0 && errno == EINTR);
  3907. if (err || (err = -!block))
  3908. break;
  3909. sigfillset(&oldmask);
  3910. sigprocmask2(SIG_SETMASK, &oldmask); /* mask is updated */
  3911. while (!got_sigchld && !pending_sig)
  3912. sigsuspend(&oldmask);
  3913. sigprocmask(SIG_SETMASK, &oldmask, NULL);
  3914. //simpler, but unsafe: a signal can set pending_sig after check, but before pause():
  3915. //while (!got_sigchld && !pending_sig)
  3916. // pause();
  3917. } while (got_sigchld);
  3918. return err;
  3919. }
  3920. static int
  3921. waitone(int block, struct job *job)
  3922. {
  3923. int pid;
  3924. int status;
  3925. struct job *jp;
  3926. struct job *thisjob = NULL;
  3927. #if BASH_WAIT_N
  3928. bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
  3929. block = (block & ~DOWAIT_JOBSTATUS);
  3930. #endif
  3931. TRACE(("dowait(0x%x) called\n", block));
  3932. /* It's wrong to call waitpid() outside of INT_OFF region:
  3933. * signal can arrive just after syscall return and handler can
  3934. * longjmp away, losing stop/exit notification processing.
  3935. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3936. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3937. *
  3938. * However, for "wait" builtin it is wrong to simply call waitpid()
  3939. * in INT_OFF region: "wait" needs to wait for any running job
  3940. * to change state, but should exit on any trap too.
  3941. * In INT_OFF region, a signal just before syscall entry can set
  3942. * pending_sig variables, but we can't check them, and we would
  3943. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3944. *
  3945. * Because of this, we run inside INT_OFF, but use a special routine
  3946. * which combines waitpid() and sigsuspend().
  3947. * This is the reason why we need to have a handler for SIGCHLD:
  3948. * SIG_DFL handler does not wake sigsuspend().
  3949. */
  3950. INT_OFF;
  3951. pid = waitproc(block, &status);
  3952. TRACE(("wait returns pid %d, status=%d\n", pid, status));
  3953. if (pid <= 0)
  3954. goto out;
  3955. for (jp = curjob; jp; jp = jp->prev_job) {
  3956. int jobstate;
  3957. struct procstat *ps;
  3958. struct procstat *psend;
  3959. if (jp->state == JOBDONE)
  3960. continue;
  3961. jobstate = JOBDONE;
  3962. ps = jp->ps;
  3963. psend = ps + jp->nprocs;
  3964. do {
  3965. if (ps->ps_pid == pid) {
  3966. TRACE(("Job %d: changing status of proc %d "
  3967. "from 0x%x to 0x%x\n",
  3968. jobno(jp), pid, ps->ps_status, status));
  3969. ps->ps_status = status;
  3970. thisjob = jp;
  3971. }
  3972. if (ps->ps_status == -1)
  3973. jobstate = JOBRUNNING;
  3974. #if JOBS
  3975. if (jobstate == JOBRUNNING)
  3976. continue;
  3977. if (WIFSTOPPED(ps->ps_status)) {
  3978. jp->stopstatus = ps->ps_status;
  3979. jobstate = JOBSTOPPED;
  3980. }
  3981. #endif
  3982. } while (++ps < psend);
  3983. if (!thisjob)
  3984. continue;
  3985. /* Found the job where one of its processes changed its state.
  3986. * Is there at least one live and running process in this job? */
  3987. if (jobstate != JOBRUNNING) {
  3988. /* No. All live processes in the job are stopped
  3989. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3990. */
  3991. thisjob->changed = 1;
  3992. if (thisjob->state != jobstate) {
  3993. TRACE(("Job %d: changing state from %d to %d\n",
  3994. jobno(thisjob), thisjob->state, jobstate));
  3995. thisjob->state = jobstate;
  3996. #if JOBS
  3997. if (jobstate == JOBSTOPPED)
  3998. set_curjob(thisjob, CUR_STOPPED);
  3999. #endif
  4000. }
  4001. }
  4002. goto out;
  4003. }
  4004. /* The process wasn't found in job list */
  4005. out:
  4006. INT_ON;
  4007. #if BASH_WAIT_N
  4008. if (want_jobexitstatus) {
  4009. pid = -1;
  4010. if (thisjob && thisjob->state == JOBDONE)
  4011. pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
  4012. }
  4013. #endif
  4014. if (thisjob && thisjob == job) {
  4015. char s[48 + 1];
  4016. int len;
  4017. len = sprint_status48(s, status, 1);
  4018. if (len) {
  4019. s[len] = '\n';
  4020. s[len + 1] = '\0';
  4021. out2str(s);
  4022. }
  4023. }
  4024. return pid;
  4025. }
  4026. static int
  4027. dowait(int block, struct job *jp)
  4028. {
  4029. smallint gotchld = *(volatile smallint *)&got_sigchld;
  4030. int rpid;
  4031. int pid;
  4032. if (jp && jp->state != JOBRUNNING)
  4033. block = DOWAIT_NONBLOCK;
  4034. if (block == DOWAIT_NONBLOCK && !gotchld)
  4035. return 1;
  4036. rpid = 1;
  4037. do {
  4038. pid = waitone(block, jp);
  4039. rpid &= !!pid;
  4040. if (!pid || (jp && jp->state != JOBRUNNING))
  4041. block = DOWAIT_NONBLOCK;
  4042. } while (pid >= 0);
  4043. return rpid;
  4044. }
  4045. #if JOBS
  4046. static void
  4047. showjob(struct job *jp, int mode)
  4048. {
  4049. struct procstat *ps;
  4050. struct procstat *psend;
  4051. int col;
  4052. int indent_col;
  4053. char s[16 + 16 + 48];
  4054. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  4055. ps = jp->ps;
  4056. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  4057. /* just output process (group) id of pipeline */
  4058. fprintf(out, "%d\n", ps->ps_pid);
  4059. return;
  4060. }
  4061. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  4062. indent_col = col;
  4063. if (jp == curjob)
  4064. s[col - 3] = '+';
  4065. else if (curjob && jp == curjob->prev_job)
  4066. s[col - 3] = '-';
  4067. if (mode & SHOW_PIDS)
  4068. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  4069. psend = ps + jp->nprocs;
  4070. if (jp->state == JOBRUNNING) {
  4071. strcpy(s + col, "Running");
  4072. col += sizeof("Running") - 1;
  4073. } else {
  4074. int status = psend[-1].ps_status;
  4075. if (jp->state == JOBSTOPPED)
  4076. status = jp->stopstatus;
  4077. col += sprint_status48(s + col, status, 0);
  4078. }
  4079. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  4080. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  4081. * or prints several "PID | <cmdN>" lines,
  4082. * depending on SHOW_PIDS bit.
  4083. * We do not print status of individual processes
  4084. * between PID and <cmdN>. bash does it, but not very well:
  4085. * first line shows overall job status, not process status,
  4086. * making it impossible to know 1st process status.
  4087. */
  4088. goto start;
  4089. do {
  4090. /* for each process */
  4091. s[0] = '\0';
  4092. col = 33;
  4093. if (mode & SHOW_PIDS)
  4094. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  4095. start:
  4096. fprintf(out, "%s%*c%s%s",
  4097. s,
  4098. 33 - col >= 0 ? 33 - col : 0, ' ',
  4099. ps == jp->ps ? "" : "| ",
  4100. ps->ps_cmd
  4101. );
  4102. } while (++ps != psend);
  4103. newline_and_flush(out);
  4104. jp->changed = 0;
  4105. if (jp->state == JOBDONE) {
  4106. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4107. freejob(jp);
  4108. }
  4109. }
  4110. /*
  4111. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4112. * statuses have changed since the last call to showjobs.
  4113. */
  4114. static void
  4115. showjobs(int mode)
  4116. {
  4117. struct job *jp;
  4118. TRACE(("showjobs(0x%x) called\n", mode));
  4119. /* Handle all finished jobs */
  4120. dowait(DOWAIT_NONBLOCK, NULL);
  4121. for (jp = curjob; jp; jp = jp->prev_job) {
  4122. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4123. showjob(jp, mode);
  4124. }
  4125. }
  4126. }
  4127. static int FAST_FUNC
  4128. jobscmd(int argc UNUSED_PARAM, char **argv)
  4129. {
  4130. int mode, m;
  4131. mode = 0;
  4132. while ((m = nextopt("lp")) != '\0') {
  4133. if (m == 'l')
  4134. mode |= SHOW_PIDS;
  4135. else
  4136. mode |= SHOW_ONLY_PGID;
  4137. }
  4138. argv = argptr;
  4139. if (*argv) {
  4140. do
  4141. showjob(getjob(*argv, 0), mode);
  4142. while (*++argv);
  4143. } else {
  4144. showjobs(mode);
  4145. }
  4146. return 0;
  4147. }
  4148. #endif /* JOBS */
  4149. /* Called only on finished or stopped jobs (no members are running) */
  4150. static int
  4151. getstatus(struct job *job)
  4152. {
  4153. int status;
  4154. int retval;
  4155. struct procstat *ps;
  4156. /* Fetch last member's status */
  4157. ps = job->ps + job->nprocs - 1;
  4158. status = ps->ps_status;
  4159. if (pipefail) {
  4160. /* "set -o pipefail" mode: use last _nonzero_ status */
  4161. while (status == 0 && --ps >= job->ps)
  4162. status = ps->ps_status;
  4163. }
  4164. retval = WEXITSTATUS(status);
  4165. if (!WIFEXITED(status)) {
  4166. #if JOBS
  4167. retval = WSTOPSIG(status);
  4168. if (!WIFSTOPPED(status))
  4169. #endif
  4170. {
  4171. /* XXX: limits number of signals */
  4172. retval = WTERMSIG(status);
  4173. #if JOBS
  4174. if (retval == SIGINT)
  4175. job->sigint = 1;
  4176. #endif
  4177. }
  4178. retval |= 128;
  4179. }
  4180. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4181. jobno(job), job->nprocs, status, retval));
  4182. return retval;
  4183. }
  4184. static int FAST_FUNC
  4185. waitcmd(int argc UNUSED_PARAM, char **argv)
  4186. {
  4187. struct job *job;
  4188. int retval;
  4189. struct job *jp;
  4190. #if BASH_WAIT_N
  4191. int status;
  4192. char one = nextopt("n");
  4193. #else
  4194. nextopt(nullstr);
  4195. #endif
  4196. retval = 0;
  4197. argv = argptr;
  4198. if (!argv[0]) {
  4199. /* wait for all jobs / one job if -n */
  4200. for (;;) {
  4201. jp = curjob;
  4202. #if BASH_WAIT_N
  4203. if (one && !jp)
  4204. /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
  4205. retval = 127;
  4206. #endif
  4207. while (1) {
  4208. if (!jp) /* no running procs */
  4209. goto ret;
  4210. if (jp->state == JOBRUNNING)
  4211. break;
  4212. jp->waited = 1;
  4213. jp = jp->prev_job;
  4214. }
  4215. /* man bash:
  4216. * "When bash is waiting for an asynchronous command via
  4217. * the wait builtin, the reception of a signal for which a trap
  4218. * has been set will cause the wait builtin to return immediately
  4219. * with an exit status greater than 128, immediately after which
  4220. * the trap is executed."
  4221. */
  4222. #if BASH_WAIT_N
  4223. status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
  4224. #else
  4225. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4226. #endif
  4227. /* if child sends us a signal *and immediately exits*,
  4228. * dowait() returns pid > 0. Check this case,
  4229. * not "if (dowait() < 0)"!
  4230. */
  4231. if (pending_sig)
  4232. goto sigout;
  4233. #if BASH_WAIT_N
  4234. if (one) {
  4235. /* wait -n waits for one _job_, not one _process_.
  4236. * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
  4237. * should wait for 2 seconds. Not 1 or 3.
  4238. */
  4239. if (status != -1 && !WIFSTOPPED(status)) {
  4240. retval = WEXITSTATUS(status);
  4241. if (WIFSIGNALED(status))
  4242. retval = 128 | WTERMSIG(status);
  4243. goto ret;
  4244. }
  4245. }
  4246. #endif
  4247. }
  4248. }
  4249. retval = 127;
  4250. do {
  4251. if (**argv != '%') {
  4252. pid_t pid = number(*argv);
  4253. job = curjob;
  4254. while (1) {
  4255. if (!job)
  4256. goto repeat;
  4257. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4258. break;
  4259. job = job->prev_job;
  4260. }
  4261. } else {
  4262. job = getjob(*argv, 0);
  4263. }
  4264. /* loop until process terminated or stopped */
  4265. dowait(DOWAIT_BLOCK_OR_SIG, job);
  4266. if (pending_sig)
  4267. goto sigout;
  4268. job->waited = 1;
  4269. retval = getstatus(job);
  4270. repeat: ;
  4271. } while (*++argv);
  4272. ret:
  4273. return retval;
  4274. sigout:
  4275. retval = 128 | pending_sig;
  4276. return retval;
  4277. }
  4278. static struct job *
  4279. growjobtab(void)
  4280. {
  4281. size_t len;
  4282. ptrdiff_t offset;
  4283. struct job *jp, *jq;
  4284. len = njobs * sizeof(*jp);
  4285. jq = jobtab;
  4286. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4287. offset = (char *)jp - (char *)jq;
  4288. if (offset) {
  4289. /* Relocate pointers */
  4290. size_t l = len;
  4291. jq = (struct job *)((char *)jq + l);
  4292. while (l) {
  4293. l -= sizeof(*jp);
  4294. jq--;
  4295. #define joff(p) ((struct job *)((char *)(p) + l))
  4296. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4297. if (joff(jp)->ps == &jq->ps0)
  4298. jmove(joff(jp)->ps);
  4299. if (joff(jp)->prev_job)
  4300. jmove(joff(jp)->prev_job);
  4301. }
  4302. if (curjob)
  4303. jmove(curjob);
  4304. #undef joff
  4305. #undef jmove
  4306. }
  4307. njobs += 4;
  4308. jobtab = jp;
  4309. jp = (struct job *)((char *)jp + len);
  4310. jq = jp + 3;
  4311. do {
  4312. jq->used = 0;
  4313. } while (--jq >= jp);
  4314. return jp;
  4315. }
  4316. /*
  4317. * Return a new job structure.
  4318. * Called with interrupts off.
  4319. */
  4320. static struct job *
  4321. makejob(/*union node *node,*/ int nprocs)
  4322. {
  4323. int i;
  4324. struct job *jp;
  4325. for (i = njobs, jp = jobtab; ; jp++) {
  4326. if (--i < 0) {
  4327. jp = growjobtab();
  4328. break;
  4329. }
  4330. if (jp->used == 0)
  4331. break;
  4332. if (jp->state != JOBDONE || !jp->waited)
  4333. continue;
  4334. #if JOBS
  4335. if (doing_jobctl)
  4336. continue;
  4337. #endif
  4338. freejob(jp);
  4339. break;
  4340. }
  4341. memset(jp, 0, sizeof(*jp));
  4342. #if JOBS
  4343. /* jp->jobctl is a bitfield.
  4344. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4345. if (doing_jobctl)
  4346. jp->jobctl = 1;
  4347. #endif
  4348. jp->prev_job = curjob;
  4349. curjob = jp;
  4350. jp->used = 1;
  4351. jp->ps = &jp->ps0;
  4352. if (nprocs > 1) {
  4353. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4354. }
  4355. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4356. jobno(jp)));
  4357. return jp;
  4358. }
  4359. #if JOBS
  4360. /*
  4361. * Return a string identifying a command (to be printed by the
  4362. * jobs command).
  4363. */
  4364. static char *cmdnextc;
  4365. static void
  4366. cmdputs(const char *s)
  4367. {
  4368. static const char vstype[VSTYPE + 1][3] ALIGN1 = {
  4369. "", "}", "-", "+", "?", "=",
  4370. "%", "%%", "#", "##"
  4371. IF_BASH_SUBSTR(, ":")
  4372. IF_BASH_PATTERN_SUBST(, "/", "//")
  4373. };
  4374. const char *p, *str;
  4375. char cc[2];
  4376. char *nextc;
  4377. unsigned char c;
  4378. unsigned char subtype = 0;
  4379. int quoted = 0;
  4380. cc[1] = '\0';
  4381. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4382. p = s;
  4383. while ((c = *p++) != '\0') {
  4384. str = NULL;
  4385. switch (c) {
  4386. case CTLESC:
  4387. c = *p++;
  4388. break;
  4389. case CTLVAR:
  4390. subtype = *p++;
  4391. if ((subtype & VSTYPE) == VSLENGTH)
  4392. str = "${#";
  4393. else
  4394. str = "${";
  4395. goto dostr;
  4396. case CTLENDVAR:
  4397. str = "\"}";
  4398. str += !(quoted & 1);
  4399. quoted >>= 1;
  4400. subtype = 0;
  4401. goto dostr;
  4402. #if BASH_PROCESS_SUBST
  4403. case CTLBACKQ:
  4404. c = '$';
  4405. str = "(...)";
  4406. break;
  4407. case CTLTOPROC:
  4408. c = '>';
  4409. str = "(...)";
  4410. break;
  4411. case CTLFROMPROC:
  4412. c = '<';
  4413. str = "(...)";
  4414. break;
  4415. #else
  4416. case CTLBACKQ:
  4417. str = "$(...)";
  4418. goto dostr;
  4419. #endif
  4420. #if ENABLE_FEATURE_SH_MATH
  4421. case CTLARI:
  4422. str = "$((";
  4423. goto dostr;
  4424. case CTLENDARI:
  4425. str = "))";
  4426. goto dostr;
  4427. #endif
  4428. case CTLQUOTEMARK:
  4429. quoted ^= 1;
  4430. c = '"';
  4431. break;
  4432. case '=':
  4433. if (subtype == 0)
  4434. break;
  4435. if ((subtype & VSTYPE) != VSNORMAL)
  4436. quoted <<= 1;
  4437. str = vstype[subtype & VSTYPE];
  4438. if (subtype & VSNUL)
  4439. c = ':';
  4440. else
  4441. goto checkstr;
  4442. break;
  4443. case '\'':
  4444. case '\\':
  4445. case '"':
  4446. case '$':
  4447. /* These can only happen inside quotes */
  4448. cc[0] = c;
  4449. str = cc;
  4450. //FIXME:
  4451. // $ true $$ &
  4452. // $ <cr>
  4453. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4454. c = '\\';
  4455. break;
  4456. default:
  4457. break;
  4458. }
  4459. USTPUTC(c, nextc);
  4460. checkstr:
  4461. if (!str)
  4462. continue;
  4463. dostr:
  4464. while ((c = *str++) != '\0') {
  4465. USTPUTC(c, nextc);
  4466. }
  4467. } /* while *p++ not NUL */
  4468. if (quoted & 1) {
  4469. USTPUTC('"', nextc);
  4470. }
  4471. *nextc = 0;
  4472. cmdnextc = nextc;
  4473. }
  4474. /* cmdtxt() and cmdlist() call each other */
  4475. static void cmdtxt(union node *n);
  4476. static void
  4477. cmdlist(union node *np, int sep)
  4478. {
  4479. for (; np; np = np->narg.next) {
  4480. if (!sep)
  4481. cmdputs(" ");
  4482. cmdtxt(np);
  4483. if (sep && np->narg.next)
  4484. cmdputs(" ");
  4485. }
  4486. }
  4487. static void
  4488. cmdtxt(union node *n)
  4489. {
  4490. union node *np;
  4491. struct nodelist *lp;
  4492. const char *p;
  4493. if (!n)
  4494. return;
  4495. switch (n->type) {
  4496. default:
  4497. #if DEBUG
  4498. abort();
  4499. #endif
  4500. case NPIPE:
  4501. lp = n->npipe.cmdlist;
  4502. for (;;) {
  4503. cmdtxt(lp->n);
  4504. lp = lp->next;
  4505. if (!lp)
  4506. break;
  4507. cmdputs(" | ");
  4508. }
  4509. break;
  4510. case NSEMI:
  4511. p = "; ";
  4512. goto binop;
  4513. case NAND:
  4514. p = " && ";
  4515. goto binop;
  4516. case NOR:
  4517. p = " || ";
  4518. binop:
  4519. cmdtxt(n->nbinary.ch1);
  4520. cmdputs(p);
  4521. n = n->nbinary.ch2;
  4522. goto donode;
  4523. case NREDIR:
  4524. case NBACKGND:
  4525. n = n->nredir.n;
  4526. goto donode;
  4527. case NNOT:
  4528. cmdputs("!");
  4529. n = n->nnot.com;
  4530. donode:
  4531. cmdtxt(n);
  4532. break;
  4533. case NIF:
  4534. cmdputs("if ");
  4535. cmdtxt(n->nif.test);
  4536. cmdputs("; then ");
  4537. if (n->nif.elsepart) {
  4538. cmdtxt(n->nif.ifpart);
  4539. cmdputs("; else ");
  4540. n = n->nif.elsepart;
  4541. } else {
  4542. n = n->nif.ifpart;
  4543. }
  4544. p = "; fi";
  4545. goto dotail;
  4546. case NSUBSHELL:
  4547. cmdputs("(");
  4548. n = n->nredir.n;
  4549. p = ")";
  4550. goto dotail;
  4551. case NWHILE:
  4552. p = "while ";
  4553. goto until;
  4554. case NUNTIL:
  4555. p = "until ";
  4556. until:
  4557. cmdputs(p);
  4558. cmdtxt(n->nbinary.ch1);
  4559. n = n->nbinary.ch2;
  4560. p = "; done";
  4561. dodo:
  4562. cmdputs("; do ");
  4563. dotail:
  4564. cmdtxt(n);
  4565. goto dotail2;
  4566. case NFOR:
  4567. cmdputs("for ");
  4568. cmdputs(n->nfor.var);
  4569. cmdputs(" in ");
  4570. cmdlist(n->nfor.args, 1);
  4571. n = n->nfor.body;
  4572. p = "; done";
  4573. goto dodo;
  4574. case NDEFUN:
  4575. cmdputs(n->ndefun.text);
  4576. p = "() { ... }";
  4577. goto dotail2;
  4578. case NCMD:
  4579. cmdlist(n->ncmd.args, 1);
  4580. cmdlist(n->ncmd.redirect, 0);
  4581. break;
  4582. case NARG:
  4583. p = n->narg.text;
  4584. dotail2:
  4585. cmdputs(p);
  4586. break;
  4587. case NHERE:
  4588. case NXHERE:
  4589. p = "<<...";
  4590. goto dotail2;
  4591. case NCASE:
  4592. cmdputs("case ");
  4593. cmdputs(n->ncase.expr->narg.text);
  4594. cmdputs(" in ");
  4595. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4596. cmdtxt(np->nclist.pattern);
  4597. cmdputs(") ");
  4598. cmdtxt(np->nclist.body);
  4599. cmdputs(";; ");
  4600. }
  4601. p = "esac";
  4602. goto dotail2;
  4603. case NTO:
  4604. p = ">";
  4605. goto redir;
  4606. case NCLOBBER:
  4607. p = ">|";
  4608. goto redir;
  4609. case NAPPEND:
  4610. p = ">>";
  4611. goto redir;
  4612. #if BASH_REDIR_OUTPUT
  4613. case NTO2:
  4614. #endif
  4615. case NTOFD:
  4616. p = ">&";
  4617. goto redir;
  4618. case NFROM:
  4619. p = "<";
  4620. goto redir;
  4621. case NFROMFD:
  4622. p = "<&";
  4623. goto redir;
  4624. case NFROMTO:
  4625. p = "<>";
  4626. redir:
  4627. cmdputs(utoa(n->nfile.fd));
  4628. cmdputs(p);
  4629. if (n->type == NTOFD || n->type == NFROMFD) {
  4630. if (n->ndup.dupfd >= 0)
  4631. cmdputs(utoa(n->ndup.dupfd));
  4632. else
  4633. cmdputs("-");
  4634. break;
  4635. }
  4636. n = n->nfile.fname;
  4637. goto donode;
  4638. }
  4639. }
  4640. static char *
  4641. commandtext(union node *n)
  4642. {
  4643. char *name;
  4644. STARTSTACKSTR(cmdnextc);
  4645. cmdtxt(n);
  4646. name = stackblock();
  4647. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4648. return ckstrdup(name);
  4649. }
  4650. #endif /* JOBS */
  4651. /*
  4652. * Fork off a subshell. If we are doing job control, give the subshell its
  4653. * own process group. Jp is a job structure that the job is to be added to.
  4654. * N is the command that will be evaluated by the child. Both jp and n may
  4655. * be NULL. The mode parameter can be one of the following:
  4656. * FORK_FG - Fork off a foreground process.
  4657. * FORK_BG - Fork off a background process.
  4658. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4659. * process group even if job control is on.
  4660. *
  4661. * When job control is turned off, background processes have their standard
  4662. * input redirected to /dev/null (except for the second and later processes
  4663. * in a pipeline).
  4664. *
  4665. * Called with interrupts off.
  4666. */
  4667. /*
  4668. * Clear traps on a fork.
  4669. */
  4670. static void
  4671. clear_traps(void)
  4672. {
  4673. char **tp;
  4674. INT_OFF;
  4675. for (tp = trap; tp <= &trap[NTRAP_LAST]; tp++) {
  4676. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4677. if (trap_ptr == trap)
  4678. free(*tp);
  4679. /* else: it "belongs" to trap_ptr vector, don't free */
  4680. *tp = NULL;
  4681. if ((tp - trap) != 0 && (tp - trap) < NSIG)
  4682. setsignal(tp - trap);
  4683. }
  4684. }
  4685. may_have_traps = 0;
  4686. INT_ON;
  4687. }
  4688. /* Lives far away from here, needed for forkchild */
  4689. static void closescript(void);
  4690. /* Called after fork(), in child */
  4691. /* jp and n are NULL when called by openhere() for heredoc support */
  4692. static NOINLINE void
  4693. forkchild(struct job *jp, union node *n, int mode)
  4694. {
  4695. int oldlvl;
  4696. TRACE(("Child shell %d\n", getpid()));
  4697. oldlvl = shlvl;
  4698. shlvl++;
  4699. /* man bash: "Non-builtin commands run by bash have signal handlers
  4700. * set to the values inherited by the shell from its parent".
  4701. * Do we do it correctly? */
  4702. closescript();
  4703. if (n && n->type == NCMD /* is it single cmd? */
  4704. /* && n->ncmd.args->type == NARG - always true? */
  4705. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4706. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4707. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4708. ) {
  4709. TRACE(("Trap hack\n"));
  4710. /* Awful hack for `trap` or $(trap).
  4711. *
  4712. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4713. * contains an example where "trap" is executed in a subshell:
  4714. *
  4715. * save_traps=$(trap)
  4716. * ...
  4717. * eval "$save_traps"
  4718. *
  4719. * Standard does not say that "trap" in subshell shall print
  4720. * parent shell's traps. It only says that its output
  4721. * must have suitable form, but then, in the above example
  4722. * (which is not supposed to be normative), it implies that.
  4723. *
  4724. * bash (and probably other shell) does implement it
  4725. * (traps are reset to defaults, but "trap" still shows them),
  4726. * but as a result, "trap" logic is hopelessly messed up:
  4727. *
  4728. * # trap
  4729. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4730. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4731. * # true | trap <--- trap is in subshell - no output (ditto)
  4732. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4733. * trap -- 'echo Ho' SIGWINCH
  4734. * # echo `(trap)` <--- in subshell in subshell - output
  4735. * trap -- 'echo Ho' SIGWINCH
  4736. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4737. * trap -- 'echo Ho' SIGWINCH
  4738. *
  4739. * The rules when to forget and when to not forget traps
  4740. * get really complex and nonsensical.
  4741. *
  4742. * Our solution: ONLY bare $(trap) or `trap` is special.
  4743. */
  4744. /* Save trap handler strings for trap builtin to print */
  4745. trap_ptr = xmemdup(trap, sizeof(trap));
  4746. /* Fall through into clearing traps */
  4747. }
  4748. clear_traps();
  4749. #if JOBS
  4750. /* do job control only in root shell */
  4751. doing_jobctl = 0;
  4752. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4753. pid_t pgrp;
  4754. if (jp->nprocs == 0)
  4755. pgrp = getpid();
  4756. else
  4757. pgrp = jp->ps[0].ps_pid;
  4758. /* this can fail because we are doing it in the parent also */
  4759. setpgid(0, pgrp);
  4760. if (mode == FORK_FG)
  4761. xtcsetpgrp(ttyfd, pgrp);
  4762. setsignal(SIGTSTP);
  4763. setsignal(SIGTTOU);
  4764. } else
  4765. #endif
  4766. if (mode == FORK_BG) {
  4767. /* man bash: "When job control is not in effect,
  4768. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4769. ignoresig(SIGINT);
  4770. ignoresig(SIGQUIT);
  4771. if (jp->nprocs == 0) {
  4772. close(0);
  4773. if (open(bb_dev_null, O_RDONLY) != 0)
  4774. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4775. }
  4776. }
  4777. if (oldlvl == 0) {
  4778. if (iflag) { /* why if iflag only? */
  4779. setsignal(SIGINT);
  4780. setsignal(SIGTERM);
  4781. }
  4782. /* man bash:
  4783. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4784. * commands run by bash have signal handlers
  4785. * set to the values inherited by the shell
  4786. * from its parent".
  4787. * Take care of the second rule: */
  4788. setsignal(SIGQUIT);
  4789. }
  4790. #if JOBS
  4791. if (n && n->type == NCMD
  4792. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4793. ) {
  4794. TRACE(("Job hack\n"));
  4795. /* "jobs": we do not want to clear job list for it,
  4796. * instead we remove only _its_ own_ job from job list
  4797. * (if it has one).
  4798. * This makes "jobs .... | cat" more useful.
  4799. */
  4800. if (jp)
  4801. freejob(curjob);
  4802. return;
  4803. }
  4804. #endif
  4805. for (jp = curjob; jp; jp = jp->prev_job)
  4806. freejob(jp);
  4807. }
  4808. /* Called after fork(), in parent */
  4809. #if !JOBS
  4810. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4811. #endif
  4812. static void
  4813. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4814. {
  4815. TRACE(("In parent shell: child = %d\n", pid));
  4816. if (!jp) /* jp is NULL when called by openhere() for heredoc support */
  4817. return;
  4818. #if JOBS
  4819. if (mode != FORK_NOJOB && jp->jobctl) {
  4820. int pgrp;
  4821. if (jp->nprocs == 0)
  4822. pgrp = pid;
  4823. else
  4824. pgrp = jp->ps[0].ps_pid;
  4825. /* This can fail because we are doing it in the child also */
  4826. setpgid(pid, pgrp);
  4827. }
  4828. #endif
  4829. if (mode == FORK_BG) {
  4830. backgndpid = pid; /* set $! */
  4831. set_curjob(jp, CUR_RUNNING);
  4832. }
  4833. if (jp) {
  4834. struct procstat *ps = &jp->ps[jp->nprocs++];
  4835. ps->ps_pid = pid;
  4836. ps->ps_status = -1;
  4837. ps->ps_cmd = nullstr;
  4838. #if JOBS
  4839. if (doing_jobctl && n)
  4840. ps->ps_cmd = commandtext(n);
  4841. #endif
  4842. }
  4843. }
  4844. /* jp and n are NULL when called by openhere() for heredoc support */
  4845. static int
  4846. forkshell(struct job *jp, union node *n, int mode)
  4847. {
  4848. int pid;
  4849. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4850. pid = fork();
  4851. if (pid < 0) {
  4852. TRACE(("Fork failed, errno=%d", errno));
  4853. if (jp)
  4854. freejob(jp);
  4855. ash_msg_and_raise_perror("can't fork");
  4856. }
  4857. if (pid == 0) {
  4858. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4859. forkchild(jp, n, mode);
  4860. } else {
  4861. forkparent(jp, n, mode, pid);
  4862. }
  4863. return pid;
  4864. }
  4865. /*
  4866. * Wait for job to finish.
  4867. *
  4868. * Under job control we have the problem that while a child process
  4869. * is running interrupts generated by the user are sent to the child
  4870. * but not to the shell. This means that an infinite loop started by
  4871. * an interactive user may be hard to kill. With job control turned off,
  4872. * an interactive user may place an interactive program inside a loop.
  4873. * If the interactive program catches interrupts, the user doesn't want
  4874. * these interrupts to also abort the loop. The approach we take here
  4875. * is to have the shell ignore interrupt signals while waiting for a
  4876. * foreground process to terminate, and then send itself an interrupt
  4877. * signal if the child process was terminated by an interrupt signal.
  4878. * Unfortunately, some programs want to do a bit of cleanup and then
  4879. * exit on interrupt; unless these processes terminate themselves by
  4880. * sending a signal to themselves (instead of calling exit) they will
  4881. * confuse this approach.
  4882. *
  4883. * Called with interrupts off.
  4884. */
  4885. static int
  4886. waitforjob(struct job *jp)
  4887. {
  4888. int st;
  4889. TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0));
  4890. /* In non-interactive shells, we _can_ get
  4891. * a keyboard signal here and be EINTRed, but we just loop
  4892. * inside dowait(), waiting for command to complete.
  4893. *
  4894. * man bash:
  4895. * "If bash is waiting for a command to complete and receives
  4896. * a signal for which a trap has been set, the trap
  4897. * will not be executed until the command completes."
  4898. *
  4899. * Reality is that even if trap is not set, bash
  4900. * will not act on the signal until command completes.
  4901. * Try this. sleep5intoff.c:
  4902. * #include <signal.h>
  4903. * #include <unistd.h>
  4904. * int main() {
  4905. * sigset_t set;
  4906. * sigemptyset(&set);
  4907. * sigaddset(&set, SIGINT);
  4908. * sigaddset(&set, SIGQUIT);
  4909. * sigprocmask(SIG_BLOCK, &set, NULL);
  4910. * sleep(5);
  4911. * return 0;
  4912. * }
  4913. * $ bash -c './sleep5intoff; echo hi'
  4914. * ^C^C^C^C <--- pressing ^C once a second
  4915. * $ _
  4916. * $ bash -c './sleep5intoff; echo hi'
  4917. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4918. * $ _
  4919. */
  4920. dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp);
  4921. if (!jp)
  4922. return exitstatus;
  4923. st = getstatus(jp);
  4924. #if JOBS
  4925. if (jp->jobctl) {
  4926. xtcsetpgrp(ttyfd, rootpid);
  4927. restore_tty_if_stopped_or_signaled(jp);
  4928. /*
  4929. * This is truly gross.
  4930. * If we're doing job control, then we did a TIOCSPGRP which
  4931. * caused us (the shell) to no longer be in the controlling
  4932. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4933. * intuit from the subprocess exit status whether a SIGINT
  4934. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4935. */
  4936. if (jp->sigint) /* TODO: do the same with all signals */
  4937. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4938. }
  4939. if (jp->state == JOBDONE)
  4940. #endif
  4941. freejob(jp);
  4942. return st;
  4943. }
  4944. /*
  4945. * return 1 if there are stopped jobs, otherwise 0
  4946. */
  4947. static int
  4948. stoppedjobs(void)
  4949. {
  4950. struct job *jp;
  4951. int retval;
  4952. retval = 0;
  4953. if (!iflag || job_warning)
  4954. goto out;
  4955. jp = curjob;
  4956. if (jp && jp->state == JOBSTOPPED) {
  4957. out2str("You have stopped jobs.\n");
  4958. job_warning = 2;
  4959. retval++;
  4960. }
  4961. out:
  4962. return retval;
  4963. }
  4964. /*
  4965. * Code for dealing with input/output redirection.
  4966. */
  4967. #undef EMPTY
  4968. #undef CLOSED
  4969. #define EMPTY -2 /* marks an unused slot in redirtab */
  4970. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4971. /*
  4972. * Handle here documents. Normally we fork off a process to write the
  4973. * data to a pipe. If the document is short, we can stuff the data in
  4974. * the pipe without forking.
  4975. */
  4976. /* openhere needs this forward reference */
  4977. static void expandhere(union node *arg);
  4978. static int
  4979. openhere(union node *redir)
  4980. {
  4981. char *p;
  4982. int pip[2];
  4983. size_t len = 0;
  4984. if (pipe(pip) < 0)
  4985. ash_msg_and_raise_perror("can't create pipe");
  4986. p = redir->nhere.doc->narg.text;
  4987. if (redir->type == NXHERE) {
  4988. expandhere(redir->nhere.doc);
  4989. p = stackblock();
  4990. }
  4991. len = strlen(p);
  4992. if (len <= PIPE_BUF) {
  4993. xwrite(pip[1], p, len);
  4994. goto out;
  4995. }
  4996. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4997. /* child */
  4998. close(pip[0]);
  4999. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  5000. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  5001. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  5002. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  5003. signal(SIGPIPE, SIG_DFL);
  5004. xwrite(pip[1], p, len);
  5005. _exit_SUCCESS();
  5006. }
  5007. out:
  5008. close(pip[1]);
  5009. return pip[0];
  5010. }
  5011. static int
  5012. openredirect(union node *redir)
  5013. {
  5014. struct stat sb;
  5015. char *fname;
  5016. int f;
  5017. switch (redir->nfile.type) {
  5018. /* Can't happen, our single caller does this itself */
  5019. // case NTOFD:
  5020. // case NFROMFD:
  5021. // return -1;
  5022. case NHERE:
  5023. case NXHERE:
  5024. return openhere(redir);
  5025. }
  5026. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  5027. * allocated space. Do it only when we know it is safe.
  5028. */
  5029. fname = redir->nfile.expfname;
  5030. switch (redir->nfile.type) {
  5031. default:
  5032. #if DEBUG
  5033. abort();
  5034. #endif
  5035. case NFROM:
  5036. f = open(fname, O_RDONLY);
  5037. if (f < 0)
  5038. goto eopen;
  5039. break;
  5040. case NFROMTO:
  5041. f = open(fname, O_RDWR|O_CREAT, 0666);
  5042. if (f < 0)
  5043. goto ecreate;
  5044. break;
  5045. case NTO:
  5046. #if BASH_REDIR_OUTPUT
  5047. case NTO2:
  5048. #endif
  5049. /* Take care of noclobber mode. */
  5050. if (Cflag) {
  5051. if (stat(fname, &sb) < 0) {
  5052. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  5053. if (f < 0)
  5054. goto ecreate;
  5055. } else if (!S_ISREG(sb.st_mode)) {
  5056. f = open(fname, O_WRONLY, 0666);
  5057. if (f < 0)
  5058. goto ecreate;
  5059. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  5060. close(f);
  5061. errno = EEXIST;
  5062. goto ecreate;
  5063. }
  5064. } else {
  5065. errno = EEXIST;
  5066. goto ecreate;
  5067. }
  5068. break;
  5069. }
  5070. /* FALLTHROUGH */
  5071. case NCLOBBER:
  5072. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  5073. if (f < 0)
  5074. goto ecreate;
  5075. break;
  5076. case NAPPEND:
  5077. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  5078. if (f < 0)
  5079. goto ecreate;
  5080. break;
  5081. }
  5082. return f;
  5083. ecreate:
  5084. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  5085. eopen:
  5086. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  5087. }
  5088. /*
  5089. * Copy a file descriptor to be >= 10. Throws exception on error.
  5090. */
  5091. static int
  5092. savefd(int from)
  5093. {
  5094. int newfd;
  5095. int err;
  5096. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  5097. err = newfd < 0 ? errno : 0;
  5098. if (err != EBADF) {
  5099. if (err)
  5100. ash_msg_and_raise_perror("%d", from);
  5101. close(from);
  5102. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5103. close_on_exec_on(newfd);
  5104. }
  5105. return newfd;
  5106. }
  5107. static int
  5108. dup2_or_raise(int from, int to)
  5109. {
  5110. int newfd;
  5111. newfd = (from != to) ? dup2(from, to) : to;
  5112. if (newfd < 0) {
  5113. /* Happens when source fd is not open: try "echo >&99" */
  5114. ash_msg_and_raise_perror("dup2(%d,%d)", from, to);
  5115. }
  5116. return newfd;
  5117. }
  5118. /* The only possible error return is EBADF (fd wasn't open).
  5119. * Transient errors retry, other errors raise exception.
  5120. */
  5121. static int
  5122. dup_CLOEXEC(int fd, int avoid_fd)
  5123. {
  5124. int newfd;
  5125. repeat:
  5126. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5127. if (newfd >= 0) {
  5128. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  5129. close_on_exec_on(newfd);
  5130. } else { /* newfd < 0 */
  5131. if (errno == EBUSY)
  5132. goto repeat;
  5133. if (errno == EINTR)
  5134. goto repeat;
  5135. if (errno != EBADF) {
  5136. /* "echo >&9999" gets EINVAL trying to save fd 1 to above 9999.
  5137. * We could try saving it _below_ 9999 instead (how?), but
  5138. * this probably means that dup2(9999,1) to effectuate >&9999
  5139. * would also not work: fd 9999 can't exist. Gracefully bail out.
  5140. * (This differs from "echo >&99" where saving works, but
  5141. * subsequent dup2(99,1) fails if fd 99 is not open).
  5142. */
  5143. ash_msg_and_raise_perror("fcntl(%d,F_DUPFD,%d)", fd, avoid_fd + 1);
  5144. }
  5145. }
  5146. return newfd;
  5147. }
  5148. static int
  5149. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5150. {
  5151. int newfd;
  5152. repeat:
  5153. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5154. if (newfd < 0) {
  5155. if (errno == EBUSY)
  5156. goto repeat;
  5157. if (errno == EINTR)
  5158. goto repeat;
  5159. /* fd was not open? */
  5160. if (errno == EBADF)
  5161. return fd;
  5162. ash_msg_and_raise_perror("%d", newfd);
  5163. }
  5164. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5165. close_on_exec_on(newfd);
  5166. close(fd);
  5167. return newfd;
  5168. }
  5169. /* Struct def and variable are moved down to the first usage site */
  5170. struct squirrel {
  5171. int orig_fd;
  5172. int moved_to;
  5173. };
  5174. struct redirtab {
  5175. struct redirtab *next;
  5176. int pair_count;
  5177. struct squirrel two_fd[];
  5178. };
  5179. #define redirlist (G_var.redirlist)
  5180. static void
  5181. add_squirrel_closed(struct redirtab *sq, int fd)
  5182. {
  5183. int i;
  5184. if (!sq)
  5185. return;
  5186. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5187. /* If we collide with an already moved fd... */
  5188. if (fd == sq->two_fd[i].orig_fd) {
  5189. /* Examples:
  5190. * "echo 3>FILE 3>&- 3>FILE"
  5191. * "echo 3>&- 3>FILE"
  5192. * No need for last redirect to insert
  5193. * another "need to close 3" indicator.
  5194. */
  5195. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5196. return;
  5197. }
  5198. }
  5199. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5200. sq->two_fd[i].orig_fd = fd;
  5201. sq->two_fd[i].moved_to = CLOSED;
  5202. }
  5203. static int
  5204. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5205. {
  5206. int i, new_fd;
  5207. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5208. avoid_fd = 9;
  5209. #if JOBS
  5210. if (fd == ttyfd) {
  5211. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5212. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5213. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5214. return 1; /* "we closed fd" */
  5215. }
  5216. #endif
  5217. /* Are we called from redirect(0)? E.g. redirect
  5218. * in a forked child. No need to save fds,
  5219. * we aren't going to use them anymore, ok to trash.
  5220. */
  5221. if (!sq)
  5222. return 0;
  5223. /* If this one of script's fds? */
  5224. if (fd != 0) {
  5225. struct parsefile *pf = g_parsefile;
  5226. while (pf) {
  5227. /* We skip fd == 0 case because of the following:
  5228. * $ ash # running ash interactively
  5229. * $ . ./script.sh
  5230. * and in script.sh: "exec 9>&0".
  5231. * Even though top-level pf_fd _is_ 0,
  5232. * it's still ok to use it: "read" builtin uses it,
  5233. * why should we cripple "exec" builtin?
  5234. */
  5235. if (fd == pf->pf_fd) {
  5236. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5237. return 1; /* "we closed fd" */
  5238. }
  5239. pf = pf->prev;
  5240. }
  5241. }
  5242. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5243. /* First: do we collide with some already moved fds? */
  5244. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5245. /* If we collide with an already moved fd... */
  5246. if (fd == sq->two_fd[i].moved_to) {
  5247. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5248. sq->two_fd[i].moved_to = new_fd;
  5249. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5250. if (new_fd < 0) /* EBADF? what? */
  5251. xfunc_die();
  5252. return 0; /* "we did not close fd" */
  5253. }
  5254. if (fd == sq->two_fd[i].orig_fd) {
  5255. /* Example: echo Hello >/dev/null 1>&2 */
  5256. TRACE(("redirect_fd %d: already moved\n", fd));
  5257. return 0; /* "we did not close fd" */
  5258. }
  5259. }
  5260. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5261. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5262. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5263. if (new_fd < 0) {
  5264. /* EBADF (fd is not open) */
  5265. /* new_fd = CLOSED; - already is -1 */
  5266. }
  5267. sq->two_fd[i].moved_to = new_fd;
  5268. sq->two_fd[i].orig_fd = fd;
  5269. /* if we move stderr, let "set -x" code know */
  5270. if (fd == preverrout_fd)
  5271. preverrout_fd = new_fd;
  5272. return 0; /* "we did not close fd" */
  5273. }
  5274. static int
  5275. internally_opened_fd(int fd, struct redirtab *sq)
  5276. {
  5277. int i;
  5278. #if JOBS
  5279. if (fd == ttyfd)
  5280. return 1;
  5281. #endif
  5282. /* If this one of script's fds? */
  5283. if (fd != 0) {
  5284. struct parsefile *pf = g_parsefile;
  5285. while (pf) {
  5286. if (fd == pf->pf_fd)
  5287. return 1;
  5288. pf = pf->prev;
  5289. }
  5290. }
  5291. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5292. if (fd == sq->two_fd[i].moved_to)
  5293. return 1;
  5294. }
  5295. return 0;
  5296. }
  5297. /*
  5298. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5299. * old file descriptors are stashed away so that the redirection can be
  5300. * undone by calling popredir.
  5301. */
  5302. /* flags passed to redirect */
  5303. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5304. static void
  5305. redirect(union node *redir, int flags)
  5306. {
  5307. struct redirtab *sv;
  5308. if (!redir)
  5309. return;
  5310. sv = NULL;
  5311. INT_OFF;
  5312. if (flags & REDIR_PUSH)
  5313. sv = redirlist;
  5314. do {
  5315. int fd;
  5316. int newfd;
  5317. int close_fd;
  5318. int closed;
  5319. fd = redir->nfile.fd;
  5320. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5321. //bb_error_msg("doing %d > %d", fd, newfd);
  5322. newfd = redir->ndup.dupfd;
  5323. close_fd = -1;
  5324. } else {
  5325. newfd = openredirect(redir); /* always >= 0 */
  5326. if (fd == newfd) {
  5327. /* open() gave us precisely the fd we wanted.
  5328. * This means that this fd was not busy
  5329. * (not opened to anywhere).
  5330. * Remember to close it on restore:
  5331. */
  5332. add_squirrel_closed(sv, fd);
  5333. continue;
  5334. }
  5335. close_fd = newfd;
  5336. }
  5337. if (fd == newfd)
  5338. continue;
  5339. /* if "N>FILE": move newfd to fd */
  5340. /* if "N>&M": dup newfd to fd */
  5341. /* if "N>&-": close fd (newfd is -1) */
  5342. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5343. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5344. if (newfd == -1) {
  5345. /* "N>&-" means "close me" */
  5346. if (!closed) {
  5347. /* ^^^ optimization: saving may already
  5348. * have closed it. If not... */
  5349. close(fd);
  5350. }
  5351. } else {
  5352. /* if newfd is a script fd or saved fd, simulate EBADF */
  5353. if (internally_opened_fd(newfd, sv)) {
  5354. errno = EBADF;
  5355. ash_msg_and_raise_perror("%d", newfd);
  5356. }
  5357. dup2_or_raise(newfd, fd);
  5358. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5359. close(close_fd);
  5360. #if BASH_REDIR_OUTPUT
  5361. if (redir->nfile.type == NTO2 && fd == 1) {
  5362. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5363. fd = 2;
  5364. newfd = 1;
  5365. close_fd = -1;
  5366. goto redirect_more;
  5367. }
  5368. #endif
  5369. }
  5370. } while ((redir = redir->nfile.next) != NULL);
  5371. INT_ON;
  5372. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5373. #define REDIR_SAVEFD2 0
  5374. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5375. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5376. // not only for calls with flags containing REDIR_SAVEFD2.
  5377. // We do this unconditionally (see save_fd_on_redirect()).
  5378. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5379. // preverrout_fd = copied_fd2;
  5380. }
  5381. static int
  5382. redirectsafe(union node *redir, int flags)
  5383. {
  5384. int err;
  5385. volatile int saveint;
  5386. struct jmploc *volatile savehandler = exception_handler;
  5387. struct jmploc jmploc;
  5388. SAVE_INT(saveint);
  5389. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5390. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5391. if (!err) {
  5392. exception_handler = &jmploc;
  5393. redirect(redir, flags);
  5394. }
  5395. exception_handler = savehandler;
  5396. if (err && exception_type != EXERROR)
  5397. longjmp(exception_handler->loc, 1);
  5398. RESTORE_INT(saveint);
  5399. return err;
  5400. }
  5401. #if BASH_PROCESS_SUBST
  5402. static void
  5403. pushfd(int fd)
  5404. {
  5405. struct redirtab *sv;
  5406. sv = ckzalloc(sizeof(*sv) + sizeof(sv->two_fd[0]));
  5407. sv->pair_count = 1;
  5408. sv->two_fd[0].orig_fd = fd;
  5409. sv->two_fd[0].moved_to = CLOSED;
  5410. sv->next = redirlist;
  5411. redirlist = sv;
  5412. }
  5413. #endif
  5414. static struct redirtab*
  5415. pushredir(union node *redir)
  5416. {
  5417. struct redirtab *sv;
  5418. int i;
  5419. if (!redir)
  5420. return redirlist;
  5421. i = 0;
  5422. do {
  5423. i++;
  5424. #if BASH_REDIR_OUTPUT
  5425. if (redir->nfile.type == NTO2)
  5426. i++;
  5427. #endif
  5428. redir = redir->nfile.next;
  5429. } while (redir);
  5430. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5431. sv->pair_count = i;
  5432. while (--i >= 0)
  5433. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5434. sv->next = redirlist;
  5435. redirlist = sv;
  5436. return sv->next;
  5437. }
  5438. /*
  5439. * Undo the effects of the last redirection.
  5440. */
  5441. static void
  5442. popredir(int drop)
  5443. {
  5444. struct redirtab *rp;
  5445. int i;
  5446. if (redirlist == NULL)
  5447. return;
  5448. INT_OFF;
  5449. rp = redirlist;
  5450. for (i = 0; i < rp->pair_count; i++) {
  5451. int fd = rp->two_fd[i].orig_fd;
  5452. int copy = rp->two_fd[i].moved_to;
  5453. if (copy == CLOSED) {
  5454. if (!drop)
  5455. close(fd);
  5456. continue;
  5457. }
  5458. if (copy != EMPTY) {
  5459. if (!drop) {
  5460. /*close(fd);*/
  5461. dup2_or_raise(copy, fd);
  5462. }
  5463. close(copy);
  5464. }
  5465. }
  5466. redirlist = rp->next;
  5467. free(rp);
  5468. INT_ON;
  5469. }
  5470. static void
  5471. unwindredir(struct redirtab *stop)
  5472. {
  5473. while (redirlist != stop)
  5474. popredir(/*drop:*/ 0);
  5475. }
  5476. /* ============ Routines to expand arguments to commands
  5477. *
  5478. * We have to deal with backquotes, shell variables, and file metacharacters.
  5479. */
  5480. #if ENABLE_FEATURE_SH_MATH
  5481. static arith_t
  5482. ash_arith(const char *s)
  5483. {
  5484. arith_state_t math_state;
  5485. arith_t result;
  5486. math_state.lookupvar = lookupvar;
  5487. math_state.setvar = setvar0;
  5488. //math_state.endofname = endofname;
  5489. INT_OFF;
  5490. result = arith(&math_state, s);
  5491. if (math_state.errmsg)
  5492. ash_msg_and_raise_error(math_state.errmsg);
  5493. INT_ON;
  5494. return result;
  5495. }
  5496. #endif
  5497. #if BASH_SUBSTR
  5498. # if ENABLE_FEATURE_SH_MATH
  5499. static int substr_atoi(const char *s)
  5500. {
  5501. arith_t t = ash_arith(s);
  5502. if (sizeof(t) > sizeof(int)) {
  5503. /* clamp very large or very large negative nums for ${v:N:M}:
  5504. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5505. */
  5506. if (t > INT_MAX)
  5507. t = INT_MAX;
  5508. if (t < INT_MIN)
  5509. t = INT_MIN;
  5510. }
  5511. return t;
  5512. }
  5513. # else
  5514. # define substr_atoi(s) number(s)
  5515. # endif
  5516. #endif
  5517. /*
  5518. * expandarg flags
  5519. */
  5520. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5521. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5522. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5523. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5524. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5525. * POSIX says for this case:
  5526. * Pathname expansion shall not be performed on the word by a
  5527. * non-interactive shell; an interactive shell may perform it, but shall
  5528. * do so only when the expansion would result in one word.
  5529. * Currently, our code complies to the above rule by never globbing
  5530. * redirection filenames.
  5531. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5532. * (this means that on a typical Linux distro, bash almost always
  5533. * performs globbing, and thus diverges from what we do).
  5534. */
  5535. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5536. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5537. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5538. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5539. #define EXP_KEEPNUL 0x200 /* do not skip NUL characters */
  5540. #define EXP_DISCARD 0x400 /* discard result of expansion */
  5541. /*
  5542. * rmescape() flags
  5543. */
  5544. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5545. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5546. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5547. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5548. /* Add CTLESC when necessary. */
  5549. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5550. /*
  5551. * Structure specifying which parts of the string should be searched
  5552. * for IFS characters.
  5553. */
  5554. struct ifsregion {
  5555. struct ifsregion *next; /* next region in list */
  5556. int begoff; /* offset of start of region */
  5557. int endoff; /* offset of end of region */
  5558. int nulonly; /* search for nul bytes only */
  5559. };
  5560. struct arglist {
  5561. struct strlist *list;
  5562. struct strlist **lastp;
  5563. };
  5564. /* output of current string */
  5565. static char *expdest;
  5566. /* list of back quote expressions */
  5567. static struct nodelist *argbackq;
  5568. /* first struct in list of ifs regions */
  5569. static struct ifsregion ifsfirst;
  5570. /* last struct in list */
  5571. static struct ifsregion *ifslastp;
  5572. /* holds expanded arg list */
  5573. static struct arglist exparg;
  5574. /*
  5575. * Break the argument string into pieces based upon IFS and add the
  5576. * strings to the argument list. The regions of the string to be
  5577. * searched for IFS characters have been stored by recordregion.
  5578. */
  5579. static void
  5580. ifsbreakup(char *string, struct arglist *arglist)
  5581. {
  5582. struct ifsregion *ifsp;
  5583. struct strlist *sp;
  5584. char *start;
  5585. char *p;
  5586. char *q;
  5587. const char *ifs, *realifs;
  5588. int ifsspc;
  5589. int nulonly;
  5590. start = string;
  5591. if (ifslastp != NULL) {
  5592. ifsspc = 0;
  5593. nulonly = 0;
  5594. realifs = ifsset() ? ifsval() : defifs;
  5595. ifsp = &ifsfirst;
  5596. do {
  5597. int afternul;
  5598. p = string + ifsp->begoff;
  5599. afternul = nulonly;
  5600. nulonly = ifsp->nulonly;
  5601. ifs = nulonly ? nullstr : realifs;
  5602. ifsspc = 0;
  5603. while (p < string + ifsp->endoff) {
  5604. q = p;
  5605. if ((unsigned char)*p == CTLESC)
  5606. p++;
  5607. if (!strchr(ifs, *p)) {
  5608. p++;
  5609. continue;
  5610. }
  5611. if (!(afternul || nulonly))
  5612. ifsspc = (strchr(defifs, *p) != NULL);
  5613. /* Ignore IFS whitespace at start */
  5614. if (q == start && ifsspc) {
  5615. p++;
  5616. start = p;
  5617. continue;
  5618. }
  5619. *q = '\0';
  5620. sp = stzalloc(sizeof(*sp));
  5621. sp->text = start;
  5622. *arglist->lastp = sp;
  5623. arglist->lastp = &sp->next;
  5624. p++;
  5625. if (!nulonly) {
  5626. for (;;) {
  5627. if (p >= string + ifsp->endoff) {
  5628. break;
  5629. }
  5630. q = p;
  5631. if ((unsigned char)*p == CTLESC)
  5632. p++;
  5633. if (strchr(ifs, *p) == NULL) {
  5634. p = q;
  5635. break;
  5636. }
  5637. if (strchr(defifs, *p) == NULL) {
  5638. if (ifsspc) {
  5639. p++;
  5640. ifsspc = 0;
  5641. } else {
  5642. p = q;
  5643. break;
  5644. }
  5645. } else
  5646. p++;
  5647. }
  5648. }
  5649. start = p;
  5650. } /* while */
  5651. ifsp = ifsp->next;
  5652. } while (ifsp != NULL);
  5653. if (nulonly)
  5654. goto add;
  5655. }
  5656. if (!*start)
  5657. return;
  5658. add:
  5659. sp = stzalloc(sizeof(*sp));
  5660. sp->text = start;
  5661. *arglist->lastp = sp;
  5662. arglist->lastp = &sp->next;
  5663. }
  5664. static void
  5665. ifsfree(void)
  5666. {
  5667. struct ifsregion *p = ifsfirst.next;
  5668. if (!p)
  5669. goto out;
  5670. INT_OFF;
  5671. do {
  5672. struct ifsregion *ifsp;
  5673. ifsp = p->next;
  5674. free(p);
  5675. p = ifsp;
  5676. } while (p);
  5677. ifsfirst.next = NULL;
  5678. INT_ON;
  5679. out:
  5680. ifslastp = NULL;
  5681. }
  5682. static size_t
  5683. esclen(const char *start, const char *p)
  5684. {
  5685. size_t esc = 0;
  5686. while (p > start && (unsigned char)*--p == CTLESC) {
  5687. esc++;
  5688. }
  5689. return esc;
  5690. }
  5691. /*
  5692. * Remove any CTLESC characters from a string.
  5693. */
  5694. #if !BASH_PATTERN_SUBST
  5695. #define rmescapes(str, flag, slash_position) \
  5696. rmescapes(str, flag)
  5697. #endif
  5698. static char *
  5699. rmescapes(char *str, int flag, int *slash_position)
  5700. {
  5701. static const char qchars[] ALIGN1 = {
  5702. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5703. char *p, *q, *r;
  5704. unsigned protect_against_glob;
  5705. unsigned globbing;
  5706. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5707. if (!p)
  5708. return str;
  5709. q = p;
  5710. r = str;
  5711. if (flag & RMESCAPE_ALLOC) {
  5712. size_t len = p - str;
  5713. size_t fulllen = len + strlen(p) + 1;
  5714. if (flag & RMESCAPE_GROW) {
  5715. int strloc = str - (char *)stackblock();
  5716. r = makestrspace(fulllen, expdest);
  5717. /* p and str may be invalidated by makestrspace */
  5718. str = (char *)stackblock() + strloc;
  5719. p = str + len;
  5720. } else if (flag & RMESCAPE_HEAP) {
  5721. r = ckmalloc(fulllen);
  5722. } else {
  5723. r = stalloc(fulllen);
  5724. }
  5725. q = r;
  5726. if (len > 0) {
  5727. q = (char *)mempcpy(q, str, len);
  5728. }
  5729. }
  5730. globbing = flag & RMESCAPE_GLOB;
  5731. protect_against_glob = globbing;
  5732. while (*p) {
  5733. if ((unsigned char)*p == CTLQUOTEMARK) {
  5734. // Note: protect_against_glob only affect whether
  5735. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5736. p++;
  5737. protect_against_glob = globbing;
  5738. continue;
  5739. }
  5740. if (*p == '\\') {
  5741. /* naked back slash */
  5742. protect_against_glob = 0;
  5743. goto copy;
  5744. }
  5745. if ((unsigned char)*p == CTLESC) {
  5746. p++;
  5747. #if DEBUG
  5748. if (*p == '\0')
  5749. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5750. #endif
  5751. if (protect_against_glob) {
  5752. /*
  5753. * We used to trust glob() and fnmatch() to eat
  5754. * superfluous escapes (\z where z has no
  5755. * special meaning anyway). But this causes
  5756. * bugs such as string of one greek letter rho
  5757. * (unicode-encoded as two bytes "cf,81")
  5758. * getting encoded as "cf,CTLESC,81"
  5759. * and here, converted to "cf,\,81" -
  5760. * which does not go well with some flavors
  5761. * of fnmatch() in unicode locales
  5762. * (for example, glibc <= 2.22).
  5763. *
  5764. * Lets add "\" only on the chars which need it.
  5765. * Testcases for less obvious chars are shown.
  5766. */
  5767. if (*p == '*'
  5768. || *p == '?'
  5769. || *p == '['
  5770. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5771. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5772. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5773. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5774. /* Some libc support [^negate], that's why "^" also needs love */
  5775. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5776. ) {
  5777. *q++ = '\\';
  5778. }
  5779. }
  5780. }
  5781. #if BASH_PATTERN_SUBST
  5782. else if (slash_position && p == str + *slash_position) {
  5783. /* stop handling globbing */
  5784. globbing = 0;
  5785. *slash_position = q - r;
  5786. slash_position = NULL;
  5787. }
  5788. #endif
  5789. protect_against_glob = globbing;
  5790. copy:
  5791. *q++ = *p++;
  5792. }
  5793. *q = '\0';
  5794. if (flag & RMESCAPE_GROW) {
  5795. expdest = r;
  5796. STADJUST(q - r + 1, expdest);
  5797. }
  5798. return r;
  5799. }
  5800. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5801. /*
  5802. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5803. *
  5804. * Returns an stalloced string.
  5805. */
  5806. static char *
  5807. preglob(const char *pattern, int flag)
  5808. {
  5809. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5810. }
  5811. /*
  5812. * Put a string on the stack.
  5813. */
  5814. static size_t
  5815. memtodest(const char *p, size_t len, int flags)
  5816. {
  5817. int syntax = flags & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5818. char *q;
  5819. char *s;
  5820. if (!len)
  5821. return 0;
  5822. q = makestrspace(len * 2, expdest);
  5823. s = q;
  5824. do {
  5825. unsigned char c = *p++;
  5826. if (c) {
  5827. if (flags & QUOTES_ESC) {
  5828. int n = SIT(c, syntax);
  5829. if (n == CCTL
  5830. || ((flags & EXP_QUOTED) && n == CBACK)
  5831. ) {
  5832. USTPUTC(CTLESC, q);
  5833. }
  5834. }
  5835. } else if (!(flags & EXP_KEEPNUL))
  5836. continue;
  5837. USTPUTC(c, q);
  5838. } while (--len);
  5839. expdest = q;
  5840. return q - s;
  5841. }
  5842. static size_t
  5843. strtodest(const char *p, int flags)
  5844. {
  5845. size_t len = strlen(p);
  5846. memtodest(p, len, flags);
  5847. return len;
  5848. }
  5849. /*
  5850. * Our own itoa().
  5851. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5852. */
  5853. static int
  5854. cvtnum(arith_t num, int flags)
  5855. {
  5856. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5857. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5858. int len = (sizeof(arith_t) >= 4) ? sizeof(arith_t) * 3 : sizeof(arith_t) * 3 + 2;
  5859. char buf[len];
  5860. len = fmtstr(buf, len, ARITH_FMT, num);
  5861. return memtodest(buf, len, flags);
  5862. }
  5863. /*
  5864. * Record the fact that we have to scan this region of the
  5865. * string for IFS characters.
  5866. */
  5867. static void
  5868. recordregion(int start, int end, int nulonly)
  5869. {
  5870. struct ifsregion *ifsp;
  5871. if (ifslastp == NULL) {
  5872. ifsp = &ifsfirst;
  5873. } else {
  5874. INT_OFF;
  5875. ifsp = ckzalloc(sizeof(*ifsp));
  5876. /*ifsp->next = NULL; - ckzalloc did it */
  5877. ifslastp->next = ifsp;
  5878. INT_ON;
  5879. }
  5880. ifslastp = ifsp;
  5881. ifslastp->begoff = start;
  5882. ifslastp->endoff = end;
  5883. ifslastp->nulonly = nulonly;
  5884. }
  5885. static void
  5886. removerecordregions(int endoff)
  5887. {
  5888. if (ifslastp == NULL)
  5889. return;
  5890. if (ifsfirst.endoff > endoff) {
  5891. while (ifsfirst.next) {
  5892. struct ifsregion *ifsp;
  5893. INT_OFF;
  5894. ifsp = ifsfirst.next->next;
  5895. free(ifsfirst.next);
  5896. ifsfirst.next = ifsp;
  5897. INT_ON;
  5898. }
  5899. if (ifsfirst.begoff > endoff) {
  5900. ifslastp = NULL;
  5901. } else {
  5902. ifslastp = &ifsfirst;
  5903. ifsfirst.endoff = endoff;
  5904. }
  5905. return;
  5906. }
  5907. ifslastp = &ifsfirst;
  5908. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5909. ifslastp = ifslastp->next;
  5910. while (ifslastp->next) {
  5911. struct ifsregion *ifsp;
  5912. INT_OFF;
  5913. ifsp = ifslastp->next->next;
  5914. free(ifslastp->next);
  5915. ifslastp->next = ifsp;
  5916. INT_ON;
  5917. }
  5918. if (ifslastp->endoff > endoff)
  5919. ifslastp->endoff = endoff;
  5920. }
  5921. static char *
  5922. exptilde(char *startp, int flag)
  5923. {
  5924. unsigned char c;
  5925. char *name;
  5926. struct passwd *pw;
  5927. const char *home;
  5928. char *p;
  5929. p = startp;
  5930. name = p + 1;
  5931. while ((c = *++p) != '\0') {
  5932. switch (c) {
  5933. case CTLESC:
  5934. return startp;
  5935. case CTLQUOTEMARK:
  5936. return startp;
  5937. case ':':
  5938. if (flag & EXP_VARTILDE)
  5939. goto done;
  5940. break;
  5941. case '/':
  5942. case CTLENDVAR:
  5943. goto done;
  5944. }
  5945. }
  5946. done:
  5947. if (flag & EXP_DISCARD)
  5948. goto out;
  5949. *p = '\0';
  5950. if (*name == '\0') {
  5951. home = lookupvar("HOME");
  5952. } else {
  5953. pw = getpwnam(name);
  5954. home = pw ? pw->pw_dir : NULL;
  5955. }
  5956. *p = c;
  5957. if (!home)
  5958. goto lose;
  5959. strtodest(home, flag | EXP_QUOTED);
  5960. out:
  5961. return p;
  5962. lose:
  5963. return startp;
  5964. }
  5965. /*
  5966. * Execute a command inside back quotes. If it's a builtin command, we
  5967. * want to save its output in a block obtained from malloc. Otherwise
  5968. * we fork off a subprocess and get the output of the command via a pipe.
  5969. * Should be called with interrupts off.
  5970. */
  5971. struct backcmd { /* result of evalbackcmd */
  5972. int fd; /* file descriptor to read from */
  5973. int nleft; /* number of chars in buffer */
  5974. char *buf; /* buffer */
  5975. struct job *jp; /* job structure for command */
  5976. };
  5977. /* These forward decls are needed to use "eval" code for backticks handling: */
  5978. /* flags in argument to evaltree */
  5979. #define EV_EXIT 01 /* exit after evaluating tree */
  5980. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5981. static int evaltree(union node *, int);
  5982. /* An evaltree() which is known to never return.
  5983. * Used to use an alias:
  5984. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5985. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5986. */
  5987. static ALWAYS_INLINE NORETURN void
  5988. evaltreenr(union node *n, int flags)
  5989. {
  5990. evaltree(n, flags);
  5991. bb_unreachable(abort());
  5992. /* NOTREACHED */
  5993. }
  5994. static void FAST_FUNC
  5995. evalbackcmd(union node *n, struct backcmd *result
  5996. IF_BASH_PROCESS_SUBST(, int ctl))
  5997. {
  5998. int pip[2];
  5999. struct job *jp;
  6000. #if BASH_PROCESS_SUBST
  6001. /* determine end of pipe used by parent (ip) and child (ic) */
  6002. const int ip = (ctl == CTLTOPROC);
  6003. const int ic = !(ctl == CTLTOPROC);
  6004. #else
  6005. const int ctl = CTLBACKQ;
  6006. const int ip = 0;
  6007. const int ic = 1;
  6008. #endif
  6009. result->fd = -1;
  6010. result->buf = NULL;
  6011. result->nleft = 0;
  6012. result->jp = NULL;
  6013. if (n == NULL) {
  6014. goto out;
  6015. }
  6016. if (pipe(pip) < 0)
  6017. ash_msg_and_raise_perror("can't create pipe");
  6018. /* process substitution uses NULL job, like openhere() */
  6019. jp = (ctl == CTLBACKQ) ? makejob(/*n,*/ 1) : NULL;
  6020. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  6021. /* child */
  6022. FORCE_INT_ON;
  6023. close(pip[ip]);
  6024. /* ic is index of child end of pipe *and* fd to connect it to */
  6025. if (pip[ic] != ic) {
  6026. /*close(ic);*/
  6027. dup2_or_raise(pip[ic], ic);
  6028. close(pip[ic]);
  6029. }
  6030. /* TODO: eflag clearing makes the following not abort:
  6031. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  6032. * which is what bash does (unless it is in POSIX mode).
  6033. * dash deleted "eflag = 0" line in the commit
  6034. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  6035. * [EVAL] Don't clear eflag in evalbackcmd
  6036. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  6037. */
  6038. eflag = 0;
  6039. ifsfree();
  6040. evaltreenr(n, EV_EXIT);
  6041. /* NOTREACHED */
  6042. }
  6043. /* parent */
  6044. #if BASH_PROCESS_SUBST
  6045. if (ctl != CTLBACKQ) {
  6046. int fd = fcntl(pip[ip], F_DUPFD, 64);
  6047. if (fd > 0) {
  6048. close(pip[ip]);
  6049. pip[ip] = fd;
  6050. }
  6051. pushfd(pip[ip]);
  6052. }
  6053. #endif
  6054. close(pip[ic]);
  6055. result->fd = pip[ip];
  6056. result->jp = jp;
  6057. out:
  6058. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  6059. result->fd, result->buf, result->nleft, result->jp));
  6060. }
  6061. /*
  6062. * Expand stuff in backwards quotes.
  6063. */
  6064. static void
  6065. expbackq(union node *cmd, int flag IF_BASH_PROCESS_SUBST(, int ctl))
  6066. {
  6067. #if !BASH_PROCESS_SUBST
  6068. const int ctl = CTLBACKQ;
  6069. #endif
  6070. struct backcmd in;
  6071. int i;
  6072. char buf[128];
  6073. char *p;
  6074. char *dest;
  6075. int startloc;
  6076. struct stackmark smark;
  6077. if (flag & EXP_DISCARD)
  6078. goto out;
  6079. INT_OFF;
  6080. startloc = expdest - (char *)stackblock();
  6081. pushstackmark(&smark, startloc);
  6082. evalbackcmd(cmd, &in IF_BASH_PROCESS_SUBST(, ctl));
  6083. popstackmark(&smark);
  6084. if (ctl != CTLBACKQ) {
  6085. sprintf(buf, DEV_FD_PREFIX"%d", in.fd);
  6086. strtodest(buf, BASESYNTAX);
  6087. goto done;
  6088. }
  6089. p = in.buf;
  6090. i = in.nleft;
  6091. if (i == 0)
  6092. goto read;
  6093. for (;;) {
  6094. memtodest(p, i, flag);
  6095. read:
  6096. if (in.fd < 0)
  6097. break;
  6098. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  6099. TRACE(("expbackq: read returns %d\n", i));
  6100. if (i <= 0)
  6101. break;
  6102. p = buf;
  6103. }
  6104. free(in.buf);
  6105. if (in.fd >= 0) {
  6106. close(in.fd);
  6107. back_exitstatus = waitforjob(in.jp);
  6108. }
  6109. done:
  6110. INT_ON;
  6111. /* Eat all trailing newlines */
  6112. dest = expdest;
  6113. for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';)
  6114. STUNPUTC(dest);
  6115. expdest = dest;
  6116. if (!(flag & EXP_QUOTED))
  6117. recordregion(startloc, dest - (char *)stackblock(), 0);
  6118. TRACE(("evalbackq: size:%d:'%.*s'\n",
  6119. (int)((dest - (char *)stackblock()) - startloc),
  6120. (int)((dest - (char *)stackblock()) - startloc),
  6121. stackblock() + startloc));
  6122. out:
  6123. argbackq = argbackq->next;
  6124. }
  6125. /* expari needs it */
  6126. static char *argstr(char *p, int flag);
  6127. #if ENABLE_FEATURE_SH_MATH
  6128. /*
  6129. * Expand arithmetic expression. Backup to start of expression,
  6130. * evaluate, place result in (backed up) result, adjust string position.
  6131. */
  6132. static char *
  6133. expari(char *start, int flag)
  6134. {
  6135. struct stackmark sm;
  6136. int begoff;
  6137. int endoff;
  6138. int len;
  6139. arith_t result;
  6140. char *p;
  6141. p = stackblock();
  6142. begoff = expdest - p;
  6143. p = argstr(start, flag & EXP_DISCARD);
  6144. if (flag & EXP_DISCARD)
  6145. goto out;
  6146. start = stackblock();
  6147. endoff = expdest - start;
  6148. start += begoff;
  6149. STADJUST(start - expdest, expdest);
  6150. removerecordregions(begoff);
  6151. if (flag & QUOTES_ESC)
  6152. rmescapes(start, 0, NULL);
  6153. pushstackmark(&sm, endoff);
  6154. result = ash_arith(start);
  6155. popstackmark(&sm);
  6156. len = cvtnum(result, flag);
  6157. if (!(flag & EXP_QUOTED))
  6158. recordregion(begoff, begoff + len, 0);
  6159. out:
  6160. return p;
  6161. }
  6162. #endif
  6163. /* argstr needs it */
  6164. static char *evalvar(char *p, int flags);
  6165. /*
  6166. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  6167. * characters to allow for further processing. Otherwise treat
  6168. * $@ like $* since no splitting will be performed.
  6169. */
  6170. static char *
  6171. argstr(char *p, int flag)
  6172. {
  6173. static const char spclchars[] ALIGN1 = {
  6174. '=',
  6175. ':',
  6176. CTLQUOTEMARK,
  6177. CTLENDVAR,
  6178. CTLESC,
  6179. CTLVAR,
  6180. CTLBACKQ,
  6181. #if BASH_PROCESS_SUBST
  6182. CTLTOPROC,
  6183. CTLFROMPROC,
  6184. #endif
  6185. #if ENABLE_FEATURE_SH_MATH
  6186. CTLARI,
  6187. CTLENDARI,
  6188. #endif
  6189. '\0'
  6190. };
  6191. const char *reject = spclchars;
  6192. int breakall = (flag & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6193. int inquotes;
  6194. size_t length;
  6195. int startloc;
  6196. reject += !!(flag & EXP_VARTILDE2);
  6197. reject += flag & EXP_VARTILDE ? 0 : 2;
  6198. inquotes = 0;
  6199. length = 0;
  6200. if (flag & EXP_TILDE) {
  6201. flag &= ~EXP_TILDE;
  6202. tilde:
  6203. if (*p == '~')
  6204. p = exptilde(p, flag);
  6205. }
  6206. start:
  6207. startloc = expdest - (char *)stackblock();
  6208. for (;;) {
  6209. int end;
  6210. unsigned char c;
  6211. length += strcspn(p + length, reject);
  6212. end = 0;
  6213. c = p[length];
  6214. if (!(c & 0x80)
  6215. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6216. || c == CTLENDVAR
  6217. ) {
  6218. /*
  6219. * c == '=' || c == ':' || c == '\0' ||
  6220. * c == CTLENDARI || c == CTLENDVAR
  6221. */
  6222. length++;
  6223. /* c == '\0' || c == CTLENDARI || c == CTLENDVAR */
  6224. end = !!((c - 1) & 0x80);
  6225. }
  6226. if (length > 0 && !(flag & EXP_DISCARD)) {
  6227. int newloc;
  6228. char *q;
  6229. q = stnputs(p, length, expdest);
  6230. q[-1] &= end - 1;
  6231. expdest = q - (flag & EXP_WORD ? end : 0);
  6232. newloc = q - (char *)stackblock() - end;
  6233. if (breakall && !inquotes && newloc > startloc) {
  6234. recordregion(startloc, newloc, 0);
  6235. }
  6236. startloc = newloc;
  6237. }
  6238. p += length + 1;
  6239. length = 0;
  6240. if (end)
  6241. break;
  6242. switch (c) {
  6243. case '=':
  6244. flag |= EXP_VARTILDE2;
  6245. reject++;
  6246. /* fall through */
  6247. case ':':
  6248. /*
  6249. * sort of a hack - expand tildes in variable
  6250. * assignments (after the first '=' and after ':'s).
  6251. */
  6252. if (*--p == '~') {
  6253. goto tilde;
  6254. }
  6255. continue;
  6256. case CTLQUOTEMARK:
  6257. /* "$@" syntax adherence hack */
  6258. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6259. p = evalvar(p + 1, flag | EXP_QUOTED) + 1;
  6260. goto start;
  6261. }
  6262. inquotes ^= EXP_QUOTED;
  6263. addquote:
  6264. if (flag & QUOTES_ESC) {
  6265. p--;
  6266. length++;
  6267. startloc++;
  6268. }
  6269. break;
  6270. case CTLESC:
  6271. startloc++;
  6272. length++;
  6273. goto addquote;
  6274. case CTLVAR:
  6275. TRACE(("argstr: evalvar('%s')\n", p));
  6276. p = evalvar(p, flag | inquotes);
  6277. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6278. goto start;
  6279. #if BASH_PROCESS_SUBST
  6280. case CTLTOPROC:
  6281. case CTLFROMPROC:
  6282. #endif
  6283. case CTLBACKQ:
  6284. expbackq(argbackq->n, flag | inquotes IF_BASH_PROCESS_SUBST(, c));
  6285. goto start;
  6286. #if ENABLE_FEATURE_SH_MATH
  6287. case CTLARI:
  6288. p = expari(p, flag | inquotes);
  6289. goto start;
  6290. #endif
  6291. }
  6292. }
  6293. return p - 1;
  6294. }
  6295. static char *
  6296. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6297. char *pattern, int quotes, int zero)
  6298. {
  6299. char *loc, *loc2;
  6300. char c;
  6301. loc = startp;
  6302. loc2 = rmesc;
  6303. do {
  6304. int match;
  6305. const char *s = loc2;
  6306. c = *loc2;
  6307. if (zero) {
  6308. *loc2 = '\0';
  6309. s = rmesc;
  6310. }
  6311. match = pmatch(pattern, s);
  6312. *loc2 = c;
  6313. if (match)
  6314. return loc;
  6315. if (quotes && (unsigned char)*loc == CTLESC)
  6316. loc++;
  6317. loc++;
  6318. loc2++;
  6319. } while (c);
  6320. return NULL;
  6321. }
  6322. static char *
  6323. scanright(char *startp, char *rmesc, char *rmescend,
  6324. char *pattern, int quotes, int match_at_start)
  6325. {
  6326. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6327. int try2optimize = match_at_start;
  6328. #endif
  6329. int esc = 0;
  6330. char *loc;
  6331. char *loc2;
  6332. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6333. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6334. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6335. * Logic:
  6336. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6337. * and on each iteration they go back two/one char until they reach the beginning.
  6338. * We try to match "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6339. * If one of these matches, return pointer past last matched char in startp.
  6340. */
  6341. /* TODO: document in what other circumstances we are called. */
  6342. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6343. int match;
  6344. char c = *loc2;
  6345. const char *s = loc2;
  6346. if (match_at_start) {
  6347. *loc2 = '\0';
  6348. s = rmesc;
  6349. }
  6350. match = pmatch(pattern, s);
  6351. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6352. *loc2 = c;
  6353. if (match)
  6354. return loc;
  6355. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6356. if (try2optimize) {
  6357. /* Maybe we can optimize this:
  6358. * if pattern ends with unescaped *, we can avoid checking
  6359. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6360. * it won't match truncated "raw_value_of_" strings too.
  6361. */
  6362. unsigned plen = strlen(pattern);
  6363. /* Does it end with "*"? */
  6364. if (plen != 0 && pattern[--plen] == '*') {
  6365. /* "xxxx*" is not escaped */
  6366. /* "xxx\*" is escaped */
  6367. /* "xx\\*" is not escaped */
  6368. /* "x\\\*" is escaped */
  6369. int slashes = 0;
  6370. while (plen != 0 && pattern[--plen] == '\\')
  6371. slashes++;
  6372. if (!(slashes & 1))
  6373. break; /* ends with unescaped "*" */
  6374. }
  6375. try2optimize = 0;
  6376. }
  6377. #endif
  6378. loc--;
  6379. if (quotes) {
  6380. if (--esc < 0) {
  6381. esc = esclen(startp, loc);
  6382. }
  6383. if (esc % 2) {
  6384. esc--;
  6385. loc--;
  6386. }
  6387. }
  6388. }
  6389. return NULL;
  6390. }
  6391. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6392. static void
  6393. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6394. {
  6395. const char *msg;
  6396. const char *tail;
  6397. tail = nullstr;
  6398. msg = "parameter not set";
  6399. if (umsg) {
  6400. if ((unsigned char)*end == CTLENDVAR) {
  6401. if (varflags & VSNUL)
  6402. tail = " or null";
  6403. } else {
  6404. msg = umsg;
  6405. }
  6406. }
  6407. ifsfree();
  6408. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6409. }
  6410. static char *
  6411. subevalvar(char *start, char *str, int strloc,
  6412. int startloc, int varflags, int flag)
  6413. {
  6414. int subtype = varflags & VSTYPE;
  6415. int quotes = flag & QUOTES_ESC;
  6416. char *startp;
  6417. char *loc;
  6418. char *rmesc, *rmescend;
  6419. long amount;
  6420. int resetloc;
  6421. int argstr_flags;
  6422. IF_BASH_PATTERN_SUBST(int workloc;)
  6423. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6424. IF_BASH_PATTERN_SUBST(char *repl;)
  6425. int zero;
  6426. char *(*scan)(char*, char*, char*, char*, int, int);
  6427. char *p;
  6428. //bb_error_msg("subevalvar(start:'%s',str:'%s',strloc:%d,startloc:%d,varflags:%x,quotes:%d)",
  6429. // start, str, strloc, startloc, varflags, quotes);
  6430. #if BASH_PATTERN_SUBST
  6431. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6432. * argstr() call expands possible variable references in pattern:
  6433. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6434. */
  6435. repl = NULL;
  6436. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6437. /* Find '/' and replace with NUL */
  6438. repl = start;
  6439. /* The pattern can't be empty.
  6440. * IOW: if the first char after "${v//" is a slash,
  6441. * it does not terminate the pattern - it's the first char of the pattern:
  6442. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6443. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6444. */
  6445. if (*repl == '/')
  6446. repl++;
  6447. for (;;) {
  6448. if (*repl == '\0') {
  6449. repl = NULL;
  6450. break;
  6451. }
  6452. /* Skip over quoted 'str'. Example: ${var/'/'} - second / is not a separator */
  6453. if ((unsigned char)*repl == CTLQUOTEMARK) {
  6454. while ((unsigned char)*++repl != CTLQUOTEMARK)
  6455. continue;
  6456. }
  6457. if (*repl == '/') {
  6458. *repl = '\0';
  6459. break;
  6460. }
  6461. if ((unsigned char)*repl == CTLENDVAR) { /* ${v/pattern} (no trailing /, no repl) */
  6462. repl = NULL;
  6463. break;
  6464. }
  6465. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6466. if ((unsigned char)*repl == CTLESC && repl[1])
  6467. repl++;
  6468. repl++;
  6469. }
  6470. }
  6471. #endif
  6472. argstr_flags = (flag & EXP_DISCARD) | EXP_TILDE;
  6473. if (!str
  6474. #if BASH_SUBSTR
  6475. && subtype != VSSUBSTR
  6476. #endif
  6477. ) {
  6478. /* EXP_CASE keeps CTLESC's */
  6479. argstr_flags |= EXP_CASE;
  6480. }
  6481. p = argstr(start, argstr_flags);
  6482. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6483. #if BASH_PATTERN_SUBST
  6484. slash_pos = -1;
  6485. if (repl) {
  6486. slash_pos = expdest - ((char *)stackblock() + strloc);
  6487. if (!(flag & EXP_DISCARD))
  6488. STPUTC('/', expdest);
  6489. //bb_error_msg("repl+1:'%s'", repl + 1);
  6490. p = argstr(repl + 1, (flag & EXP_DISCARD) | EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6491. *repl = '/';
  6492. }
  6493. #endif
  6494. if (flag & EXP_DISCARD)
  6495. return p;
  6496. startp = (char *)stackblock() + startloc;
  6497. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6498. switch (subtype) {
  6499. case VSASSIGN:
  6500. setvar0(str, startp);
  6501. loc = startp;
  6502. goto out;
  6503. case VSQUESTION:
  6504. varunset(start, str, startp, varflags);
  6505. /* NOTREACHED */
  6506. #if BASH_SUBSTR
  6507. case VSSUBSTR: {
  6508. int pos, len, orig_len;
  6509. char *colon;
  6510. char *vstr;
  6511. loc = vstr = stackblock() + strloc;
  6512. /* Read POS in ${var:POS:LEN} */
  6513. colon = strchr(loc, ':');
  6514. if (colon) *colon = '\0';
  6515. pos = substr_atoi(loc);
  6516. if (colon) *colon = ':';
  6517. /* Read LEN in ${var:POS:LEN} */
  6518. len = vstr - startp - 1;
  6519. /* *loc != '\0', guaranteed by parser */
  6520. if (quotes) {
  6521. char *ptr;
  6522. /* Adjust the length by the number of escapes */
  6523. for (ptr = startp; ptr < (vstr - 1); ptr++) {
  6524. if ((unsigned char)*ptr == CTLESC) {
  6525. len--;
  6526. ptr++;
  6527. }
  6528. }
  6529. }
  6530. orig_len = len;
  6531. if (*loc++ == ':') {
  6532. /* ${var::LEN} */
  6533. len = substr_atoi(loc);
  6534. } else {
  6535. /* Skip POS in ${var:POS:LEN} */
  6536. len = orig_len;
  6537. while (*loc && *loc != ':')
  6538. loc++;
  6539. if (*loc++ == ':')
  6540. len = substr_atoi(loc);
  6541. }
  6542. if (pos < 0) {
  6543. /* ${VAR:$((-n)):l} starts n chars from the end */
  6544. pos = orig_len + pos;
  6545. }
  6546. if ((unsigned)pos >= orig_len) {
  6547. /* apart from obvious ${VAR:999999:l},
  6548. * covers ${VAR:$((-9999999)):l} - result is ""
  6549. * (bash compat)
  6550. */
  6551. pos = 0;
  6552. len = 0;
  6553. }
  6554. if (len < 0) {
  6555. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6556. len = (orig_len - pos) + len;
  6557. }
  6558. if ((unsigned)len > (orig_len - pos))
  6559. len = orig_len - pos;
  6560. if (!quotes) {
  6561. /* want: loc = mempcpy(startp, startp + pos, len)
  6562. * but it does not allow overlapping arguments */
  6563. loc = startp;
  6564. while (--len >= 0) {
  6565. *loc = loc[pos];
  6566. loc++;
  6567. }
  6568. } else {
  6569. for (vstr = startp; pos != 0; pos--) {
  6570. if ((unsigned char)*vstr == CTLESC)
  6571. vstr++;
  6572. vstr++;
  6573. }
  6574. for (loc = startp; len != 0; len--) {
  6575. if ((unsigned char)*vstr == CTLESC)
  6576. *loc++ = *vstr++;
  6577. *loc++ = *vstr++;
  6578. }
  6579. }
  6580. *loc = '\0';
  6581. goto out;
  6582. }
  6583. #endif /* BASH_SUBSTR */
  6584. }
  6585. resetloc = expdest - (char *)stackblock();
  6586. #if BASH_PATTERN_SUBST
  6587. repl = NULL;
  6588. /* We'll comeback here if we grow the stack while handling
  6589. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6590. * stack will need rebasing, and we'll need to remove our work
  6591. * areas each time
  6592. */
  6593. restart:
  6594. #endif
  6595. amount = expdest - ((char *)stackblock() + resetloc);
  6596. STADJUST(-amount, expdest);
  6597. startp = (char *)stackblock() + startloc;
  6598. rmesc = startp;
  6599. rmescend = (char *)stackblock() + strloc;
  6600. //bb_error_msg("str7:'%s'", rmescend);
  6601. if (quotes) {
  6602. //TODO: how to handle slash_pos here if string changes (shortens?)
  6603. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6604. if (rmesc != startp) {
  6605. rmescend = expdest;
  6606. startp = (char *)stackblock() + startloc;
  6607. }
  6608. }
  6609. rmescend--;
  6610. str = (char *)stackblock() + strloc;
  6611. /*
  6612. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6613. * The result is a_\_z_c (not a\_\_z_c)!
  6614. *
  6615. * The search pattern and replace string treat backslashes differently!
  6616. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6617. * and string. It's only used on the first call.
  6618. */
  6619. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6620. rmescapes(str, RMESCAPE_GLOB,
  6621. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6622. );
  6623. #if BASH_PATTERN_SUBST
  6624. workloc = expdest - (char *)stackblock();
  6625. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6626. size_t no_meta_len, first_escaped;
  6627. int len;
  6628. char *idx, *end;
  6629. if (!repl) {
  6630. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6631. repl = nullstr;
  6632. if (slash_pos >= 0) {
  6633. repl = str + slash_pos;
  6634. *repl++ = '\0';
  6635. }
  6636. }
  6637. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6638. /* If there's no pattern to match, return the expansion unmolested */
  6639. if (str[0] == '\0')
  6640. goto out1;
  6641. first_escaped = (str[0] == '\\' && str[1]);
  6642. /* "first_escaped" trick allows to treat e.g. "\*no_glob_chars"
  6643. * as literal too (as it is semi-common, and easy to accomodate
  6644. * by just using str + 1).
  6645. */
  6646. no_meta_len = strpbrk(str + first_escaped * 2, "*?[\\") ? 0 : strlen(str);
  6647. len = 0;
  6648. idx = startp;
  6649. end = str - 1;
  6650. while (idx <= end) {
  6651. try_to_match:
  6652. if (no_meta_len == 0) {
  6653. /* pattern has meta chars, have to glob */
  6654. loc = scanright(idx, rmesc, rmescend, str, quotes, /*match_at_start:*/ 1);
  6655. } else {
  6656. /* Testcase for very slow replace (performs about 22k replaces):
  6657. * x=::::::::::::::::::::::
  6658. * 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}
  6659. * echo "${x//:/|}"
  6660. * To test "first_escaped" logic, replace : with *.
  6661. */
  6662. if (strncmp(rmesc, str + first_escaped, no_meta_len - first_escaped) != 0)
  6663. goto no_match;
  6664. loc = idx;
  6665. if (!quotes) {
  6666. loc += no_meta_len - first_escaped;
  6667. } else {
  6668. size_t n = no_meta_len - first_escaped;
  6669. do {
  6670. if ((unsigned char)*loc == CTLESC)
  6671. loc++;
  6672. loc++;
  6673. } while (--n != 0);
  6674. }
  6675. }
  6676. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6677. if (!loc) {
  6678. char *restart_detect;
  6679. no_match:
  6680. /* No match, advance */
  6681. restart_detect = stackblock();
  6682. skip_matching:
  6683. if (idx >= end)
  6684. break;
  6685. STPUTC(*idx, expdest);
  6686. if (stackblock() != restart_detect)
  6687. goto restart;
  6688. if (quotes && (unsigned char)*idx == CTLESC) {
  6689. idx++;
  6690. len++;
  6691. STPUTC(*idx, expdest);
  6692. if (stackblock() != restart_detect)
  6693. goto restart;
  6694. }
  6695. idx++;
  6696. len++;
  6697. rmesc++;
  6698. /* continue; - prone to quadratic behavior, smarter code: */
  6699. if (str[0] == '*') {
  6700. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6701. * it would never match "ong_string" etc, no point in trying.
  6702. */
  6703. goto skip_matching;
  6704. }
  6705. goto try_to_match;
  6706. }
  6707. if (subtype == VSREPLACEALL) {
  6708. while (idx < loc) {
  6709. if (quotes && (unsigned char)*idx == CTLESC)
  6710. idx++;
  6711. idx++;
  6712. rmesc++;
  6713. }
  6714. } else {
  6715. idx = loc;
  6716. }
  6717. /* The STPUTC invocations above may resize and move the
  6718. * stack via realloc(3). Since repl is a pointer into the
  6719. * stack, we need to reconstruct it relative to stackblock().
  6720. */
  6721. if (slash_pos >= 0)
  6722. repl = (char *)stackblock() + strloc + slash_pos + 1;
  6723. //bb_error_msg("repl:'%s'", repl);
  6724. for (loc = (char*)repl; *loc; loc++) {
  6725. char *restart_detect = stackblock();
  6726. if (quotes && *loc == '\\') {
  6727. STPUTC(CTLESC, expdest);
  6728. if (stackblock() != restart_detect)
  6729. goto restart;
  6730. len++;
  6731. }
  6732. STPUTC(*loc, expdest);
  6733. if (stackblock() != restart_detect)
  6734. goto restart;
  6735. len++;
  6736. }
  6737. if (subtype == VSREPLACE) {
  6738. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6739. while (*idx) {
  6740. char *restart_detect = stackblock();
  6741. STPUTC(*idx, expdest);
  6742. if (stackblock() != restart_detect)
  6743. goto restart;
  6744. len++;
  6745. idx++;
  6746. }
  6747. break;
  6748. }
  6749. }
  6750. /* We've put the replaced text into a buffer at workloc, now
  6751. * move it to the right place and adjust the stack.
  6752. */
  6753. STPUTC('\0', expdest);
  6754. startp = (char *)stackblock() + startloc;
  6755. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6756. //bb_error_msg("startp:'%s'", startp);
  6757. loc = startp + len;
  6758. goto out;
  6759. }
  6760. #endif /* BASH_PATTERN_SUBST */
  6761. subtype -= VSTRIMRIGHT;
  6762. #if DEBUG
  6763. if (subtype < 0 || subtype > 7)
  6764. abort();
  6765. #endif
  6766. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6767. zero = subtype >> 1;
  6768. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6769. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6770. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6771. if (loc) {
  6772. if (zero) {
  6773. memmove(startp, loc, str - loc);
  6774. loc = startp + (str - loc) - 1;
  6775. }
  6776. *loc = '\0';
  6777. } else
  6778. loc = str - 1;
  6779. out:
  6780. amount = loc - expdest;
  6781. STADJUST(amount, expdest);
  6782. #if BASH_PATTERN_SUBST
  6783. out1:
  6784. #endif
  6785. /* Remove any recorded regions beyond start of variable */
  6786. removerecordregions(startloc);
  6787. return p;
  6788. }
  6789. /*
  6790. * Add the value of a specialized variable to the stack string.
  6791. * name parameter (examples):
  6792. * ash -c 'echo $1' name:'1='
  6793. * ash -c 'echo $qwe' name:'qwe='
  6794. * ash -c 'echo $$' name:'$='
  6795. * ash -c 'echo ${$}' name:'$='
  6796. * ash -c 'echo ${$##q}' name:'$=q'
  6797. * ash -c 'echo ${#$}' name:'$='
  6798. * note: examples with bad shell syntax:
  6799. * ash -c 'echo ${#$1}' name:'$=1'
  6800. * ash -c 'echo ${#1#}' name:'1=#'
  6801. */
  6802. static NOINLINE ssize_t
  6803. varvalue(char *name, int varflags, int flags, int quoted)
  6804. {
  6805. const char *p;
  6806. int num;
  6807. int i;
  6808. ssize_t len = 0;
  6809. int sep;
  6810. int subtype = varflags & VSTYPE;
  6811. int discard = (subtype == VSPLUS || subtype == VSLENGTH) | (flags & EXP_DISCARD);
  6812. if (!subtype) {
  6813. if (discard)
  6814. return -1;
  6815. ifsfree();
  6816. raise_error_syntax("bad substitution");
  6817. }
  6818. flags |= EXP_KEEPNUL;
  6819. flags &= discard ? ~QUOTES_ESC : ~0;
  6820. sep = (flags & EXP_FULL) << CHAR_BIT;
  6821. switch (*name) {
  6822. case '$':
  6823. num = rootpid;
  6824. goto numvar;
  6825. case '?':
  6826. num = exitstatus;
  6827. goto numvar;
  6828. case '#':
  6829. num = shellparam.nparam;
  6830. goto numvar;
  6831. case '!':
  6832. num = backgndpid;
  6833. if (num == 0)
  6834. return -1;
  6835. numvar:
  6836. len = cvtnum(num, flags);
  6837. goto check_1char_name;
  6838. case '-':
  6839. expdest = makestrspace(NOPTS, expdest);
  6840. for (i = NOPTS - 1; i >= 0; i--) {
  6841. if (optlist[i] && optletters(i)) {
  6842. USTPUTC(optletters(i), expdest);
  6843. len++;
  6844. }
  6845. }
  6846. check_1char_name:
  6847. #if 0
  6848. /* handles cases similar to ${#$1} */
  6849. if (name[2] != '\0')
  6850. raise_error_syntax("bad substitution");
  6851. #endif
  6852. break;
  6853. case '@':
  6854. if (quoted && sep)
  6855. goto param;
  6856. /* fall through */
  6857. case '*': {
  6858. char **ap;
  6859. char sepc;
  6860. char c;
  6861. /* We will set c to 0 or ~0 depending on whether
  6862. * we're doing field splitting. We won't do field
  6863. * splitting if either we're quoted or sep is zero.
  6864. *
  6865. * Instead of testing (quoted || !sep) the following
  6866. * trick optimises away any branches by using the
  6867. * fact that EXP_QUOTED (which is the only bit that
  6868. * can be set in quoted) is the same as EXP_FULL <<
  6869. * CHAR_BIT (which is the only bit that can be set
  6870. * in sep).
  6871. */
  6872. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6873. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6874. #endif
  6875. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6876. sep &= ~quoted;
  6877. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6878. param:
  6879. sepc = sep;
  6880. ap = shellparam.p;
  6881. if (!ap)
  6882. return -1;
  6883. while ((p = *ap++) != NULL) {
  6884. len += strtodest(p, flags);
  6885. if (*ap && sep) {
  6886. len++;
  6887. memtodest(&sepc, 1, flags);
  6888. }
  6889. }
  6890. break;
  6891. } /* case '*' */
  6892. case '0':
  6893. case '1':
  6894. case '2':
  6895. case '3':
  6896. case '4':
  6897. case '5':
  6898. case '6':
  6899. case '7':
  6900. case '8':
  6901. case '9':
  6902. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6903. if (num < 0 || num > shellparam.nparam)
  6904. return -1;
  6905. p = num ? shellparam.p[num - 1] : arg0;
  6906. goto value;
  6907. default:
  6908. /* NB: name has form "VAR=..." */
  6909. p = lookupvar(name);
  6910. value:
  6911. if (!p)
  6912. return -1;
  6913. len = strtodest(p, flags);
  6914. #if ENABLE_UNICODE_SUPPORT
  6915. if (subtype == VSLENGTH && len > 0) {
  6916. reinit_unicode_for_ash();
  6917. if (unicode_status == UNICODE_ON) {
  6918. STADJUST(-len, expdest);
  6919. discard = 0;
  6920. len = unicode_strlen(p);
  6921. }
  6922. }
  6923. #endif
  6924. break;
  6925. }
  6926. if (discard)
  6927. STADJUST(-len, expdest);
  6928. return len;
  6929. }
  6930. /*
  6931. * Expand a variable, and return a pointer to the next character in the
  6932. * input string.
  6933. */
  6934. static char *
  6935. evalvar(char *p, int flag)
  6936. {
  6937. char varflags;
  6938. char subtype;
  6939. char *var;
  6940. int patloc;
  6941. int startloc;
  6942. ssize_t varlen;
  6943. int discard;
  6944. int quoted;
  6945. varflags = (unsigned char) *p++;
  6946. subtype = varflags & VSTYPE;
  6947. quoted = flag & EXP_QUOTED;
  6948. var = p;
  6949. startloc = expdest - (char *)stackblock();
  6950. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6951. again:
  6952. varlen = varvalue(var, varflags, flag, quoted);
  6953. if (varflags & VSNUL)
  6954. varlen--;
  6955. discard = varlen < 0 ? EXP_DISCARD : 0;
  6956. switch (subtype) {
  6957. case VSPLUS:
  6958. discard ^= EXP_DISCARD;
  6959. /* fall through */
  6960. case 0:
  6961. case VSMINUS:
  6962. p = argstr(p, flag | EXP_TILDE | EXP_WORD | (discard ^ EXP_DISCARD));
  6963. goto record;
  6964. case VSASSIGN:
  6965. case VSQUESTION:
  6966. p = subevalvar(p, var, 0, startloc, varflags,
  6967. (flag & ~QUOTES_ESC) | (discard ^ EXP_DISCARD));
  6968. if ((flag | ~discard) & EXP_DISCARD)
  6969. goto record;
  6970. varflags &= ~VSNUL;
  6971. subtype = VSNORMAL;
  6972. goto again;
  6973. }
  6974. if ((discard & ~flag) && uflag)
  6975. varunset(p, var, 0, 0);
  6976. if (subtype == VSLENGTH) {
  6977. p++;
  6978. if (flag & EXP_DISCARD)
  6979. return p;
  6980. cvtnum(varlen > 0 ? varlen : 0, flag);
  6981. goto really_record;
  6982. }
  6983. if (subtype == VSNORMAL)
  6984. goto record;
  6985. #if DEBUG
  6986. switch (subtype) {
  6987. case VSTRIMLEFT:
  6988. case VSTRIMLEFTMAX:
  6989. case VSTRIMRIGHT:
  6990. case VSTRIMRIGHTMAX:
  6991. #if BASH_SUBSTR
  6992. case VSSUBSTR:
  6993. #endif
  6994. #if BASH_PATTERN_SUBST
  6995. case VSREPLACE:
  6996. case VSREPLACEALL:
  6997. #endif
  6998. break;
  6999. default:
  7000. abort();
  7001. }
  7002. #endif
  7003. flag |= discard;
  7004. if (!(flag & EXP_DISCARD)) {
  7005. /*
  7006. * Terminate the string and start recording the pattern
  7007. * right after it
  7008. */
  7009. STPUTC('\0', expdest);
  7010. }
  7011. patloc = expdest - (char *)stackblock();
  7012. p = subevalvar(p, NULL, patloc, startloc, varflags, flag);
  7013. record:
  7014. if ((flag | discard) & EXP_DISCARD)
  7015. return p;
  7016. really_record:
  7017. if (quoted) {
  7018. quoted = *var == '@' && shellparam.nparam;
  7019. if (!quoted)
  7020. return p;
  7021. }
  7022. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  7023. return p;
  7024. }
  7025. /*
  7026. * Add a file name to the list.
  7027. */
  7028. static void
  7029. addfname(const char *name)
  7030. {
  7031. struct strlist *sp;
  7032. sp = stzalloc(sizeof(*sp));
  7033. sp->text = sstrdup(name);
  7034. *exparg.lastp = sp;
  7035. exparg.lastp = &sp->next;
  7036. }
  7037. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  7038. static int
  7039. hasmeta(const char *p)
  7040. {
  7041. static const char chars[] ALIGN1 = {
  7042. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  7043. };
  7044. for (;;) {
  7045. p = strpbrk(p, chars);
  7046. if (!p)
  7047. break;
  7048. switch ((unsigned char)*p) {
  7049. case CTLQUOTEMARK:
  7050. for (;;) {
  7051. p++;
  7052. if ((unsigned char)*p == CTLQUOTEMARK)
  7053. break;
  7054. if ((unsigned char)*p == CTLESC)
  7055. p++;
  7056. if (*p == '\0') /* huh? */
  7057. return 0;
  7058. }
  7059. break;
  7060. case '\\':
  7061. case CTLESC:
  7062. p++;
  7063. if (*p == '\0')
  7064. return 0;
  7065. break;
  7066. case '[':
  7067. if (!strchr(p + 1, ']')) {
  7068. /* It's not a properly closed [] pattern,
  7069. * but other metas may follow. Continue checking.
  7070. * my[file* _is_ globbed by bash
  7071. * and matches filenames like "my[file1".
  7072. */
  7073. break;
  7074. }
  7075. /* fallthrough */
  7076. default:
  7077. /* case '*': */
  7078. /* case '?': */
  7079. return 1;
  7080. }
  7081. p++;
  7082. }
  7083. return 0;
  7084. }
  7085. /* If we want to use glob() from libc... */
  7086. #if !ENABLE_ASH_INTERNAL_GLOB
  7087. /* Add the result of glob() to the list */
  7088. static void
  7089. addglob(const glob_t *pglob)
  7090. {
  7091. char **p = pglob->gl_pathv;
  7092. do {
  7093. addfname(*p);
  7094. } while (*++p);
  7095. }
  7096. static void
  7097. expandmeta(struct strlist *str /*, int flag*/)
  7098. {
  7099. /* TODO - EXP_REDIR */
  7100. while (str) {
  7101. char *p;
  7102. glob_t pglob;
  7103. int i;
  7104. if (fflag)
  7105. goto nometa;
  7106. if (!hasmeta(str->text))
  7107. goto nometa;
  7108. INT_OFF;
  7109. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7110. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  7111. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  7112. //
  7113. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  7114. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  7115. // Which means you need to unescape the string, right? Not so fast:
  7116. // if there _is_ a file named "file\?" (with backslash), it is returned
  7117. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  7118. // You DON'T KNOW by looking at the result whether you need to unescape it.
  7119. //
  7120. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  7121. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  7122. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  7123. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  7124. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  7125. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  7126. i = glob(p, 0, NULL, &pglob);
  7127. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  7128. if (p != str->text)
  7129. free(p);
  7130. switch (i) {
  7131. case 0:
  7132. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  7133. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  7134. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  7135. goto nometa2;
  7136. #endif
  7137. addglob(&pglob);
  7138. globfree(&pglob);
  7139. INT_ON;
  7140. break;
  7141. case GLOB_NOMATCH:
  7142. //nometa2:
  7143. globfree(&pglob);
  7144. INT_ON;
  7145. nometa:
  7146. *exparg.lastp = str;
  7147. rmescapes(str->text, 0, NULL);
  7148. exparg.lastp = &str->next;
  7149. break;
  7150. default: /* GLOB_NOSPACE */
  7151. globfree(&pglob);
  7152. INT_ON;
  7153. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  7154. }
  7155. str = str->next;
  7156. }
  7157. }
  7158. #else
  7159. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  7160. /*
  7161. * Do metacharacter (i.e. *, ?, [...]) expansion.
  7162. */
  7163. typedef struct exp_t {
  7164. char *dir;
  7165. unsigned dir_max;
  7166. } exp_t;
  7167. static void
  7168. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  7169. {
  7170. #define expdir exp->dir
  7171. #define expdir_max exp->dir_max
  7172. char *enddir = expdir + expdir_len;
  7173. char *p;
  7174. const char *cp;
  7175. char *start;
  7176. char *endname;
  7177. int metaflag;
  7178. struct stat statb;
  7179. DIR *dirp;
  7180. struct dirent *dp;
  7181. int atend;
  7182. int matchdot;
  7183. int esc;
  7184. metaflag = 0;
  7185. start = name;
  7186. for (p = name; esc = 0, *p; p += esc + 1) {
  7187. if (*p == '*' || *p == '?')
  7188. metaflag = 1;
  7189. else if (*p == '[') {
  7190. char *q = p + 1;
  7191. if (*q == '!')
  7192. q++;
  7193. for (;;) {
  7194. if (*q == '\\')
  7195. q++;
  7196. if (*q == '/' || *q == '\0')
  7197. break;
  7198. if (*++q == ']') {
  7199. metaflag = 1;
  7200. break;
  7201. }
  7202. }
  7203. } else {
  7204. if (*p == '\\' && p[1])
  7205. esc++;
  7206. if (p[esc] == '/') {
  7207. if (metaflag)
  7208. break;
  7209. start = p + esc + 1;
  7210. }
  7211. }
  7212. }
  7213. if (metaflag == 0) { /* we've reached the end of the file name */
  7214. if (!expdir_len)
  7215. return;
  7216. p = name;
  7217. do {
  7218. if (*p == '\\' && p[1])
  7219. p++;
  7220. *enddir++ = *p;
  7221. } while (*p++);
  7222. if (lstat(expdir, &statb) == 0)
  7223. addfname(expdir);
  7224. return;
  7225. }
  7226. endname = p;
  7227. if (name < start) {
  7228. p = name;
  7229. do {
  7230. if (*p == '\\' && p[1])
  7231. p++;
  7232. *enddir++ = *p++;
  7233. } while (p < start);
  7234. }
  7235. *enddir = '\0';
  7236. cp = expdir;
  7237. expdir_len = enddir - cp;
  7238. if (!expdir_len)
  7239. cp = ".";
  7240. dirp = opendir(cp);
  7241. if (dirp == NULL)
  7242. return;
  7243. if (*endname == 0) {
  7244. atend = 1;
  7245. } else {
  7246. atend = 0;
  7247. *endname = '\0';
  7248. endname += esc + 1;
  7249. }
  7250. name_len -= endname - name;
  7251. matchdot = 0;
  7252. p = start;
  7253. if (*p == '\\')
  7254. p++;
  7255. if (*p == '.')
  7256. matchdot++;
  7257. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7258. if (dp->d_name[0] == '.' && !matchdot)
  7259. continue;
  7260. if (pmatch(start, dp->d_name)) {
  7261. if (atend) {
  7262. strcpy(enddir, dp->d_name);
  7263. addfname(expdir);
  7264. } else {
  7265. unsigned offset;
  7266. unsigned len;
  7267. p = stpcpy(enddir, dp->d_name);
  7268. *p = '/';
  7269. offset = p - expdir + 1;
  7270. len = offset + name_len + NAME_MAX;
  7271. if (len > expdir_max) {
  7272. len += PATH_MAX;
  7273. expdir = ckrealloc(expdir, len);
  7274. expdir_max = len;
  7275. }
  7276. expmeta(exp, endname, name_len, offset);
  7277. enddir = expdir + expdir_len;
  7278. }
  7279. }
  7280. }
  7281. closedir(dirp);
  7282. if (!atend)
  7283. endname[-esc - 1] = esc ? '\\' : '/';
  7284. #undef expdir
  7285. #undef expdir_max
  7286. }
  7287. static struct strlist *
  7288. msort(struct strlist *list, int len)
  7289. {
  7290. struct strlist *p, *q = NULL;
  7291. struct strlist **lpp;
  7292. int half;
  7293. int n;
  7294. if (len <= 1)
  7295. return list;
  7296. half = len >> 1;
  7297. p = list;
  7298. for (n = half; --n >= 0;) {
  7299. q = p;
  7300. p = p->next;
  7301. }
  7302. q->next = NULL; /* terminate first half of list */
  7303. q = msort(list, half); /* sort first half of list */
  7304. p = msort(p, len - half); /* sort second half */
  7305. lpp = &list;
  7306. for (;;) {
  7307. #if ENABLE_LOCALE_SUPPORT
  7308. if (strcoll(p->text, q->text) < 0)
  7309. #else
  7310. if (strcmp(p->text, q->text) < 0)
  7311. #endif
  7312. {
  7313. *lpp = p;
  7314. lpp = &p->next;
  7315. p = *lpp;
  7316. if (p == NULL) {
  7317. *lpp = q;
  7318. break;
  7319. }
  7320. } else {
  7321. *lpp = q;
  7322. lpp = &q->next;
  7323. q = *lpp;
  7324. if (q == NULL) {
  7325. *lpp = p;
  7326. break;
  7327. }
  7328. }
  7329. }
  7330. return list;
  7331. }
  7332. /*
  7333. * Sort the results of file name expansion. It calculates the number of
  7334. * strings to sort and then calls msort (short for merge sort) to do the
  7335. * work.
  7336. */
  7337. static struct strlist *
  7338. expsort(struct strlist *str)
  7339. {
  7340. int len;
  7341. struct strlist *sp;
  7342. len = 0;
  7343. for (sp = str; sp; sp = sp->next)
  7344. len++;
  7345. return msort(str, len);
  7346. }
  7347. static void
  7348. expandmeta(struct strlist *str /*, int flag*/)
  7349. {
  7350. /* TODO - EXP_REDIR */
  7351. while (str) {
  7352. exp_t exp;
  7353. struct strlist **savelastp;
  7354. struct strlist *sp;
  7355. char *p;
  7356. unsigned len;
  7357. if (fflag)
  7358. goto nometa;
  7359. if (!hasmeta(str->text))
  7360. goto nometa;
  7361. savelastp = exparg.lastp;
  7362. INT_OFF;
  7363. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7364. len = strlen(p);
  7365. exp.dir_max = len + PATH_MAX;
  7366. exp.dir = ckmalloc(exp.dir_max);
  7367. expmeta(&exp, p, len, 0);
  7368. free(exp.dir);
  7369. if (p != str->text)
  7370. free(p);
  7371. INT_ON;
  7372. if (exparg.lastp == savelastp) {
  7373. /*
  7374. * no matches
  7375. */
  7376. nometa:
  7377. *exparg.lastp = str;
  7378. rmescapes(str->text, 0, NULL);
  7379. exparg.lastp = &str->next;
  7380. } else {
  7381. *exparg.lastp = NULL;
  7382. *savelastp = sp = expsort(*savelastp);
  7383. while (sp->next != NULL)
  7384. sp = sp->next;
  7385. exparg.lastp = &sp->next;
  7386. }
  7387. str = str->next;
  7388. }
  7389. }
  7390. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7391. /*
  7392. * Perform variable substitution and command substitution on an argument,
  7393. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7394. * perform splitting and file name expansion. When arglist is NULL, perform
  7395. * here document expansion.
  7396. */
  7397. static void
  7398. expandarg(union node *arg, struct arglist *arglist, int flag)
  7399. {
  7400. struct strlist *sp;
  7401. char *p;
  7402. argbackq = arg->narg.backquote;
  7403. STARTSTACKSTR(expdest);
  7404. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7405. argstr(arg->narg.text, flag);
  7406. if (arglist == NULL) {
  7407. /* here document expanded */
  7408. goto out;
  7409. }
  7410. p = grabstackstr(expdest);
  7411. TRACE(("expandarg: p:'%s'\n", p));
  7412. exparg.lastp = &exparg.list;
  7413. /*
  7414. * TODO - EXP_REDIR
  7415. */
  7416. if (flag & EXP_FULL) {
  7417. ifsbreakup(p, &exparg);
  7418. *exparg.lastp = NULL;
  7419. exparg.lastp = &exparg.list;
  7420. expandmeta(exparg.list /*, flag*/);
  7421. } else {
  7422. sp = stzalloc(sizeof(*sp));
  7423. sp->text = p;
  7424. *exparg.lastp = sp;
  7425. exparg.lastp = &sp->next;
  7426. }
  7427. *exparg.lastp = NULL;
  7428. if (exparg.list) {
  7429. *arglist->lastp = exparg.list;
  7430. arglist->lastp = exparg.lastp;
  7431. }
  7432. out:
  7433. ifsfree();
  7434. }
  7435. /*
  7436. * Expand shell variables and backquotes inside a here document.
  7437. */
  7438. static void
  7439. expandhere(union node *arg)
  7440. {
  7441. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7442. }
  7443. /*
  7444. * Returns true if the pattern matches the string.
  7445. */
  7446. static int
  7447. patmatch(char *pattern, const char *string)
  7448. {
  7449. char *p = preglob(pattern, 0);
  7450. int r = pmatch(p, string);
  7451. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7452. return r;
  7453. }
  7454. /*
  7455. * See if a pattern matches in a case statement.
  7456. */
  7457. static int
  7458. casematch(union node *pattern, char *val)
  7459. {
  7460. struct stackmark smark;
  7461. int result;
  7462. setstackmark(&smark);
  7463. argbackq = pattern->narg.backquote;
  7464. STARTSTACKSTR(expdest);
  7465. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7466. ifsfree();
  7467. result = patmatch(stackblock(), val);
  7468. popstackmark(&smark);
  7469. return result;
  7470. }
  7471. /* ============ find_command */
  7472. struct builtincmd {
  7473. const char *name;
  7474. int (*builtin)(int, char **) FAST_FUNC;
  7475. /* unsigned flags; */
  7476. };
  7477. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7478. /* "regular" builtins always take precedence over commands,
  7479. * regardless of PATH=....%builtin... position */
  7480. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7481. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7482. struct cmdentry {
  7483. smallint cmdtype; /* CMDxxx */
  7484. union param {
  7485. int index;
  7486. /* index >= 0 for commands without path (slashes) */
  7487. /* (TODO: what exactly does the value mean? PATH position?) */
  7488. /* index == -1 for commands with slashes */
  7489. /* index == (-2 - applet_no) for NOFORK applets */
  7490. const struct builtincmd *cmd;
  7491. struct funcnode *func;
  7492. } u;
  7493. };
  7494. /* values of cmdtype */
  7495. #define CMDUNKNOWN -1 /* no entry in table for command */
  7496. #define CMDNORMAL 0 /* command is an executable program */
  7497. #define CMDFUNCTION 1 /* command is a shell function */
  7498. #define CMDBUILTIN 2 /* command is a shell builtin */
  7499. /* action to find_command() */
  7500. #define DO_ERR 0x01 /* prints errors */
  7501. #define DO_ABS 0x02 /* checks absolute paths */
  7502. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7503. #define DO_ALTPATH 0x08 /* using alternate path */
  7504. #define DO_REGBLTIN 0x10 /* regular built-ins and functions only */
  7505. static void find_command(char *, struct cmdentry *, int, const char *);
  7506. /* ============ Hashing commands */
  7507. /*
  7508. * When commands are first encountered, they are entered in a hash table.
  7509. * This ensures that a full path search will not have to be done for them
  7510. * on each invocation.
  7511. *
  7512. * We should investigate converting to a linear search, even though that
  7513. * would make the command name "hash" a misnomer.
  7514. */
  7515. struct tblentry {
  7516. struct tblentry *next; /* next entry in hash chain */
  7517. union param param; /* definition of builtin function */
  7518. smallint cmdtype; /* CMDxxx */
  7519. char rehash; /* if set, cd done since entry created */
  7520. char cmdname[1]; /* name of command */
  7521. };
  7522. static struct tblentry **cmdtable;
  7523. #define INIT_G_cmdtable() do { \
  7524. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7525. } while (0)
  7526. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7527. static void
  7528. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7529. {
  7530. #if ENABLE_FEATURE_SH_STANDALONE
  7531. if (applet_no >= 0) {
  7532. if (APPLET_IS_NOEXEC(applet_no)) {
  7533. clearenv();
  7534. while (*envp)
  7535. putenv(*envp++);
  7536. popredir(/*drop:*/ 1);
  7537. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7538. }
  7539. /* re-exec ourselves with the new arguments */
  7540. execve(bb_busybox_exec_path, argv, envp);
  7541. /* If they called chroot or otherwise made the binary no longer
  7542. * executable, fall through */
  7543. }
  7544. #endif
  7545. repeat:
  7546. #ifdef SYSV
  7547. do {
  7548. execve(cmd, argv, envp);
  7549. } while (errno == EINTR);
  7550. #else
  7551. execve(cmd, argv, envp);
  7552. #endif
  7553. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7554. /* Run "cmd" as a shell script:
  7555. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7556. * "If the execve() function fails with ENOEXEC, the shell
  7557. * shall execute a command equivalent to having a shell invoked
  7558. * with the command name as its first operand,
  7559. * with any remaining arguments passed to the new shell"
  7560. *
  7561. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7562. * just call ourselves.
  7563. *
  7564. * Note that bash reads ~80 chars of the file, and if it sees
  7565. * a zero byte before it sees newline, it doesn't try to
  7566. * interpret it, but fails with "cannot execute binary file"
  7567. * message and exit code 126. For one, this prevents attempts
  7568. * to interpret foreign ELF binaries as shell scripts.
  7569. */
  7570. argv[0] = (char*) cmd;
  7571. cmd = bb_busybox_exec_path;
  7572. /* NB: this is only possible because all callers of shellexec()
  7573. * ensure that the argv[-1] slot exists!
  7574. */
  7575. argv--;
  7576. argv[0] = (char*) "ash";
  7577. goto repeat;
  7578. }
  7579. }
  7580. /*
  7581. * Exec a program. Never returns. If you change this routine, you may
  7582. * have to change the find_command routine as well.
  7583. * argv[-1] must exist and be writable! See tryexec() for why.
  7584. */
  7585. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7586. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7587. {
  7588. char *cmdname;
  7589. int e;
  7590. char **envp;
  7591. int exerrno;
  7592. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7593. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7594. if (strchr(prog, '/') != NULL
  7595. #if ENABLE_FEATURE_SH_STANDALONE
  7596. || (applet_no = find_applet_by_name(prog)) >= 0
  7597. #endif
  7598. ) {
  7599. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7600. if (applet_no >= 0) {
  7601. /* We tried execing ourself, but it didn't work.
  7602. * Maybe /proc/self/exe doesn't exist?
  7603. * Try $PATH search.
  7604. */
  7605. goto try_PATH;
  7606. }
  7607. e = errno;
  7608. } else {
  7609. try_PATH:
  7610. e = ENOENT;
  7611. while (padvance(&path, argv[0]) >= 0) {
  7612. cmdname = stackblock();
  7613. if (--idx < 0 && pathopt == NULL) {
  7614. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7615. if (errno != ENOENT && errno != ENOTDIR)
  7616. e = errno;
  7617. }
  7618. }
  7619. }
  7620. /* Map to POSIX errors */
  7621. switch (e) {
  7622. default:
  7623. exerrno = 126;
  7624. break;
  7625. case ELOOP:
  7626. case ENAMETOOLONG:
  7627. case ENOENT:
  7628. case ENOTDIR:
  7629. exerrno = 127;
  7630. break;
  7631. }
  7632. exitstatus = exerrno;
  7633. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7634. prog, e, suppress_int));
  7635. ash_msg_and_raise(EXEND, "%s: %s", prog, errmsg(e, "not found"));
  7636. /* NOTREACHED */
  7637. }
  7638. static void
  7639. printentry(struct tblentry *cmdp)
  7640. {
  7641. int idx;
  7642. const char *path;
  7643. char *name;
  7644. idx = cmdp->param.index;
  7645. path = pathval();
  7646. do {
  7647. padvance(&path, cmdp->cmdname);
  7648. } while (--idx >= 0);
  7649. name = stackblock();
  7650. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7651. }
  7652. /*
  7653. * Clear out command entries.
  7654. */
  7655. static void
  7656. clearcmdentry(void)
  7657. {
  7658. struct tblentry **tblp;
  7659. struct tblentry **pp;
  7660. struct tblentry *cmdp;
  7661. INT_OFF;
  7662. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7663. pp = tblp;
  7664. while ((cmdp = *pp) != NULL) {
  7665. if (cmdp->cmdtype == CMDNORMAL
  7666. || (cmdp->cmdtype == CMDBUILTIN
  7667. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7668. && builtinloc > 0
  7669. )
  7670. ) {
  7671. *pp = cmdp->next;
  7672. free(cmdp);
  7673. } else {
  7674. pp = &cmdp->next;
  7675. }
  7676. }
  7677. }
  7678. INT_ON;
  7679. }
  7680. /*
  7681. * Locate a command in the command hash table. If "add" is nonzero,
  7682. * add the command to the table if it is not already present. The
  7683. * variable "lastcmdentry" is set to point to the address of the link
  7684. * pointing to the entry, so that delete_cmd_entry can delete the
  7685. * entry.
  7686. *
  7687. * Interrupts must be off if called with add != 0.
  7688. */
  7689. static struct tblentry **lastcmdentry;
  7690. static struct tblentry *
  7691. cmdlookup(const char *name, int add)
  7692. {
  7693. unsigned int hashval;
  7694. const char *p;
  7695. struct tblentry *cmdp;
  7696. struct tblentry **pp;
  7697. p = name;
  7698. hashval = (unsigned char)*p << 4;
  7699. while (*p)
  7700. hashval += (unsigned char)*p++;
  7701. hashval &= 0x7FFF;
  7702. pp = &cmdtable[hashval % CMDTABLESIZE];
  7703. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7704. if (strcmp(cmdp->cmdname, name) == 0)
  7705. break;
  7706. pp = &cmdp->next;
  7707. }
  7708. if (add && cmdp == NULL) {
  7709. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7710. + strlen(name)
  7711. /* + 1 - already done because
  7712. * tblentry::cmdname is char[1] */);
  7713. /*cmdp->next = NULL; - ckzalloc did it */
  7714. cmdp->cmdtype = CMDUNKNOWN;
  7715. strcpy(cmdp->cmdname, name);
  7716. }
  7717. lastcmdentry = pp;
  7718. return cmdp;
  7719. }
  7720. /*
  7721. * Delete the command entry returned on the last lookup.
  7722. */
  7723. static void
  7724. delete_cmd_entry(void)
  7725. {
  7726. struct tblentry *cmdp;
  7727. INT_OFF;
  7728. cmdp = *lastcmdentry;
  7729. *lastcmdentry = cmdp->next;
  7730. if (cmdp->cmdtype == CMDFUNCTION)
  7731. freefunc(cmdp->param.func);
  7732. free(cmdp);
  7733. INT_ON;
  7734. }
  7735. /*
  7736. * Add a new command entry, replacing any existing command entry for
  7737. * the same name - except special builtins.
  7738. */
  7739. static void
  7740. addcmdentry(char *name, struct cmdentry *entry)
  7741. {
  7742. struct tblentry *cmdp;
  7743. cmdp = cmdlookup(name, 1);
  7744. if (cmdp->cmdtype == CMDFUNCTION) {
  7745. freefunc(cmdp->param.func);
  7746. }
  7747. cmdp->cmdtype = entry->cmdtype;
  7748. cmdp->param = entry->u;
  7749. cmdp->rehash = 0;
  7750. }
  7751. static int FAST_FUNC
  7752. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7753. {
  7754. struct tblentry **pp;
  7755. struct tblentry *cmdp;
  7756. int c;
  7757. struct cmdentry entry;
  7758. char *name;
  7759. if (nextopt("r") != '\0') {
  7760. clearcmdentry();
  7761. return 0;
  7762. }
  7763. if (*argptr == NULL) {
  7764. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7765. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7766. if (cmdp->cmdtype == CMDNORMAL)
  7767. printentry(cmdp);
  7768. }
  7769. }
  7770. return 0;
  7771. }
  7772. c = 0;
  7773. while ((name = *argptr) != NULL) {
  7774. cmdp = cmdlookup(name, 0);
  7775. if (cmdp != NULL
  7776. && (cmdp->cmdtype == CMDNORMAL
  7777. || (cmdp->cmdtype == CMDBUILTIN
  7778. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7779. && builtinloc > 0
  7780. )
  7781. )
  7782. ) {
  7783. delete_cmd_entry();
  7784. }
  7785. find_command(name, &entry, DO_ERR, pathval());
  7786. if (entry.cmdtype == CMDUNKNOWN)
  7787. c = 1;
  7788. argptr++;
  7789. }
  7790. return c;
  7791. }
  7792. /*
  7793. * Called when a cd is done. Marks all commands so the next time they
  7794. * are executed they will be rehashed.
  7795. */
  7796. static void
  7797. hashcd(void)
  7798. {
  7799. struct tblentry **pp;
  7800. struct tblentry *cmdp;
  7801. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7802. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7803. if (cmdp->cmdtype == CMDNORMAL
  7804. || (cmdp->cmdtype == CMDBUILTIN
  7805. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7806. && builtinloc > 0)
  7807. ) {
  7808. cmdp->rehash = 1;
  7809. }
  7810. }
  7811. }
  7812. }
  7813. /*
  7814. * Fix command hash table when PATH changed.
  7815. * Called before PATH is changed. The argument is the new value of PATH;
  7816. * pathval() still returns the old value at this point.
  7817. * Called with interrupts off.
  7818. */
  7819. static void FAST_FUNC
  7820. changepath(const char *newval)
  7821. {
  7822. const char *new;
  7823. int idx;
  7824. int bltin;
  7825. new = newval;
  7826. idx = 0;
  7827. bltin = -1;
  7828. for (;;) {
  7829. if (*new == '%' && prefix(new + 1, "builtin")) {
  7830. bltin = idx;
  7831. break;
  7832. }
  7833. new = strchr(new, ':');
  7834. if (!new)
  7835. break;
  7836. idx++;
  7837. new++;
  7838. }
  7839. builtinloc = bltin;
  7840. clearcmdentry();
  7841. }
  7842. enum {
  7843. TEOF,
  7844. TNL,
  7845. TREDIR,
  7846. TWORD,
  7847. TSEMI,
  7848. TBACKGND,
  7849. TAND,
  7850. TOR,
  7851. TPIPE,
  7852. TLP,
  7853. TRP,
  7854. TENDCASE,
  7855. TENDBQUOTE,
  7856. TNOT,
  7857. TCASE,
  7858. TDO,
  7859. TDONE,
  7860. TELIF,
  7861. TELSE,
  7862. TESAC,
  7863. TFI,
  7864. TFOR,
  7865. #if BASH_FUNCTION
  7866. TFUNCTION,
  7867. #endif
  7868. TIF,
  7869. TIN,
  7870. TTHEN,
  7871. TUNTIL,
  7872. TWHILE,
  7873. TBEGIN,
  7874. TEND
  7875. };
  7876. typedef smallint token_id_t;
  7877. /* Nth bit indicates if token marks the end of a list */
  7878. enum {
  7879. tokendlist = 0
  7880. /* 0 */ | (1u << TEOF)
  7881. /* 1 */ | (0u << TNL)
  7882. /* 2 */ | (0u << TREDIR)
  7883. /* 3 */ | (0u << TWORD)
  7884. /* 4 */ | (0u << TSEMI)
  7885. /* 5 */ | (0u << TBACKGND)
  7886. /* 6 */ | (0u << TAND)
  7887. /* 7 */ | (0u << TOR)
  7888. /* 8 */ | (0u << TPIPE)
  7889. /* 9 */ | (0u << TLP)
  7890. /* 10 */ | (1u << TRP)
  7891. /* 11 */ | (1u << TENDCASE)
  7892. /* 12 */ | (1u << TENDBQUOTE)
  7893. /* 13 */ | (0u << TNOT)
  7894. /* 14 */ | (0u << TCASE)
  7895. /* 15 */ | (1u << TDO)
  7896. /* 16 */ | (1u << TDONE)
  7897. /* 17 */ | (1u << TELIF)
  7898. /* 18 */ | (1u << TELSE)
  7899. /* 19 */ | (1u << TESAC)
  7900. /* 20 */ | (1u << TFI)
  7901. /* 21 */ | (0u << TFOR)
  7902. #if BASH_FUNCTION
  7903. /* 22 */ | (0u << TFUNCTION)
  7904. #endif
  7905. /* 23 */ | (0u << TIF)
  7906. /* 24 */ | (0u << TIN)
  7907. /* 25 */ | (1u << TTHEN)
  7908. /* 26 */ | (0u << TUNTIL)
  7909. /* 27 */ | (0u << TWHILE)
  7910. /* 28 */ | (0u << TBEGIN)
  7911. /* 29 */ | (1u << TEND)
  7912. , /* thus far 29 bits used */
  7913. };
  7914. static const char *const tokname_array[] ALIGN_PTR = {
  7915. "end of file",
  7916. "newline",
  7917. "redirection",
  7918. "word",
  7919. ";",
  7920. "&",
  7921. "&&",
  7922. "||",
  7923. "|",
  7924. "(",
  7925. ")",
  7926. ";;",
  7927. "`",
  7928. #define KWDOFFSET 13
  7929. /* the following are keywords */
  7930. "!",
  7931. "case",
  7932. "do",
  7933. "done",
  7934. "elif",
  7935. "else",
  7936. "esac",
  7937. "fi",
  7938. "for",
  7939. #if BASH_FUNCTION
  7940. "function",
  7941. #endif
  7942. "if",
  7943. "in",
  7944. "then",
  7945. "until",
  7946. "while",
  7947. "{",
  7948. "}",
  7949. };
  7950. /* Wrapper around strcmp for qsort/bsearch/... */
  7951. static int
  7952. pstrcmp(const void *a, const void *b)
  7953. {
  7954. return strcmp((char*)a, *(char**)b);
  7955. }
  7956. static const char *const *
  7957. findkwd(const char *s)
  7958. {
  7959. return bsearch(s, tokname_array + KWDOFFSET,
  7960. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7961. sizeof(tokname_array[0]), pstrcmp);
  7962. }
  7963. /*
  7964. * Locate and print what a word is...
  7965. */
  7966. static int
  7967. describe_command(char *command, const char *path, int describe_command_verbose)
  7968. {
  7969. struct cmdentry entry;
  7970. #if ENABLE_ASH_ALIAS
  7971. const struct alias *ap;
  7972. #endif
  7973. if (describe_command_verbose) {
  7974. out1str(command);
  7975. }
  7976. /* First look at the keywords */
  7977. if (findkwd(command)) {
  7978. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7979. goto out;
  7980. }
  7981. #if ENABLE_ASH_ALIAS
  7982. /* Then look at the aliases */
  7983. ap = lookupalias(command, 0);
  7984. if (ap != NULL) {
  7985. if (!describe_command_verbose) {
  7986. out1str("alias ");
  7987. printalias(ap);
  7988. return 0;
  7989. }
  7990. out1fmt(" is an alias for %s", ap->val);
  7991. goto out;
  7992. }
  7993. #endif
  7994. /* Brute force */
  7995. path = path ? path : pathval();
  7996. find_command(command, &entry, DO_ABS, path);
  7997. switch (entry.cmdtype) {
  7998. case CMDNORMAL: {
  7999. int j = entry.u.index;
  8000. char *p;
  8001. if (j < 0) {
  8002. p = command;
  8003. } else {
  8004. do {
  8005. padvance(&path, command);
  8006. } while (--j >= 0);
  8007. p = stackblock();
  8008. }
  8009. if (describe_command_verbose) {
  8010. out1fmt(" is %s", p);
  8011. } else {
  8012. out1str(p);
  8013. }
  8014. break;
  8015. }
  8016. case CMDFUNCTION:
  8017. if (describe_command_verbose) {
  8018. /*out1str(" is a shell function");*/
  8019. out1str(" is a function"); /* bash says this */
  8020. } else {
  8021. out1str(command);
  8022. }
  8023. break;
  8024. case CMDBUILTIN:
  8025. if (describe_command_verbose) {
  8026. out1fmt(" is a %sshell builtin",
  8027. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  8028. "special " : nullstr
  8029. );
  8030. } else {
  8031. out1str(command);
  8032. }
  8033. break;
  8034. default:
  8035. if (describe_command_verbose) {
  8036. out1str(": not found\n");
  8037. }
  8038. return 127;
  8039. }
  8040. out:
  8041. out1str("\n");
  8042. return 0;
  8043. }
  8044. static int FAST_FUNC
  8045. typecmd(int argc UNUSED_PARAM, char **argv)
  8046. {
  8047. int i = 1;
  8048. int err = 0;
  8049. int verbose = 1;
  8050. /* type -p ... ? (we don't bother checking for 'p') */
  8051. if (argv[1] && argv[1][0] == '-') {
  8052. i++;
  8053. verbose = 0;
  8054. }
  8055. while (argv[i]) {
  8056. err |= describe_command(argv[i++], NULL, verbose);
  8057. }
  8058. return err;
  8059. }
  8060. static struct strlist *
  8061. fill_arglist(struct arglist *arglist, union node **argpp)
  8062. {
  8063. struct strlist **lastp = arglist->lastp;
  8064. union node *argp;
  8065. while ((argp = *argpp) != NULL) {
  8066. expandarg(argp, arglist, EXP_FULL | EXP_TILDE);
  8067. *argpp = argp->narg.next;
  8068. if (*lastp)
  8069. break;
  8070. }
  8071. return *lastp;
  8072. }
  8073. #if ENABLE_ASH_CMDCMD
  8074. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  8075. static int
  8076. parse_command_args(struct arglist *arglist, union node **argpp, const char **path)
  8077. {
  8078. struct strlist *sp = arglist->list;
  8079. char *cp, c;
  8080. for (;;) {
  8081. sp = sp->next ? sp->next : fill_arglist(arglist, argpp);
  8082. if (!sp)
  8083. return 0;
  8084. cp = sp->text;
  8085. if (*cp++ != '-')
  8086. break;
  8087. c = *cp++;
  8088. if (!c)
  8089. break;
  8090. if (c == '-' && !*cp) {
  8091. if (!sp->next && !fill_arglist(arglist, argpp))
  8092. return 0;
  8093. sp = sp->next;
  8094. break;
  8095. }
  8096. do {
  8097. switch (c) {
  8098. case 'p':
  8099. *path = bb_default_path;
  8100. break;
  8101. default:
  8102. /* run 'typecmd' for other options */
  8103. return 0;
  8104. }
  8105. c = *cp++;
  8106. } while (c);
  8107. }
  8108. arglist->list = sp;
  8109. return DO_NOFUNC;
  8110. }
  8111. static int FAST_FUNC
  8112. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8113. {
  8114. char *cmd;
  8115. int c;
  8116. enum {
  8117. VERIFY_BRIEF = 1,
  8118. VERIFY_VERBOSE = 2,
  8119. } verify = 0;
  8120. const char *path = NULL;
  8121. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  8122. * never reaches this function.
  8123. */
  8124. while ((c = nextopt("pvV")) != '\0')
  8125. if (c == 'V')
  8126. verify |= VERIFY_VERBOSE;
  8127. else if (c == 'v')
  8128. /*verify |= VERIFY_BRIEF*/;
  8129. #if DEBUG
  8130. else if (c != 'p')
  8131. abort();
  8132. #endif
  8133. else
  8134. path = bb_default_path;
  8135. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  8136. cmd = *argptr;
  8137. if (/*verify && */ cmd)
  8138. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  8139. return 0;
  8140. }
  8141. #endif
  8142. /*static int funcblocksize; // size of structures in function */
  8143. /*static int funcstringsize; // size of strings in node */
  8144. static void *funcblock; /* block to allocate function from */
  8145. static char *funcstring_end; /* end of block to allocate strings from */
  8146. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  8147. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  8148. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  8149. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  8150. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  8151. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  8152. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8153. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8154. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8155. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  8156. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8157. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8158. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  8159. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  8160. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  8161. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  8162. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  8163. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8164. #if BASH_REDIR_OUTPUT
  8165. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  8166. #endif
  8167. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  8168. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  8169. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8170. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  8171. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8172. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8173. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8174. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8175. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  8176. };
  8177. static int calcsize(int funcblocksize, union node *n);
  8178. static int
  8179. sizenodelist(int funcblocksize, struct nodelist *lp)
  8180. {
  8181. while (lp) {
  8182. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  8183. funcblocksize = calcsize(funcblocksize, lp->n);
  8184. lp = lp->next;
  8185. }
  8186. return funcblocksize;
  8187. }
  8188. static int
  8189. calcsize(int funcblocksize, union node *n)
  8190. {
  8191. if (n == NULL)
  8192. return funcblocksize;
  8193. funcblocksize += nodesize[n->type];
  8194. switch (n->type) {
  8195. case NCMD:
  8196. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  8197. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  8198. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  8199. break;
  8200. case NPIPE:
  8201. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  8202. break;
  8203. case NREDIR:
  8204. case NBACKGND:
  8205. case NSUBSHELL:
  8206. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  8207. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  8208. break;
  8209. case NAND:
  8210. case NOR:
  8211. case NSEMI:
  8212. case NWHILE:
  8213. case NUNTIL:
  8214. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  8215. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  8216. break;
  8217. case NIF:
  8218. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  8219. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  8220. funcblocksize = calcsize(funcblocksize, n->nif.test);
  8221. break;
  8222. case NFOR:
  8223. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  8224. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  8225. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  8226. break;
  8227. case NCASE:
  8228. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  8229. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  8230. break;
  8231. case NCLIST:
  8232. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  8233. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  8234. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  8235. break;
  8236. case NDEFUN:
  8237. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8238. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8239. break;
  8240. case NARG:
  8241. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8242. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8243. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8244. break;
  8245. case NTO:
  8246. #if BASH_REDIR_OUTPUT
  8247. case NTO2:
  8248. #endif
  8249. case NCLOBBER:
  8250. case NFROM:
  8251. case NFROMTO:
  8252. case NAPPEND:
  8253. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8254. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8255. break;
  8256. case NTOFD:
  8257. case NFROMFD:
  8258. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8259. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8260. break;
  8261. case NHERE:
  8262. case NXHERE:
  8263. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8264. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8265. break;
  8266. case NNOT:
  8267. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8268. break;
  8269. };
  8270. return funcblocksize;
  8271. }
  8272. static char *
  8273. nodeckstrdup(char *s)
  8274. {
  8275. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8276. return strcpy(funcstring_end, s);
  8277. }
  8278. static union node *copynode(union node *);
  8279. static struct nodelist *
  8280. copynodelist(struct nodelist *lp)
  8281. {
  8282. struct nodelist *start;
  8283. struct nodelist **lpp;
  8284. lpp = &start;
  8285. while (lp) {
  8286. *lpp = funcblock;
  8287. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8288. (*lpp)->n = copynode(lp->n);
  8289. lp = lp->next;
  8290. lpp = &(*lpp)->next;
  8291. }
  8292. *lpp = NULL;
  8293. return start;
  8294. }
  8295. static union node *
  8296. copynode(union node *n)
  8297. {
  8298. union node *new;
  8299. if (n == NULL)
  8300. return NULL;
  8301. new = funcblock;
  8302. funcblock = (char *) funcblock + nodesize[n->type];
  8303. switch (n->type) {
  8304. case NCMD:
  8305. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8306. new->ncmd.args = copynode(n->ncmd.args);
  8307. new->ncmd.assign = copynode(n->ncmd.assign);
  8308. new->ncmd.linno = n->ncmd.linno;
  8309. break;
  8310. case NPIPE:
  8311. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8312. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8313. break;
  8314. case NREDIR:
  8315. case NBACKGND:
  8316. case NSUBSHELL:
  8317. new->nredir.redirect = copynode(n->nredir.redirect);
  8318. new->nredir.n = copynode(n->nredir.n);
  8319. new->nredir.linno = n->nredir.linno;
  8320. break;
  8321. case NAND:
  8322. case NOR:
  8323. case NSEMI:
  8324. case NWHILE:
  8325. case NUNTIL:
  8326. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8327. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8328. break;
  8329. case NIF:
  8330. new->nif.elsepart = copynode(n->nif.elsepart);
  8331. new->nif.ifpart = copynode(n->nif.ifpart);
  8332. new->nif.test = copynode(n->nif.test);
  8333. break;
  8334. case NFOR:
  8335. new->nfor.var = nodeckstrdup(n->nfor.var);
  8336. new->nfor.body = copynode(n->nfor.body);
  8337. new->nfor.args = copynode(n->nfor.args);
  8338. new->nfor.linno = n->nfor.linno;
  8339. break;
  8340. case NCASE:
  8341. new->ncase.cases = copynode(n->ncase.cases);
  8342. new->ncase.expr = copynode(n->ncase.expr);
  8343. new->ncase.linno = n->ncase.linno;
  8344. break;
  8345. case NCLIST:
  8346. new->nclist.body = copynode(n->nclist.body);
  8347. new->nclist.pattern = copynode(n->nclist.pattern);
  8348. new->nclist.next = copynode(n->nclist.next);
  8349. break;
  8350. case NDEFUN:
  8351. new->ndefun.body = copynode(n->ndefun.body);
  8352. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8353. new->ndefun.linno = n->ndefun.linno;
  8354. break;
  8355. case NARG:
  8356. new->narg.backquote = copynodelist(n->narg.backquote);
  8357. new->narg.text = nodeckstrdup(n->narg.text);
  8358. new->narg.next = copynode(n->narg.next);
  8359. break;
  8360. case NTO:
  8361. #if BASH_REDIR_OUTPUT
  8362. case NTO2:
  8363. #endif
  8364. case NCLOBBER:
  8365. case NFROM:
  8366. case NFROMTO:
  8367. case NAPPEND:
  8368. new->nfile.fname = copynode(n->nfile.fname);
  8369. new->nfile.fd = n->nfile.fd;
  8370. new->nfile.next = copynode(n->nfile.next);
  8371. break;
  8372. case NTOFD:
  8373. case NFROMFD:
  8374. new->ndup.vname = copynode(n->ndup.vname);
  8375. new->ndup.dupfd = n->ndup.dupfd;
  8376. new->ndup.fd = n->ndup.fd;
  8377. new->ndup.next = copynode(n->ndup.next);
  8378. break;
  8379. case NHERE:
  8380. case NXHERE:
  8381. new->nhere.doc = copynode(n->nhere.doc);
  8382. new->nhere.fd = n->nhere.fd;
  8383. new->nhere.next = copynode(n->nhere.next);
  8384. break;
  8385. case NNOT:
  8386. new->nnot.com = copynode(n->nnot.com);
  8387. break;
  8388. };
  8389. new->type = n->type;
  8390. return new;
  8391. }
  8392. /*
  8393. * Make a copy of a parse tree.
  8394. */
  8395. static struct funcnode *
  8396. copyfunc(union node *n)
  8397. {
  8398. struct funcnode *f;
  8399. size_t blocksize;
  8400. /*funcstringsize = 0;*/
  8401. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8402. f = ckzalloc(blocksize /* + funcstringsize */);
  8403. funcblock = (char *) f + offsetof(struct funcnode, n);
  8404. funcstring_end = (char *) f + blocksize;
  8405. copynode(n);
  8406. /* f->count = 0; - ckzalloc did it */
  8407. return f;
  8408. }
  8409. /*
  8410. * Define a shell function.
  8411. */
  8412. static void
  8413. defun(union node *func)
  8414. {
  8415. struct cmdentry entry;
  8416. INT_OFF;
  8417. entry.cmdtype = CMDFUNCTION;
  8418. entry.u.func = copyfunc(func);
  8419. addcmdentry(func->ndefun.text, &entry);
  8420. INT_ON;
  8421. }
  8422. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8423. #define SKIPBREAK (1 << 0)
  8424. #define SKIPCONT (1 << 1)
  8425. #define SKIPFUNC (1 << 2)
  8426. #define SKIPFUNCDEF (1 << 3)
  8427. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8428. static int skipcount; /* number of levels to skip */
  8429. static int loopnest; /* current loop nesting level */
  8430. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8431. /* Forward decl way out to parsing code - dotrap needs it */
  8432. static int evalstring(char *s, int flags);
  8433. /* Called to execute a trap.
  8434. * Single callsite - at the end of evaltree().
  8435. * If we return non-zero, evaltree raises EXEXIT exception.
  8436. *
  8437. * Perhaps we should avoid entering new trap handlers
  8438. * while we are executing a trap handler. [is it a TODO?]
  8439. */
  8440. static void
  8441. dotrap(void)
  8442. {
  8443. uint8_t *g;
  8444. int sig;
  8445. int status, last_status;
  8446. if (!pending_sig)
  8447. return;
  8448. status = savestatus;
  8449. last_status = status;
  8450. if (status < 0) {
  8451. status = exitstatus;
  8452. savestatus = status;
  8453. }
  8454. pending_sig = 0;
  8455. barrier();
  8456. TRACE(("dotrap entered\n"));
  8457. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8458. char *p;
  8459. if (!*g)
  8460. continue;
  8461. if (evalskip) {
  8462. pending_sig = sig;
  8463. break;
  8464. }
  8465. p = trap[sig];
  8466. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8467. * don't upset it by resetting gotsig[SIGINT-1] */
  8468. if (sig == SIGINT && !p)
  8469. continue;
  8470. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8471. *g = 0;
  8472. if (!p)
  8473. continue;
  8474. trap_depth++;
  8475. evalstring(p, 0);
  8476. trap_depth--;
  8477. if (evalskip != SKIPFUNC)
  8478. exitstatus = status;
  8479. }
  8480. savestatus = last_status;
  8481. TRACE(("dotrap returns\n"));
  8482. }
  8483. /* forward declarations - evaluation is fairly recursive business... */
  8484. static int evalloop(union node *, int);
  8485. static int evalfor(union node *, int);
  8486. static int evalcase(union node *, int);
  8487. static int evalsubshell(union node *, int);
  8488. static void expredir(union node *);
  8489. static int evalpipe(union node *, int);
  8490. static int evalcommand(union node *, int);
  8491. static int evalbltin(const struct builtincmd *, int, char **, int);
  8492. static void prehash(union node *);
  8493. /*
  8494. * Evaluate a parse tree. The value is left in the global variable
  8495. * exitstatus.
  8496. */
  8497. static int
  8498. evaltree(union node *n, int flags)
  8499. {
  8500. int checkexit = 0;
  8501. int (*evalfn)(union node *, int);
  8502. struct stackmark smark;
  8503. int status = 0;
  8504. setstackmark(&smark);
  8505. if (nflag)
  8506. goto out;
  8507. if (n == NULL) {
  8508. TRACE(("evaltree(NULL) called\n"));
  8509. goto out;
  8510. }
  8511. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8512. dotrap();
  8513. switch (n->type) {
  8514. default:
  8515. #if DEBUG
  8516. out1fmt("Node type = %d\n", n->type);
  8517. fflush_all();
  8518. break;
  8519. #endif
  8520. case NNOT:
  8521. status = !evaltree(n->nnot.com, EV_TESTED);
  8522. goto setstatus;
  8523. case NREDIR:
  8524. errlinno = lineno = n->nredir.linno;
  8525. expredir(n->nredir.redirect);
  8526. pushredir(n->nredir.redirect);
  8527. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8528. if (!status) {
  8529. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8530. }
  8531. if (n->nredir.redirect)
  8532. popredir(/*drop:*/ 0);
  8533. goto setstatus;
  8534. case NCMD:
  8535. evalfn = evalcommand;
  8536. checkexit:
  8537. checkexit = ~flags & EV_TESTED;
  8538. goto calleval;
  8539. case NFOR:
  8540. evalfn = evalfor;
  8541. goto calleval;
  8542. case NWHILE:
  8543. case NUNTIL:
  8544. evalfn = evalloop;
  8545. goto calleval;
  8546. case NSUBSHELL:
  8547. case NBACKGND:
  8548. evalfn = evalsubshell;
  8549. goto checkexit;
  8550. case NPIPE:
  8551. evalfn = evalpipe;
  8552. goto checkexit;
  8553. case NCASE:
  8554. evalfn = evalcase;
  8555. goto calleval;
  8556. case NAND:
  8557. case NOR:
  8558. case NSEMI: {
  8559. #if NAND + 1 != NOR
  8560. #error NAND + 1 != NOR
  8561. #endif
  8562. #if NOR + 1 != NSEMI
  8563. #error NOR + 1 != NSEMI
  8564. #endif
  8565. unsigned is_or = n->type - NAND;
  8566. status = evaltree(
  8567. n->nbinary.ch1,
  8568. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8569. );
  8570. if ((!status) == is_or || evalskip)
  8571. break;
  8572. n = n->nbinary.ch2;
  8573. evaln:
  8574. evalfn = evaltree;
  8575. calleval:
  8576. status = evalfn(n, flags);
  8577. goto setstatus;
  8578. }
  8579. case NIF:
  8580. status = evaltree(n->nif.test, EV_TESTED);
  8581. if (evalskip)
  8582. break;
  8583. if (!status) {
  8584. n = n->nif.ifpart;
  8585. goto evaln;
  8586. } else if (n->nif.elsepart) {
  8587. n = n->nif.elsepart;
  8588. goto evaln;
  8589. }
  8590. status = 0;
  8591. goto setstatus;
  8592. case NDEFUN:
  8593. defun(n);
  8594. /* Not necessary. To test it:
  8595. * "false; f() { qwerty; }; echo $?" should print 0.
  8596. */
  8597. /* status = 0; */
  8598. setstatus:
  8599. exitstatus = status;
  8600. break;
  8601. }
  8602. out:
  8603. /* Order of checks below is important:
  8604. * signal handlers trigger before exit caused by "set -e".
  8605. */
  8606. dotrap();
  8607. if (checkexit && status) {
  8608. if (trap[NTRAP_ERR] && !in_trap_ERR) {
  8609. int err;
  8610. struct jmploc *volatile savehandler = exception_handler;
  8611. struct jmploc jmploc;
  8612. in_trap_ERR = 1;
  8613. trap_depth++;
  8614. err = setjmp(jmploc.loc);
  8615. if (!err) {
  8616. exception_handler = &jmploc;
  8617. savestatus = exitstatus;
  8618. evalstring(trap[NTRAP_ERR], 0);
  8619. }
  8620. trap_depth--;
  8621. in_trap_ERR = 0;
  8622. exception_handler = savehandler;
  8623. if (err && exception_type != EXERROR)
  8624. longjmp(exception_handler->loc, 1);
  8625. exitstatus = savestatus;
  8626. }
  8627. if (eflag)
  8628. goto exexit;
  8629. }
  8630. if (flags & EV_EXIT) {
  8631. exexit:
  8632. raise_exception(EXEND); /* does not return */
  8633. }
  8634. popstackmark(&smark);
  8635. TRACE(("leaving evaltree (no interrupts)\n"));
  8636. return exitstatus;
  8637. }
  8638. static int
  8639. skiploop(void)
  8640. {
  8641. int skip = evalskip;
  8642. switch (skip) {
  8643. case 0:
  8644. break;
  8645. case SKIPBREAK:
  8646. case SKIPCONT:
  8647. if (--skipcount <= 0) {
  8648. evalskip = 0;
  8649. break;
  8650. }
  8651. skip = SKIPBREAK;
  8652. break;
  8653. }
  8654. return skip;
  8655. }
  8656. static int
  8657. evalloop(union node *n, int flags)
  8658. {
  8659. int skip;
  8660. int status;
  8661. loopnest++;
  8662. status = 0;
  8663. flags &= EV_TESTED;
  8664. do {
  8665. int i;
  8666. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8667. skip = skiploop();
  8668. if (skip == SKIPFUNC)
  8669. status = i;
  8670. if (skip)
  8671. continue;
  8672. if (n->type != NWHILE)
  8673. i = !i;
  8674. if (i != 0)
  8675. break;
  8676. status = evaltree(n->nbinary.ch2, flags);
  8677. skip = skiploop();
  8678. } while (!(skip & ~SKIPCONT));
  8679. loopnest--;
  8680. return status;
  8681. }
  8682. static int
  8683. evalfor(union node *n, int flags)
  8684. {
  8685. struct arglist arglist;
  8686. union node *argp;
  8687. struct strlist *sp;
  8688. int status = 0;
  8689. errlinno = lineno = n->ncase.linno;
  8690. arglist.list = NULL;
  8691. arglist.lastp = &arglist.list;
  8692. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8693. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8694. }
  8695. *arglist.lastp = NULL;
  8696. loopnest++;
  8697. flags &= EV_TESTED;
  8698. for (sp = arglist.list; sp; sp = sp->next) {
  8699. setvar0(n->nfor.var, sp->text);
  8700. status = evaltree(n->nfor.body, flags);
  8701. if (skiploop() & ~SKIPCONT)
  8702. break;
  8703. }
  8704. loopnest--;
  8705. return status;
  8706. }
  8707. static int
  8708. evalcase(union node *n, int flags)
  8709. {
  8710. union node *cp;
  8711. union node *patp;
  8712. struct arglist arglist;
  8713. int status = 0;
  8714. errlinno = lineno = n->ncase.linno;
  8715. arglist.list = NULL;
  8716. arglist.lastp = &arglist.list;
  8717. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8718. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8719. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8720. if (casematch(patp, arglist.list->text)) {
  8721. /* Ensure body is non-empty as otherwise
  8722. * EV_EXIT may prevent us from setting the
  8723. * exit status.
  8724. */
  8725. if (evalskip == 0 && cp->nclist.body) {
  8726. status = evaltree(cp->nclist.body, flags);
  8727. }
  8728. goto out;
  8729. }
  8730. }
  8731. }
  8732. out:
  8733. return status;
  8734. }
  8735. /*
  8736. * Kick off a subshell to evaluate a tree.
  8737. */
  8738. static int
  8739. evalsubshell(union node *n, int flags)
  8740. {
  8741. struct job *jp;
  8742. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8743. int status;
  8744. errlinno = lineno = n->nredir.linno;
  8745. expredir(n->nredir.redirect);
  8746. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8747. goto nofork;
  8748. INT_OFF;
  8749. if (backgnd == FORK_FG)
  8750. get_tty_state();
  8751. jp = makejob(/*n,*/ 1);
  8752. if (forkshell(jp, n, backgnd) == 0) {
  8753. /* child */
  8754. INT_ON;
  8755. flags |= EV_EXIT;
  8756. if (backgnd)
  8757. flags &= ~EV_TESTED;
  8758. nofork:
  8759. redirect(n->nredir.redirect, 0);
  8760. evaltreenr(n->nredir.n, flags);
  8761. /* never returns */
  8762. }
  8763. /* parent */
  8764. status = 0;
  8765. if (backgnd == FORK_FG)
  8766. status = waitforjob(jp);
  8767. INT_ON;
  8768. return status;
  8769. }
  8770. /*
  8771. * Compute the names of the files in a redirection list.
  8772. */
  8773. static void fixredir(union node *, const char *, int);
  8774. static void
  8775. expredir(union node *n)
  8776. {
  8777. union node *redir;
  8778. for (redir = n; redir; redir = redir->nfile.next) {
  8779. struct arglist fn;
  8780. fn.list = NULL;
  8781. fn.lastp = &fn.list;
  8782. switch (redir->type) {
  8783. case NFROMTO:
  8784. case NFROM:
  8785. case NTO:
  8786. #if BASH_REDIR_OUTPUT
  8787. case NTO2:
  8788. #endif
  8789. case NCLOBBER:
  8790. case NAPPEND:
  8791. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8792. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8793. #if BASH_REDIR_OUTPUT
  8794. store_expfname:
  8795. #endif
  8796. #if 0
  8797. // By the design of stack allocator, the loop of this kind:
  8798. // while true; do while true; do break; done </dev/null; done
  8799. // will look like a memory leak: ash plans to free expfname's
  8800. // of "/dev/null" as soon as it finishes running the loop
  8801. // (in this case, never).
  8802. // This "fix" is wrong:
  8803. if (redir->nfile.expfname)
  8804. stunalloc(redir->nfile.expfname);
  8805. // It results in corrupted state of stacked allocations.
  8806. #endif
  8807. redir->nfile.expfname = fn.list->text;
  8808. break;
  8809. case NFROMFD:
  8810. case NTOFD: /* >& */
  8811. if (redir->ndup.vname) {
  8812. expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
  8813. if (fn.list == NULL)
  8814. ash_msg_and_raise_error("redir error");
  8815. #if BASH_REDIR_OUTPUT
  8816. if (!isdigit_str(fn.list->text)) {
  8817. /* >&file, not >&fd */
  8818. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8819. ash_msg_and_raise_error("redir error");
  8820. redir->type = NTO2;
  8821. goto store_expfname;
  8822. }
  8823. #endif
  8824. fixredir(redir, fn.list->text, 1);
  8825. }
  8826. break;
  8827. }
  8828. }
  8829. }
  8830. /*
  8831. * Evaluate a pipeline. All the processes in the pipeline are children
  8832. * of the process creating the pipeline. (This differs from some versions
  8833. * of the shell, which make the last process in a pipeline the parent
  8834. * of all the rest.)
  8835. */
  8836. static int
  8837. evalpipe(union node *n, int flags)
  8838. {
  8839. struct job *jp;
  8840. struct nodelist *lp;
  8841. int pipelen;
  8842. int prevfd;
  8843. int pip[2];
  8844. int status = 0;
  8845. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8846. pipelen = 0;
  8847. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8848. pipelen++;
  8849. flags |= EV_EXIT;
  8850. INT_OFF;
  8851. if (n->npipe.pipe_backgnd == 0)
  8852. get_tty_state();
  8853. jp = makejob(/*n,*/ pipelen);
  8854. prevfd = -1;
  8855. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8856. prehash(lp->n);
  8857. pip[1] = -1;
  8858. if (lp->next) {
  8859. if (pipe(pip) < 0) {
  8860. close(prevfd);
  8861. ash_msg_and_raise_perror("can't create pipe");
  8862. }
  8863. }
  8864. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8865. /* child */
  8866. INT_ON;
  8867. if (pip[1] >= 0) {
  8868. close(pip[0]);
  8869. }
  8870. if (prevfd > 0) {
  8871. dup2(prevfd, 0);
  8872. close(prevfd);
  8873. }
  8874. if (pip[1] > 1) {
  8875. dup2(pip[1], 1);
  8876. close(pip[1]);
  8877. }
  8878. evaltreenr(lp->n, flags);
  8879. /* never returns */
  8880. }
  8881. /* parent */
  8882. if (prevfd >= 0)
  8883. close(prevfd);
  8884. prevfd = pip[0];
  8885. /* Don't want to trigger debugging */
  8886. if (pip[1] != -1)
  8887. close(pip[1]);
  8888. }
  8889. if (n->npipe.pipe_backgnd == 0) {
  8890. status = waitforjob(jp);
  8891. TRACE(("evalpipe: job done exit status %d\n", status));
  8892. }
  8893. INT_ON;
  8894. return status;
  8895. }
  8896. /* setinteractive needs this forward reference */
  8897. #if ENABLE_FEATURE_TAB_COMPLETION
  8898. static const char *ash_command_name(int i) FAST_FUNC;
  8899. #endif
  8900. /*
  8901. * Controls whether the shell is interactive or not.
  8902. */
  8903. static void
  8904. setinteractive(int on)
  8905. {
  8906. static smallint is_interactive;
  8907. if (++on == is_interactive)
  8908. return;
  8909. is_interactive = on;
  8910. setsignal(SIGINT);
  8911. setsignal(SIGQUIT);
  8912. setsignal(SIGTERM);
  8913. if (is_interactive > 1) {
  8914. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8915. /* Looks like they want an interactive shell */
  8916. static smallint did_banner;
  8917. if (!did_banner) {
  8918. /* note: ash and hush share this string */
  8919. out1fmt("\n\n%s %s\n"
  8920. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8921. "\n",
  8922. bb_banner,
  8923. "built-in shell (ash)"
  8924. );
  8925. did_banner = 1;
  8926. }
  8927. #endif
  8928. #if ENABLE_FEATURE_EDITING
  8929. if (!line_input_state) {
  8930. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  8931. # if ENABLE_FEATURE_TAB_COMPLETION
  8932. line_input_state->get_exe_name = ash_command_name;
  8933. # endif
  8934. # if EDITING_HAS_sh_get_var
  8935. line_input_state->sh_get_var = lookupvar;
  8936. # endif
  8937. }
  8938. #endif
  8939. }
  8940. }
  8941. static void
  8942. optschanged(void)
  8943. {
  8944. #if DEBUG
  8945. opentrace();
  8946. #endif
  8947. setinteractive(iflag);
  8948. setjobctl(mflag);
  8949. #if ENABLE_FEATURE_EDITING_VI
  8950. if (line_input_state) {
  8951. if (viflag)
  8952. line_input_state->flags |= VI_MODE;
  8953. else
  8954. line_input_state->flags &= ~VI_MODE;
  8955. }
  8956. #else
  8957. viflag = 0; /* forcibly keep the option off */
  8958. #endif
  8959. }
  8960. struct localvar_list {
  8961. struct localvar_list *next;
  8962. struct localvar *lv;
  8963. };
  8964. static struct localvar_list *localvar_stack;
  8965. /*
  8966. * Called after a function returns.
  8967. * Interrupts must be off.
  8968. */
  8969. static void
  8970. poplocalvars(int keep)
  8971. {
  8972. struct localvar_list *ll;
  8973. struct localvar *lvp, *next;
  8974. struct var *vp;
  8975. INT_OFF;
  8976. ll = localvar_stack;
  8977. localvar_stack = ll->next;
  8978. next = ll->lv;
  8979. free(ll);
  8980. while ((lvp = next) != NULL) {
  8981. next = lvp->next;
  8982. vp = lvp->vp;
  8983. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8984. if (keep) {
  8985. int bits = VSTRFIXED;
  8986. if (lvp->flags != VUNSET) {
  8987. if (vp->var_text == lvp->text)
  8988. bits |= VTEXTFIXED;
  8989. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8990. free((char*)lvp->text);
  8991. }
  8992. vp->flags &= ~bits;
  8993. vp->flags |= (lvp->flags & bits);
  8994. if ((vp->flags &
  8995. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8996. unsetvar(vp->var_text);
  8997. } else if (vp == NULL) { /* $- saved */
  8998. memcpy(optlist, lvp->text, sizeof(optlist));
  8999. free((char*)lvp->text);
  9000. optschanged();
  9001. } else if (lvp->flags == VUNSET) {
  9002. vp->flags &= ~(VSTRFIXED|VREADONLY);
  9003. unsetvar(vp->var_text);
  9004. } else {
  9005. if (vp->var_func)
  9006. vp->var_func(var_end(lvp->text));
  9007. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  9008. free((char*)vp->var_text);
  9009. vp->flags = lvp->flags;
  9010. vp->var_text = lvp->text;
  9011. }
  9012. free(lvp);
  9013. }
  9014. INT_ON;
  9015. }
  9016. /*
  9017. * Create a new localvar environment.
  9018. */
  9019. static struct localvar_list *
  9020. pushlocalvars(int push)
  9021. {
  9022. struct localvar_list *ll;
  9023. struct localvar_list *top;
  9024. top = localvar_stack;
  9025. if (!push)
  9026. goto out;
  9027. INT_OFF;
  9028. ll = ckzalloc(sizeof(*ll));
  9029. /*ll->lv = NULL; - zalloc did it */
  9030. ll->next = top;
  9031. localvar_stack = ll;
  9032. INT_ON;
  9033. out:
  9034. return top;
  9035. }
  9036. static void
  9037. unwindlocalvars(struct localvar_list *stop)
  9038. {
  9039. while (localvar_stack != stop)
  9040. poplocalvars(0);
  9041. }
  9042. static int
  9043. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  9044. {
  9045. volatile struct shparam saveparam;
  9046. struct jmploc *volatile savehandler;
  9047. struct jmploc jmploc;
  9048. int e;
  9049. int savelineno;
  9050. int savefuncline;
  9051. char *savefuncname;
  9052. char *savetrap = NULL;
  9053. if (!Eflag) {
  9054. savetrap = trap[NTRAP_ERR];
  9055. trap[NTRAP_ERR] = NULL;
  9056. }
  9057. savelineno = lineno;
  9058. saveparam = shellparam;
  9059. savefuncline = funcline;
  9060. savefuncname = funcname;
  9061. savehandler = exception_handler;
  9062. e = setjmp(jmploc.loc);
  9063. if (e) {
  9064. goto funcdone;
  9065. }
  9066. INT_OFF;
  9067. exception_handler = &jmploc;
  9068. shellparam.malloced = 0;
  9069. func->count++;
  9070. funcname = func->n.ndefun.text;
  9071. funcline = func->n.ndefun.linno;
  9072. INT_ON;
  9073. shellparam.nparam = argc - 1;
  9074. shellparam.p = argv + 1;
  9075. #if ENABLE_ASH_GETOPTS
  9076. shellparam.optind = 1;
  9077. shellparam.optoff = -1;
  9078. #endif
  9079. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  9080. funcdone:
  9081. INT_OFF;
  9082. funcname = savefuncname;
  9083. if (savetrap) {
  9084. if (!trap[NTRAP_ERR])
  9085. trap[NTRAP_ERR] = savetrap;
  9086. else
  9087. free(savetrap);
  9088. }
  9089. funcline = savefuncline;
  9090. lineno = savelineno;
  9091. freefunc(func);
  9092. freeparam(&shellparam);
  9093. shellparam = saveparam;
  9094. exception_handler = savehandler;
  9095. INT_ON;
  9096. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  9097. return e;
  9098. }
  9099. /*
  9100. * Make a variable a local variable. When a variable is made local, it's
  9101. * value and flags are saved in a localvar structure. The saved values
  9102. * will be restored when the shell function returns. We handle the name
  9103. * "-" as a special case: it makes changes to "set +-options" local
  9104. * (options will be restored on return from the function).
  9105. */
  9106. static void
  9107. mklocal(char *name, int flags)
  9108. {
  9109. struct localvar *lvp;
  9110. struct var *vp;
  9111. char *eq = strchr(name, '=');
  9112. INT_OFF;
  9113. /* Cater for duplicate "local". Examples:
  9114. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  9115. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  9116. */
  9117. lvp = localvar_stack->lv;
  9118. while (lvp) {
  9119. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  9120. if (eq)
  9121. setvareq(name, 0);
  9122. /* else:
  9123. * it's a duplicate "local VAR" declaration, do nothing
  9124. */
  9125. goto ret;
  9126. }
  9127. lvp = lvp->next;
  9128. }
  9129. lvp = ckzalloc(sizeof(*lvp));
  9130. if (LONE_DASH(name)) {
  9131. char *p;
  9132. p = ckmalloc(sizeof(optlist));
  9133. lvp->text = memcpy(p, optlist, sizeof(optlist));
  9134. vp = NULL;
  9135. } else {
  9136. vp = *findvar(name);
  9137. if (vp == NULL) {
  9138. /* variable did not exist yet */
  9139. if (eq)
  9140. vp = setvareq(name, VSTRFIXED | flags);
  9141. else
  9142. vp = setvar(name, NULL, VSTRFIXED | flags);
  9143. lvp->flags = VUNSET;
  9144. } else {
  9145. lvp->text = vp->var_text;
  9146. lvp->flags = vp->flags;
  9147. /* make sure neither "struct var" nor string gets freed
  9148. * during (un)setting:
  9149. */
  9150. vp->flags |= VSTRFIXED|VTEXTFIXED;
  9151. if (eq)
  9152. setvareq(name, flags);
  9153. else
  9154. /* "local VAR" unsets VAR: */
  9155. unsetvar(name);
  9156. }
  9157. }
  9158. lvp->vp = vp;
  9159. lvp->next = localvar_stack->lv;
  9160. localvar_stack->lv = lvp;
  9161. ret:
  9162. INT_ON;
  9163. }
  9164. /*
  9165. * The "local" command.
  9166. */
  9167. static int FAST_FUNC
  9168. localcmd(int argc UNUSED_PARAM, char **argv)
  9169. {
  9170. char *name;
  9171. if (!localvar_stack)
  9172. ash_msg_and_raise_error("not in a function");
  9173. argv = argptr;
  9174. while ((name = *argv++) != NULL) {
  9175. mklocal(name, 0);
  9176. }
  9177. return 0;
  9178. }
  9179. static int FAST_FUNC
  9180. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9181. {
  9182. return 1;
  9183. }
  9184. static int FAST_FUNC
  9185. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9186. {
  9187. return 0;
  9188. }
  9189. static int FAST_FUNC
  9190. execcmd(int argc UNUSED_PARAM, char **argv)
  9191. {
  9192. optionarg = NULL;
  9193. while (nextopt("a:") != '\0')
  9194. /* nextopt() sets optionarg to "-a ARGV0" */;
  9195. argv = argptr;
  9196. if (argv[0]) {
  9197. char *prog;
  9198. iflag = 0; /* exit on error */
  9199. mflag = 0;
  9200. optschanged();
  9201. /* We should set up signals for "exec CMD"
  9202. * the same way as for "CMD" without "exec".
  9203. * But optschanged->setinteractive->setsignal
  9204. * still thought we are a root shell. Therefore, for example,
  9205. * SIGQUIT is still set to IGN. Fix it:
  9206. */
  9207. shlvl++;
  9208. setsignal(SIGQUIT);
  9209. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  9210. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  9211. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  9212. prog = argv[0];
  9213. if (optionarg)
  9214. argv[0] = optionarg;
  9215. shellexec(prog, argv, pathval(), 0);
  9216. /* NOTREACHED */
  9217. }
  9218. return 0;
  9219. }
  9220. /*
  9221. * The return command.
  9222. */
  9223. static int FAST_FUNC
  9224. returncmd(int argc UNUSED_PARAM, char **argv)
  9225. {
  9226. int skip;
  9227. int status;
  9228. /*
  9229. * If called outside a function, do what ksh does;
  9230. * skip the rest of the file.
  9231. */
  9232. if (argv[1]) {
  9233. skip = SKIPFUNC;
  9234. status = number(argv[1]);
  9235. } else {
  9236. skip = SKIPFUNCDEF;
  9237. status = exitstatus;
  9238. }
  9239. evalskip = skip;
  9240. return status;
  9241. }
  9242. /* Forward declarations for builtintab[] */
  9243. static int breakcmd(int, char **) FAST_FUNC;
  9244. static int dotcmd(int, char **) FAST_FUNC;
  9245. static int evalcmd(int, char **, int) FAST_FUNC;
  9246. static int exitcmd(int, char **) FAST_FUNC;
  9247. static int exportcmd(int, char **) FAST_FUNC;
  9248. #if ENABLE_ASH_GETOPTS
  9249. static int getoptscmd(int, char **) FAST_FUNC;
  9250. #endif
  9251. #if ENABLE_ASH_HELP
  9252. static int helpcmd(int, char **) FAST_FUNC;
  9253. #endif
  9254. #if MAX_HISTORY
  9255. static int historycmd(int, char **) FAST_FUNC;
  9256. #endif
  9257. #if ENABLE_FEATURE_SH_MATH
  9258. static int letcmd(int, char **) FAST_FUNC;
  9259. #endif
  9260. static int readcmd(int, char **) FAST_FUNC;
  9261. static int setcmd(int, char **) FAST_FUNC;
  9262. static int shiftcmd(int, char **) FAST_FUNC;
  9263. static int timescmd(int, char **) FAST_FUNC;
  9264. static int trapcmd(int, char **) FAST_FUNC;
  9265. static int umaskcmd(int, char **) FAST_FUNC;
  9266. static int unsetcmd(int, char **) FAST_FUNC;
  9267. static int ulimitcmd(int, char **) FAST_FUNC;
  9268. #define BUILTIN_NOSPEC "0"
  9269. #define BUILTIN_SPECIAL "1"
  9270. #define BUILTIN_REGULAR "2"
  9271. #define BUILTIN_SPEC_REG "3"
  9272. #define BUILTIN_ASSIGN "4"
  9273. #define BUILTIN_SPEC_ASSG "5"
  9274. #define BUILTIN_REG_ASSG "6"
  9275. #define BUILTIN_SPEC_REG_ASSG "7"
  9276. /* Stubs for calling non-FAST_FUNC's */
  9277. #if ENABLE_ASH_ECHO
  9278. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  9279. #endif
  9280. #if ENABLE_ASH_PRINTF
  9281. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  9282. #endif
  9283. #if ENABLE_ASH_TEST || BASH_TEST2
  9284. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main2(&groupinfo, argc, argv); }
  9285. #endif
  9286. #if ENABLE_ASH_SLEEP
  9287. static int FAST_FUNC sleepcmd(int argc, char **argv) { return sleep_main(argc, argv); }
  9288. #endif
  9289. /* Keep these in proper order since it is searched via bsearch() */
  9290. static const struct builtincmd builtintab[] = {
  9291. { BUILTIN_SPEC_REG "." , dotcmd },
  9292. { BUILTIN_SPEC_REG ":" , truecmd },
  9293. #if ENABLE_ASH_TEST
  9294. { BUILTIN_REGULAR "[" , testcmd },
  9295. #endif
  9296. #if BASH_TEST2
  9297. { BUILTIN_REGULAR "[[" , testcmd },
  9298. #endif
  9299. #if ENABLE_ASH_ALIAS
  9300. { BUILTIN_REG_ASSG "alias" , aliascmd },
  9301. #endif
  9302. #if JOBS
  9303. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  9304. #endif
  9305. { BUILTIN_SPEC_REG "break" , breakcmd },
  9306. { BUILTIN_REGULAR "cd" , cdcmd },
  9307. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9308. #if ENABLE_ASH_CMDCMD
  9309. { BUILTIN_REGULAR "command" , commandcmd },
  9310. #endif
  9311. { BUILTIN_SPEC_REG "continue", breakcmd },
  9312. #if ENABLE_ASH_ECHO
  9313. { BUILTIN_REGULAR "echo" , echocmd },
  9314. #endif
  9315. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9316. { BUILTIN_SPEC_REG "exec" , execcmd },
  9317. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9318. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9319. { BUILTIN_REGULAR "false" , falsecmd },
  9320. #if JOBS
  9321. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9322. #endif
  9323. #if ENABLE_ASH_GETOPTS
  9324. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9325. #endif
  9326. { BUILTIN_REGULAR "hash" , hashcmd },
  9327. #if ENABLE_ASH_HELP
  9328. { BUILTIN_NOSPEC "help" , helpcmd },
  9329. #endif
  9330. #if MAX_HISTORY
  9331. { BUILTIN_NOSPEC "history" , historycmd },
  9332. #endif
  9333. #if JOBS
  9334. { BUILTIN_REGULAR "jobs" , jobscmd },
  9335. { BUILTIN_REGULAR "kill" , killcmd },
  9336. #endif
  9337. #if ENABLE_FEATURE_SH_MATH
  9338. { BUILTIN_NOSPEC "let" , letcmd },
  9339. #endif
  9340. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9341. #if ENABLE_ASH_PRINTF
  9342. { BUILTIN_REGULAR "printf" , printfcmd },
  9343. #endif
  9344. { BUILTIN_REGULAR "pwd" , pwdcmd },
  9345. { BUILTIN_REGULAR "read" , readcmd },
  9346. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9347. { BUILTIN_SPEC_REG "return" , returncmd },
  9348. { BUILTIN_SPEC_REG "set" , setcmd },
  9349. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9350. #if ENABLE_ASH_SLEEP
  9351. { BUILTIN_REGULAR "sleep" , sleepcmd },
  9352. #endif
  9353. #if BASH_SOURCE
  9354. { BUILTIN_SPEC_REG "source" , dotcmd },
  9355. #endif
  9356. #if ENABLE_ASH_TEST
  9357. { BUILTIN_REGULAR "test" , testcmd },
  9358. #endif
  9359. { BUILTIN_SPEC_REG "times" , timescmd },
  9360. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9361. { BUILTIN_REGULAR "true" , truecmd },
  9362. { BUILTIN_REGULAR "type" , typecmd },
  9363. { BUILTIN_REGULAR "ulimit" , ulimitcmd },
  9364. { BUILTIN_REGULAR "umask" , umaskcmd },
  9365. #if ENABLE_ASH_ALIAS
  9366. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9367. #endif
  9368. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9369. { BUILTIN_REGULAR "wait" , waitcmd },
  9370. };
  9371. /* Should match the above table! */
  9372. #define COMMANDCMD (builtintab + \
  9373. /* . : */ 2 + \
  9374. /* [ */ 1 * ENABLE_ASH_TEST + \
  9375. /* [[ */ 1 * BASH_TEST2 + \
  9376. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9377. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9378. /* break cd cddir */ 3)
  9379. #define EVALCMD (COMMANDCMD + \
  9380. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9381. /* continue */ 1 + \
  9382. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9383. 0)
  9384. #define EXECCMD (EVALCMD + \
  9385. /* eval */ 1)
  9386. /*
  9387. * Search the table of builtin commands.
  9388. */
  9389. static int
  9390. pstrcmp1(const void *a, const void *b)
  9391. {
  9392. return strcmp((char*)a, *(char**)b + 1);
  9393. }
  9394. static struct builtincmd *
  9395. find_builtin(const char *name)
  9396. {
  9397. struct builtincmd *bp;
  9398. bp = bsearch(
  9399. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9400. pstrcmp1
  9401. );
  9402. return bp;
  9403. }
  9404. #if ENABLE_FEATURE_TAB_COMPLETION
  9405. static const char * FAST_FUNC
  9406. ash_command_name(int i)
  9407. {
  9408. int n;
  9409. if (/*i >= 0 &&*/ i < ARRAY_SIZE(builtintab))
  9410. return builtintab[i].name + 1;
  9411. i -= ARRAY_SIZE(builtintab);
  9412. for (n = 0; n < CMDTABLESIZE; n++) {
  9413. struct tblentry *cmdp;
  9414. for (cmdp = cmdtable[n]; cmdp; cmdp = cmdp->next) {
  9415. if (cmdp->cmdtype == CMDFUNCTION && --i < 0)
  9416. return cmdp->cmdname;
  9417. }
  9418. }
  9419. # if ENABLE_ASH_ALIAS
  9420. for (n = 0; n < ATABSIZE; n++) {
  9421. struct alias *ap;
  9422. for (ap = atab[n]; ap; ap = ap->next) {
  9423. if (--i < 0)
  9424. return ap->name;
  9425. }
  9426. }
  9427. #endif
  9428. return NULL;
  9429. }
  9430. #endif
  9431. /*
  9432. * Execute a simple command.
  9433. */
  9434. static void unwindfiles(struct parsefile *stop);
  9435. static int
  9436. isassignment(const char *p)
  9437. {
  9438. const char *q = endofname(p);
  9439. if (p == q)
  9440. return 0;
  9441. return *q == '=';
  9442. }
  9443. static int FAST_FUNC
  9444. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9445. {
  9446. /* Preserve exitstatus of a previous possible redirection
  9447. * as POSIX mandates */
  9448. return back_exitstatus;
  9449. }
  9450. static int
  9451. evalcommand(union node *cmd, int flags)
  9452. {
  9453. static const struct builtincmd null_bltin = {
  9454. BUILTIN_REGULAR "", bltincmd
  9455. };
  9456. struct localvar_list *localvar_stop;
  9457. struct parsefile *file_stop;
  9458. struct redirtab *redir_stop;
  9459. union node *argp;
  9460. struct arglist arglist;
  9461. struct arglist varlist;
  9462. char **argv;
  9463. int argc;
  9464. struct strlist *osp;
  9465. const struct strlist *sp;
  9466. struct cmdentry cmdentry;
  9467. struct job *jp;
  9468. char *lastarg;
  9469. const char *path;
  9470. int spclbltin;
  9471. int cmd_flag;
  9472. int status;
  9473. char **nargv;
  9474. smallint cmd_is_exec;
  9475. int vflags;
  9476. int vlocal;
  9477. errlinno = lineno = cmd->ncmd.linno;
  9478. /* First expand the arguments. */
  9479. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9480. #if BASH_PROCESS_SUBST
  9481. redir_stop = redirlist;
  9482. #endif
  9483. file_stop = g_parsefile;
  9484. back_exitstatus = 0;
  9485. cmdentry.cmdtype = CMDBUILTIN;
  9486. cmdentry.u.cmd = &null_bltin;
  9487. varlist.lastp = &varlist.list;
  9488. *varlist.lastp = NULL;
  9489. arglist.lastp = &arglist.list;
  9490. *arglist.lastp = NULL;
  9491. cmd_flag = 0;
  9492. cmd_is_exec = 0;
  9493. spclbltin = -1;
  9494. vflags = 0;
  9495. vlocal = 0;
  9496. path = NULL;
  9497. argc = 0;
  9498. argp = cmd->ncmd.args;
  9499. osp = fill_arglist(&arglist, &argp);
  9500. if (osp) {
  9501. int pseudovarflag = 0;
  9502. for (;;) {
  9503. find_command(arglist.list->text, &cmdentry,
  9504. cmd_flag | DO_REGBLTIN, pathval());
  9505. vlocal++;
  9506. /* implement bltin and command here */
  9507. if (cmdentry.cmdtype != CMDBUILTIN)
  9508. break;
  9509. pseudovarflag = IS_BUILTIN_ASSIGN(cmdentry.u.cmd);
  9510. if (spclbltin < 0) {
  9511. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9512. vlocal = !spclbltin;
  9513. }
  9514. cmd_is_exec = cmdentry.u.cmd == EXECCMD;
  9515. #if ENABLE_ASH_CMDCMD
  9516. if (cmdentry.u.cmd != COMMANDCMD)
  9517. break;
  9518. cmd_flag = parse_command_args(&arglist, &argp, &path);
  9519. if (!cmd_flag)
  9520. #endif
  9521. break;
  9522. }
  9523. for (; argp; argp = argp->narg.next)
  9524. expandarg(argp, &arglist,
  9525. pseudovarflag &&
  9526. isassignment(argp->narg.text) ?
  9527. EXP_VARTILDE : EXP_FULL | EXP_TILDE);
  9528. for (sp = arglist.list; sp; sp = sp->next)
  9529. argc++;
  9530. if (cmd_is_exec && argc > 1)
  9531. vflags = VEXPORT;
  9532. }
  9533. localvar_stop = pushlocalvars(vlocal);
  9534. /* Reserve one extra spot at the front for shellexec. */
  9535. nargv = stalloc(sizeof(char *) * (argc + 2));
  9536. argv = ++nargv;
  9537. for (sp = arglist.list; sp; sp = sp->next) {
  9538. TRACE(("evalcommand arg: %s\n", sp->text));
  9539. *nargv++ = sp->text;
  9540. }
  9541. *nargv = NULL;
  9542. lastarg = NULL;
  9543. if (iflag && funcline == 0 && argc > 0)
  9544. lastarg = nargv[-1];
  9545. expredir(cmd->ncmd.redirect);
  9546. #if !BASH_PROCESS_SUBST
  9547. redir_stop = pushredir(cmd->ncmd.redirect);
  9548. #else
  9549. pushredir(cmd->ncmd.redirect);
  9550. #endif
  9551. preverrout_fd = 2;
  9552. if (BASH_XTRACEFD && xflag) {
  9553. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9554. * we do not emulate this. We only use its value.
  9555. */
  9556. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9557. if (xtracefd && is_number(xtracefd))
  9558. preverrout_fd = atoi(xtracefd);
  9559. }
  9560. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9561. if (status) {
  9562. bail:
  9563. exitstatus = status;
  9564. /* We have a redirection error. */
  9565. if (spclbltin > 0)
  9566. raise_exception(EXERROR); /* does not return */
  9567. goto out;
  9568. }
  9569. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9570. struct strlist **spp;
  9571. spp = varlist.lastp;
  9572. expandarg(argp, &varlist, EXP_VARTILDE);
  9573. if (vlocal)
  9574. mklocal((*spp)->text, VEXPORT);
  9575. else
  9576. setvareq((*spp)->text, vflags);
  9577. }
  9578. /* Print the command if xflag is set. */
  9579. if (xflag && !inps4) {
  9580. const char *pfx = "";
  9581. inps4 = 1;
  9582. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9583. inps4 = 0;
  9584. sp = varlist.list;
  9585. while (sp) {
  9586. char *varval = sp->text;
  9587. char *eq = strchrnul(varval, '=');
  9588. if (*eq)
  9589. eq++;
  9590. fdprintf(preverrout_fd, "%s%.*s%s",
  9591. pfx,
  9592. (int)(eq - varval), varval,
  9593. maybe_single_quote(eq)
  9594. );
  9595. sp = sp->next;
  9596. pfx = " ";
  9597. }
  9598. sp = arglist.list;
  9599. while (sp) {
  9600. fdprintf(preverrout_fd, "%s%s",
  9601. pfx,
  9602. /* always quote if matches reserved word: */
  9603. findkwd(sp->text)
  9604. ? single_quote(sp->text)
  9605. : maybe_single_quote(sp->text)
  9606. );
  9607. sp = sp->next;
  9608. pfx = " ";
  9609. }
  9610. safe_write(preverrout_fd, "\n", 1);
  9611. }
  9612. /* Now locate the command. */
  9613. if (cmdentry.cmdtype != CMDBUILTIN
  9614. || !(IS_BUILTIN_REGULAR(cmdentry.u.cmd))
  9615. ) {
  9616. path = path ? path : pathval();
  9617. find_command(argv[0], &cmdentry, cmd_flag | DO_ERR, path);
  9618. }
  9619. jp = NULL;
  9620. /* Execute the command. */
  9621. switch (cmdentry.cmdtype) {
  9622. case CMDUNKNOWN:
  9623. status = 127;
  9624. flush_stdout_stderr();
  9625. goto bail;
  9626. default: {
  9627. #if ENABLE_FEATURE_SH_STANDALONE \
  9628. && ENABLE_FEATURE_SH_NOFORK \
  9629. && NUM_APPLETS > 1
  9630. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9631. * around run_nofork_applet() call.
  9632. * (2) Should this check also be done in forkshell()?
  9633. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9634. */
  9635. /* find_command() encodes applet_no as (-2 - applet_no) */
  9636. int applet_no = (- cmdentry.u.index - 2);
  9637. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9638. char **sv_environ;
  9639. INT_OFF;
  9640. sv_environ = environ;
  9641. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9642. /*
  9643. * Run <applet>_main().
  9644. * Signals (^C) can't interrupt here.
  9645. * Otherwise we can mangle stdio or malloc internal state.
  9646. * This makes applets which can run for a long time
  9647. * and/or wait for user input ineligible for NOFORK:
  9648. * for example, "yes" or "rm" (rm -i waits for input).
  9649. */
  9650. exitstatus = run_nofork_applet(applet_no, argv);
  9651. environ = sv_environ;
  9652. /*
  9653. * Try enabling NOFORK for "yes" applet.
  9654. * ^C _will_ stop it (write returns EINTR),
  9655. * but this causes stdout FILE to be stuck
  9656. * and needing clearerr(). What if other applets
  9657. * also can get EINTRs? Do we need to switch
  9658. * our signals to SA_RESTART?
  9659. */
  9660. /*clearerr(stdout);*/
  9661. INT_ON;
  9662. break;
  9663. }
  9664. #endif
  9665. /* Can we avoid forking? For example, very last command
  9666. * in a script or a subshell does not need forking,
  9667. * we can just exec it.
  9668. */
  9669. if (!(flags & EV_EXIT) || may_have_traps) {
  9670. /* No, forking off a child is necessary */
  9671. INT_OFF;
  9672. get_tty_state();
  9673. jp = makejob(/*cmd,*/ 1);
  9674. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9675. /* parent */
  9676. break;
  9677. }
  9678. /* child */
  9679. FORCE_INT_ON;
  9680. /* fall through to exec'ing external program */
  9681. }
  9682. shellexec(argv[0], argv, path, cmdentry.u.index);
  9683. /* NOTREACHED */
  9684. } /* default */
  9685. case CMDBUILTIN:
  9686. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)
  9687. && !(exception_type == EXERROR && spclbltin <= 0)
  9688. ) {
  9689. raise:
  9690. longjmp(exception_handler->loc, 1);
  9691. }
  9692. break;
  9693. case CMDFUNCTION:
  9694. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9695. goto raise;
  9696. break;
  9697. } /* switch */
  9698. status = waitforjob(jp);
  9699. if (jp)
  9700. TRACE(("forked child exited with %d\n", status));
  9701. FORCE_INT_ON;
  9702. out:
  9703. if (cmd->ncmd.redirect)
  9704. popredir(/*drop:*/ cmd_is_exec);
  9705. unwindredir(redir_stop);
  9706. unwindfiles(file_stop);
  9707. unwindlocalvars(localvar_stop);
  9708. if (lastarg) {
  9709. /* dsl: I think this is intended to be used to support
  9710. * '_' in 'vi' command mode during line editing...
  9711. * However I implemented that within libedit itself.
  9712. */
  9713. setvar0("_", lastarg);
  9714. }
  9715. return status;
  9716. }
  9717. static int
  9718. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9719. {
  9720. char *volatile savecmdname;
  9721. struct jmploc *volatile savehandler;
  9722. struct jmploc jmploc;
  9723. int status;
  9724. int i;
  9725. savecmdname = commandname;
  9726. savehandler = exception_handler;
  9727. i = setjmp(jmploc.loc);
  9728. if (i)
  9729. goto cmddone;
  9730. exception_handler = &jmploc;
  9731. commandname = argv[0];
  9732. argptr = argv + 1;
  9733. optptr = NULL; /* initialize nextopt */
  9734. if (cmd == EVALCMD)
  9735. status = evalcmd(argc, argv, flags);
  9736. else
  9737. status = (*cmd->builtin)(argc, argv);
  9738. flush_stdout_stderr();
  9739. status |= ferror(stdout);
  9740. exitstatus = status;
  9741. cmddone:
  9742. clearerr(stdout);
  9743. commandname = savecmdname;
  9744. exception_handler = savehandler;
  9745. return i;
  9746. }
  9747. static int
  9748. goodname(const char *p)
  9749. {
  9750. return endofname(p)[0] == '\0';
  9751. }
  9752. /*
  9753. * Search for a command. This is called before we fork so that the
  9754. * location of the command will be available in the parent as well as
  9755. * the child. The check for "goodname" is an overly conservative
  9756. * check that the name will not be subject to expansion.
  9757. */
  9758. static void
  9759. prehash(union node *n)
  9760. {
  9761. struct cmdentry entry;
  9762. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9763. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9764. }
  9765. /* ============ Builtin commands
  9766. *
  9767. * Builtin commands whose functions are closely tied to evaluation
  9768. * are implemented here.
  9769. */
  9770. /*
  9771. * Handle break and continue commands. Break, continue, and return are
  9772. * all handled by setting the evalskip flag. The evaluation routines
  9773. * above all check this flag, and if it is set they start skipping
  9774. * commands rather than executing them. The variable skipcount is
  9775. * the number of loops to break/continue, or the number of function
  9776. * levels to return. (The latter is always 1.) It should probably
  9777. * be an error to break out of more loops than exist, but it isn't
  9778. * in the standard shell so we don't make it one here.
  9779. */
  9780. static int FAST_FUNC
  9781. breakcmd(int argc UNUSED_PARAM, char **argv)
  9782. {
  9783. int n = argv[1] ? number(argv[1]) : 1;
  9784. if (n <= 0)
  9785. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9786. if (n > loopnest)
  9787. n = loopnest;
  9788. if (n > 0) {
  9789. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9790. skipcount = n;
  9791. }
  9792. return 0;
  9793. }
  9794. /*
  9795. * This implements the input routines used by the parser.
  9796. */
  9797. enum {
  9798. INPUT_PUSH_FILE = 1,
  9799. INPUT_NOFILE_OK = 2,
  9800. };
  9801. static smallint checkkwd;
  9802. /* values of checkkwd variable */
  9803. #define CHKALIAS 0x1
  9804. #define CHKKWD 0x2
  9805. #define CHKNL 0x4
  9806. #define CHKEOFMARK 0x8
  9807. /*
  9808. * Push a string back onto the input at this current parsefile level.
  9809. * We handle aliases this way.
  9810. */
  9811. #if !ENABLE_ASH_ALIAS
  9812. #define pushstring(s, ap) pushstring(s)
  9813. #endif
  9814. static void
  9815. pushstring(char *s, struct alias *ap)
  9816. {
  9817. struct strpush *sp;
  9818. int len;
  9819. len = strlen(s);
  9820. INT_OFF;
  9821. if (g_parsefile->strpush || g_parsefile->spfree) {
  9822. sp = ckzalloc(sizeof(*sp));
  9823. sp->prev = g_parsefile->strpush;
  9824. } else {
  9825. sp = &(g_parsefile->basestrpush);
  9826. }
  9827. g_parsefile->strpush = sp;
  9828. sp->prev_string = g_parsefile->next_to_pgetc;
  9829. sp->prev_left_in_line = g_parsefile->left_in_line;
  9830. sp->unget = g_parsefile->unget;
  9831. sp->spfree = g_parsefile->spfree;
  9832. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9833. #if ENABLE_ASH_ALIAS
  9834. sp->ap = ap;
  9835. if (ap) {
  9836. ap->flag |= ALIASINUSE;
  9837. sp->string = s;
  9838. }
  9839. #endif
  9840. g_parsefile->next_to_pgetc = s;
  9841. g_parsefile->left_in_line = len;
  9842. g_parsefile->unget = 0;
  9843. g_parsefile->spfree = NULL;
  9844. INT_ON;
  9845. }
  9846. static void popstring(void)
  9847. {
  9848. struct strpush *sp = g_parsefile->strpush;
  9849. INT_OFF;
  9850. #if ENABLE_ASH_ALIAS
  9851. if (sp->ap) {
  9852. if (g_parsefile->next_to_pgetc[-1] == ' '
  9853. || g_parsefile->next_to_pgetc[-1] == '\t'
  9854. ) {
  9855. checkkwd |= CHKALIAS;
  9856. }
  9857. if (sp->string != sp->ap->val) {
  9858. free(sp->string);
  9859. }
  9860. }
  9861. #endif
  9862. g_parsefile->next_to_pgetc = sp->prev_string;
  9863. g_parsefile->left_in_line = sp->prev_left_in_line;
  9864. g_parsefile->unget = sp->unget;
  9865. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9866. g_parsefile->strpush = sp->prev;
  9867. g_parsefile->spfree = sp;
  9868. INT_ON;
  9869. }
  9870. static int
  9871. preadfd(void)
  9872. {
  9873. int nr;
  9874. char *buf = g_parsefile->buf;
  9875. g_parsefile->next_to_pgetc = buf;
  9876. #if ENABLE_FEATURE_EDITING
  9877. /* retry: */
  9878. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9879. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9880. else {
  9881. # if ENABLE_ASH_IDLE_TIMEOUT
  9882. int timeout = -1;
  9883. const char *tmout_var = lookupvar("TMOUT");
  9884. if (tmout_var) {
  9885. timeout = atoi(tmout_var) * 1000;
  9886. if (timeout <= 0)
  9887. timeout = -1;
  9888. }
  9889. line_input_state->timeout = timeout;
  9890. # endif
  9891. # if ENABLE_FEATURE_TAB_COMPLETION
  9892. line_input_state->path_lookup = pathval();
  9893. # endif
  9894. reinit_unicode_for_ash();
  9895. again:
  9896. /* For shell, LI_INTERRUPTIBLE is set:
  9897. * read_line_input will abort on either
  9898. * getting EINTR in poll() and bb_got_signal became != 0,
  9899. * or if it sees bb_got_signal != 0
  9900. * (IOW: if signal arrives before poll() is reached).
  9901. * Interactive testcases:
  9902. * (while kill -INT $$; do sleep 1; done) &
  9903. * #^^^ prints ^C, prints prompt, repeats
  9904. * trap 'echo I' int; (while kill -INT $$; do sleep 1; done) &
  9905. * #^^^ prints ^C, prints "I", prints prompt, repeats
  9906. * trap 'echo T' term; (while kill $$; do sleep 1; done) &
  9907. * #^^^ prints "T", prints prompt, repeats
  9908. * #(bash 5.0.17 exits after first "T", looks like a bug)
  9909. */
  9910. bb_got_signal = 0;
  9911. INT_OFF; /* no longjmp'ing out of read_line_input please */
  9912. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9913. if (bb_got_signal == SIGINT)
  9914. write(STDOUT_FILENO, "^C\n", 3);
  9915. INT_ON; /* here non-blocked SIGINT will longjmp */
  9916. if (nr == 0) {
  9917. /* ^C pressed, "convert" to SIGINT */
  9918. write(STDOUT_FILENO, "^C\n", 3);
  9919. raise(SIGINT); /* here non-blocked SIGINT will longjmp */
  9920. /* raise(SIGINT) did not work! (e.g. if SIGINT
  9921. * is SIG_IGNed on startup, it stays SIG_IGNed)
  9922. */
  9923. if (trap[SIGINT]) {
  9924. empty_line_input:
  9925. buf[0] = '\n';
  9926. buf[1] = '\0';
  9927. return 1;
  9928. }
  9929. exitstatus = 128 + SIGINT;
  9930. /* bash behavior on ^C + ignored SIGINT: */
  9931. goto again;
  9932. }
  9933. if (nr < 0) {
  9934. if (errno == 0) {
  9935. /* ^D pressed */
  9936. nr = 0;
  9937. }
  9938. else if (errno == EINTR) { /* got signal? */
  9939. if (bb_got_signal != SIGINT)
  9940. write(STDOUT_FILENO, "\n", 1);
  9941. goto empty_line_input;
  9942. }
  9943. # if ENABLE_ASH_IDLE_TIMEOUT
  9944. else if (errno == EAGAIN && timeout > 0) {
  9945. puts("\007timed out waiting for input: auto-logout");
  9946. exitshell();
  9947. }
  9948. # endif
  9949. }
  9950. }
  9951. #else
  9952. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9953. #endif
  9954. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9955. if (nr < 0) {
  9956. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9957. int flags = fcntl(0, F_GETFL);
  9958. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9959. flags &= ~O_NONBLOCK;
  9960. if (fcntl(0, F_SETFL, flags) >= 0) {
  9961. out2str("sh: turning off NDELAY mode\n");
  9962. goto retry;
  9963. }
  9964. }
  9965. }
  9966. }
  9967. #endif
  9968. return nr;
  9969. }
  9970. /*
  9971. * Refill the input buffer and return the next input character:
  9972. *
  9973. * 1) If a string was pushed back on the input, pop it;
  9974. * 2) If we are reading from a string we can't refill the buffer, return EOF.
  9975. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9976. * 4) Process input up to the next newline, deleting nul characters.
  9977. */
  9978. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9979. #define pgetc_debug(...) ((void)0)
  9980. static int __pgetc(void);
  9981. static int
  9982. preadbuffer(void)
  9983. {
  9984. char *q;
  9985. int more;
  9986. if (g_parsefile->buf == NULL) {
  9987. pgetc_debug("preadbuffer PEOF1");
  9988. return PEOF;
  9989. }
  9990. more = g_parsefile->left_in_buffer;
  9991. if (more <= 0) {
  9992. flush_stdout_stderr();
  9993. again:
  9994. more = preadfd();
  9995. if (more <= 0) {
  9996. g_parsefile->left_in_buffer = g_parsefile->left_in_line = 0;
  9997. pgetc_debug("preadbuffer PEOF2");
  9998. return PEOF;
  9999. }
  10000. }
  10001. /* Find out where's the end of line.
  10002. * Set g_parsefile->left_in_line
  10003. * and g_parsefile->left_in_buffer acordingly.
  10004. * NUL chars are deleted.
  10005. */
  10006. q = g_parsefile->next_to_pgetc;
  10007. for (;;) {
  10008. char c;
  10009. more--;
  10010. c = *q;
  10011. if (c == '\0') {
  10012. memmove(q, q + 1, more);
  10013. } else {
  10014. q++;
  10015. if (c == '\n') {
  10016. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  10017. break;
  10018. }
  10019. }
  10020. if (more <= 0) {
  10021. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  10022. if (g_parsefile->left_in_line < 0)
  10023. goto again;
  10024. break;
  10025. }
  10026. }
  10027. g_parsefile->left_in_buffer = more;
  10028. if (vflag) {
  10029. char save = *q;
  10030. *q = '\0';
  10031. out2str(g_parsefile->next_to_pgetc);
  10032. *q = save;
  10033. }
  10034. pgetc_debug("preadbuffer at %d:%p'%s'",
  10035. g_parsefile->left_in_line,
  10036. g_parsefile->next_to_pgetc,
  10037. g_parsefile->next_to_pgetc);
  10038. return (unsigned char)*g_parsefile->next_to_pgetc++;
  10039. }
  10040. static void
  10041. nlprompt(void)
  10042. {
  10043. if (trap_depth == 0)
  10044. g_parsefile->linno++;
  10045. setprompt_if(doprompt, 2);
  10046. }
  10047. static void
  10048. nlnoprompt(void)
  10049. {
  10050. if (trap_depth == 0)
  10051. g_parsefile->linno++;
  10052. needprompt = doprompt;
  10053. }
  10054. static void freestrings(struct strpush *sp)
  10055. {
  10056. INT_OFF;
  10057. do {
  10058. struct strpush *psp;
  10059. #if ENABLE_ASH_ALIAS
  10060. if (sp->ap) {
  10061. sp->ap->flag &= ~ALIASINUSE;
  10062. if (sp->ap->flag & ALIASDEAD) {
  10063. unalias(sp->ap->name);
  10064. }
  10065. }
  10066. #endif
  10067. psp = sp;
  10068. sp = sp->spfree;
  10069. if (psp != &(g_parsefile->basestrpush))
  10070. free(psp);
  10071. } while (sp);
  10072. g_parsefile->spfree = NULL;
  10073. INT_ON;
  10074. }
  10075. static int __pgetc(void)
  10076. {
  10077. int c;
  10078. pgetc_debug("pgetc at %d:%p'%s'",
  10079. g_parsefile->left_in_line,
  10080. g_parsefile->next_to_pgetc,
  10081. g_parsefile->next_to_pgetc);
  10082. if (g_parsefile->unget)
  10083. return g_parsefile->lastc[--g_parsefile->unget];
  10084. if (--g_parsefile->left_in_line >= 0)
  10085. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  10086. else {
  10087. if (unlikely(g_parsefile->strpush)) {
  10088. popstring();
  10089. return __pgetc();
  10090. }
  10091. c = preadbuffer();
  10092. }
  10093. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  10094. g_parsefile->lastc[0] = c;
  10095. return c;
  10096. }
  10097. /*
  10098. * Read a character from the script, returning PEOF on end of file.
  10099. * Nul characters in the input are silently discarded.
  10100. */
  10101. static int pgetc(void)
  10102. {
  10103. struct strpush *sp = g_parsefile->spfree;
  10104. if (unlikely(sp))
  10105. freestrings(sp);
  10106. return __pgetc();
  10107. }
  10108. /*
  10109. * Undo a call to pgetc. Only two characters may be pushed back.
  10110. * PEOF may be pushed back.
  10111. */
  10112. static void
  10113. pungetc(void)
  10114. {
  10115. g_parsefile->unget++;
  10116. }
  10117. /* This one eats backslash+newline */
  10118. static int
  10119. pgetc_eatbnl(void)
  10120. {
  10121. int c;
  10122. while ((c = pgetc()) == '\\') {
  10123. if (pgetc() != '\n') {
  10124. pungetc();
  10125. break;
  10126. }
  10127. nlprompt();
  10128. }
  10129. return c;
  10130. }
  10131. struct synstack {
  10132. smalluint syntax;
  10133. uint8_t innerdq :1;
  10134. uint8_t varpushed :1;
  10135. uint8_t dblquote :1;
  10136. int varnest; /* levels of variables expansion */
  10137. int dqvarnest; /* levels of variables expansion within double quotes */
  10138. int parenlevel; /* levels of parens in arithmetic */
  10139. struct synstack *prev;
  10140. struct synstack *next;
  10141. };
  10142. static int
  10143. pgetc_top(struct synstack *stack)
  10144. {
  10145. return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
  10146. }
  10147. static void
  10148. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  10149. {
  10150. memset(next, 0, sizeof(*next));
  10151. next->syntax = syntax;
  10152. next->next = *stack;
  10153. (*stack)->prev = next;
  10154. *stack = next;
  10155. }
  10156. static ALWAYS_INLINE void
  10157. synstack_pop(struct synstack **stack)
  10158. {
  10159. *stack = (*stack)->next;
  10160. }
  10161. /*
  10162. * To handle the "." command, a stack of input files is used. Pushfile
  10163. * adds a new entry to the stack and popfile restores the previous level.
  10164. */
  10165. static void
  10166. pushfile(void)
  10167. {
  10168. struct parsefile *pf;
  10169. pf = ckzalloc(sizeof(*pf));
  10170. pf->prev = g_parsefile;
  10171. pf->pf_fd = -1;
  10172. /*pf->strpush = NULL; - ckzalloc did it */
  10173. /*pf->spfree = NULL;*/
  10174. /*pf->basestrpush.prev = NULL;*/
  10175. /*pf->unget = 0;*/
  10176. g_parsefile = pf;
  10177. }
  10178. static void
  10179. popfile(void)
  10180. {
  10181. struct parsefile *pf = g_parsefile;
  10182. if (pf == &basepf)
  10183. return;
  10184. INT_OFF;
  10185. if (pf->pf_fd >= 0)
  10186. close(pf->pf_fd);
  10187. free(pf->buf);
  10188. if (g_parsefile->spfree)
  10189. freestrings(g_parsefile->spfree);
  10190. while (pf->strpush) {
  10191. popstring();
  10192. freestrings(g_parsefile->spfree);
  10193. }
  10194. g_parsefile = pf->prev;
  10195. free(pf);
  10196. INT_ON;
  10197. }
  10198. static void
  10199. unwindfiles(struct parsefile *stop)
  10200. {
  10201. while (g_parsefile != stop)
  10202. popfile();
  10203. }
  10204. /*
  10205. * Return to top level.
  10206. */
  10207. static void
  10208. popallfiles(void)
  10209. {
  10210. unwindfiles(&basepf);
  10211. }
  10212. /*
  10213. * Close the file(s) that the shell is reading commands from. Called
  10214. * after a fork is done.
  10215. */
  10216. static void
  10217. closescript(void)
  10218. {
  10219. popallfiles();
  10220. if (g_parsefile->pf_fd > 0) {
  10221. close(g_parsefile->pf_fd);
  10222. g_parsefile->pf_fd = 0;
  10223. }
  10224. }
  10225. /*
  10226. * Like setinputfile, but takes an open file descriptor. Call this with
  10227. * interrupts off.
  10228. */
  10229. static void
  10230. setinputfd(int fd, int push)
  10231. {
  10232. if (push) {
  10233. pushfile();
  10234. g_parsefile->buf = NULL;
  10235. }
  10236. g_parsefile->pf_fd = fd;
  10237. if (g_parsefile->buf == NULL)
  10238. g_parsefile->buf = ckmalloc(IBUFSIZ);
  10239. g_parsefile->left_in_buffer = 0;
  10240. g_parsefile->left_in_line = 0;
  10241. g_parsefile->linno = 1;
  10242. }
  10243. /*
  10244. * Set the input to take input from a file. If push is set, push the
  10245. * old input onto the stack first.
  10246. */
  10247. static int
  10248. setinputfile(const char *fname, int flags)
  10249. {
  10250. int fd;
  10251. INT_OFF;
  10252. fd = open(fname, O_RDONLY | O_CLOEXEC);
  10253. if (fd < 0) {
  10254. if (flags & INPUT_NOFILE_OK)
  10255. goto out;
  10256. exitstatus = 127;
  10257. ash_msg_and_raise_perror("can't open '%s'", fname);
  10258. }
  10259. if (fd < 10)
  10260. fd = savefd(fd);
  10261. else if (O_CLOEXEC == 0) /* old libc */
  10262. close_on_exec_on(fd);
  10263. setinputfd(fd, flags & INPUT_PUSH_FILE);
  10264. out:
  10265. INT_ON;
  10266. return fd;
  10267. }
  10268. /*
  10269. * Like setinputfile, but takes input from a string.
  10270. */
  10271. static void
  10272. setinputstring(char *string)
  10273. {
  10274. INT_OFF;
  10275. pushfile();
  10276. g_parsefile->next_to_pgetc = string;
  10277. g_parsefile->left_in_line = strlen(string);
  10278. g_parsefile->buf = NULL;
  10279. g_parsefile->linno = lineno;
  10280. INT_ON;
  10281. }
  10282. /*
  10283. * Routines to check for mail.
  10284. */
  10285. #if ENABLE_ASH_MAIL
  10286. /* Hash of mtimes of mailboxes */
  10287. /* Cleared to 0 if MAIL or MAILPATH is changed */
  10288. static unsigned mailtime_hash;
  10289. /*
  10290. * Print appropriate message(s) if mail has arrived.
  10291. * If mailtime_hash is zero,
  10292. * then the value of MAIL has changed,
  10293. * so we just update the hash value.
  10294. */
  10295. static void
  10296. chkmail(void)
  10297. {
  10298. const char *mpath;
  10299. char *p;
  10300. char *q;
  10301. unsigned new_hash;
  10302. struct stackmark smark;
  10303. struct stat statb;
  10304. setstackmark(&smark);
  10305. mpath = mpathset() ? mpathval() : mailval();
  10306. new_hash = 0;
  10307. for (;;) {
  10308. int len;
  10309. len = padvance_magic(&mpath, nullstr, 2);
  10310. if (len < 0)
  10311. break;
  10312. p = stackblock();
  10313. if (*p == '\0')
  10314. continue;
  10315. for (q = p; *q; q++)
  10316. continue;
  10317. #if DEBUG
  10318. if (q[-1] != '/')
  10319. abort();
  10320. #endif
  10321. q[-1] = '\0'; /* delete trailing '/' */
  10322. if (stat(p, &statb) < 0) {
  10323. continue;
  10324. }
  10325. /* Very simplistic "hash": just a sum of all mtimes */
  10326. new_hash += (unsigned)statb.st_mtime;
  10327. }
  10328. if (mailtime_hash != new_hash) {
  10329. if (mailtime_hash != 0)
  10330. out2str("you have mail\n");
  10331. mailtime_hash = new_hash;
  10332. }
  10333. popstackmark(&smark);
  10334. }
  10335. static void FAST_FUNC
  10336. changemail(const char *val UNUSED_PARAM)
  10337. {
  10338. mailtime_hash = 0;
  10339. }
  10340. #else
  10341. # define chkmail() ((void)0)
  10342. #endif /* ASH_MAIL */
  10343. /* ============ ??? */
  10344. /*
  10345. * Set the shell parameters.
  10346. */
  10347. static void
  10348. setparam(char **argv)
  10349. {
  10350. char **newparam;
  10351. char **ap;
  10352. int nparam;
  10353. for (nparam = 0; argv[nparam]; nparam++)
  10354. continue;
  10355. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10356. while (*argv) {
  10357. *ap++ = ckstrdup(*argv++);
  10358. }
  10359. *ap = NULL;
  10360. freeparam(&shellparam);
  10361. shellparam.malloced = 1;
  10362. shellparam.nparam = nparam;
  10363. shellparam.p = newparam;
  10364. #if ENABLE_ASH_GETOPTS
  10365. shellparam.optind = 1;
  10366. shellparam.optoff = -1;
  10367. #endif
  10368. }
  10369. /*
  10370. * Process shell options. The global variable argptr contains a pointer
  10371. * to the argument list; we advance it past the options.
  10372. *
  10373. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10374. * For a non-interactive shell, an error condition encountered
  10375. * by a special built-in ... shall cause the shell to write a diagnostic message
  10376. * to standard error and exit as shown in the following table:
  10377. * Error Special Built-In
  10378. * ...
  10379. * Utility syntax error (option or operand error) Shall exit
  10380. * ...
  10381. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10382. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10383. * and shell continues), and people rely on this behavior!
  10384. * Testcase:
  10385. * set -o barfoo 2>/dev/null
  10386. * echo $?
  10387. *
  10388. * Oh well. Let's mimic that.
  10389. */
  10390. static int
  10391. plus_minus_o(char *name, int val)
  10392. {
  10393. int i;
  10394. if (name) {
  10395. for (i = 0; i < NOPTS; i++) {
  10396. if (strcmp(name, optnames(i)) == 0) {
  10397. optlist[i] = val;
  10398. return 0;
  10399. }
  10400. }
  10401. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10402. return 1;
  10403. }
  10404. for (i = 0; i < NOPTS; i++) {
  10405. if (optnames(i)[0] == '\0')
  10406. continue;
  10407. if (val) {
  10408. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10409. } else {
  10410. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10411. }
  10412. }
  10413. return 0;
  10414. }
  10415. static void
  10416. setoption(int flag, int val)
  10417. {
  10418. int i;
  10419. for (i = 0; i < NOPTS; i++) {
  10420. if (optletters(i) == flag && optnames(i)[0] != '\0') {
  10421. optlist[i] = val;
  10422. return;
  10423. }
  10424. }
  10425. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10426. /* NOTREACHED */
  10427. }
  10428. /* If login_sh is not NULL, we are called to parse command line opts,
  10429. * not "set -opts"
  10430. */
  10431. static int
  10432. options(int *login_sh)
  10433. {
  10434. char *p;
  10435. int val;
  10436. int c;
  10437. if (login_sh != NULL) /* if we came from startup code */
  10438. minusc = NULL;
  10439. while ((p = *argptr) != NULL) {
  10440. c = *p++;
  10441. if (c != '-' && c != '+')
  10442. break;
  10443. argptr++;
  10444. val = 0; /* val = 0 if c == '+' */
  10445. if (c == '-') {
  10446. val = 1;
  10447. if (p[0] == '\0' || LONE_DASH(p)) {
  10448. if (login_sh == NULL) { /* we came from setcmd() */
  10449. /* "-" means turn off -x and -v */
  10450. if (p[0] == '\0')
  10451. xflag = vflag = 0;
  10452. /* "--" means reset params */
  10453. else if (*argptr == NULL)
  10454. setparam(argptr);
  10455. }
  10456. break; /* "-" or "--" terminates options */
  10457. }
  10458. }
  10459. /* first char was + or - */
  10460. while ((c = *p++) != '\0') {
  10461. if (login_sh != NULL) { /* if we came from startup code */
  10462. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10463. if (c == 'c') {
  10464. minusc = p; /* command is after shell args */
  10465. cflag = 1;
  10466. continue;
  10467. }
  10468. if (c == 's') { /* -s, +s */
  10469. sflag = 1;
  10470. continue;
  10471. }
  10472. if (c == 'i') { /* -i, +i */
  10473. iflag = 1;
  10474. continue;
  10475. }
  10476. if (c == 'l') {
  10477. *login_sh = 1; /* -l or +l == --login */
  10478. continue;
  10479. }
  10480. /* bash does not accept +-login, we also won't */
  10481. if (val && (c == '-')) { /* long options */
  10482. if (strcmp(p, "login") == 0) {
  10483. *login_sh = 1;
  10484. break;
  10485. }
  10486. /* TODO: --noprofile: e.g. if I want to run emergency shell from sulogin,
  10487. * I want minimal/no shell init scripts - but it insists on running it as "-ash"...
  10488. */
  10489. ash_msg_and_raise_error("bad option '%s'", p - 2);
  10490. }
  10491. }
  10492. if (c == 'o') {
  10493. if (plus_minus_o(*argptr, val)) {
  10494. /* it already printed err message */
  10495. return 1; /* error */
  10496. }
  10497. if (*argptr)
  10498. argptr++;
  10499. } else {
  10500. setoption(c, val);
  10501. }
  10502. }
  10503. }
  10504. return 0;
  10505. }
  10506. /*
  10507. * The shift builtin command.
  10508. */
  10509. static int FAST_FUNC
  10510. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10511. {
  10512. int n;
  10513. char **ap1, **ap2;
  10514. n = 1;
  10515. if (argv[1])
  10516. n = number(argv[1]);
  10517. if (n > shellparam.nparam)
  10518. return 1;
  10519. INT_OFF;
  10520. shellparam.nparam -= n;
  10521. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10522. if (shellparam.malloced)
  10523. free(*ap1);
  10524. }
  10525. ap2 = shellparam.p;
  10526. while ((*ap2++ = *ap1++) != NULL)
  10527. continue;
  10528. #if ENABLE_ASH_GETOPTS
  10529. shellparam.optind = 1;
  10530. shellparam.optoff = -1;
  10531. #endif
  10532. INT_ON;
  10533. return 0;
  10534. }
  10535. /*
  10536. * POSIX requires that 'set' (but not export or readonly) output the
  10537. * variables in lexicographic order - by the locale's collating order (sigh).
  10538. * Maybe we could keep them in an ordered balanced binary tree
  10539. * instead of hashed lists.
  10540. * For now just roll 'em through qsort for printing...
  10541. */
  10542. static int
  10543. showvars(const char *sep_prefix, int on, int off)
  10544. {
  10545. const char *sep;
  10546. char **ep, **epend;
  10547. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10548. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10549. sep = *sep_prefix ? " " : sep_prefix;
  10550. for (; ep < epend; ep++) {
  10551. const char *p;
  10552. const char *q;
  10553. p = endofname(*ep);
  10554. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10555. * makes "export -p" to have output not suitable for "eval":
  10556. * import os
  10557. * os.environ["test-test"]="test"
  10558. * if os.fork() == 0:
  10559. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10560. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10561. */
  10562. q = nullstr;
  10563. if (*p == '=')
  10564. q = single_quote(++p);
  10565. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10566. }
  10567. return 0;
  10568. }
  10569. /*
  10570. * The set command builtin.
  10571. */
  10572. static int FAST_FUNC
  10573. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10574. {
  10575. int retval;
  10576. if (!argv[1])
  10577. return showvars(nullstr, 0, VUNSET);
  10578. INT_OFF;
  10579. retval = options(/*login_sh:*/ NULL);
  10580. if (retval == 0) { /* if no parse error... */
  10581. optschanged();
  10582. if (*argptr != NULL) {
  10583. setparam(argptr);
  10584. }
  10585. }
  10586. INT_ON;
  10587. return retval;
  10588. }
  10589. #if ENABLE_ASH_RANDOM_SUPPORT
  10590. static void FAST_FUNC
  10591. change_random(const char *value)
  10592. {
  10593. uint32_t t;
  10594. if (value == NULL) {
  10595. /* "get", generate */
  10596. t = next_random(&random_gen);
  10597. /* set without recursion */
  10598. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10599. vrandom.flags &= ~VNOFUNC;
  10600. } else {
  10601. /* set/reset */
  10602. t = strtoul(value, NULL, 10);
  10603. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10604. }
  10605. }
  10606. #endif
  10607. #if BASH_EPOCH_VARS
  10608. static void FAST_FUNC
  10609. change_epoch(struct var *vepoch, const char *fmt)
  10610. {
  10611. struct timeval tv;
  10612. char buffer[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
  10613. xgettimeofday(&tv);
  10614. sprintf(buffer, fmt, (unsigned long long)tv.tv_sec, (unsigned)tv.tv_usec);
  10615. setvar(vepoch->var_text, buffer, VNOFUNC);
  10616. vepoch->flags &= ~VNOFUNC;
  10617. }
  10618. static void FAST_FUNC
  10619. change_seconds(const char *value UNUSED_PARAM)
  10620. {
  10621. change_epoch(&vepochs, "%llu");
  10622. }
  10623. static void FAST_FUNC
  10624. change_realtime(const char *value UNUSED_PARAM)
  10625. {
  10626. change_epoch(&vepochr, "%llu.%06u");
  10627. }
  10628. #endif
  10629. #if ENABLE_ASH_GETOPTS
  10630. static int
  10631. getopts(char *optstr, char *optvar, char **optfirst)
  10632. {
  10633. char *p, *q;
  10634. char c = '?';
  10635. int done = 0;
  10636. char sbuf[2];
  10637. char **optnext;
  10638. int ind = shellparam.optind;
  10639. int off = shellparam.optoff;
  10640. sbuf[1] = '\0';
  10641. shellparam.optind = -1;
  10642. optnext = optfirst + ind - 1;
  10643. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10644. p = NULL;
  10645. else
  10646. p = optnext[-1] + off;
  10647. if (p == NULL || *p == '\0') {
  10648. /* Current word is done, advance */
  10649. p = *optnext;
  10650. if (p == NULL || *p != '-' || *++p == '\0') {
  10651. atend:
  10652. unsetvar("OPTARG");
  10653. p = NULL;
  10654. done = 1;
  10655. goto out;
  10656. }
  10657. optnext++;
  10658. if (LONE_DASH(p)) /* check for "--" */
  10659. goto atend;
  10660. }
  10661. c = *p++;
  10662. for (q = optstr; *q != c;) {
  10663. if (*q == '\0') {
  10664. /* OPTERR is a bashism */
  10665. const char *cp = lookupvar("OPTERR");
  10666. if ((cp && LONE_CHAR(cp, '0'))
  10667. || (optstr[0] == ':')
  10668. ) {
  10669. sbuf[0] = c;
  10670. /*sbuf[1] = '\0'; - already is */
  10671. setvar0("OPTARG", sbuf);
  10672. } else {
  10673. fprintf(stderr, "Illegal option -%c\n", c);
  10674. unsetvar("OPTARG");
  10675. }
  10676. c = '?';
  10677. goto out;
  10678. }
  10679. if (*++q == ':')
  10680. q++;
  10681. }
  10682. if (*++q == ':') {
  10683. if (*p == '\0' && (p = *optnext) == NULL) {
  10684. /* OPTERR is a bashism */
  10685. const char *cp = lookupvar("OPTERR");
  10686. if ((cp && LONE_CHAR(cp, '0'))
  10687. || (optstr[0] == ':')
  10688. ) {
  10689. sbuf[0] = c;
  10690. /*sbuf[1] = '\0'; - already is */
  10691. setvar0("OPTARG", sbuf);
  10692. c = ':';
  10693. } else {
  10694. fprintf(stderr, "No arg for -%c option\n", c);
  10695. unsetvar("OPTARG");
  10696. c = '?';
  10697. }
  10698. goto out;
  10699. }
  10700. if (p == *optnext)
  10701. optnext++;
  10702. setvar0("OPTARG", p);
  10703. p = NULL;
  10704. } else
  10705. setvar0("OPTARG", nullstr);
  10706. out:
  10707. ind = optnext - optfirst + 1;
  10708. setvar("OPTIND", itoa(ind), VNOFUNC);
  10709. sbuf[0] = c;
  10710. /*sbuf[1] = '\0'; - already is */
  10711. setvar0(optvar, sbuf);
  10712. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10713. shellparam.optind = ind;
  10714. return done;
  10715. }
  10716. /*
  10717. * The getopts builtin. Shellparam.optnext points to the next argument
  10718. * to be processed. Shellparam.optptr points to the next character to
  10719. * be processed in the current argument. If shellparam.optnext is NULL,
  10720. * then it's the first time getopts has been called.
  10721. */
  10722. static int FAST_FUNC
  10723. getoptscmd(int argc, char **argv)
  10724. {
  10725. char **optbase;
  10726. if (argc < 3)
  10727. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10728. if (argc == 3) {
  10729. optbase = shellparam.p;
  10730. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10731. shellparam.optind = 1;
  10732. shellparam.optoff = -1;
  10733. }
  10734. } else {
  10735. optbase = &argv[3];
  10736. if ((unsigned)shellparam.optind > argc - 2) {
  10737. shellparam.optind = 1;
  10738. shellparam.optoff = -1;
  10739. }
  10740. }
  10741. return getopts(argv[1], argv[2], optbase);
  10742. }
  10743. #endif /* ASH_GETOPTS */
  10744. /* ============ Shell parser */
  10745. struct heredoc {
  10746. struct heredoc *next; /* next here document in list */
  10747. union node *here; /* redirection node */
  10748. char *eofmark; /* string indicating end of input */
  10749. smallint striptabs; /* if set, strip leading tabs */
  10750. };
  10751. static smallint tokpushback; /* last token pushed back */
  10752. static smallint quoteflag; /* set if (part of) last token was quoted */
  10753. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10754. static struct heredoc *heredoclist; /* list of here documents to read */
  10755. static char *wordtext; /* text of last word returned by readtoken */
  10756. static struct nodelist *backquotelist;
  10757. static union node *redirnode;
  10758. static struct heredoc *heredoc;
  10759. static const char *
  10760. tokname(char *buf, int tok)
  10761. {
  10762. if (tok < TSEMI)
  10763. return tokname_array[tok];
  10764. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10765. return buf;
  10766. }
  10767. /* raise_error_unexpected_syntax:
  10768. * Called when an unexpected token is read during the parse. The argument
  10769. * is the token that is expected, or -1 if more than one type of token can
  10770. * occur at this point.
  10771. */
  10772. static void raise_error_unexpected_syntax(int) NORETURN;
  10773. static void
  10774. raise_error_unexpected_syntax(int token)
  10775. {
  10776. char msg[64];
  10777. char buf[16];
  10778. int l;
  10779. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10780. if (token >= 0)
  10781. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10782. raise_error_syntax(msg);
  10783. /* NOTREACHED */
  10784. }
  10785. /* parsing is heavily cross-recursive, need these forward decls */
  10786. static union node *andor(void);
  10787. static union node *pipeline(void);
  10788. static union node *parse_command(void);
  10789. static void parseheredoc(void);
  10790. static int readtoken(void);
  10791. static union node *
  10792. list(int nlflag)
  10793. {
  10794. int chknl = nlflag & 1 ? 0 : CHKNL;
  10795. union node *n1, *n2, *n3;
  10796. int tok;
  10797. n1 = NULL;
  10798. for (;;) {
  10799. checkkwd = chknl | CHKKWD | CHKALIAS;
  10800. tok = readtoken();
  10801. switch (tok) {
  10802. case TNL:
  10803. parseheredoc();
  10804. return n1;
  10805. case TEOF:
  10806. if (!n1 && !chknl)
  10807. n1 = NODE_EOF;
  10808. out_eof:
  10809. parseheredoc();
  10810. tokpushback++;
  10811. lasttoken = TEOF;
  10812. return n1;
  10813. }
  10814. tokpushback++;
  10815. if (nlflag == 2 && ((1 << tok) & tokendlist))
  10816. return n1;
  10817. nlflag |= 2;
  10818. n2 = andor();
  10819. tok = readtoken();
  10820. if (tok == TBACKGND) {
  10821. if (n2->type == NPIPE) {
  10822. n2->npipe.pipe_backgnd = 1;
  10823. } else {
  10824. if (n2->type != NREDIR) {
  10825. n3 = stzalloc(sizeof(struct nredir));
  10826. n3->nredir.n = n2;
  10827. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10828. n2 = n3;
  10829. }
  10830. n2->type = NBACKGND;
  10831. }
  10832. }
  10833. if (n1 == NULL) {
  10834. n1 = n2;
  10835. } else {
  10836. n3 = stzalloc(sizeof(struct nbinary));
  10837. n3->type = NSEMI;
  10838. n3->nbinary.ch1 = n1;
  10839. n3->nbinary.ch2 = n2;
  10840. n1 = n3;
  10841. }
  10842. switch (tok) {
  10843. case TEOF:
  10844. goto out_eof;
  10845. case TNL:
  10846. tokpushback = 1;
  10847. /* fall through */
  10848. case TBACKGND:
  10849. case TSEMI:
  10850. break;
  10851. default:
  10852. if (!chknl)
  10853. raise_error_unexpected_syntax(-1);
  10854. tokpushback = 1;
  10855. return n1;
  10856. }
  10857. }
  10858. }
  10859. static union node *
  10860. andor(void)
  10861. {
  10862. union node *n1, *n2, *n3;
  10863. int t;
  10864. n1 = pipeline();
  10865. for (;;) {
  10866. t = readtoken();
  10867. if (t == TAND) {
  10868. t = NAND;
  10869. } else if (t == TOR) {
  10870. t = NOR;
  10871. } else {
  10872. tokpushback = 1;
  10873. return n1;
  10874. }
  10875. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10876. n2 = pipeline();
  10877. n3 = stzalloc(sizeof(struct nbinary));
  10878. n3->type = t;
  10879. n3->nbinary.ch1 = n1;
  10880. n3->nbinary.ch2 = n2;
  10881. n1 = n3;
  10882. }
  10883. }
  10884. static union node *
  10885. pipeline(void)
  10886. {
  10887. union node *n1, *n2, *pipenode;
  10888. struct nodelist *lp, *prev;
  10889. int negate;
  10890. negate = 0;
  10891. TRACE(("pipeline: entered\n"));
  10892. if (readtoken() == TNOT) {
  10893. negate = !negate;
  10894. checkkwd = CHKKWD | CHKALIAS;
  10895. } else
  10896. tokpushback = 1;
  10897. n1 = parse_command();
  10898. if (readtoken() == TPIPE) {
  10899. pipenode = stzalloc(sizeof(struct npipe));
  10900. pipenode->type = NPIPE;
  10901. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10902. lp = stzalloc(sizeof(struct nodelist));
  10903. pipenode->npipe.cmdlist = lp;
  10904. lp->n = n1;
  10905. do {
  10906. prev = lp;
  10907. lp = stzalloc(sizeof(struct nodelist));
  10908. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10909. lp->n = parse_command();
  10910. prev->next = lp;
  10911. } while (readtoken() == TPIPE);
  10912. lp->next = NULL;
  10913. n1 = pipenode;
  10914. }
  10915. tokpushback = 1;
  10916. if (negate) {
  10917. n2 = stzalloc(sizeof(struct nnot));
  10918. n2->type = NNOT;
  10919. n2->nnot.com = n1;
  10920. return n2;
  10921. }
  10922. return n1;
  10923. }
  10924. static union node *
  10925. makename(void)
  10926. {
  10927. union node *n;
  10928. n = stzalloc(sizeof(struct narg));
  10929. n->type = NARG;
  10930. /*n->narg.next = NULL; - stzalloc did it */
  10931. n->narg.text = wordtext;
  10932. n->narg.backquote = backquotelist;
  10933. return n;
  10934. }
  10935. static void
  10936. fixredir(union node *n, const char *text, int err)
  10937. {
  10938. int fd;
  10939. TRACE(("Fix redir %s %d\n", text, err));
  10940. if (!err)
  10941. n->ndup.vname = NULL;
  10942. if (LONE_DASH(text)) {
  10943. n->ndup.dupfd = -1;
  10944. return;
  10945. }
  10946. fd = bb_strtou(text, NULL, 10);
  10947. if (!errno && fd >= 0)
  10948. n->ndup.dupfd = fd;
  10949. else {
  10950. /* This also fails on very large numbers
  10951. * which overflow "int" - bb_strtou() does not
  10952. * silently truncate results to word width.
  10953. */
  10954. if (err)
  10955. raise_error_syntax("bad fd number");
  10956. n->ndup.vname = makename();
  10957. }
  10958. }
  10959. static void
  10960. parsefname(void)
  10961. {
  10962. union node *n = redirnode;
  10963. if (n->type == NHERE)
  10964. checkkwd = CHKEOFMARK;
  10965. if (readtoken() != TWORD)
  10966. raise_error_unexpected_syntax(-1);
  10967. if (n->type == NHERE) {
  10968. struct heredoc *here = heredoc;
  10969. struct heredoc *p;
  10970. if (quoteflag == 0)
  10971. n->type = NXHERE;
  10972. TRACE(("Here document %d\n", n->type));
  10973. rmescapes(wordtext, 0, NULL);
  10974. here->eofmark = wordtext;
  10975. here->next = NULL;
  10976. if (heredoclist == NULL)
  10977. heredoclist = here;
  10978. else {
  10979. for (p = heredoclist; p->next; p = p->next)
  10980. continue;
  10981. p->next = here;
  10982. }
  10983. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10984. fixredir(n, wordtext, 0);
  10985. } else {
  10986. n->nfile.fname = makename();
  10987. }
  10988. }
  10989. static union node *
  10990. simplecmd(void)
  10991. {
  10992. union node *args, **app;
  10993. union node *n = NULL;
  10994. union node *vars, **vpp;
  10995. union node **rpp, *redir;
  10996. int savecheckkwd;
  10997. int savelinno;
  10998. #if BASH_TEST2
  10999. smallint double_brackets_flag = 0;
  11000. #endif
  11001. IF_BASH_FUNCTION(smallint function_flag = 0;)
  11002. args = NULL;
  11003. app = &args;
  11004. vars = NULL;
  11005. vpp = &vars;
  11006. redir = NULL;
  11007. rpp = &redir;
  11008. savecheckkwd = CHKALIAS;
  11009. savelinno = g_parsefile->linno;
  11010. for (;;) {
  11011. int t;
  11012. checkkwd = savecheckkwd;
  11013. t = readtoken();
  11014. switch (t) {
  11015. #if BASH_FUNCTION
  11016. case TFUNCTION:
  11017. if (readtoken() != TWORD)
  11018. raise_error_unexpected_syntax(TWORD);
  11019. tokpushback = 1;
  11020. function_flag = 1;
  11021. break;
  11022. #endif
  11023. #if BASH_TEST2
  11024. case TAND: /* "&&" */
  11025. case TOR: /* "||" */
  11026. if (!double_brackets_flag) {
  11027. tokpushback = 1;
  11028. goto out;
  11029. }
  11030. /* pass "&&" or "||" to [[ ]] as literal args */
  11031. wordtext = (char *) (t == TAND ? "&&" : "||");
  11032. #endif
  11033. case TWORD:
  11034. n = stzalloc(sizeof(struct narg));
  11035. n->type = NARG;
  11036. /*n->narg.next = NULL; - stzalloc did it */
  11037. n->narg.text = wordtext;
  11038. #if BASH_TEST2
  11039. if (strcmp("[[", wordtext) == 0)
  11040. double_brackets_flag = 1;
  11041. else if (strcmp("]]", wordtext) == 0)
  11042. double_brackets_flag = 0;
  11043. #endif
  11044. n->narg.backquote = backquotelist;
  11045. if (savecheckkwd && isassignment(wordtext)) {
  11046. *vpp = n;
  11047. vpp = &n->narg.next;
  11048. } else {
  11049. *app = n;
  11050. app = &n->narg.next;
  11051. savecheckkwd = 0;
  11052. }
  11053. #if BASH_FUNCTION
  11054. if (function_flag) {
  11055. checkkwd = CHKNL | CHKKWD;
  11056. t = readtoken();
  11057. tokpushback = 1;
  11058. switch (t) {
  11059. case TBEGIN:
  11060. case TIF:
  11061. case TCASE:
  11062. case TUNTIL:
  11063. case TWHILE:
  11064. case TFOR:
  11065. goto do_func;
  11066. case TLP:
  11067. function_flag = 0;
  11068. break;
  11069. # if BASH_TEST2
  11070. case TWORD:
  11071. if (strcmp("[[", wordtext) == 0)
  11072. goto do_func;
  11073. /* fall through */
  11074. # endif
  11075. default:
  11076. raise_error_unexpected_syntax(-1);
  11077. }
  11078. }
  11079. #endif
  11080. break;
  11081. case TREDIR:
  11082. *rpp = n = redirnode;
  11083. rpp = &n->nfile.next;
  11084. parsefname(); /* read name of redirection file */
  11085. break;
  11086. case TLP:
  11087. IF_BASH_FUNCTION(do_func:)
  11088. if (args && app == &args->narg.next
  11089. && !vars && !redir
  11090. ) {
  11091. // struct builtincmd *bcmd;
  11092. // const char *name;
  11093. /* We have a function */
  11094. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  11095. raise_error_unexpected_syntax(TRP);
  11096. //bash allows functions named "123", "..", "return"!
  11097. // name = n->narg.text;
  11098. // if (!goodname(name)
  11099. // || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  11100. // ) {
  11101. // raise_error_syntax("bad function name");
  11102. // }
  11103. n->type = NDEFUN;
  11104. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11105. n->ndefun.text = n->narg.text;
  11106. n->ndefun.linno = g_parsefile->linno;
  11107. n->ndefun.body = parse_command();
  11108. return n;
  11109. }
  11110. IF_BASH_FUNCTION(function_flag = 0;)
  11111. /* fall through */
  11112. default:
  11113. tokpushback = 1;
  11114. goto out;
  11115. }
  11116. }
  11117. out:
  11118. *app = NULL;
  11119. *vpp = NULL;
  11120. *rpp = NULL;
  11121. n = stzalloc(sizeof(struct ncmd));
  11122. if (NCMD != 0)
  11123. n->type = NCMD;
  11124. n->ncmd.linno = savelinno;
  11125. n->ncmd.args = args;
  11126. n->ncmd.assign = vars;
  11127. n->ncmd.redirect = redir;
  11128. return n;
  11129. }
  11130. static union node *
  11131. parse_command(void)
  11132. {
  11133. union node *n1, *n2;
  11134. union node *ap, **app;
  11135. union node *cp, **cpp;
  11136. union node *redir, **rpp;
  11137. union node **rpp2;
  11138. int t;
  11139. int savelinno;
  11140. redir = NULL;
  11141. rpp2 = &redir;
  11142. savelinno = g_parsefile->linno;
  11143. switch (readtoken()) {
  11144. default:
  11145. raise_error_unexpected_syntax(-1);
  11146. /* NOTREACHED */
  11147. case TIF:
  11148. n1 = stzalloc(sizeof(struct nif));
  11149. n1->type = NIF;
  11150. n1->nif.test = list(0);
  11151. if (readtoken() != TTHEN)
  11152. raise_error_unexpected_syntax(TTHEN);
  11153. n1->nif.ifpart = list(0);
  11154. n2 = n1;
  11155. while (readtoken() == TELIF) {
  11156. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  11157. n2 = n2->nif.elsepart;
  11158. n2->type = NIF;
  11159. n2->nif.test = list(0);
  11160. if (readtoken() != TTHEN)
  11161. raise_error_unexpected_syntax(TTHEN);
  11162. n2->nif.ifpart = list(0);
  11163. }
  11164. if (lasttoken == TELSE)
  11165. n2->nif.elsepart = list(0);
  11166. else {
  11167. n2->nif.elsepart = NULL;
  11168. tokpushback = 1;
  11169. }
  11170. t = TFI;
  11171. break;
  11172. case TWHILE:
  11173. case TUNTIL: {
  11174. int got;
  11175. n1 = stzalloc(sizeof(struct nbinary));
  11176. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  11177. n1->nbinary.ch1 = list(0);
  11178. got = readtoken();
  11179. if (got != TDO) {
  11180. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  11181. got == TWORD ? wordtext : ""));
  11182. raise_error_unexpected_syntax(TDO);
  11183. }
  11184. n1->nbinary.ch2 = list(0);
  11185. t = TDONE;
  11186. break;
  11187. }
  11188. case TFOR:
  11189. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  11190. raise_error_syntax("bad for loop variable");
  11191. n1 = stzalloc(sizeof(struct nfor));
  11192. n1->type = NFOR;
  11193. n1->nfor.linno = savelinno;
  11194. n1->nfor.var = wordtext;
  11195. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11196. if (readtoken() == TIN) {
  11197. app = &ap;
  11198. while (readtoken() == TWORD) {
  11199. n2 = stzalloc(sizeof(struct narg));
  11200. n2->type = NARG;
  11201. /*n2->narg.next = NULL; - stzalloc did it */
  11202. n2->narg.text = wordtext;
  11203. n2->narg.backquote = backquotelist;
  11204. *app = n2;
  11205. app = &n2->narg.next;
  11206. }
  11207. *app = NULL;
  11208. n1->nfor.args = ap;
  11209. if (lasttoken != TNL && lasttoken != TSEMI)
  11210. raise_error_unexpected_syntax(-1);
  11211. } else {
  11212. n2 = stzalloc(sizeof(struct narg));
  11213. n2->type = NARG;
  11214. /*n2->narg.next = NULL; - stzalloc did it */
  11215. n2->narg.text = (char *)dolatstr;
  11216. /*n2->narg.backquote = NULL;*/
  11217. n1->nfor.args = n2;
  11218. /*
  11219. * Newline or semicolon here is optional (but note
  11220. * that the original Bourne shell only allowed NL).
  11221. */
  11222. if (lasttoken != TSEMI)
  11223. tokpushback = 1;
  11224. }
  11225. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11226. if (readtoken() != TDO)
  11227. raise_error_unexpected_syntax(TDO);
  11228. n1->nfor.body = list(0);
  11229. t = TDONE;
  11230. break;
  11231. case TCASE:
  11232. n1 = stzalloc(sizeof(struct ncase));
  11233. n1->type = NCASE;
  11234. n1->ncase.linno = savelinno;
  11235. if (readtoken() != TWORD)
  11236. raise_error_unexpected_syntax(TWORD);
  11237. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  11238. n2->type = NARG;
  11239. /*n2->narg.next = NULL; - stzalloc did it */
  11240. n2->narg.text = wordtext;
  11241. n2->narg.backquote = backquotelist;
  11242. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11243. if (readtoken() != TIN)
  11244. raise_error_unexpected_syntax(TIN);
  11245. cpp = &n1->ncase.cases;
  11246. next_case:
  11247. checkkwd = CHKNL | CHKKWD;
  11248. t = readtoken();
  11249. while (t != TESAC) {
  11250. if (lasttoken == TLP)
  11251. readtoken();
  11252. *cpp = cp = stzalloc(sizeof(struct nclist));
  11253. cp->type = NCLIST;
  11254. app = &cp->nclist.pattern;
  11255. for (;;) {
  11256. *app = ap = stzalloc(sizeof(struct narg));
  11257. ap->type = NARG;
  11258. /*ap->narg.next = NULL; - stzalloc did it */
  11259. ap->narg.text = wordtext;
  11260. ap->narg.backquote = backquotelist;
  11261. if (readtoken() != TPIPE)
  11262. break;
  11263. app = &ap->narg.next;
  11264. readtoken();
  11265. }
  11266. //ap->narg.next = NULL;
  11267. if (lasttoken != TRP)
  11268. raise_error_unexpected_syntax(TRP);
  11269. cp->nclist.body = list(2);
  11270. cpp = &cp->nclist.next;
  11271. checkkwd = CHKNL | CHKKWD;
  11272. t = readtoken();
  11273. if (t != TESAC) {
  11274. if (t != TENDCASE)
  11275. raise_error_unexpected_syntax(TENDCASE);
  11276. goto next_case;
  11277. }
  11278. }
  11279. *cpp = NULL;
  11280. goto redir;
  11281. case TLP:
  11282. n1 = stzalloc(sizeof(struct nredir));
  11283. n1->type = NSUBSHELL;
  11284. n1->nredir.linno = savelinno;
  11285. n1->nredir.n = list(0);
  11286. /*n1->nredir.redirect = NULL; - stzalloc did it */
  11287. t = TRP;
  11288. break;
  11289. case TBEGIN:
  11290. n1 = list(0);
  11291. t = TEND;
  11292. break;
  11293. IF_BASH_FUNCTION(case TFUNCTION:)
  11294. case TWORD:
  11295. case TREDIR:
  11296. tokpushback = 1;
  11297. return simplecmd();
  11298. }
  11299. if (readtoken() != t)
  11300. raise_error_unexpected_syntax(t);
  11301. redir:
  11302. /* Now check for redirection which may follow command */
  11303. checkkwd = CHKKWD | CHKALIAS;
  11304. rpp = rpp2;
  11305. while (readtoken() == TREDIR) {
  11306. *rpp = n2 = redirnode;
  11307. rpp = &n2->nfile.next;
  11308. parsefname();
  11309. }
  11310. tokpushback = 1;
  11311. *rpp = NULL;
  11312. if (redir) {
  11313. if (n1->type != NSUBSHELL) {
  11314. n2 = stzalloc(sizeof(struct nredir));
  11315. n2->type = NREDIR;
  11316. n2->nredir.linno = savelinno;
  11317. n2->nredir.n = n1;
  11318. n1 = n2;
  11319. }
  11320. n1->nredir.redirect = redir;
  11321. }
  11322. return n1;
  11323. }
  11324. #if BASH_DOLLAR_SQUOTE
  11325. static int
  11326. decode_dollar_squote(void)
  11327. {
  11328. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  11329. int c, cnt;
  11330. char *p;
  11331. char buf[4];
  11332. c = pgetc();
  11333. p = strchr(C_escapes, c);
  11334. if (p) {
  11335. buf[0] = c;
  11336. p = buf;
  11337. cnt = 3;
  11338. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  11339. do {
  11340. c = pgetc();
  11341. *++p = c;
  11342. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  11343. pungetc();
  11344. } else if (c == 'x') { /* \xHH */
  11345. do {
  11346. c = pgetc();
  11347. *++p = c;
  11348. } while (isxdigit(c) && --cnt);
  11349. pungetc();
  11350. if (cnt == 3) { /* \x but next char is "bad" */
  11351. c = 'x';
  11352. goto unrecognized;
  11353. }
  11354. } else { /* simple seq like \\ or \t */
  11355. p++;
  11356. }
  11357. *p = '\0';
  11358. p = buf;
  11359. c = bb_process_escape_sequence((void*)&p);
  11360. } else { /* unrecognized "\z": print both chars unless ' or " */
  11361. if (c != '\'' && c != '"') {
  11362. unrecognized:
  11363. c |= 0x100; /* "please encode \, then me" */
  11364. }
  11365. }
  11366. return c;
  11367. }
  11368. #endif
  11369. /* Used by expandstr to get here-doc like behaviour. */
  11370. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  11371. static ALWAYS_INLINE int
  11372. realeofmark(const char *eofmark)
  11373. {
  11374. return eofmark && eofmark != FAKEEOFMARK;
  11375. }
  11376. /*
  11377. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  11378. * is not NULL, read a here document. In the latter case, eofmark is the
  11379. * word which marks the end of the document and striptabs is true if
  11380. * leading tabs should be stripped from the document. The argument c
  11381. * is the first character of the input token or document.
  11382. *
  11383. * Because C does not have internal subroutines, I have simulated them
  11384. * using goto's to implement the subroutine linkage. The following macros
  11385. * will run code that appears at the end of readtoken1.
  11386. */
  11387. #define CHECKEND() {goto checkend; checkend_return:;}
  11388. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  11389. #define PARSESUB() {goto parsesub; parsesub_return:;}
  11390. #define PARSEBACKQOLD() {style = OLD; goto parsebackq; parsebackq_oldreturn:;}
  11391. #define PARSEBACKQNEW() {style = NEW; goto parsebackq; parsebackq_newreturn:;}
  11392. #define PARSEPROCSUB() {style = PSUB; goto parsebackq; parsebackq_psreturn:;}
  11393. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  11394. static int
  11395. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  11396. {
  11397. /* NB: syntax parameter fits into smallint */
  11398. /* c parameter is an unsigned char or PEOF */
  11399. char *out;
  11400. size_t len;
  11401. struct nodelist *bqlist;
  11402. smallint quotef;
  11403. smallint style;
  11404. enum { OLD, NEW, PSUB };
  11405. #define oldstyle (style == OLD)
  11406. smallint pssyntax; /* we are expanding a prompt string */
  11407. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  11408. /* syntax stack */
  11409. struct synstack synbase = { };
  11410. struct synstack *synstack = &synbase;
  11411. #if ENABLE_ASH_EXPAND_PRMT
  11412. pssyntax = (syntax == PSSYNTAX);
  11413. if (pssyntax)
  11414. syntax = DQSYNTAX;
  11415. #else
  11416. pssyntax = 0; /* constant */
  11417. #endif
  11418. synstack->syntax = syntax;
  11419. if (syntax == DQSYNTAX)
  11420. synstack->dblquote = 1;
  11421. quotef = 0;
  11422. bqlist = NULL;
  11423. STARTSTACKSTR(out);
  11424. loop:
  11425. /* For each line, until end of word */
  11426. CHECKEND(); /* set c to PEOF if at end of here document */
  11427. for (;;) { /* until end of line or end of word */
  11428. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11429. switch (SIT(c, synstack->syntax)) {
  11430. case CNL: /* '\n' */
  11431. if (synstack->syntax == BASESYNTAX
  11432. && !synstack->varnest
  11433. ) {
  11434. goto endword; /* exit outer loop */
  11435. }
  11436. USTPUTC(c, out);
  11437. nlprompt();
  11438. c = pgetc_top(synstack);
  11439. goto loop; /* continue outer loop */
  11440. case CWORD:
  11441. USTPUTC(c, out);
  11442. break;
  11443. case CCTL:
  11444. #if BASH_DOLLAR_SQUOTE
  11445. if (c == '\\' && bash_dollar_squote) {
  11446. c = decode_dollar_squote();
  11447. if (c == '\0') {
  11448. /* skip $'\000', $'\x00' (like bash) */
  11449. break;
  11450. }
  11451. if (c & 0x100) {
  11452. /* Unknown escape. Encode as '\z' */
  11453. c = (unsigned char)c;
  11454. if (eofmark == NULL || synstack->dblquote)
  11455. USTPUTC(CTLESC, out);
  11456. USTPUTC('\\', out);
  11457. }
  11458. }
  11459. #endif
  11460. if (!eofmark || synstack->dblquote || synstack->varnest)
  11461. USTPUTC(CTLESC, out);
  11462. USTPUTC(c, out);
  11463. break;
  11464. case CBACK: /* backslash */
  11465. c = pgetc();
  11466. if (c == PEOF) {
  11467. USTPUTC(CTLESC, out);
  11468. USTPUTC('\\', out);
  11469. pungetc();
  11470. } else {
  11471. if (pssyntax && c == '$') {
  11472. USTPUTC(CTLESC, out);
  11473. USTPUTC('\\', out);
  11474. }
  11475. /* Backslash is retained if we are in "str"
  11476. * and next char isn't dquote-special.
  11477. */
  11478. if (synstack->dblquote
  11479. && c != '\\'
  11480. && c != '`'
  11481. && c != '$'
  11482. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11483. && (c != '}' || !synstack->varnest)
  11484. ) {
  11485. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11486. USTPUTC('\\', out);
  11487. }
  11488. USTPUTC(CTLESC, out);
  11489. USTPUTC(c, out);
  11490. quotef = 1;
  11491. }
  11492. break;
  11493. case CSQUOTE:
  11494. synstack->syntax = SQSYNTAX;
  11495. quotemark:
  11496. if (eofmark == NULL) {
  11497. USTPUTC(CTLQUOTEMARK, out);
  11498. }
  11499. break;
  11500. case CDQUOTE:
  11501. synstack->syntax = DQSYNTAX;
  11502. synstack->dblquote = 1;
  11503. toggledq:
  11504. if (synstack->varnest)
  11505. synstack->innerdq ^= 1;
  11506. goto quotemark;
  11507. case CENDQUOTE:
  11508. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11509. if (eofmark != NULL && synstack->varnest == 0) {
  11510. USTPUTC(c, out);
  11511. break;
  11512. }
  11513. if (synstack->dqvarnest == 0) {
  11514. synstack->syntax = BASESYNTAX;
  11515. synstack->dblquote = 0;
  11516. }
  11517. quotef = 1;
  11518. if (c == '"')
  11519. goto toggledq;
  11520. goto quotemark;
  11521. case CVAR: /* '$' */
  11522. PARSESUB(); /* parse substitution */
  11523. break;
  11524. case CENDVAR: /* '}' */
  11525. if (!synstack->innerdq && synstack->varnest > 0) {
  11526. if (!--synstack->varnest && synstack->varpushed)
  11527. synstack_pop(&synstack);
  11528. else if (synstack->dqvarnest > 0)
  11529. synstack->dqvarnest--;
  11530. c = CTLENDVAR;
  11531. }
  11532. USTPUTC(c, out);
  11533. break;
  11534. #if ENABLE_FEATURE_SH_MATH
  11535. case CLP: /* '(' in arithmetic */
  11536. synstack->parenlevel++;
  11537. USTPUTC(c, out);
  11538. break;
  11539. case CRP: /* ')' in arithmetic */
  11540. if (synstack->parenlevel > 0) {
  11541. synstack->parenlevel--;
  11542. } else {
  11543. if (pgetc_eatbnl() == ')') {
  11544. c = CTLENDARI;
  11545. synstack_pop(&synstack);
  11546. } else {
  11547. /*
  11548. * unbalanced parens
  11549. * (don't 2nd guess - no error)
  11550. */
  11551. pungetc();
  11552. }
  11553. }
  11554. USTPUTC(c, out);
  11555. break;
  11556. #endif
  11557. case CBQUOTE: /* '`' */
  11558. if (checkkwd & CHKEOFMARK) {
  11559. quotef = 1;
  11560. USTPUTC('`', out);
  11561. break;
  11562. }
  11563. PARSEBACKQOLD();
  11564. break;
  11565. case CENDFILE:
  11566. goto endword; /* exit outer loop */
  11567. default:
  11568. if (synstack->varnest == 0) {
  11569. #if BASH_REDIR_OUTPUT
  11570. if (c == '&') {
  11571. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11572. if (pgetc() == '>')
  11573. c = 0x100 + '>'; /* flag &> */
  11574. pungetc();
  11575. }
  11576. #endif
  11577. #if BASH_PROCESS_SUBST
  11578. if (c == '<' || c == '>') {
  11579. if (pgetc() == '(') {
  11580. PARSEPROCSUB();
  11581. break;
  11582. }
  11583. pungetc();
  11584. }
  11585. #endif
  11586. goto endword; /* exit outer loop */
  11587. }
  11588. USTPUTC(c, out);
  11589. }
  11590. c = pgetc_top(synstack);
  11591. } /* for (;;) */
  11592. endword:
  11593. #if ENABLE_FEATURE_SH_MATH
  11594. if (synstack->syntax == ARISYNTAX)
  11595. raise_error_syntax("missing '))'");
  11596. #endif
  11597. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11598. raise_error_syntax("unterminated quoted string");
  11599. if (synstack->varnest != 0) {
  11600. /* { */
  11601. raise_error_syntax("missing '}'");
  11602. }
  11603. USTPUTC('\0', out);
  11604. len = out - (char *)stackblock();
  11605. out = stackblock();
  11606. if (eofmark == NULL) {
  11607. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11608. && quotef == 0
  11609. ) {
  11610. if (isdigit_str(out)) {
  11611. PARSEREDIR(); /* passed as params: out, c */
  11612. lasttoken = TREDIR;
  11613. return lasttoken;
  11614. }
  11615. /* else: non-number X seen, interpret it
  11616. * as "NNNX>file" = "NNNX >file" */
  11617. }
  11618. pungetc();
  11619. }
  11620. quoteflag = quotef;
  11621. backquotelist = bqlist;
  11622. grabstackblock(len);
  11623. wordtext = out;
  11624. lasttoken = TWORD;
  11625. return lasttoken;
  11626. /* end of readtoken routine */
  11627. /*
  11628. * Check to see whether we are at the end of the here document. When this
  11629. * is called, c is set to the first character of the next input line. If
  11630. * we are at the end of the here document, this routine sets the c to PEOF.
  11631. */
  11632. checkend: {
  11633. if (realeofmark(eofmark)) {
  11634. int markloc;
  11635. char *p;
  11636. if (striptabs) {
  11637. while (c == '\t')
  11638. c = pgetc();
  11639. }
  11640. markloc = out - (char *)stackblock();
  11641. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11642. if (c != *p)
  11643. goto more_heredoc;
  11644. /* FIXME: fails for backslash-newlined terminator:
  11645. * cat <<EOF
  11646. * ...
  11647. * EO\
  11648. * F
  11649. * (see heredoc_bkslash_newline2.tests)
  11650. */
  11651. c = pgetc();
  11652. }
  11653. if (c == '\n' || c == PEOF) {
  11654. c = PEOF;
  11655. if (trap_depth == 0)
  11656. g_parsefile->linno++;
  11657. needprompt = doprompt;
  11658. } else {
  11659. int len_here;
  11660. more_heredoc:
  11661. p = (char *)stackblock() + markloc + 1;
  11662. len_here = out - p;
  11663. if (len_here) {
  11664. len_here -= (c >= PEOF);
  11665. c = p[-1];
  11666. if (len_here) {
  11667. char *str;
  11668. str = alloca(len_here + 1);
  11669. *(char *)mempcpy(str, p, len_here) = '\0';
  11670. pushstring(str, NULL);
  11671. }
  11672. }
  11673. }
  11674. STADJUST((char *)stackblock() + markloc - out, out);
  11675. }
  11676. goto checkend_return;
  11677. }
  11678. /*
  11679. * Parse a redirection operator. The variable "out" points to a string
  11680. * specifying the fd to be redirected. The variable "c" contains the
  11681. * first character of the redirection operator.
  11682. */
  11683. parseredir: {
  11684. /* out is already checked to be a valid number or "" */
  11685. int fd = (*out == '\0' ? -1 : atoi(out));
  11686. union node *np;
  11687. np = stzalloc(sizeof(struct nfile));
  11688. if (c == '>') {
  11689. np->nfile.fd = 1;
  11690. c = pgetc_eatbnl();
  11691. if (c == '>')
  11692. np->type = NAPPEND;
  11693. else if (c == '|')
  11694. np->type = NCLOBBER;
  11695. else if (c == '&')
  11696. np->type = NTOFD;
  11697. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11698. else {
  11699. np->type = NTO;
  11700. pungetc();
  11701. }
  11702. }
  11703. #if BASH_REDIR_OUTPUT
  11704. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11705. np->nfile.fd = 1;
  11706. pgetc(); /* this is '>', no need to check */
  11707. np->type = NTO2;
  11708. }
  11709. #endif
  11710. else { /* c == '<' */
  11711. /*np->nfile.fd = 0; - stzalloc did it */
  11712. c = pgetc_eatbnl();
  11713. switch (c) {
  11714. case '<':
  11715. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11716. np = stzalloc(sizeof(struct nhere));
  11717. /*np->nfile.fd = 0; - stzalloc did it */
  11718. }
  11719. np->type = NHERE;
  11720. heredoc = stzalloc(sizeof(struct heredoc));
  11721. heredoc->here = np;
  11722. c = pgetc_eatbnl();
  11723. if (c == '-') {
  11724. heredoc->striptabs = 1;
  11725. } else {
  11726. /*heredoc->striptabs = 0; - stzalloc did it */
  11727. pungetc();
  11728. }
  11729. break;
  11730. case '&':
  11731. np->type = NFROMFD;
  11732. break;
  11733. case '>':
  11734. np->type = NFROMTO;
  11735. break;
  11736. default:
  11737. np->type = NFROM;
  11738. pungetc();
  11739. break;
  11740. }
  11741. }
  11742. if (fd >= 0)
  11743. np->nfile.fd = fd;
  11744. redirnode = np;
  11745. goto parseredir_return;
  11746. }
  11747. /*
  11748. * Parse a substitution. At this point, we have read the dollar sign
  11749. * and nothing else.
  11750. */
  11751. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11752. * (assuming ascii char codes, as the original implementation did) */
  11753. #define is_special(c) \
  11754. (((unsigned)(c) - 33 < 32) \
  11755. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11756. parsesub: {
  11757. unsigned char subtype;
  11758. int typeloc;
  11759. c = pgetc_eatbnl();
  11760. if ((checkkwd & CHKEOFMARK)
  11761. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11762. ) {
  11763. #if BASH_DOLLAR_SQUOTE
  11764. if (synstack->syntax != DQSYNTAX && c == '\'')
  11765. bash_dollar_squote = 1;
  11766. else
  11767. #endif
  11768. USTPUTC('$', out);
  11769. pungetc();
  11770. } else if (c == '(') {
  11771. /* $(command) or $((arith)) */
  11772. if (pgetc_eatbnl() == '(') {
  11773. #if ENABLE_FEATURE_SH_MATH
  11774. PARSEARITH();
  11775. #else
  11776. raise_error_syntax("support for $((arith)) is disabled");
  11777. #endif
  11778. } else {
  11779. pungetc();
  11780. PARSEBACKQNEW();
  11781. }
  11782. } else {
  11783. /* $VAR, $<specialchar>, ${...}, or PEOF */
  11784. smalluint newsyn = synstack->syntax;
  11785. USTPUTC(CTLVAR, out);
  11786. typeloc = out - (char *)stackblock();
  11787. STADJUST(1, out);
  11788. subtype = VSNORMAL;
  11789. if (c == '{') {
  11790. c = pgetc_eatbnl();
  11791. subtype = 0;
  11792. }
  11793. varname:
  11794. if (is_name(c)) {
  11795. /* $[{[#]]NAME[}] */
  11796. do {
  11797. STPUTC(c, out);
  11798. c = pgetc_eatbnl();
  11799. } while (is_in_name(c));
  11800. } else if (isdigit(c)) {
  11801. /* $[{[#]]NUM[}] */
  11802. do {
  11803. STPUTC(c, out);
  11804. c = pgetc_eatbnl();
  11805. } while ((subtype == 0 || subtype == VSLENGTH) && isdigit(c));
  11806. } else if (c != '}') {
  11807. /* $[{[#]]<specialchar>[}] */
  11808. int cc = c;
  11809. c = pgetc_eatbnl();
  11810. if (!subtype && cc == '#') {
  11811. subtype = VSLENGTH;
  11812. if (c == '_' || isalnum(c))
  11813. goto varname;
  11814. cc = c;
  11815. c = pgetc_eatbnl();
  11816. if (cc == '}' || c != '}') {
  11817. pungetc();
  11818. subtype = 0;
  11819. c = cc;
  11820. cc = '#';
  11821. }
  11822. }
  11823. if (!is_special(cc)) {
  11824. if (subtype == VSLENGTH)
  11825. subtype = 0;
  11826. goto badsub;
  11827. }
  11828. USTPUTC(cc, out);
  11829. } else
  11830. goto badsub;
  11831. if (subtype == 0) {
  11832. static const char types[] ALIGN1 = "}-+?=";
  11833. /* ${VAR...} but not $VAR or ${#VAR} */
  11834. /* c == first char after VAR */
  11835. int cc = c;
  11836. switch (c) {
  11837. case ':':
  11838. c = pgetc_eatbnl();
  11839. #if BASH_SUBSTR
  11840. /* This check is only needed to not misinterpret
  11841. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11842. * constructs.
  11843. */
  11844. if (!strchr(types, c)) {
  11845. subtype = VSSUBSTR;
  11846. pungetc();
  11847. break; /* "goto badsub" is bigger (!) */
  11848. }
  11849. #endif
  11850. subtype = VSNUL;
  11851. /*FALLTHROUGH*/
  11852. default: {
  11853. const char *p = strchr(types, c);
  11854. if (p == NULL)
  11855. break;
  11856. subtype |= p - types + VSNORMAL;
  11857. break;
  11858. }
  11859. case '%':
  11860. case '#':
  11861. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11862. c = pgetc_eatbnl();
  11863. if (c == cc)
  11864. subtype++;
  11865. else
  11866. pungetc();
  11867. newsyn = BASESYNTAX;
  11868. break;
  11869. #if BASH_PATTERN_SUBST
  11870. case '/':
  11871. /* ${v/[/]pattern/repl} */
  11872. //TODO: encode pattern and repl separately.
  11873. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11874. // are broken (should print "ONE")
  11875. subtype = VSREPLACE;
  11876. newsyn = BASESYNTAX;
  11877. c = pgetc_eatbnl();
  11878. if (c != '/')
  11879. goto badsub;
  11880. subtype++; /* VSREPLACEALL */
  11881. break;
  11882. #endif
  11883. }
  11884. } else {
  11885. if (subtype == VSLENGTH && c != '}')
  11886. subtype = 0;
  11887. badsub:
  11888. pungetc();
  11889. }
  11890. if (newsyn == ARISYNTAX)
  11891. newsyn = DQSYNTAX;
  11892. if ((newsyn != synstack->syntax || synstack->innerdq)
  11893. && subtype != VSNORMAL
  11894. ) {
  11895. synstack_push(&synstack,
  11896. synstack->prev ?: alloca(sizeof(*synstack)),
  11897. newsyn);
  11898. synstack->varpushed = 1;
  11899. synstack->dblquote = newsyn != BASESYNTAX;
  11900. }
  11901. ((unsigned char *)stackblock())[typeloc] = subtype;
  11902. if (subtype != VSNORMAL) {
  11903. synstack->varnest++;
  11904. if (synstack->dblquote)
  11905. synstack->dqvarnest++;
  11906. }
  11907. STPUTC('=', out);
  11908. }
  11909. goto parsesub_return;
  11910. }
  11911. /*
  11912. * Called to parse command substitutions. Newstyle is set if the command
  11913. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11914. * list of commands (passed by reference), and savelen is the number of
  11915. * characters on the top of the stack which must be preserved.
  11916. */
  11917. parsebackq: {
  11918. struct nodelist **nlpp;
  11919. union node *n;
  11920. char *str;
  11921. size_t savelen;
  11922. struct heredoc *saveheredoclist;
  11923. smallint saveprompt = 0;
  11924. str = NULL;
  11925. savelen = out - (char *)stackblock();
  11926. if (savelen > 0) {
  11927. /*
  11928. * FIXME: this can allocate very large block on stack and SEGV.
  11929. * Example:
  11930. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11931. * allocates 100kb for every command subst. With about
  11932. * a hundred command substitutions stack overflows.
  11933. * With larger prepended string, SEGV happens sooner.
  11934. */
  11935. str = alloca(savelen);
  11936. memcpy(str, stackblock(), savelen);
  11937. }
  11938. if (oldstyle) {
  11939. /* We must read until the closing backquote, giving special
  11940. * treatment to some slashes, and then push the string and
  11941. * reread it as input, interpreting it normally.
  11942. */
  11943. char *pout;
  11944. size_t psavelen;
  11945. char *pstr;
  11946. STARTSTACKSTR(pout);
  11947. for (;;) {
  11948. int pc;
  11949. setprompt_if(needprompt, 2);
  11950. pc = pgetc_eatbnl();
  11951. switch (pc) {
  11952. case '`':
  11953. goto done;
  11954. case '\\':
  11955. pc = pgetc(); /* not pgetc_eatbnl! */
  11956. if (pc != '\\' && pc != '`' && pc != '$'
  11957. && (!synstack->dblquote || pc != '"')
  11958. ) {
  11959. STPUTC('\\', pout);
  11960. }
  11961. break;
  11962. case PEOF:
  11963. raise_error_syntax("EOF in backquote substitution");
  11964. case '\n':
  11965. nlnoprompt();
  11966. break;
  11967. default:
  11968. break;
  11969. }
  11970. STPUTC(pc, pout);
  11971. }
  11972. done:
  11973. STPUTC('\0', pout);
  11974. psavelen = pout - (char *)stackblock();
  11975. if (psavelen > 0) {
  11976. pstr = grabstackstr(pout);
  11977. setinputstring(pstr);
  11978. }
  11979. }
  11980. nlpp = &bqlist;
  11981. while (*nlpp)
  11982. nlpp = &(*nlpp)->next;
  11983. *nlpp = stzalloc(sizeof(**nlpp));
  11984. /* (*nlpp)->next = NULL; - stzalloc did it */
  11985. saveheredoclist = heredoclist;
  11986. heredoclist = NULL;
  11987. if (oldstyle) {
  11988. saveprompt = doprompt;
  11989. doprompt = 0;
  11990. }
  11991. n = list(2);
  11992. if (oldstyle)
  11993. doprompt = saveprompt;
  11994. else {
  11995. if (readtoken() != TRP)
  11996. raise_error_unexpected_syntax(TRP);
  11997. setinputstring(nullstr);
  11998. }
  11999. parseheredoc();
  12000. heredoclist = saveheredoclist;
  12001. (*nlpp)->n = n;
  12002. /* Start reading from old file again. */
  12003. popfile();
  12004. /* Ignore any pushed back tokens left from the backquote parsing. */
  12005. if (oldstyle)
  12006. tokpushback = 0;
  12007. out = growstackto(savelen + 1);
  12008. if (str) {
  12009. memcpy(out, str, savelen);
  12010. STADJUST(savelen, out);
  12011. }
  12012. #if BASH_PROCESS_SUBST
  12013. if (style == PSUB)
  12014. USTPUTC(c == '<' ? CTLFROMPROC : CTLTOPROC, out);
  12015. else
  12016. #endif
  12017. USTPUTC(CTLBACKQ, out);
  12018. if (oldstyle)
  12019. goto parsebackq_oldreturn;
  12020. #if BASH_PROCESS_SUBST
  12021. else if (style == PSUB)
  12022. goto parsebackq_psreturn;
  12023. #endif
  12024. goto parsebackq_newreturn;
  12025. }
  12026. #if ENABLE_FEATURE_SH_MATH
  12027. /*
  12028. * Parse an arithmetic expansion (indicate start of one and set state)
  12029. */
  12030. parsearith: {
  12031. synstack_push(&synstack,
  12032. synstack->prev ?: alloca(sizeof(*synstack)),
  12033. ARISYNTAX);
  12034. synstack->dblquote = 1;
  12035. USTPUTC(CTLARI, out);
  12036. goto parsearith_return;
  12037. }
  12038. #endif
  12039. } /* end of readtoken */
  12040. /*
  12041. * Read the next input token.
  12042. * If the token is a word, we set backquotelist to the list of cmds in
  12043. * backquotes. We set quoteflag to true if any part of the word was
  12044. * quoted.
  12045. * If the token is TREDIR, then we set redirnode to a structure containing
  12046. * the redirection.
  12047. *
  12048. * [Change comment: here documents and internal procedures]
  12049. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  12050. * word parsing code into a separate routine. In this case, readtoken
  12051. * doesn't need to have any internal procedures, but parseword does.
  12052. * We could also make parseoperator in essence the main routine, and
  12053. * have parseword (readtoken1?) handle both words and redirection.]
  12054. */
  12055. #define NEW_xxreadtoken
  12056. #ifdef NEW_xxreadtoken
  12057. /* singles must be first! */
  12058. static const char xxreadtoken_chars[7] ALIGN1 = {
  12059. '\n', '(', ')', /* singles */
  12060. '&', '|', ';', /* doubles */
  12061. 0
  12062. };
  12063. #define xxreadtoken_singles 3
  12064. #define xxreadtoken_doubles 3
  12065. static const char xxreadtoken_tokens[] ALIGN1 = {
  12066. TNL, TLP, TRP, /* only single occurrence allowed */
  12067. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  12068. TEOF, /* corresponds to trailing nul */
  12069. TAND, TOR, TENDCASE /* if double occurrence */
  12070. };
  12071. static int
  12072. xxreadtoken(void)
  12073. {
  12074. int c;
  12075. if (tokpushback) {
  12076. tokpushback = 0;
  12077. return lasttoken;
  12078. }
  12079. setprompt_if(needprompt, 2);
  12080. for (;;) { /* until token or start of word found */
  12081. c = pgetc_eatbnl();
  12082. if (c == ' ' || c == '\t')
  12083. continue;
  12084. if (c == '#') {
  12085. while ((c = pgetc()) != '\n' && c != PEOF)
  12086. continue;
  12087. pungetc();
  12088. } else if (c == '\\') {
  12089. break; /* return readtoken1(...) */
  12090. } else {
  12091. const char *p;
  12092. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  12093. if (c != PEOF) {
  12094. if (c == '\n') {
  12095. nlnoprompt();
  12096. }
  12097. p = strchr(xxreadtoken_chars, c);
  12098. if (p == NULL)
  12099. break; /* return readtoken1(...) */
  12100. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  12101. int cc = pgetc_eatbnl();
  12102. if (cc == c) { /* double occurrence? */
  12103. p += xxreadtoken_doubles + 1;
  12104. } else {
  12105. pungetc();
  12106. #if BASH_REDIR_OUTPUT
  12107. if (c == '&' && cc == '>') /* &> */
  12108. break; /* return readtoken1(...) */
  12109. #endif
  12110. }
  12111. }
  12112. }
  12113. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  12114. return lasttoken;
  12115. }
  12116. } /* for (;;) */
  12117. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  12118. }
  12119. #else /* old xxreadtoken */
  12120. #define RETURN(token) return lasttoken = token
  12121. static int
  12122. xxreadtoken(void)
  12123. {
  12124. int c;
  12125. if (tokpushback) {
  12126. tokpushback = 0;
  12127. return lasttoken;
  12128. }
  12129. setprompt_if(needprompt, 2);
  12130. for (;;) { /* until token or start of word found */
  12131. c = pgetc_eatbnl();
  12132. switch (c) {
  12133. case ' ': case '\t':
  12134. continue;
  12135. case '#':
  12136. while ((c = pgetc()) != '\n' && c != PEOF)
  12137. continue;
  12138. pungetc();
  12139. continue;
  12140. case '\n':
  12141. nlnoprompt();
  12142. RETURN(TNL);
  12143. case PEOF:
  12144. RETURN(TEOF);
  12145. case '&':
  12146. if (pgetc_eatbnl() == '&')
  12147. RETURN(TAND);
  12148. pungetc();
  12149. RETURN(TBACKGND);
  12150. case '|':
  12151. if (pgetc_eatbnl() == '|')
  12152. RETURN(TOR);
  12153. pungetc();
  12154. RETURN(TPIPE);
  12155. case ';':
  12156. if (pgetc_eatbnl() == ';')
  12157. RETURN(TENDCASE);
  12158. pungetc();
  12159. RETURN(TSEMI);
  12160. case '(':
  12161. RETURN(TLP);
  12162. case ')':
  12163. RETURN(TRP);
  12164. }
  12165. break;
  12166. }
  12167. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  12168. #undef RETURN
  12169. }
  12170. #endif /* old xxreadtoken */
  12171. static int
  12172. readtoken(void)
  12173. {
  12174. int t;
  12175. int kwd = checkkwd;
  12176. #if DEBUG
  12177. smallint alreadyseen = tokpushback;
  12178. #endif
  12179. #if ENABLE_ASH_ALIAS
  12180. top:
  12181. #endif
  12182. t = xxreadtoken();
  12183. /*
  12184. * eat newlines
  12185. */
  12186. if (kwd & CHKNL) {
  12187. while (t == TNL) {
  12188. parseheredoc();
  12189. checkkwd = 0;
  12190. t = xxreadtoken();
  12191. }
  12192. }
  12193. kwd |= checkkwd;
  12194. checkkwd = 0;
  12195. if (t != TWORD || quoteflag) {
  12196. goto out;
  12197. }
  12198. /*
  12199. * check for keywords
  12200. */
  12201. if (kwd & CHKKWD) {
  12202. const char *const *pp;
  12203. pp = findkwd(wordtext);
  12204. if (pp) {
  12205. lasttoken = t = pp - tokname_array;
  12206. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  12207. goto out;
  12208. }
  12209. }
  12210. if (kwd & CHKALIAS) {
  12211. #if ENABLE_ASH_ALIAS
  12212. struct alias *ap;
  12213. ap = lookupalias(wordtext, 1);
  12214. if (ap != NULL) {
  12215. if (*ap->val) {
  12216. pushstring(ap->val, ap);
  12217. }
  12218. goto top;
  12219. }
  12220. #endif
  12221. }
  12222. out:
  12223. #if DEBUG
  12224. if (!alreadyseen)
  12225. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  12226. else
  12227. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  12228. #endif
  12229. return t;
  12230. }
  12231. /*
  12232. * Read and parse a command. Returns NODE_EOF on end of file.
  12233. * (NULL is a valid parse tree indicating a blank line.)
  12234. */
  12235. static union node *
  12236. parsecmd(int interact)
  12237. {
  12238. tokpushback = 0;
  12239. checkkwd = 0;
  12240. heredoclist = 0;
  12241. doprompt = interact;
  12242. setprompt_if(doprompt, doprompt);
  12243. needprompt = 0;
  12244. return list(1);
  12245. }
  12246. /*
  12247. * Input any here documents.
  12248. */
  12249. static void
  12250. parseheredoc(void)
  12251. {
  12252. struct heredoc *here;
  12253. union node *n;
  12254. here = heredoclist;
  12255. heredoclist = NULL;
  12256. while (here) {
  12257. tokpushback = 0;
  12258. setprompt_if(needprompt, 2);
  12259. if (here->here->type == NHERE)
  12260. readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
  12261. else
  12262. readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
  12263. n = stzalloc(sizeof(struct narg));
  12264. n->narg.type = NARG;
  12265. /*n->narg.next = NULL; - stzalloc did it */
  12266. n->narg.text = wordtext;
  12267. n->narg.backquote = backquotelist;
  12268. here->here->nhere.doc = n;
  12269. here = here->next;
  12270. }
  12271. }
  12272. static const char *
  12273. expandstr(const char *ps, int syntax_type)
  12274. {
  12275. struct parsefile *file_stop;
  12276. struct jmploc *volatile savehandler;
  12277. struct heredoc *saveheredoclist;
  12278. const char *result;
  12279. int saveprompt;
  12280. struct jmploc jmploc;
  12281. union node n;
  12282. int err;
  12283. file_stop = g_parsefile;
  12284. /* XXX Fix (char *) cast. */
  12285. setinputstring((char *)ps);
  12286. saveheredoclist = heredoclist;
  12287. heredoclist = NULL;
  12288. saveprompt = doprompt;
  12289. doprompt = 0;
  12290. result = ps;
  12291. savehandler = exception_handler;
  12292. err = setjmp(jmploc.loc);
  12293. if (err)
  12294. goto out;
  12295. /* readtoken1() might die horribly.
  12296. * Try a prompt with syntactically wrong command:
  12297. * PS1='$(date "+%H:%M:%S) > '
  12298. */
  12299. exception_handler = &jmploc;
  12300. readtoken1(pgetc_eatbnl(), syntax_type, FAKEEOFMARK, 0);
  12301. n.narg.type = NARG;
  12302. n.narg.next = NULL;
  12303. n.narg.text = wordtext;
  12304. n.narg.backquote = backquotelist;
  12305. /* expandarg() might fail too:
  12306. * PS1='$((123+))'
  12307. */
  12308. expandarg(&n, NULL, EXP_QUOTED);
  12309. result = stackblock();
  12310. out:
  12311. exception_handler = savehandler;
  12312. if (err && exception_type != EXERROR)
  12313. longjmp(exception_handler->loc, 1);
  12314. doprompt = saveprompt;
  12315. /* Try: PS1='`xxx(`' */
  12316. unwindfiles(file_stop);
  12317. heredoclist = saveheredoclist;
  12318. return result;
  12319. }
  12320. static inline int
  12321. parser_eof(void)
  12322. {
  12323. return tokpushback && lasttoken == TEOF;
  12324. }
  12325. /*
  12326. * Execute a command or commands contained in a string.
  12327. */
  12328. static int
  12329. evalstring(char *s, int flags)
  12330. {
  12331. struct jmploc *volatile savehandler;
  12332. struct jmploc jmploc;
  12333. int ex;
  12334. union node *n;
  12335. struct stackmark smark;
  12336. int status;
  12337. s = sstrdup(s);
  12338. setinputstring(s);
  12339. setstackmark(&smark);
  12340. status = 0;
  12341. /* On exception inside execution loop, we must popfile().
  12342. * Try interactively:
  12343. * readonly a=a
  12344. * command eval "a=b" # throws "is read only" error
  12345. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  12346. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  12347. */
  12348. savehandler = exception_handler;
  12349. ex = setjmp(jmploc.loc);
  12350. if (ex)
  12351. goto out;
  12352. exception_handler = &jmploc;
  12353. while ((n = parsecmd(0)) != NODE_EOF) {
  12354. int i;
  12355. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  12356. if (n)
  12357. status = i;
  12358. popstackmark(&smark);
  12359. if (evalskip)
  12360. break;
  12361. }
  12362. out:
  12363. popstackmark(&smark);
  12364. popfile();
  12365. stunalloc(s);
  12366. exception_handler = savehandler;
  12367. if (ex)
  12368. longjmp(exception_handler->loc, ex);
  12369. return status;
  12370. }
  12371. /*
  12372. * The eval command.
  12373. */
  12374. static int FAST_FUNC
  12375. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  12376. {
  12377. char *p;
  12378. char *concat;
  12379. if (argv[1]) {
  12380. p = argv[1];
  12381. argv += 2;
  12382. if (argv[0]) {
  12383. STARTSTACKSTR(concat);
  12384. for (;;) {
  12385. concat = stack_putstr(p, concat);
  12386. p = *argv++;
  12387. if (p == NULL)
  12388. break;
  12389. STPUTC(' ', concat);
  12390. }
  12391. STPUTC('\0', concat);
  12392. p = grabstackstr(concat);
  12393. }
  12394. return evalstring(p, flags & EV_TESTED);
  12395. }
  12396. return 0;
  12397. }
  12398. /*
  12399. * Read and execute commands.
  12400. * "Top" is nonzero for the top level command loop;
  12401. * it turns on prompting if the shell is interactive.
  12402. */
  12403. static int
  12404. cmdloop(int top)
  12405. {
  12406. union node *n;
  12407. struct stackmark smark;
  12408. int inter;
  12409. int status = 0;
  12410. int numeof = 0;
  12411. TRACE(("cmdloop(%d) called\n", top));
  12412. for (;;) {
  12413. int skip;
  12414. setstackmark(&smark);
  12415. #if JOBS
  12416. if (doing_jobctl)
  12417. showjobs(SHOW_CHANGED|SHOW_STDERR);
  12418. #endif
  12419. inter = 0;
  12420. if (iflag && top) {
  12421. inter++;
  12422. chkmail();
  12423. }
  12424. n = parsecmd(inter);
  12425. #if DEBUG
  12426. if (DEBUG > 2 && debug && (n != NODE_EOF))
  12427. showtree(n);
  12428. #endif
  12429. if (n == NODE_EOF) {
  12430. if (!top || numeof >= 50)
  12431. break;
  12432. if (!stoppedjobs()) {
  12433. if (!iflag)
  12434. break;
  12435. if (!Iflag) {
  12436. newline_and_flush(stderr);
  12437. break;
  12438. }
  12439. /* "set -o ignoreeof" active, do not exit command loop on ^D */
  12440. out2str("\nUse \"exit\" to leave shell.\n");
  12441. }
  12442. numeof++;
  12443. } else {
  12444. int i;
  12445. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12446. job_warning >>= 1;
  12447. numeof = 0;
  12448. i = evaltree(n, 0);
  12449. if (n)
  12450. status = i;
  12451. }
  12452. popstackmark(&smark);
  12453. skip = evalskip;
  12454. if (skip) {
  12455. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  12456. break;
  12457. }
  12458. }
  12459. return status;
  12460. }
  12461. /*
  12462. * Take commands from a file. To be compatible we should do a path
  12463. * search for the file, which is necessary to find sub-commands.
  12464. */
  12465. static char *
  12466. find_dot_file(char *basename)
  12467. {
  12468. char *fullname;
  12469. const char *path;
  12470. struct stat statb;
  12471. int len;
  12472. /* don't try this for absolute or relative paths */
  12473. if (strchr(basename, '/'))
  12474. return basename;
  12475. path = pathval();
  12476. while ((len = padvance(&path, basename)) >= 0) {
  12477. fullname = stackblock();
  12478. if ((!pathopt || *pathopt == 'f')
  12479. && !stat(fullname, &statb) && S_ISREG(statb.st_mode)
  12480. ) {
  12481. /* This will be freed by the caller. */
  12482. return stalloc(len);
  12483. }
  12484. }
  12485. /* not found in PATH */
  12486. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12487. return basename;
  12488. #else
  12489. ash_msg_and_raise_error("%s: not found", basename);
  12490. /* NOTREACHED */
  12491. #endif
  12492. }
  12493. static int FAST_FUNC
  12494. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12495. {
  12496. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12497. int status = 0;
  12498. char *fullname;
  12499. char **argv;
  12500. char *args_need_save;
  12501. volatile struct shparam saveparam;
  12502. //???
  12503. // struct strlist *sp;
  12504. // for (sp = cmdenviron; sp; sp = sp->next)
  12505. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12506. nextopt(nullstr); /* handle possible "--" */
  12507. argv = argptr;
  12508. if (!argv[0]) {
  12509. /* bash says: "bash: .: filename argument required" */
  12510. return 2; /* bash compat */
  12511. }
  12512. /* This aborts if file isn't found, which is POSIXly correct.
  12513. * bash returns exitcode 1 instead.
  12514. */
  12515. fullname = find_dot_file(argv[0]);
  12516. argv++;
  12517. args_need_save = argv[0];
  12518. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12519. int argc;
  12520. saveparam = shellparam;
  12521. shellparam.malloced = 0;
  12522. argc = 1;
  12523. while (argv[argc])
  12524. argc++;
  12525. shellparam.nparam = argc;
  12526. shellparam.p = argv;
  12527. };
  12528. /* This aborts if file can't be opened, which is POSIXly correct.
  12529. * bash returns exitcode 1 instead.
  12530. */
  12531. setinputfile(fullname, INPUT_PUSH_FILE);
  12532. commandname = fullname;
  12533. status = cmdloop(0);
  12534. popfile();
  12535. if (args_need_save) {
  12536. freeparam(&shellparam);
  12537. shellparam = saveparam;
  12538. };
  12539. return status;
  12540. }
  12541. static int FAST_FUNC
  12542. exitcmd(int argc UNUSED_PARAM, char **argv)
  12543. {
  12544. if (stoppedjobs())
  12545. return 0;
  12546. if (argv[1])
  12547. savestatus = number(argv[1]);
  12548. //TODO: this script
  12549. // trap 'echo trap:$FUNCNAME' EXIT
  12550. // f() { exit; }
  12551. // f
  12552. //prints "trap:f" in bash. We can call exitshell() here to achieve this.
  12553. //For now, keeping dash code:
  12554. raise_exception(EXEXIT);
  12555. /* NOTREACHED */
  12556. }
  12557. /*
  12558. * Read a file containing shell functions.
  12559. */
  12560. static void
  12561. readcmdfile(char *name)
  12562. {
  12563. setinputfile(name, INPUT_PUSH_FILE);
  12564. cmdloop(0);
  12565. popfile();
  12566. }
  12567. /* ============ find_command inplementation */
  12568. static int test_exec(/*const char *fullname,*/ struct stat *statb)
  12569. {
  12570. /*
  12571. * TODO: use faccessat(AT_FDCWD, fullname, X_OK, AT_EACCESS)
  12572. * instead: executability may depend on ACLs, capabilities
  12573. * and who knows what else, not just mode bits.
  12574. * (faccessat2 syscall was added to Linux in May 14 2020)
  12575. */
  12576. mode_t stmode;
  12577. uid_t euid;
  12578. enum { ANY_IX = S_IXUSR | S_IXGRP | S_IXOTH };
  12579. /* Do we already know with no extra syscalls? */
  12580. if (!S_ISREG(statb->st_mode))
  12581. return 0; /* not a regular file */
  12582. if ((statb->st_mode & ANY_IX) == 0)
  12583. return 0; /* no one can execute */
  12584. if ((statb->st_mode & ANY_IX) == ANY_IX)
  12585. return 1; /* anyone can execute */
  12586. /* Executability depends on our euid/egid/supplementary groups */
  12587. stmode = S_IXOTH;
  12588. euid = get_cached_euid(&groupinfo.euid);
  12589. if (euid == 0)
  12590. /* for root user, any X bit is good enough */
  12591. stmode = ANY_IX;
  12592. else if (statb->st_uid == euid)
  12593. stmode = S_IXUSR;
  12594. else if (statb->st_gid == get_cached_egid(&groupinfo.egid))
  12595. stmode = S_IXGRP;
  12596. else if (is_in_supplementary_groups(&groupinfo, statb->st_gid))
  12597. stmode = S_IXGRP;
  12598. return statb->st_mode & stmode;
  12599. }
  12600. /*
  12601. * Resolve a command name. If you change this routine, you may have to
  12602. * change the shellexec routine as well.
  12603. */
  12604. static void
  12605. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12606. {
  12607. struct tblentry *cmdp;
  12608. int idx;
  12609. int prev;
  12610. char *fullname;
  12611. struct stat statb;
  12612. int e;
  12613. int updatetbl;
  12614. struct builtincmd *bcmd;
  12615. int len;
  12616. /* If name contains a slash, don't use PATH or hash table */
  12617. if (strchr(name, '/') != NULL) {
  12618. entry->u.index = -1;
  12619. if (act & DO_ABS) {
  12620. while (stat(name, &statb) < 0) {
  12621. #ifdef SYSV
  12622. if (errno == EINTR)
  12623. continue;
  12624. #endif
  12625. absfail:
  12626. entry->cmdtype = CMDUNKNOWN;
  12627. return;
  12628. }
  12629. if (!test_exec(/*name,*/ &statb))
  12630. goto absfail;
  12631. }
  12632. entry->cmdtype = CMDNORMAL;
  12633. return;
  12634. }
  12635. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12636. updatetbl = (path == pathval());
  12637. if (!updatetbl)
  12638. act |= DO_ALTPATH;
  12639. /* If name is in the table, check answer will be ok */
  12640. cmdp = cmdlookup(name, 0);
  12641. if (cmdp != NULL) {
  12642. int bit;
  12643. switch (cmdp->cmdtype) {
  12644. default:
  12645. #if DEBUG
  12646. abort();
  12647. #endif
  12648. case CMDNORMAL:
  12649. bit = DO_ALTPATH | DO_REGBLTIN;
  12650. break;
  12651. case CMDFUNCTION:
  12652. bit = DO_NOFUNC;
  12653. break;
  12654. case CMDBUILTIN:
  12655. bit = IS_BUILTIN_REGULAR(cmdp->param.cmd) ? 0 : DO_REGBLTIN;
  12656. break;
  12657. }
  12658. if (act & bit) {
  12659. if (act & bit & DO_REGBLTIN)
  12660. goto fail;
  12661. updatetbl = 0;
  12662. cmdp = NULL;
  12663. } else if (cmdp->rehash == 0)
  12664. /* if not invalidated by cd, we're done */
  12665. goto success;
  12666. }
  12667. /* If %builtin not in path, check for builtin next */
  12668. bcmd = find_builtin(name);
  12669. if (bcmd) {
  12670. if (IS_BUILTIN_REGULAR(bcmd))
  12671. goto builtin_success;
  12672. if (act & DO_ALTPATH)
  12673. goto builtin_success;
  12674. if (builtinloc <= 0)
  12675. goto builtin_success;
  12676. }
  12677. if (act & DO_REGBLTIN)
  12678. goto fail;
  12679. #if ENABLE_FEATURE_SH_STANDALONE
  12680. {
  12681. int applet_no = find_applet_by_name(name);
  12682. if (applet_no >= 0) {
  12683. entry->cmdtype = CMDNORMAL;
  12684. entry->u.index = -2 - applet_no;
  12685. return;
  12686. }
  12687. }
  12688. #endif
  12689. /* We have to search path. */
  12690. prev = -1; /* where to start */
  12691. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12692. if (cmdp->cmdtype == CMDBUILTIN)
  12693. prev = builtinloc;
  12694. else
  12695. prev = cmdp->param.index;
  12696. }
  12697. e = ENOENT;
  12698. idx = -1;
  12699. loop:
  12700. while ((len = padvance(&path, name)) >= 0) {
  12701. const char *lpathopt = pathopt;
  12702. fullname = stackblock();
  12703. idx++;
  12704. if (lpathopt) {
  12705. if (*lpathopt == 'b') {
  12706. if (bcmd)
  12707. goto builtin_success;
  12708. continue;
  12709. } else if (!(act & DO_NOFUNC)) {
  12710. /* handled below */
  12711. } else {
  12712. /* ignore unimplemented options */
  12713. continue;
  12714. }
  12715. }
  12716. /* if rehash, don't redo absolute path names */
  12717. if (fullname[0] == '/' && idx <= prev) {
  12718. if (idx < prev)
  12719. continue;
  12720. TRACE(("searchexec \"%s\": no change\n", name));
  12721. goto success;
  12722. }
  12723. while (stat(fullname, &statb) < 0) {
  12724. #ifdef SYSV
  12725. if (errno == EINTR)
  12726. continue;
  12727. #endif
  12728. if (errno != ENOENT && errno != ENOTDIR)
  12729. e = errno;
  12730. goto loop;
  12731. }
  12732. if (lpathopt) { /* this is a %func directory */
  12733. stalloc(len);
  12734. /* NB: stalloc will return space pointed by fullname
  12735. * (because we don't have any intervening allocations
  12736. * between stunalloc above and this stalloc) */
  12737. readcmdfile(fullname);
  12738. cmdp = cmdlookup(name, 0);
  12739. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12740. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12741. stunalloc(fullname);
  12742. goto success;
  12743. }
  12744. e = EACCES; /* if we fail, this will be the error */
  12745. if (!test_exec(/*fullname,*/ &statb))
  12746. continue;
  12747. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12748. if (!updatetbl) {
  12749. entry->cmdtype = CMDNORMAL;
  12750. entry->u.index = idx;
  12751. return;
  12752. }
  12753. INT_OFF;
  12754. cmdp = cmdlookup(name, 1);
  12755. cmdp->cmdtype = CMDNORMAL;
  12756. cmdp->param.index = idx;
  12757. INT_ON;
  12758. goto success;
  12759. }
  12760. /* We failed. If there was an entry for this command, delete it */
  12761. if (cmdp && updatetbl)
  12762. delete_cmd_entry();
  12763. if (act & DO_ERR) {
  12764. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12765. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12766. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12767. char *argv[3];
  12768. argv[0] = (char*) "command_not_found_handle";
  12769. argv[1] = name;
  12770. argv[2] = NULL;
  12771. evalfun(hookp->param.func, 2, argv, 0);
  12772. entry->cmdtype = CMDUNKNOWN;
  12773. return;
  12774. }
  12775. #endif
  12776. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12777. }
  12778. fail:
  12779. entry->cmdtype = CMDUNKNOWN;
  12780. return;
  12781. builtin_success:
  12782. if (!updatetbl) {
  12783. entry->cmdtype = CMDBUILTIN;
  12784. entry->u.cmd = bcmd;
  12785. return;
  12786. }
  12787. INT_OFF;
  12788. cmdp = cmdlookup(name, 1);
  12789. cmdp->cmdtype = CMDBUILTIN;
  12790. cmdp->param.cmd = bcmd;
  12791. INT_ON;
  12792. success:
  12793. cmdp->rehash = 0;
  12794. entry->cmdtype = cmdp->cmdtype;
  12795. entry->u = cmdp->param;
  12796. }
  12797. /*
  12798. * The trap builtin.
  12799. */
  12800. static int FAST_FUNC
  12801. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12802. {
  12803. char *action;
  12804. char **ap;
  12805. int signo, exitcode;
  12806. nextopt(nullstr);
  12807. ap = argptr;
  12808. if (!*ap) {
  12809. for (signo = 0; signo <= NTRAP_LAST; signo++) {
  12810. char *tr = trap_ptr[signo];
  12811. if (tr) {
  12812. /* note: bash adds "SIG", but only if invoked
  12813. * as "bash". If called as "sh", or if set -o posix,
  12814. * then it prints short signal names.
  12815. * We are printing short names: */
  12816. out1fmt("trap -- %s %s\n",
  12817. single_quote(tr),
  12818. (signo == NTRAP_ERR) ? "ERR" : get_signame(signo));
  12819. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12820. * In this case, we will exit very soon, no need to free(). */
  12821. /* if (trap_ptr != trap && tp[0]) */
  12822. /* free(tr); */
  12823. }
  12824. }
  12825. /*
  12826. if (trap_ptr != trap) {
  12827. free(trap_ptr);
  12828. trap_ptr = trap;
  12829. }
  12830. */
  12831. return 0;
  12832. }
  12833. /* Why the second check?
  12834. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12835. * In this case, NUM is signal no, not an action.
  12836. */
  12837. action = NULL;
  12838. if (ap[1] && !is_number(ap[0]))
  12839. action = *ap++;
  12840. exitcode = 0;
  12841. while (*ap) {
  12842. signo = strcmp(*ap, "ERR") == 0 ? NTRAP_ERR : get_signum(*ap);
  12843. if (signo < 0) {
  12844. /* Mimic bash message exactly */
  12845. ash_msg("%s: invalid signal specification", *ap);
  12846. exitcode = 1;
  12847. goto next;
  12848. }
  12849. INT_OFF;
  12850. if (action) {
  12851. if (LONE_DASH(action))
  12852. action = NULL;
  12853. else {
  12854. if (action[0]) /* not NULL and not "" and not "-" */
  12855. may_have_traps = 1;
  12856. action = ckstrdup(action);
  12857. }
  12858. }
  12859. free(trap[signo]);
  12860. trap[signo] = action;
  12861. if (signo != 0 && signo < NSIG)
  12862. setsignal(signo);
  12863. INT_ON;
  12864. next:
  12865. ap++;
  12866. }
  12867. return exitcode;
  12868. }
  12869. /* ============ Builtins */
  12870. #if ENABLE_ASH_HELP
  12871. static int FAST_FUNC
  12872. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12873. {
  12874. unsigned col;
  12875. unsigned i;
  12876. out1fmt(
  12877. "Built-in commands:\n"
  12878. "------------------\n");
  12879. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12880. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12881. builtintab[i].name + 1);
  12882. if (col > 60) {
  12883. out1fmt("\n");
  12884. col = 0;
  12885. }
  12886. }
  12887. # if ENABLE_FEATURE_SH_STANDALONE
  12888. {
  12889. const char *a = applet_names;
  12890. while (*a) {
  12891. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12892. if (col > 60) {
  12893. out1fmt("\n");
  12894. col = 0;
  12895. }
  12896. while (*a++ != '\0')
  12897. continue;
  12898. }
  12899. }
  12900. # endif
  12901. newline_and_flush(stdout);
  12902. return EXIT_SUCCESS;
  12903. }
  12904. #endif
  12905. #if MAX_HISTORY
  12906. static int FAST_FUNC
  12907. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12908. {
  12909. show_history(line_input_state);
  12910. return EXIT_SUCCESS;
  12911. }
  12912. #endif
  12913. /*
  12914. * The export and readonly commands.
  12915. */
  12916. static int FAST_FUNC
  12917. exportcmd(int argc UNUSED_PARAM, char **argv)
  12918. {
  12919. struct var *vp;
  12920. char *name;
  12921. const char *p;
  12922. char **aptr;
  12923. char opt;
  12924. int flag;
  12925. int flag_off;
  12926. /* "readonly" in bash accepts, but ignores -n.
  12927. * We do the same: it saves a conditional in nextopt's param.
  12928. */
  12929. flag_off = 0;
  12930. while ((opt = nextopt("np")) != '\0') {
  12931. if (opt == 'n')
  12932. flag_off = VEXPORT;
  12933. }
  12934. flag = VEXPORT;
  12935. if (argv[0][0] == 'r') {
  12936. flag = VREADONLY;
  12937. flag_off = 0; /* readonly ignores -n */
  12938. }
  12939. flag_off = ~flag_off;
  12940. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12941. {
  12942. aptr = argptr;
  12943. name = *aptr;
  12944. if (name) {
  12945. do {
  12946. p = strchr(name, '=');
  12947. if (p != NULL) {
  12948. p++;
  12949. } else {
  12950. vp = *findvar(name);
  12951. if (vp) {
  12952. vp->flags = ((vp->flags | flag) & flag_off);
  12953. continue;
  12954. }
  12955. }
  12956. setvar(name, p, (flag & flag_off));
  12957. } while ((name = *++aptr) != NULL);
  12958. return 0;
  12959. }
  12960. }
  12961. /* No arguments. Show the list of exported or readonly vars.
  12962. * -n is ignored.
  12963. */
  12964. showvars(argv[0], flag, 0);
  12965. return 0;
  12966. }
  12967. /*
  12968. * Delete a function if it exists.
  12969. */
  12970. static void
  12971. unsetfunc(const char *name)
  12972. {
  12973. struct tblentry *cmdp;
  12974. cmdp = cmdlookup(name, 0);
  12975. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12976. delete_cmd_entry();
  12977. }
  12978. /*
  12979. * The unset builtin command. We unset the function before we unset the
  12980. * variable to allow a function to be unset when there is a readonly variable
  12981. * with the same name.
  12982. */
  12983. static int FAST_FUNC
  12984. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12985. {
  12986. char **ap;
  12987. int i;
  12988. int flag = 0;
  12989. while ((i = nextopt("vf")) != 0) {
  12990. flag = i;
  12991. }
  12992. for (ap = argptr; *ap; ap++) {
  12993. if (flag != 'f') {
  12994. unsetvar(*ap);
  12995. continue;
  12996. }
  12997. if (flag != 'v')
  12998. unsetfunc(*ap);
  12999. }
  13000. return 0;
  13001. }
  13002. static const unsigned char timescmd_str[] ALIGN1 = {
  13003. ' ', offsetof(struct tms, tms_utime),
  13004. '\n', offsetof(struct tms, tms_stime),
  13005. ' ', offsetof(struct tms, tms_cutime),
  13006. '\n', offsetof(struct tms, tms_cstime),
  13007. 0
  13008. };
  13009. static int FAST_FUNC
  13010. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  13011. {
  13012. unsigned clk_tck;
  13013. const unsigned char *p;
  13014. struct tms buf;
  13015. clk_tck = bb_clk_tck();
  13016. times(&buf);
  13017. p = timescmd_str;
  13018. do {
  13019. unsigned sec, frac;
  13020. unsigned long t;
  13021. t = *(clock_t *)(((char *) &buf) + p[1]);
  13022. sec = t / clk_tck;
  13023. frac = t % clk_tck;
  13024. out1fmt("%um%u.%03us%c",
  13025. sec / 60, sec % 60,
  13026. (frac * 1000) / clk_tck,
  13027. p[0]);
  13028. p += 2;
  13029. } while (*p);
  13030. return 0;
  13031. }
  13032. #if ENABLE_FEATURE_SH_MATH
  13033. /*
  13034. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  13035. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  13036. *
  13037. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  13038. */
  13039. static int FAST_FUNC
  13040. letcmd(int argc UNUSED_PARAM, char **argv)
  13041. {
  13042. arith_t i;
  13043. argv++;
  13044. if (!*argv)
  13045. ash_msg_and_raise_error("expression expected");
  13046. do {
  13047. i = ash_arith(*argv);
  13048. } while (*++argv);
  13049. return !i;
  13050. }
  13051. #endif
  13052. /*
  13053. * The read builtin. Options:
  13054. * -r Do not interpret '\' specially
  13055. * -s Turn off echo (tty only)
  13056. * -n NCHARS Read NCHARS max
  13057. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  13058. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  13059. * -u FD Read from given FD instead of fd 0
  13060. * -d DELIM End on DELIM char, not newline
  13061. * This uses unbuffered input, which may be avoidable in some cases.
  13062. * TODO: bash also has:
  13063. * -a ARRAY Read into array[0],[1],etc
  13064. * -e Use line editing (tty only)
  13065. */
  13066. static int FAST_FUNC
  13067. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  13068. {
  13069. struct builtin_read_params params;
  13070. const char *r;
  13071. int i;
  13072. memset(&params, 0, sizeof(params));
  13073. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  13074. switch (i) {
  13075. case 'p':
  13076. params.opt_p = optionarg;
  13077. break;
  13078. case 'n':
  13079. params.opt_n = optionarg;
  13080. break;
  13081. case 's':
  13082. params.read_flags |= BUILTIN_READ_SILENT;
  13083. break;
  13084. case 't':
  13085. params.opt_t = optionarg;
  13086. break;
  13087. case 'r':
  13088. params.read_flags |= BUILTIN_READ_RAW;
  13089. break;
  13090. case 'u':
  13091. params.opt_u = optionarg;
  13092. break;
  13093. #if BASH_READ_D
  13094. case 'd':
  13095. params.opt_d = optionarg;
  13096. break;
  13097. #endif
  13098. default:
  13099. break;
  13100. }
  13101. }
  13102. if (!ENABLE_ASH_BASH_COMPAT && !argptr) {
  13103. bb_simple_error_msg("read: need variable name");
  13104. return 1;
  13105. }
  13106. params.argv = argptr;
  13107. params.setvar = setvar0;
  13108. params.ifs = bltinlookup("IFS"); /* can be NULL */
  13109. /* "read -s" needs to save/restore termios, can't allow ^C
  13110. * to jump out of it.
  13111. */
  13112. again:
  13113. INT_OFF;
  13114. r = shell_builtin_read(&params);
  13115. INT_ON;
  13116. if ((uintptr_t)r == 1 && errno == EINTR) {
  13117. /* To get SIGCHLD: sleep 1 & read x; echo $x
  13118. * Correct behavior is to not exit "read"
  13119. */
  13120. if (pending_sig == 0)
  13121. goto again;
  13122. }
  13123. if ((uintptr_t)r > 1)
  13124. ash_msg_and_raise_error(r);
  13125. return (uintptr_t)r;
  13126. }
  13127. static int FAST_FUNC
  13128. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  13129. {
  13130. static const char permuser[3] ALIGN1 = "ogu";
  13131. mode_t mask;
  13132. int symbolic_mode = 0;
  13133. while (nextopt("S") != '\0') {
  13134. symbolic_mode = 1;
  13135. }
  13136. INT_OFF;
  13137. mask = umask(0);
  13138. umask(mask);
  13139. INT_ON;
  13140. if (*argptr == NULL) {
  13141. if (symbolic_mode) {
  13142. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  13143. char *p = buf;
  13144. int i;
  13145. i = 2;
  13146. for (;;) {
  13147. *p++ = ',';
  13148. *p++ = permuser[i];
  13149. *p++ = '=';
  13150. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  13151. if (!(mask & 0400)) *p++ = 'r';
  13152. if (!(mask & 0200)) *p++ = 'w';
  13153. if (!(mask & 0100)) *p++ = 'x';
  13154. mask <<= 3;
  13155. if (--i < 0)
  13156. break;
  13157. }
  13158. *p = '\0';
  13159. puts(buf + 1);
  13160. } else {
  13161. out1fmt("%04o\n", mask);
  13162. }
  13163. } else {
  13164. char *modestr = *argptr;
  13165. /* numeric umasks are taken as-is */
  13166. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  13167. if (!isdigit(modestr[0]))
  13168. mask ^= 0777;
  13169. mask = bb_parse_mode(modestr, mask);
  13170. if ((unsigned)mask > 0777) {
  13171. ash_msg_and_raise_error("illegal mode: %s", modestr);
  13172. }
  13173. if (!isdigit(modestr[0]))
  13174. mask ^= 0777;
  13175. umask(mask);
  13176. }
  13177. return 0;
  13178. }
  13179. static int FAST_FUNC
  13180. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  13181. {
  13182. return shell_builtin_ulimit(argv);
  13183. }
  13184. /* ============ main() and helpers */
  13185. /*
  13186. * This routine is called when an error or an interrupt occurs in an
  13187. * interactive shell and control is returned to the main command loop
  13188. * but prior to exitshell.
  13189. */
  13190. static void
  13191. exitreset(void)
  13192. {
  13193. /* from eval.c: */
  13194. if (savestatus >= 0) {
  13195. if (exception_type == EXEXIT || evalskip == SKIPFUNCDEF)
  13196. exitstatus = savestatus;
  13197. savestatus = -1;
  13198. }
  13199. evalskip = 0;
  13200. loopnest = 0;
  13201. inps4 = 0;
  13202. /* from expand.c: */
  13203. ifsfree();
  13204. /* from redir.c: */
  13205. unwindredir(NULL);
  13206. }
  13207. /*
  13208. * This routine is called when an error or an interrupt occurs in an
  13209. * interactive shell and control is returned to the main command loop.
  13210. * (In dash, this function is auto-generated by build machinery).
  13211. */
  13212. static void
  13213. reset(void)
  13214. {
  13215. /* from input.c: */
  13216. g_parsefile->left_in_buffer = 0;
  13217. g_parsefile->left_in_line = 0; /* clear input buffer */
  13218. g_parsefile->unget = 0;
  13219. popallfiles();
  13220. /* from var.c: */
  13221. unwindlocalvars(NULL);
  13222. }
  13223. /*
  13224. * Called to exit the shell.
  13225. */
  13226. static void
  13227. exitshell(void)
  13228. {
  13229. struct jmploc loc;
  13230. char *p;
  13231. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  13232. save_history(line_input_state); /* may be NULL */
  13233. #endif
  13234. savestatus = exitstatus;
  13235. TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
  13236. if (setjmp(loc.loc))
  13237. goto out;
  13238. exception_handler = &loc;
  13239. p = trap[0];
  13240. if (p) {
  13241. trap[0] = NULL;
  13242. evalskip = 0;
  13243. trap_depth++;
  13244. evalstring(p, 0);
  13245. trap_depth--;
  13246. evalskip = SKIPFUNCDEF;
  13247. /*free(p); - we'll exit soon */
  13248. }
  13249. out:
  13250. exitreset();
  13251. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  13252. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  13253. */
  13254. setjobctl(0);
  13255. flush_stdout_stderr();
  13256. _exit(exitstatus);
  13257. /* NOTREACHED */
  13258. }
  13259. /* Don't inline: conserve stack of caller from having our locals too */
  13260. static NOINLINE void
  13261. init(void)
  13262. {
  13263. /* we will never free this */
  13264. basepf.next_to_pgetc = basepf.buf = ckzalloc(IBUFSIZ);
  13265. basepf.linno = 1;
  13266. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  13267. setsignal(SIGCHLD);
  13268. {
  13269. char **envp;
  13270. const char *p;
  13271. initvar();
  13272. for (envp = environ; envp && *envp; envp++) {
  13273. /* Used to have
  13274. * p = endofname(*envp);
  13275. * if (p != *envp && *p == '=') {
  13276. * here to weed out badly-named variables, but this breaks
  13277. * scenarios where people do want them passed to children:
  13278. * import os
  13279. * os.environ["test-test"]="test"
  13280. * if os.fork() == 0:
  13281. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  13282. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  13283. */
  13284. if (strchr(*envp, '=')) {
  13285. setvareq(*envp, VEXPORT|VTEXTFIXED);
  13286. }
  13287. }
  13288. setvareq((char*)defifsvar, VTEXTFIXED);
  13289. setvareq((char*)defoptindvar, VTEXTFIXED);
  13290. setvar0("PPID", utoa(getppid()));
  13291. #if BASH_SHLVL_VAR
  13292. p = lookupvar("SHLVL");
  13293. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  13294. #endif
  13295. #if BASH_HOSTNAME_VAR
  13296. if (!lookupvar("HOSTNAME")) {
  13297. struct utsname uts;
  13298. uname(&uts);
  13299. setvar0("HOSTNAME", uts.nodename);
  13300. }
  13301. #endif
  13302. p = lookupvar("PWD");
  13303. if (p) {
  13304. struct stat st1, st2;
  13305. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  13306. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  13307. ) {
  13308. p = NULL;
  13309. }
  13310. }
  13311. setpwd(p, 0);
  13312. }
  13313. }
  13314. //usage:#define ash_trivial_usage
  13315. //usage: "[-il] [-|+Cabefmnuvx] [-|+o OPT]... [-c 'SCRIPT' [ARG0 ARGS] | FILE ARGS | -s ARGS]"
  13316. //////// comes from ^^^^^^^^^^optletters
  13317. //usage:#define ash_full_usage "\n\n"
  13318. //usage: "Unix shell interpreter"
  13319. /*
  13320. * Process the shell command line arguments.
  13321. */
  13322. static int
  13323. procargs(char **argv)
  13324. {
  13325. int i;
  13326. const char *xminusc;
  13327. char **xargv;
  13328. int login_sh;
  13329. xargv = argv;
  13330. login_sh = xargv[0] && xargv[0][0] == '-';
  13331. #if NUM_SCRIPTS > 0
  13332. if (minusc)
  13333. goto setarg0;
  13334. #endif
  13335. arg0 = xargv[0];
  13336. /* if (xargv[0]) - mmm, this is always true! */
  13337. xargv++;
  13338. argptr = xargv;
  13339. for (i = 0; i < NOPTS; i++)
  13340. optlist[i] = 2;
  13341. if (options(&login_sh)) {
  13342. /* it already printed err message */
  13343. raise_exception(EXERROR); /* does not return */
  13344. }
  13345. xargv = argptr;
  13346. xminusc = minusc;
  13347. if (*xargv == NULL) {
  13348. if (xminusc)
  13349. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  13350. sflag = 1;
  13351. }
  13352. if (iflag == 2 /* no explicit -i given */
  13353. && sflag == 1 /* -s given (or implied) */
  13354. && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
  13355. && isatty(0) && isatty(1) /* we are on tty */
  13356. ) {
  13357. iflag = 1;
  13358. }
  13359. if (mflag == 2)
  13360. mflag = iflag;
  13361. /* Unset options which weren't explicitly set or unset */
  13362. for (i = 0; i < NOPTS; i++)
  13363. optlist[i] &= 1; /* same effect as "if (optlist[i] == 2) optlist[i] = 0;" */
  13364. #if DEBUG == 2
  13365. debug = 1;
  13366. #endif
  13367. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  13368. if (xminusc) {
  13369. minusc = *xargv++;
  13370. if (*xargv)
  13371. goto setarg0;
  13372. } else if (!sflag) {
  13373. setinputfile(*xargv, 0);
  13374. setarg0:
  13375. arg0 = *xargv++;
  13376. commandname = arg0;
  13377. }
  13378. shellparam.p = xargv;
  13379. #if ENABLE_ASH_GETOPTS
  13380. shellparam.optind = 1;
  13381. shellparam.optoff = -1;
  13382. #endif
  13383. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  13384. while (*xargv) {
  13385. shellparam.nparam++;
  13386. xargv++;
  13387. }
  13388. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  13389. * Try:
  13390. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  13391. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  13392. * NB: must do it before setting up signals (in optschanged())
  13393. * and reading .profile etc (after we return from here):
  13394. */
  13395. if (iflag)
  13396. signal(SIGHUP, SIG_DFL);
  13397. optschanged();
  13398. return login_sh;
  13399. }
  13400. /*
  13401. * Read /etc/profile, ~/.profile, $ENV.
  13402. */
  13403. static void
  13404. read_profile(const char *name)
  13405. {
  13406. name = expandstr(name, DQSYNTAX);
  13407. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  13408. return;
  13409. cmdloop(0);
  13410. popfile();
  13411. }
  13412. #if PROFILE
  13413. static short profile_buf[16384];
  13414. extern int etext();
  13415. #endif
  13416. /*
  13417. * Main routine. We initialize things, parse the arguments, execute
  13418. * profiles if we're a login shell, and then call cmdloop to execute
  13419. * commands. The setjmp call sets up the location to jump to when an
  13420. * exception occurs. When an exception occurs the variable "state"
  13421. * is used to figure out how far we had gotten.
  13422. */
  13423. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13424. #if NUM_SCRIPTS > 0
  13425. int ash_main(int argc, char **argv)
  13426. #else
  13427. int ash_main(int argc UNUSED_PARAM, char **argv)
  13428. #endif
  13429. /* note: 'argc' is used only if embedded scripts are enabled */
  13430. {
  13431. volatile smallint state;
  13432. struct jmploc jmploc;
  13433. struct stackmark smark;
  13434. int login_sh;
  13435. /* Initialize global data */
  13436. INIT_G_misc();
  13437. INIT_G_memstack();
  13438. INIT_G_var();
  13439. #if ENABLE_ASH_ALIAS
  13440. INIT_G_alias();
  13441. #endif
  13442. INIT_G_cmdtable();
  13443. #if PROFILE
  13444. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  13445. #endif
  13446. state = 0;
  13447. if (setjmp(jmploc.loc)) {
  13448. smallint e;
  13449. smallint s;
  13450. exitreset();
  13451. e = exception_type;
  13452. s = state;
  13453. if (e == EXEND || e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  13454. exitshell();
  13455. }
  13456. reset();
  13457. if (e == EXINT) {
  13458. newline_and_flush(stderr);
  13459. }
  13460. popstackmark(&smark);
  13461. FORCE_INT_ON; /* enable interrupts */
  13462. if (s == 1)
  13463. goto state1;
  13464. if (s == 2)
  13465. goto state2;
  13466. if (s == 3)
  13467. goto state3;
  13468. goto state4;
  13469. }
  13470. exception_handler = &jmploc;
  13471. rootpid = getpid();
  13472. init();
  13473. setstackmark(&smark);
  13474. #if NUM_SCRIPTS > 0
  13475. if (argc < 0)
  13476. /* Non-NULL minusc tells procargs that an embedded script is being run */
  13477. minusc = get_script_content(-argc - 1);
  13478. #endif
  13479. login_sh = procargs(argv);
  13480. #if DEBUG
  13481. TRACE(("Shell args: "));
  13482. trace_puts_args(argv);
  13483. #endif
  13484. if (login_sh) {
  13485. const char *hp;
  13486. state = 1;
  13487. read_profile("/etc/profile");
  13488. state1:
  13489. state = 2;
  13490. hp = lookupvar("HOME");
  13491. if (hp)
  13492. read_profile("$HOME/.profile");
  13493. }
  13494. state2:
  13495. state = 3;
  13496. if (iflag
  13497. #ifndef linux
  13498. && getuid() == geteuid() && getgid() == getegid()
  13499. #endif
  13500. ) {
  13501. const char *shinit = lookupvar("ENV");
  13502. if (shinit != NULL && *shinit != '\0')
  13503. read_profile(shinit);
  13504. }
  13505. popstackmark(&smark);
  13506. state3:
  13507. state = 4;
  13508. if (minusc) {
  13509. /* evalstring pushes parsefile stack.
  13510. * Ensure we don't falsely claim that 0 (stdin)
  13511. * is one of stacked source fds.
  13512. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13513. // if (!sflag) g_parsefile->pf_fd = -1;
  13514. // ^^ not necessary since now we special-case fd 0
  13515. // in save_fd_on_redirect()
  13516. lineno = 0; // bash compat
  13517. // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
  13518. // The above makes
  13519. // ash -sc 'echo $-'
  13520. // continue reading input from stdin after running 'echo'.
  13521. // bash does not do this: it prints "hBcs" and exits.
  13522. evalstring(minusc, EV_EXIT);
  13523. }
  13524. if (sflag || minusc == NULL) {
  13525. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13526. if (line_input_state) {
  13527. const char *hp = lookupvar("HISTFILE");
  13528. if (!hp) {
  13529. hp = lookupvar("HOME");
  13530. if (hp) {
  13531. INT_OFF;
  13532. hp = concat_path_file(hp, ".ash_history");
  13533. setvar0("HISTFILE", hp);
  13534. free((char*)hp);
  13535. INT_ON;
  13536. hp = lookupvar("HISTFILE");
  13537. }
  13538. }
  13539. if (hp)
  13540. line_input_state->hist_file = xstrdup(hp);
  13541. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13542. hp = lookupvar("HISTFILESIZE");
  13543. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13544. # endif
  13545. }
  13546. #endif
  13547. state4: /* XXX ??? - why isn't this before the "if" statement */
  13548. cmdloop(1);
  13549. }
  13550. #if PROFILE
  13551. monitor(0);
  13552. #endif
  13553. #ifdef GPROF
  13554. {
  13555. extern void _mcleanup(void);
  13556. _mcleanup();
  13557. }
  13558. #endif
  13559. TRACE(("End of main reached\n"));
  13560. exitshell();
  13561. /* NOTREACHED */
  13562. }
  13563. /*-
  13564. * Copyright (c) 1989, 1991, 1993, 1994
  13565. * The Regents of the University of California. All rights reserved.
  13566. *
  13567. * This code is derived from software contributed to Berkeley by
  13568. * Kenneth Almquist.
  13569. *
  13570. * Redistribution and use in source and binary forms, with or without
  13571. * modification, are permitted provided that the following conditions
  13572. * are met:
  13573. * 1. Redistributions of source code must retain the above copyright
  13574. * notice, this list of conditions and the following disclaimer.
  13575. * 2. Redistributions in binary form must reproduce the above copyright
  13576. * notice, this list of conditions and the following disclaimer in the
  13577. * documentation and/or other materials provided with the distribution.
  13578. * 3. Neither the name of the University nor the names of its contributors
  13579. * may be used to endorse or promote products derived from this software
  13580. * without specific prior written permission.
  13581. *
  13582. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13583. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13584. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13585. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13586. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13587. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13588. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13589. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13590. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13591. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13592. * SUCH DAMAGE.
  13593. */