3
0

ash.c 330 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * This code is derived from software contributed to Berkeley by
  6. * Kenneth Almquist.
  7. *
  8. * Original BSD copyright notice is retained at the end of this file.
  9. *
  10. * Copyright (c) 1989, 1991, 1993, 1994
  11. * The Regents of the University of California. All rights reserved.
  12. *
  13. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  14. * was re-ported from NetBSD and debianized.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  17. */
  18. //config:config SHELL_ASH
  19. //config: bool #hidden option
  20. //config: depends on !NOMMU
  21. //config:
  22. //config:config ASH
  23. //config: bool "ash (78 kb)"
  24. //config: default y
  25. //config: depends on !NOMMU
  26. //config: select SHELL_ASH
  27. //config: help
  28. //config: The most complete and most pedantically correct shell included with
  29. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  30. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  31. //config: (written by Kenneth Almquist) from NetBSD.
  32. //config:
  33. //config:# ash options
  34. //config:# note: Don't remove !NOMMU part in the next line; it would break
  35. //config:# menuconfig's indenting.
  36. //config:if !NOMMU && (SHELL_ASH || ASH || SH_IS_ASH || BASH_IS_ASH)
  37. //config:
  38. //config:config ASH_OPTIMIZE_FOR_SIZE
  39. //config: bool "Optimize for size instead of speed"
  40. //config: default y
  41. //config: depends on SHELL_ASH
  42. //config:
  43. //config:config ASH_INTERNAL_GLOB
  44. //config: bool "Use internal glob() implementation"
  45. //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
  46. //config: depends on SHELL_ASH
  47. //config: help
  48. //config: Do not use glob() function from libc, use internal implementation.
  49. //config: Use this if you are getting "glob.h: No such file or directory"
  50. //config: or similar build errors.
  51. //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
  52. //config: which would break ash if you select N here.
  53. //config:
  54. //config:config ASH_BASH_COMPAT
  55. //config: bool "bash-compatible extensions"
  56. //config: default y
  57. //config: depends on SHELL_ASH
  58. //config:
  59. //config:config ASH_BASH_SOURCE_CURDIR
  60. //config: bool "'source' and '.' builtins search current directory after $PATH"
  61. //config: default n # do not encourage non-standard behavior
  62. //config: depends on ASH_BASH_COMPAT
  63. //config: help
  64. //config: This is not compliant with standards. Avoid if possible.
  65. //config:
  66. //config:config ASH_BASH_NOT_FOUND_HOOK
  67. //config: bool "command_not_found_handle hook support"
  68. //config: default y
  69. //config: depends on ASH_BASH_COMPAT
  70. //config: help
  71. //config: Enable support for the 'command_not_found_handle' hook function,
  72. //config: from GNU bash, which allows for alternative command not found
  73. //config: handling.
  74. //config:
  75. //config:config ASH_JOB_CONTROL
  76. //config: bool "Job control"
  77. //config: default y
  78. //config: depends on SHELL_ASH
  79. //config:
  80. //config:config ASH_ALIAS
  81. //config: bool "Alias support"
  82. //config: default y
  83. //config: depends on SHELL_ASH
  84. //config:
  85. //config:config ASH_RANDOM_SUPPORT
  86. //config: bool "Pseudorandom generator and $RANDOM variable"
  87. //config: default y
  88. //config: depends on SHELL_ASH
  89. //config: help
  90. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  91. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  92. //config: You can reset the generator by using a specified start value.
  93. //config: After "unset RANDOM" the generator will switch off and this
  94. //config: variable will no longer have special treatment.
  95. //config:
  96. //config:config ASH_EXPAND_PRMT
  97. //config: bool "Expand prompt string"
  98. //config: default y
  99. //config: depends on SHELL_ASH
  100. //config: help
  101. //config: $PS# may contain volatile content, such as backquote commands.
  102. //config: This option recreates the prompt string from the environment
  103. //config: variable each time it is displayed.
  104. //config:
  105. //config:config ASH_IDLE_TIMEOUT
  106. //config: bool "Idle timeout variable $TMOUT"
  107. //config: default y
  108. //config: depends on SHELL_ASH
  109. //config: help
  110. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  111. //config:
  112. //config:config ASH_MAIL
  113. //config: bool "Check for new mail in interactive shell"
  114. //config: default y
  115. //config: depends on SHELL_ASH
  116. //config: help
  117. //config: Enable "check for new mail" function:
  118. //config: if set, $MAIL file and $MAILPATH list of files
  119. //config: are checked for mtime changes, and "you have mail"
  120. //config: message is printed if change is detected.
  121. //config:
  122. //config:config ASH_ECHO
  123. //config: bool "echo builtin"
  124. //config: default y
  125. //config: depends on SHELL_ASH
  126. //config:
  127. //config:config ASH_PRINTF
  128. //config: bool "printf builtin"
  129. //config: default y
  130. //config: depends on SHELL_ASH
  131. //config:
  132. //config:config ASH_TEST
  133. //config: bool "test builtin"
  134. //config: default y
  135. //config: depends on SHELL_ASH
  136. //config:
  137. //config:config ASH_HELP
  138. //config: bool "help builtin"
  139. //config: default y
  140. //config: depends on SHELL_ASH
  141. //config:
  142. //config:config ASH_GETOPTS
  143. //config: bool "getopts builtin"
  144. //config: default y
  145. //config: depends on SHELL_ASH
  146. //config:
  147. //config:config ASH_CMDCMD
  148. //config: bool "command builtin"
  149. //config: default y
  150. //config: depends on SHELL_ASH
  151. //config: help
  152. //config: Enable support for the 'command' builtin, which allows
  153. //config: you to run the specified command or builtin,
  154. //config: even when there is a function with the same name.
  155. //config:
  156. //config:endif # ash options
  157. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  158. // APPLET_ODDNAME:name main location suid_type help
  159. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  160. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  161. //kbuild:lib-$(CONFIG_SHELL_ASH) += ash.o ash_ptr_hack.o shell_common.o
  162. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  163. /*
  164. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  165. * DEBUG=2 to compile in and turn on debugging.
  166. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  167. * debugging info is written to ./trace, quit signal generates core dump.
  168. */
  169. #define DEBUG 0
  170. /* Tweak debug output verbosity here */
  171. #define DEBUG_TIME 0
  172. #define DEBUG_PID 1
  173. #define DEBUG_SIG 1
  174. #define DEBUG_INTONOFF 0
  175. #define PROFILE 0
  176. #define JOBS ENABLE_ASH_JOB_CONTROL
  177. #include <fnmatch.h>
  178. #include <sys/times.h>
  179. #include <sys/utsname.h> /* for setting $HOSTNAME */
  180. #include "busybox.h" /* for applet_names */
  181. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
  182. # include "embedded_scripts.h"
  183. #else
  184. # define NUM_SCRIPTS 0
  185. #endif
  186. /* So far, all bash compat is controlled by one config option */
  187. /* Separate defines document which part of code implements what */
  188. /* function keyword */
  189. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  190. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  191. /* &>file */
  192. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  193. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  194. /* $'...' */
  195. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  196. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  197. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  198. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  199. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  200. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  201. /* BASH_TEST2: [[ EXPR ]]
  202. * Status of [[ support:
  203. * && and || work as they should
  204. * = is glob match operator, not equality operator: STR = GLOB
  205. * == same as =
  206. * =~ is regex match operator: STR =~ REGEX
  207. * TODO:
  208. * singleword+noglob expansion:
  209. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  210. * [[ /bin/n* ]]; echo 0:$?
  211. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  212. * ( ) < > should not have special meaning (IOW: should not require quoting)
  213. * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
  214. */
  215. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  216. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  217. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  218. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  219. #define BASH_EPOCH_VARS ENABLE_ASH_BASH_COMPAT
  220. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  221. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  222. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  223. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  224. #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
  225. /* <(...) and >(...) */
  226. #if HAVE_DEV_FD
  227. # define BASH_PROCESS_SUBST ENABLE_ASH_BASH_COMPAT
  228. # define IF_BASH_PROCESS_SUBST IF_ASH_BASH_COMPAT
  229. #else
  230. # define BASH_PROCESS_SUBST 0
  231. # define IF_BASH_PROCESS_SUBST(...)
  232. #endif
  233. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  234. /* Bionic at least up to version 24 has no glob() */
  235. # undef ENABLE_ASH_INTERNAL_GLOB
  236. # define ENABLE_ASH_INTERNAL_GLOB 1
  237. #endif
  238. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  239. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  240. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  241. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  242. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  243. # error fails to match dirname, subsequently not expanding <pattern> in it.
  244. // Testcase:
  245. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  246. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  247. #endif
  248. #if !ENABLE_ASH_INTERNAL_GLOB
  249. # include <glob.h>
  250. #endif
  251. #include "unicode.h"
  252. #include "shell_common.h"
  253. #if ENABLE_FEATURE_SH_MATH
  254. # include "math.h"
  255. #else
  256. typedef long arith_t;
  257. # define ARITH_FMT "%ld"
  258. #endif
  259. #if ENABLE_ASH_RANDOM_SUPPORT
  260. # include "random.h"
  261. #else
  262. # define CLEAR_RANDOM_T(rnd) ((void)0)
  263. #endif
  264. #include "NUM_APPLETS.h"
  265. #if NUM_APPLETS == 1
  266. /* STANDALONE does not make sense, and won't compile */
  267. # undef CONFIG_FEATURE_SH_STANDALONE
  268. # undef ENABLE_FEATURE_SH_STANDALONE
  269. # undef IF_FEATURE_SH_STANDALONE
  270. # undef IF_NOT_FEATURE_SH_STANDALONE
  271. # define ENABLE_FEATURE_SH_STANDALONE 0
  272. # define IF_FEATURE_SH_STANDALONE(...)
  273. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  274. #endif
  275. #ifndef F_DUPFD_CLOEXEC
  276. # define F_DUPFD_CLOEXEC F_DUPFD
  277. #endif
  278. #ifndef O_CLOEXEC
  279. # define O_CLOEXEC 0
  280. #endif
  281. #ifndef PIPE_BUF
  282. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  283. #endif
  284. #ifndef unlikely
  285. # define unlikely(cond) (cond)
  286. #endif
  287. #if !BB_MMU
  288. # error "Do not even bother, ash will not run on NOMMU machine"
  289. #endif
  290. /* ============ Hash table sizes. Configurable. */
  291. #define VTABSIZE 39
  292. #define ATABSIZE 39
  293. #define CMDTABLESIZE 31 /* should be prime */
  294. /* ============ Shell options */
  295. /* If you add/change options hare, update --help text too */
  296. static const char *const optletters_optnames[] = {
  297. "e" "errexit",
  298. "f" "noglob",
  299. /* bash has '-o ignoreeof', but no short synonym -I for it */
  300. /* (in bash, set -I disables invisible variables (what's that?)) */
  301. "I" "ignoreeof",
  302. /* The below allowed this invocation:
  303. * ash -c 'set -i; echo $-; sleep 5; echo $-'
  304. * to be ^C-ed and get to interactive ash prompt.
  305. * bash does not support such "set -i".
  306. * In our code, this is denoted by empty long name:
  307. */
  308. "i" "",
  309. /* (removing "i" altogether would remove it from "$-", not good) */
  310. "m" "monitor",
  311. "n" "noexec",
  312. /* Ditto: bash has no "set -s", "set -c" */
  313. "s" "",
  314. "c" "",
  315. "x" "xtrace",
  316. "v" "verbose",
  317. "C" "noclobber",
  318. "a" "allexport",
  319. "b" "notify",
  320. "u" "nounset",
  321. "E" "errtrace",
  322. "\0" "vi"
  323. #if BASH_PIPEFAIL
  324. ,"\0" "pipefail"
  325. #endif
  326. #if DEBUG
  327. ,"\0" "nolog"
  328. ,"\0" "debug"
  329. #endif
  330. };
  331. //bash 4.4.23 also has these opts (with these defaults):
  332. //braceexpand on
  333. //emacs on
  334. //errtrace off
  335. //functrace off
  336. //hashall on
  337. //histexpand off
  338. //history on
  339. //interactive-comments on
  340. //keyword off
  341. //onecmd off
  342. //physical off
  343. //posix off
  344. //privileged off
  345. #define optletters(n) optletters_optnames[n][0]
  346. #define optnames(n) (optletters_optnames[n] + 1)
  347. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  348. /* ============ Misc data */
  349. #define msg_illnum "Illegal number: %s"
  350. /*
  351. * We enclose jmp_buf in a structure so that we can declare pointers to
  352. * jump locations. The global variable handler contains the location to
  353. * jump to when an exception occurs, and the global variable exception_type
  354. * contains a code identifying the exception. To implement nested
  355. * exception handlers, the user should save the value of handler on entry
  356. * to an inner scope, set handler to point to a jmploc structure for the
  357. * inner scope, and restore handler on exit from the scope.
  358. */
  359. struct jmploc {
  360. jmp_buf loc;
  361. };
  362. struct globals_misc {
  363. uint8_t exitstatus; /* exit status of last command */
  364. uint8_t back_exitstatus;/* exit status of backquoted command */
  365. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  366. smallint inps4; /* Prevent PS4 nesting. */
  367. int savestatus; /* exit status of last command outside traps */
  368. int rootpid; /* pid of main shell */
  369. /* shell level: 0 for the main shell, 1 for its children, and so on */
  370. int shlvl;
  371. #define rootshell (!shlvl)
  372. int errlinno;
  373. char *minusc; /* argument to -c option */
  374. char *curdir; // = nullstr; /* current working directory */
  375. char *physdir; // = nullstr; /* physical working directory */
  376. char *arg0; /* value of $0 */
  377. struct jmploc *exception_handler;
  378. volatile int suppress_int; /* counter */
  379. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  380. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  381. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  382. smallint exception_type; /* kind of exception: */
  383. #define EXINT 0 /* SIGINT received */
  384. #define EXERROR 1 /* a generic error */
  385. #define EXEND 3 /* exit the shell */
  386. #define EXEXIT 4 /* exit the shell via exitcmd */
  387. char nullstr[1]; /* zero length string */
  388. char optlist[NOPTS];
  389. #define eflag optlist[0]
  390. #define fflag optlist[1]
  391. #define Iflag optlist[2]
  392. #define iflag optlist[3]
  393. #define mflag optlist[4]
  394. #define nflag optlist[5]
  395. #define sflag optlist[6]
  396. #define cflag optlist[7]
  397. #define xflag optlist[8]
  398. #define vflag optlist[9]
  399. #define Cflag optlist[10]
  400. #define aflag optlist[11]
  401. #define bflag optlist[12]
  402. #define uflag optlist[13]
  403. #define Eflag optlist[14]
  404. #define viflag optlist[15]
  405. #if BASH_PIPEFAIL
  406. # define pipefail optlist[16]
  407. #else
  408. # define pipefail 0
  409. #endif
  410. #if DEBUG
  411. # define nolog optlist[16 + BASH_PIPEFAIL]
  412. # define debug optlist[17 + BASH_PIPEFAIL]
  413. #endif
  414. /* trap handler commands */
  415. /*
  416. * Sigmode records the current value of the signal handlers for the various
  417. * modes. A value of zero means that the current handler is not known.
  418. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  419. */
  420. char sigmode[NSIG - 1];
  421. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  422. #define S_CATCH 2 /* signal is caught */
  423. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  424. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  425. /* indicates specified signal received */
  426. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  427. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  428. char *trap[NSIG + 1];
  429. /* trap[0] is EXIT trap, trap[NTRAP_ERR] is ERR trap, other trap[i] are signal traps */
  430. #define NTRAP_ERR NSIG
  431. #define NTRAP_LAST NSIG
  432. char **trap_ptr; /* used only by "trap hack" */
  433. /* Rarely referenced stuff */
  434. #if ENABLE_ASH_RANDOM_SUPPORT
  435. random_t random_gen;
  436. #endif
  437. pid_t backgndpid; /* pid of last background process */
  438. };
  439. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  440. #define G_misc (*ash_ptr_to_globals_misc)
  441. #define exitstatus (G_misc.exitstatus )
  442. #define back_exitstatus (G_misc.back_exitstatus )
  443. #define job_warning (G_misc.job_warning)
  444. #define inps4 (G_misc.inps4 )
  445. #define savestatus (G_misc.savestatus )
  446. #define rootpid (G_misc.rootpid )
  447. #define shlvl (G_misc.shlvl )
  448. #define errlinno (G_misc.errlinno )
  449. #define minusc (G_misc.minusc )
  450. #define curdir (G_misc.curdir )
  451. #define physdir (G_misc.physdir )
  452. #define arg0 (G_misc.arg0 )
  453. #define exception_handler (G_misc.exception_handler)
  454. #define exception_type (G_misc.exception_type )
  455. #define suppress_int (G_misc.suppress_int )
  456. #define pending_int (G_misc.pending_int )
  457. #define got_sigchld (G_misc.got_sigchld )
  458. #define pending_sig (G_misc.pending_sig )
  459. #define nullstr (G_misc.nullstr )
  460. #define optlist (G_misc.optlist )
  461. #define sigmode (G_misc.sigmode )
  462. #define gotsig (G_misc.gotsig )
  463. #define may_have_traps (G_misc.may_have_traps )
  464. #define trap (G_misc.trap )
  465. #define trap_ptr (G_misc.trap_ptr )
  466. #define random_gen (G_misc.random_gen )
  467. #define backgndpid (G_misc.backgndpid )
  468. #define INIT_G_misc() do { \
  469. XZALLOC_CONST_PTR(&ash_ptr_to_globals_misc, sizeof(G_misc)); \
  470. savestatus = -1; \
  471. curdir = nullstr; \
  472. physdir = nullstr; \
  473. trap_ptr = trap; \
  474. } while (0)
  475. /* ============ DEBUG */
  476. #if DEBUG
  477. static void trace_printf(const char *fmt, ...);
  478. static void trace_vprintf(const char *fmt, va_list va);
  479. # define TRACE(param) trace_printf param
  480. # define TRACEV(param) trace_vprintf param
  481. # define close(fd) do { \
  482. int dfd = (fd); \
  483. if (close(dfd) < 0) \
  484. bb_error_msg("bug on %d: closing %d(0x%x)", \
  485. __LINE__, dfd, dfd); \
  486. } while (0)
  487. #else
  488. # define TRACE(param)
  489. # define TRACEV(param)
  490. #endif
  491. /* ============ Utility functions */
  492. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  493. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  494. static int
  495. isdigit_str9(const char *str)
  496. {
  497. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  498. while (--maxlen && isdigit(*str))
  499. str++;
  500. return (*str == '\0');
  501. }
  502. static const char *
  503. var_end(const char *var)
  504. {
  505. while (*var)
  506. if (*var++ == '=')
  507. break;
  508. return var;
  509. }
  510. /* ============ Parser data */
  511. /*
  512. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  513. */
  514. struct strlist {
  515. struct strlist *next;
  516. char *text;
  517. };
  518. struct alias;
  519. struct strpush {
  520. struct strpush *prev; /* preceding string on stack */
  521. char *prev_string;
  522. int prev_left_in_line;
  523. #if ENABLE_ASH_ALIAS
  524. struct alias *ap; /* if push was associated with an alias */
  525. #endif
  526. char *string; /* remember the string since it may change */
  527. /* Delay freeing so we can stop nested aliases. */
  528. struct strpush *spfree;
  529. /* Remember last two characters for pungetc. */
  530. int lastc[2];
  531. /* Number of outstanding calls to pungetc. */
  532. int unget;
  533. };
  534. /*
  535. * The parsefile structure pointed to by the global variable parsefile
  536. * contains information about the current file being read.
  537. */
  538. struct parsefile {
  539. struct parsefile *prev; /* preceding file on stack */
  540. int linno; /* current line */
  541. int pf_fd; /* file descriptor (or -1 if string) */
  542. int left_in_line; /* number of chars left in this line */
  543. int left_in_buffer; /* number of chars left in this buffer past the line */
  544. char *next_to_pgetc; /* next char in buffer */
  545. char *buf; /* input buffer */
  546. struct strpush *strpush; /* for pushing strings at this level */
  547. struct strpush basestrpush; /* so pushing one is fast */
  548. /* Delay freeing so we can stop nested aliases. */
  549. struct strpush *spfree;
  550. /* Remember last two characters for pungetc. */
  551. int lastc[2];
  552. /* Number of outstanding calls to pungetc. */
  553. int unget;
  554. };
  555. static struct parsefile basepf; /* top level input file */
  556. static struct parsefile *g_parsefile = &basepf; /* current input file */
  557. static char *commandname; /* currently executing command */
  558. /* ============ Interrupts / exceptions */
  559. static void exitshell(void) NORETURN;
  560. /*
  561. * These macros allow the user to suspend the handling of interrupt signals
  562. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  563. * much more efficient and portable. (But hacking the kernel is so much
  564. * more fun than worrying about efficiency and portability. :-))
  565. */
  566. #if DEBUG_INTONOFF
  567. # define INT_OFF do { \
  568. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  569. suppress_int++; \
  570. barrier(); \
  571. } while (0)
  572. #else
  573. # define INT_OFF do { \
  574. suppress_int++; \
  575. barrier(); \
  576. } while (0)
  577. #endif
  578. /*
  579. * Called to raise an exception. Since C doesn't include exceptions, we
  580. * just do a longjmp to the exception handler. The type of exception is
  581. * stored in the global variable "exception_type".
  582. */
  583. static void raise_exception(int) NORETURN;
  584. static void
  585. raise_exception(int e)
  586. {
  587. #if DEBUG
  588. if (exception_handler == NULL)
  589. abort();
  590. #endif
  591. INT_OFF;
  592. exception_type = e;
  593. longjmp(exception_handler->loc, 1);
  594. }
  595. #if DEBUG
  596. #define raise_exception(e) do { \
  597. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  598. raise_exception(e); \
  599. } while (0)
  600. #endif
  601. /*
  602. * Called when a SIGINT is received. (If the user specifies
  603. * that SIGINT is to be trapped or ignored using the trap builtin, then
  604. * this routine is not called.) Suppressint is nonzero when interrupts
  605. * are held using the INT_OFF macro. (The test for iflag is just
  606. * defensive programming.)
  607. */
  608. static void raise_interrupt(void) NORETURN;
  609. static void
  610. raise_interrupt(void)
  611. {
  612. pending_int = 0;
  613. /* Signal is not automatically unmasked after it is raised,
  614. * do it ourself - unmask all signals */
  615. sigprocmask_allsigs(SIG_UNBLOCK);
  616. /* pending_sig = 0; - now done in signal_handler() */
  617. if (!(rootshell && iflag)) {
  618. /* Kill ourself with SIGINT */
  619. signal(SIGINT, SIG_DFL);
  620. raise(SIGINT);
  621. }
  622. /* bash: ^C even on empty command line sets $? */
  623. exitstatus = SIGINT + 128;
  624. raise_exception(EXINT);
  625. /* NOTREACHED */
  626. }
  627. #if DEBUG
  628. #define raise_interrupt() do { \
  629. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  630. raise_interrupt(); \
  631. } while (0)
  632. #endif
  633. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  634. int_on(void)
  635. {
  636. barrier();
  637. if (--suppress_int == 0 && pending_int) {
  638. raise_interrupt();
  639. }
  640. }
  641. #if DEBUG_INTONOFF
  642. # define INT_ON do { \
  643. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  644. int_on(); \
  645. } while (0)
  646. #else
  647. # define INT_ON int_on()
  648. #endif
  649. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  650. force_int_on(void)
  651. {
  652. barrier();
  653. suppress_int = 0;
  654. if (pending_int)
  655. raise_interrupt();
  656. }
  657. #define FORCE_INT_ON force_int_on()
  658. #define SAVE_INT(v) ((v) = suppress_int)
  659. #define RESTORE_INT(v) do { \
  660. barrier(); \
  661. suppress_int = (v); \
  662. if (suppress_int == 0 && pending_int) \
  663. raise_interrupt(); \
  664. } while (0)
  665. /* ============ Stdout/stderr output */
  666. static void
  667. outstr(const char *p, FILE *file)
  668. {
  669. INT_OFF;
  670. fputs(p, file);
  671. INT_ON;
  672. }
  673. static void
  674. flush_stdout_stderr(void)
  675. {
  676. INT_OFF;
  677. fflush_all();
  678. INT_ON;
  679. }
  680. /* Was called outcslow(c,FILE*), but c was always '\n' */
  681. static void
  682. newline_and_flush(FILE *dest)
  683. {
  684. INT_OFF;
  685. putc('\n', dest);
  686. fflush(dest);
  687. INT_ON;
  688. }
  689. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  690. static int
  691. out1fmt(const char *fmt, ...)
  692. {
  693. va_list ap;
  694. int r;
  695. INT_OFF;
  696. va_start(ap, fmt);
  697. r = vprintf(fmt, ap);
  698. va_end(ap);
  699. INT_ON;
  700. return r;
  701. }
  702. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  703. static int
  704. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  705. {
  706. va_list ap;
  707. int ret;
  708. INT_OFF;
  709. va_start(ap, fmt);
  710. ret = vsnprintf(outbuf, length, fmt, ap);
  711. va_end(ap);
  712. INT_ON;
  713. return ret > (int)length ? length : ret;
  714. }
  715. static void
  716. out1str(const char *p)
  717. {
  718. outstr(p, stdout);
  719. }
  720. static void
  721. out2str(const char *p)
  722. {
  723. outstr(p, stderr);
  724. flush_stdout_stderr();
  725. }
  726. /* ============ Parser structures */
  727. /* control characters in argument strings */
  728. #define CTL_FIRST CTLESC
  729. #define CTLESC ((unsigned char)'\201') /* escape next character */
  730. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  731. #define CTLENDVAR ((unsigned char)'\203')
  732. #define CTLBACKQ ((unsigned char)'\204')
  733. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  734. #define CTLENDARI ((unsigned char)'\207')
  735. #define CTLQUOTEMARK ((unsigned char)'\210')
  736. #define CTL_LAST CTLQUOTEMARK
  737. #if BASH_PROCESS_SUBST
  738. # define CTLTOPROC ((unsigned char)'\211')
  739. # define CTLFROMPROC ((unsigned char)'\212')
  740. # undef CTL_LAST
  741. # define CTL_LAST CTLFROMPROC
  742. #endif
  743. /* variable substitution byte (follows CTLVAR) */
  744. #define VSTYPE 0x0f /* type of variable substitution */
  745. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  746. /* values of VSTYPE field */
  747. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  748. #define VSMINUS 0x2 /* ${var-text} */
  749. #define VSPLUS 0x3 /* ${var+text} */
  750. #define VSQUESTION 0x4 /* ${var?message} */
  751. #define VSASSIGN 0x5 /* ${var=text} */
  752. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  753. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  754. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  755. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  756. #define VSLENGTH 0xa /* ${#var} */
  757. #if BASH_SUBSTR
  758. #define VSSUBSTR 0xc /* ${var:position:length} */
  759. #endif
  760. #if BASH_PATTERN_SUBST
  761. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  762. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  763. #endif
  764. static const char dolatstr[] ALIGN1 = {
  765. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  766. };
  767. #define DOLATSTRLEN 6
  768. #define NCMD 0
  769. #define NPIPE 1
  770. #define NREDIR 2
  771. #define NBACKGND 3
  772. #define NSUBSHELL 4
  773. #define NAND 5
  774. #define NOR 6
  775. #define NSEMI 7
  776. #define NIF 8
  777. #define NWHILE 9
  778. #define NUNTIL 10
  779. #define NFOR 11
  780. #define NCASE 12
  781. #define NCLIST 13
  782. #define NDEFUN 14
  783. #define NARG 15
  784. #define NTO 16
  785. #if BASH_REDIR_OUTPUT
  786. #define NTO2 17
  787. #endif
  788. #define NCLOBBER 18
  789. #define NFROM 19
  790. #define NFROMTO 20
  791. #define NAPPEND 21
  792. #define NTOFD 22
  793. #define NFROMFD 23
  794. #define NHERE 24
  795. #define NXHERE 25
  796. #define NNOT 26
  797. #define N_NUMBER 27
  798. union node;
  799. struct ncmd {
  800. smallint type; /* Nxxxx */
  801. int linno;
  802. union node *assign;
  803. union node *args;
  804. union node *redirect;
  805. };
  806. struct npipe {
  807. smallint type;
  808. smallint pipe_backgnd;
  809. struct nodelist *cmdlist;
  810. };
  811. struct nredir {
  812. smallint type;
  813. int linno;
  814. union node *n;
  815. union node *redirect;
  816. };
  817. struct nbinary {
  818. smallint type;
  819. union node *ch1;
  820. union node *ch2;
  821. };
  822. struct nif {
  823. smallint type;
  824. union node *test;
  825. union node *ifpart;
  826. union node *elsepart;
  827. };
  828. struct nfor {
  829. smallint type;
  830. int linno;
  831. union node *args;
  832. union node *body;
  833. char *var;
  834. };
  835. struct ncase {
  836. smallint type;
  837. int linno;
  838. union node *expr;
  839. union node *cases;
  840. };
  841. struct nclist {
  842. smallint type;
  843. union node *next;
  844. union node *pattern;
  845. union node *body;
  846. };
  847. struct ndefun {
  848. smallint type;
  849. int linno;
  850. char *text;
  851. union node *body;
  852. };
  853. struct narg {
  854. smallint type;
  855. union node *next;
  856. char *text;
  857. struct nodelist *backquote;
  858. };
  859. /* nfile and ndup layout must match!
  860. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  861. * that it is actually NTO2 (>&file), and change its type.
  862. */
  863. struct nfile {
  864. smallint type;
  865. union node *next;
  866. int fd;
  867. int _unused_dupfd;
  868. union node *fname;
  869. char *expfname;
  870. };
  871. struct ndup {
  872. smallint type;
  873. union node *next;
  874. int fd;
  875. int dupfd;
  876. union node *vname;
  877. char *_unused_expfname;
  878. };
  879. struct nhere {
  880. smallint type;
  881. union node *next;
  882. int fd;
  883. union node *doc;
  884. };
  885. struct nnot {
  886. smallint type;
  887. union node *com;
  888. };
  889. union node {
  890. smallint type;
  891. struct ncmd ncmd;
  892. struct npipe npipe;
  893. struct nredir nredir;
  894. struct nbinary nbinary;
  895. struct nif nif;
  896. struct nfor nfor;
  897. struct ncase ncase;
  898. struct nclist nclist;
  899. struct ndefun ndefun;
  900. struct narg narg;
  901. struct nfile nfile;
  902. struct ndup ndup;
  903. struct nhere nhere;
  904. struct nnot nnot;
  905. };
  906. /*
  907. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  908. * It must be distinct from NULL.
  909. */
  910. #define NODE_EOF ((union node *) -1L)
  911. struct nodelist {
  912. struct nodelist *next;
  913. union node *n;
  914. };
  915. struct funcnode {
  916. int count;
  917. union node n;
  918. };
  919. /*
  920. * Free a parse tree.
  921. */
  922. static void
  923. freefunc(struct funcnode *f)
  924. {
  925. if (f && --f->count < 0)
  926. free(f);
  927. }
  928. /* ============ Debugging output */
  929. #if DEBUG
  930. static FILE *tracefile;
  931. static void
  932. trace_printf(const char *fmt, ...)
  933. {
  934. va_list va;
  935. if (debug != 1)
  936. return;
  937. if (DEBUG_TIME)
  938. fprintf(tracefile, "%u ", (int) time(NULL));
  939. if (DEBUG_PID)
  940. fprintf(tracefile, "[%u] ", (int) getpid());
  941. if (DEBUG_SIG)
  942. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  943. va_start(va, fmt);
  944. vfprintf(tracefile, fmt, va);
  945. va_end(va);
  946. }
  947. static void
  948. trace_vprintf(const char *fmt, va_list va)
  949. {
  950. if (debug != 1)
  951. return;
  952. vfprintf(tracefile, fmt, va);
  953. fprintf(tracefile, "\n");
  954. }
  955. static void
  956. trace_puts(const char *s)
  957. {
  958. if (debug != 1)
  959. return;
  960. fputs(s, tracefile);
  961. }
  962. static void
  963. trace_puts_quoted(char *s)
  964. {
  965. char *p;
  966. char c;
  967. if (debug != 1)
  968. return;
  969. putc('"', tracefile);
  970. for (p = s; *p; p++) {
  971. switch ((unsigned char)*p) {
  972. case '\n': c = 'n'; goto backslash;
  973. case '\t': c = 't'; goto backslash;
  974. case '\r': c = 'r'; goto backslash;
  975. case '\"': c = '\"'; goto backslash;
  976. case '\\': c = '\\'; goto backslash;
  977. case CTLESC: c = 'e'; goto backslash;
  978. case CTLVAR: c = 'v'; goto backslash;
  979. case CTLBACKQ: c = 'q'; goto backslash;
  980. #if BASH_PROCESS_SUBST
  981. case CTLTOPROC: c = 'p'; goto backslash;
  982. case CTLFROMPROC: c = 'P'; goto backslash;
  983. #endif
  984. backslash:
  985. putc('\\', tracefile);
  986. putc(c, tracefile);
  987. break;
  988. default:
  989. if (*p >= ' ' && *p <= '~')
  990. putc(*p, tracefile);
  991. else {
  992. putc('\\', tracefile);
  993. putc((*p >> 6) & 03, tracefile);
  994. putc((*p >> 3) & 07, tracefile);
  995. putc(*p & 07, tracefile);
  996. }
  997. break;
  998. }
  999. }
  1000. putc('"', tracefile);
  1001. }
  1002. static void
  1003. trace_puts_args(char **ap)
  1004. {
  1005. if (debug != 1)
  1006. return;
  1007. if (!*ap)
  1008. return;
  1009. while (1) {
  1010. trace_puts_quoted(*ap);
  1011. if (!*++ap) {
  1012. putc('\n', tracefile);
  1013. break;
  1014. }
  1015. putc(' ', tracefile);
  1016. }
  1017. }
  1018. static void
  1019. opentrace(void)
  1020. {
  1021. char s[100];
  1022. #ifdef O_APPEND
  1023. int flags;
  1024. #endif
  1025. if (debug != 1) {
  1026. if (tracefile)
  1027. fflush(tracefile);
  1028. /* leave open because libedit might be using it */
  1029. return;
  1030. }
  1031. strcpy(s, "./trace");
  1032. if (tracefile) {
  1033. if (!freopen(s, "a", tracefile)) {
  1034. fprintf(stderr, "Can't re-open %s\n", s);
  1035. debug = 0;
  1036. return;
  1037. }
  1038. } else {
  1039. tracefile = fopen(s, "a");
  1040. if (tracefile == NULL) {
  1041. fprintf(stderr, "Can't open %s\n", s);
  1042. debug = 0;
  1043. return;
  1044. }
  1045. }
  1046. #ifdef O_APPEND
  1047. flags = fcntl(fileno(tracefile), F_GETFL);
  1048. if (flags >= 0)
  1049. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  1050. #endif
  1051. setlinebuf(tracefile);
  1052. fputs("\nTracing started.\n", tracefile);
  1053. }
  1054. static void
  1055. indent(int amount, char *pfx, FILE *fp)
  1056. {
  1057. int i;
  1058. for (i = 0; i < amount; i++) {
  1059. if (pfx && i == amount - 1)
  1060. fputs(pfx, fp);
  1061. putc('\t', fp);
  1062. }
  1063. }
  1064. /* little circular references here... */
  1065. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  1066. static void
  1067. sharg(union node *arg, FILE *fp)
  1068. {
  1069. char *p;
  1070. struct nodelist *bqlist;
  1071. unsigned char subtype;
  1072. if (arg->type != NARG) {
  1073. out1fmt("<node type %d>\n", arg->type);
  1074. abort();
  1075. }
  1076. bqlist = arg->narg.backquote;
  1077. for (p = arg->narg.text; *p; p++) {
  1078. switch ((unsigned char)*p) {
  1079. case CTLESC:
  1080. p++;
  1081. putc(*p, fp);
  1082. break;
  1083. case CTLVAR:
  1084. putc('$', fp);
  1085. putc('{', fp);
  1086. subtype = *++p;
  1087. if (subtype == VSLENGTH)
  1088. putc('#', fp);
  1089. while (*p != '=') {
  1090. putc(*p, fp);
  1091. p++;
  1092. }
  1093. if (subtype & VSNUL)
  1094. putc(':', fp);
  1095. switch (subtype & VSTYPE) {
  1096. case VSNORMAL:
  1097. putc('}', fp);
  1098. break;
  1099. case VSMINUS:
  1100. putc('-', fp);
  1101. break;
  1102. case VSPLUS:
  1103. putc('+', fp);
  1104. break;
  1105. case VSQUESTION:
  1106. putc('?', fp);
  1107. break;
  1108. case VSASSIGN:
  1109. putc('=', fp);
  1110. break;
  1111. case VSTRIMLEFT:
  1112. putc('#', fp);
  1113. break;
  1114. case VSTRIMLEFTMAX:
  1115. putc('#', fp);
  1116. putc('#', fp);
  1117. break;
  1118. case VSTRIMRIGHT:
  1119. putc('%', fp);
  1120. break;
  1121. case VSTRIMRIGHTMAX:
  1122. putc('%', fp);
  1123. putc('%', fp);
  1124. break;
  1125. case VSLENGTH:
  1126. break;
  1127. default:
  1128. out1fmt("<subtype %d>", subtype);
  1129. }
  1130. break;
  1131. case CTLENDVAR:
  1132. putc('}', fp);
  1133. break;
  1134. #if BASH_PROCESS_SUBST
  1135. case CTLTOPROC:
  1136. putc('>', fp);
  1137. goto backq;
  1138. case CTLFROMPROC:
  1139. putc('<', fp);
  1140. goto backq;
  1141. #endif
  1142. case CTLBACKQ:
  1143. putc('$', fp);
  1144. IF_BASH_PROCESS_SUBST(backq:)
  1145. putc('(', fp);
  1146. shtree(bqlist->n, -1, NULL, fp);
  1147. putc(')', fp);
  1148. break;
  1149. default:
  1150. putc(*p, fp);
  1151. break;
  1152. }
  1153. }
  1154. }
  1155. static void
  1156. shcmd(union node *cmd, FILE *fp)
  1157. {
  1158. union node *np;
  1159. int first;
  1160. const char *s;
  1161. int dftfd;
  1162. first = 1;
  1163. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1164. if (!first)
  1165. putc(' ', fp);
  1166. sharg(np, fp);
  1167. first = 0;
  1168. }
  1169. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1170. if (!first)
  1171. putc(' ', fp);
  1172. dftfd = 0;
  1173. switch (np->nfile.type) {
  1174. case NTO: s = ">>"+1; dftfd = 1; break;
  1175. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1176. case NAPPEND: s = ">>"; dftfd = 1; break;
  1177. #if BASH_REDIR_OUTPUT
  1178. case NTO2:
  1179. #endif
  1180. case NTOFD: s = ">&"; dftfd = 1; break;
  1181. case NFROM: s = "<"; break;
  1182. case NFROMFD: s = "<&"; break;
  1183. case NFROMTO: s = "<>"; break;
  1184. default: s = "*error*"; break;
  1185. }
  1186. if (np->nfile.fd != dftfd)
  1187. fprintf(fp, "%d", np->nfile.fd);
  1188. fputs(s, fp);
  1189. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1190. fprintf(fp, "%d", np->ndup.dupfd);
  1191. } else {
  1192. sharg(np->nfile.fname, fp);
  1193. }
  1194. first = 0;
  1195. }
  1196. }
  1197. static void
  1198. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1199. {
  1200. struct nodelist *lp;
  1201. const char *s;
  1202. if (n == NULL)
  1203. return;
  1204. indent(ind, pfx, fp);
  1205. if (n == NODE_EOF) {
  1206. fputs("<EOF>", fp);
  1207. return;
  1208. }
  1209. switch (n->type) {
  1210. case NSEMI:
  1211. s = "; ";
  1212. goto binop;
  1213. case NAND:
  1214. s = " && ";
  1215. goto binop;
  1216. case NOR:
  1217. s = " || ";
  1218. binop:
  1219. shtree(n->nbinary.ch1, ind, NULL, fp);
  1220. /* if (ind < 0) */
  1221. fputs(s, fp);
  1222. shtree(n->nbinary.ch2, ind, NULL, fp);
  1223. break;
  1224. case NCMD:
  1225. shcmd(n, fp);
  1226. if (ind >= 0)
  1227. putc('\n', fp);
  1228. break;
  1229. case NPIPE:
  1230. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1231. shtree(lp->n, 0, NULL, fp);
  1232. if (lp->next)
  1233. fputs(" | ", fp);
  1234. }
  1235. if (n->npipe.pipe_backgnd)
  1236. fputs(" &", fp);
  1237. if (ind >= 0)
  1238. putc('\n', fp);
  1239. break;
  1240. default:
  1241. fprintf(fp, "<node type %d>", n->type);
  1242. if (ind >= 0)
  1243. putc('\n', fp);
  1244. break;
  1245. }
  1246. }
  1247. static void
  1248. showtree(union node *n)
  1249. {
  1250. trace_puts("showtree called\n");
  1251. shtree(n, 1, NULL, stderr);
  1252. }
  1253. #endif /* DEBUG */
  1254. /* ============ Message printing */
  1255. static void
  1256. ash_vmsg(const char *msg, va_list ap)
  1257. {
  1258. fprintf(stderr, "%s: ", arg0);
  1259. if (commandname) {
  1260. if (strcmp(arg0, commandname))
  1261. fprintf(stderr, "%s: ", commandname);
  1262. if (!iflag || g_parsefile->pf_fd > 0)
  1263. fprintf(stderr, "line %d: ", errlinno);
  1264. }
  1265. vfprintf(stderr, msg, ap);
  1266. newline_and_flush(stderr);
  1267. }
  1268. /*
  1269. * Exverror is called to raise the error exception. If the second argument
  1270. * is not NULL then error prints an error message using printf style
  1271. * formatting. It then raises the error exception.
  1272. */
  1273. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1274. static void
  1275. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1276. {
  1277. #if DEBUG
  1278. if (msg) {
  1279. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1280. TRACEV((msg, ap));
  1281. } else
  1282. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1283. if (msg)
  1284. #endif
  1285. ash_vmsg(msg, ap);
  1286. flush_stdout_stderr();
  1287. raise_exception(cond);
  1288. /* NOTREACHED */
  1289. }
  1290. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1291. static void
  1292. ash_msg_and_raise_error(const char *msg, ...)
  1293. {
  1294. va_list ap;
  1295. exitstatus = 2;
  1296. va_start(ap, msg);
  1297. ash_vmsg_and_raise(EXERROR, msg, ap);
  1298. /* NOTREACHED */
  1299. va_end(ap);
  1300. }
  1301. /*
  1302. * 'fmt' must be a string literal.
  1303. */
  1304. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1305. static void raise_error_syntax(const char *) NORETURN;
  1306. static void
  1307. raise_error_syntax(const char *msg)
  1308. {
  1309. errlinno = g_parsefile->linno;
  1310. ash_msg_and_raise_error("syntax error: %s", msg);
  1311. /* NOTREACHED */
  1312. }
  1313. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1314. static void
  1315. ash_msg_and_raise(int cond, const char *msg, ...)
  1316. {
  1317. va_list ap;
  1318. va_start(ap, msg);
  1319. ash_vmsg_and_raise(cond, msg, ap);
  1320. /* NOTREACHED */
  1321. va_end(ap);
  1322. }
  1323. /*
  1324. * error/warning routines for external builtins
  1325. */
  1326. static void
  1327. ash_msg(const char *fmt, ...)
  1328. {
  1329. va_list ap;
  1330. va_start(ap, fmt);
  1331. ash_vmsg(fmt, ap);
  1332. va_end(ap);
  1333. }
  1334. /*
  1335. * Return a string describing an error. The returned string may be a
  1336. * pointer to a static buffer that will be overwritten on the next call.
  1337. * Action describes the operation that got the error.
  1338. */
  1339. static const char *
  1340. errmsg(int e, const char *em)
  1341. {
  1342. if (e == ENOENT || e == ENOTDIR) {
  1343. return em;
  1344. }
  1345. return strerror(e);
  1346. }
  1347. /* ============ Memory allocation */
  1348. #if 0
  1349. /* I consider these wrappers nearly useless:
  1350. * ok, they return you to nearest exception handler, but
  1351. * how much memory do you leak in the process, making
  1352. * memory starvation worse?
  1353. */
  1354. static void *
  1355. ckrealloc(void * p, size_t nbytes)
  1356. {
  1357. p = realloc(p, nbytes);
  1358. if (!p)
  1359. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1360. return p;
  1361. }
  1362. static void *
  1363. ckmalloc(size_t nbytes)
  1364. {
  1365. return ckrealloc(NULL, nbytes);
  1366. }
  1367. static void *
  1368. ckzalloc(size_t nbytes)
  1369. {
  1370. return memset(ckmalloc(nbytes), 0, nbytes);
  1371. }
  1372. static char *
  1373. ckstrdup(const char *s)
  1374. {
  1375. char *p = strdup(s);
  1376. if (!p)
  1377. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1378. return p;
  1379. }
  1380. #else
  1381. /* Using bbox equivalents. They exit if out of memory */
  1382. # define ckrealloc xrealloc
  1383. # define ckmalloc xmalloc
  1384. # define ckzalloc xzalloc
  1385. # define ckstrdup xstrdup
  1386. #endif
  1387. /*
  1388. * It appears that grabstackstr() will barf with such alignments
  1389. * because stalloc() will return a string allocated in a new stackblock.
  1390. */
  1391. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1392. enum {
  1393. /* Most machines require the value returned from malloc to be aligned
  1394. * in some way. The following macro will get this right
  1395. * on many machines. */
  1396. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1397. /* Minimum size of a block */
  1398. MINSIZE = SHELL_ALIGN(504),
  1399. };
  1400. struct stack_block {
  1401. struct stack_block *prev;
  1402. char space[MINSIZE];
  1403. };
  1404. struct stackmark {
  1405. struct stack_block *stackp;
  1406. char *stacknxt;
  1407. size_t stacknleft;
  1408. };
  1409. struct globals_memstack {
  1410. struct stack_block *g_stackp; // = &stackbase;
  1411. char *g_stacknxt; // = stackbase.space;
  1412. char *sstrend; // = stackbase.space + MINSIZE;
  1413. size_t g_stacknleft; // = MINSIZE;
  1414. struct stack_block stackbase;
  1415. };
  1416. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1417. #define G_memstack (*ash_ptr_to_globals_memstack)
  1418. #define g_stackp (G_memstack.g_stackp )
  1419. #define g_stacknxt (G_memstack.g_stacknxt )
  1420. #define sstrend (G_memstack.sstrend )
  1421. #define g_stacknleft (G_memstack.g_stacknleft)
  1422. #define stackbase (G_memstack.stackbase )
  1423. #define INIT_G_memstack() do { \
  1424. XZALLOC_CONST_PTR(&ash_ptr_to_globals_memstack, sizeof(G_memstack)); \
  1425. g_stackp = &stackbase; \
  1426. g_stacknxt = stackbase.space; \
  1427. g_stacknleft = MINSIZE; \
  1428. sstrend = stackbase.space + MINSIZE; \
  1429. } while (0)
  1430. #define stackblock() ((void *)g_stacknxt)
  1431. #define stackblocksize() g_stacknleft
  1432. /*
  1433. * Parse trees for commands are allocated in lifo order, so we use a stack
  1434. * to make this more efficient, and also to avoid all sorts of exception
  1435. * handling code to handle interrupts in the middle of a parse.
  1436. *
  1437. * The size 504 was chosen because the Ultrix malloc handles that size
  1438. * well.
  1439. */
  1440. static void *
  1441. stalloc(size_t nbytes)
  1442. {
  1443. char *p;
  1444. size_t aligned;
  1445. aligned = SHELL_ALIGN(nbytes);
  1446. if (aligned > g_stacknleft) {
  1447. size_t len;
  1448. size_t blocksize;
  1449. struct stack_block *sp;
  1450. blocksize = aligned;
  1451. if (blocksize < MINSIZE)
  1452. blocksize = MINSIZE;
  1453. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1454. if (len < blocksize)
  1455. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1456. INT_OFF;
  1457. sp = ckmalloc(len);
  1458. sp->prev = g_stackp;
  1459. g_stacknxt = sp->space;
  1460. g_stacknleft = blocksize;
  1461. sstrend = g_stacknxt + blocksize;
  1462. g_stackp = sp;
  1463. INT_ON;
  1464. }
  1465. p = g_stacknxt;
  1466. g_stacknxt += aligned;
  1467. g_stacknleft -= aligned;
  1468. return p;
  1469. }
  1470. static void *
  1471. stzalloc(size_t nbytes)
  1472. {
  1473. return memset(stalloc(nbytes), 0, nbytes);
  1474. }
  1475. static void
  1476. stunalloc(void *p)
  1477. {
  1478. #if DEBUG
  1479. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1480. write(STDERR_FILENO, "stunalloc\n", 10);
  1481. abort();
  1482. }
  1483. #endif
  1484. g_stacknleft += g_stacknxt - (char *)p;
  1485. g_stacknxt = p;
  1486. }
  1487. /*
  1488. * Like strdup but works with the ash stack.
  1489. */
  1490. static char *
  1491. sstrdup(const char *p)
  1492. {
  1493. size_t len = strlen(p) + 1;
  1494. return memcpy(stalloc(len), p, len);
  1495. }
  1496. static ALWAYS_INLINE void
  1497. grabstackblock(size_t len)
  1498. {
  1499. stalloc(len);
  1500. }
  1501. static void
  1502. pushstackmark(struct stackmark *mark, size_t len)
  1503. {
  1504. mark->stackp = g_stackp;
  1505. mark->stacknxt = g_stacknxt;
  1506. mark->stacknleft = g_stacknleft;
  1507. grabstackblock(len);
  1508. }
  1509. static void
  1510. setstackmark(struct stackmark *mark)
  1511. {
  1512. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1513. }
  1514. static void
  1515. popstackmark(struct stackmark *mark)
  1516. {
  1517. struct stack_block *sp;
  1518. if (!mark->stackp)
  1519. return;
  1520. INT_OFF;
  1521. while (g_stackp != mark->stackp) {
  1522. sp = g_stackp;
  1523. g_stackp = sp->prev;
  1524. free(sp);
  1525. }
  1526. g_stacknxt = mark->stacknxt;
  1527. g_stacknleft = mark->stacknleft;
  1528. sstrend = mark->stacknxt + mark->stacknleft;
  1529. INT_ON;
  1530. }
  1531. /*
  1532. * When the parser reads in a string, it wants to stick the string on the
  1533. * stack and only adjust the stack pointer when it knows how big the
  1534. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1535. * of space on top of the stack and stackblocklen returns the length of
  1536. * this block. Growstackblock will grow this space by at least one byte,
  1537. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1538. * part of the block that has been used.
  1539. */
  1540. static void
  1541. growstackblock(size_t min)
  1542. {
  1543. size_t newlen;
  1544. newlen = g_stacknleft * 2;
  1545. if (newlen < g_stacknleft)
  1546. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1547. min = SHELL_ALIGN(min | 128);
  1548. if (newlen < min)
  1549. newlen += min;
  1550. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1551. struct stack_block *sp;
  1552. struct stack_block *prevstackp;
  1553. size_t grosslen;
  1554. INT_OFF;
  1555. sp = g_stackp;
  1556. prevstackp = sp->prev;
  1557. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1558. sp = ckrealloc(sp, grosslen);
  1559. sp->prev = prevstackp;
  1560. g_stackp = sp;
  1561. g_stacknxt = sp->space;
  1562. g_stacknleft = newlen;
  1563. sstrend = sp->space + newlen;
  1564. INT_ON;
  1565. } else {
  1566. char *oldspace = g_stacknxt;
  1567. size_t oldlen = g_stacknleft;
  1568. char *p = stalloc(newlen);
  1569. /* free the space we just allocated */
  1570. g_stacknxt = memcpy(p, oldspace, oldlen);
  1571. g_stacknleft += newlen;
  1572. }
  1573. }
  1574. /*
  1575. * The following routines are somewhat easier to use than the above.
  1576. * The user declares a variable of type STACKSTR, which may be declared
  1577. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1578. * the user uses the macro STPUTC to add characters to the string. In
  1579. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1580. * grown as necessary. When the user is done, she can just leave the
  1581. * string there and refer to it using stackblock(). Or she can allocate
  1582. * the space for it using grabstackstr(). If it is necessary to allow
  1583. * someone else to use the stack temporarily and then continue to grow
  1584. * the string, the user should use grabstack to allocate the space, and
  1585. * then call ungrabstr(p) to return to the previous mode of operation.
  1586. *
  1587. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1588. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1589. * is space for at least one character.
  1590. */
  1591. static void *
  1592. growstackstr(void)
  1593. {
  1594. size_t len = stackblocksize();
  1595. growstackblock(0);
  1596. return (char *)stackblock() + len;
  1597. }
  1598. static char *
  1599. growstackto(size_t len)
  1600. {
  1601. if (stackblocksize() < len)
  1602. growstackblock(len);
  1603. return stackblock();
  1604. }
  1605. /*
  1606. * Called from CHECKSTRSPACE.
  1607. */
  1608. static char *
  1609. makestrspace(size_t newlen, char *p)
  1610. {
  1611. size_t len = p - g_stacknxt;
  1612. return growstackto(len + newlen) + len;
  1613. }
  1614. static char *
  1615. stnputs(const char *s, size_t n, char *p)
  1616. {
  1617. p = makestrspace(n, p);
  1618. p = (char *)mempcpy(p, s, n);
  1619. return p;
  1620. }
  1621. static char *
  1622. stack_putstr(const char *s, char *p)
  1623. {
  1624. return stnputs(s, strlen(s), p);
  1625. }
  1626. static char *
  1627. _STPUTC(int c, char *p)
  1628. {
  1629. if (p == sstrend)
  1630. p = growstackstr();
  1631. *p++ = c;
  1632. return p;
  1633. }
  1634. #define STARTSTACKSTR(p) ((p) = stackblock())
  1635. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1636. #define CHECKSTRSPACE(n, p) do { \
  1637. char *q = (p); \
  1638. size_t l = (n); \
  1639. size_t m = sstrend - q; \
  1640. if (l > m) \
  1641. (p) = makestrspace(l, q); \
  1642. } while (0)
  1643. #define USTPUTC(c, p) (*(p)++ = (c))
  1644. #define STACKSTRNUL(p) do { \
  1645. if ((p) == sstrend) \
  1646. (p) = growstackstr(); \
  1647. *(p) = '\0'; \
  1648. } while (0)
  1649. #define STUNPUTC(p) (--(p))
  1650. #define STTOPC(p) ((p)[-1])
  1651. #define STADJUST(amount, p) ((p) += (amount))
  1652. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1653. #define ungrabstackstr(s, p) stunalloc(s)
  1654. #define stackstrend() ((void *)sstrend)
  1655. /* ============ String helpers */
  1656. /*
  1657. * prefix -- see if pfx is a prefix of string.
  1658. */
  1659. static char *
  1660. prefix(const char *string, const char *pfx)
  1661. {
  1662. while (*pfx) {
  1663. if (*pfx++ != *string++)
  1664. return NULL;
  1665. }
  1666. return (char *) string;
  1667. }
  1668. /*
  1669. * Check for a valid number. This should be elsewhere.
  1670. */
  1671. static int
  1672. is_number(const char *p)
  1673. {
  1674. do {
  1675. if (!isdigit(*p))
  1676. return 0;
  1677. } while (*++p != '\0');
  1678. return 1;
  1679. }
  1680. /*
  1681. * Convert a string of digits to an integer, printing an error message on
  1682. * failure.
  1683. */
  1684. static int
  1685. number(const char *s)
  1686. {
  1687. if (!is_number(s))
  1688. ash_msg_and_raise_error(msg_illnum, s);
  1689. return atoi(s);
  1690. }
  1691. /*
  1692. * Produce a single quoted string suitable as input to the shell.
  1693. * The return string is allocated on the stack.
  1694. */
  1695. static char *
  1696. single_quote(const char *s)
  1697. {
  1698. char *p;
  1699. STARTSTACKSTR(p);
  1700. do {
  1701. char *q;
  1702. size_t len;
  1703. len = strchrnul(s, '\'') - s;
  1704. q = p = makestrspace(len + 3, p);
  1705. *q++ = '\'';
  1706. q = (char *)mempcpy(q, s, len);
  1707. *q++ = '\'';
  1708. s += len;
  1709. STADJUST(q - p, p);
  1710. if (*s != '\'')
  1711. break;
  1712. len = 0;
  1713. do len++; while (*++s == '\'');
  1714. q = p = makestrspace(len + 3, p);
  1715. *q++ = '"';
  1716. q = (char *)mempcpy(q, s - len, len);
  1717. *q++ = '"';
  1718. STADJUST(q - p, p);
  1719. } while (*s);
  1720. USTPUTC('\0', p);
  1721. return stackblock();
  1722. }
  1723. /*
  1724. * Produce a possibly single quoted string suitable as input to the shell.
  1725. * If quoting was done, the return string is allocated on the stack,
  1726. * otherwise a pointer to the original string is returned.
  1727. */
  1728. static const char *
  1729. maybe_single_quote(const char *s)
  1730. {
  1731. const char *p = s;
  1732. while (*p) {
  1733. /* Assuming ACSII */
  1734. /* quote ctrl_chars space !"#$%&'()* */
  1735. if (*p < '+')
  1736. goto need_quoting;
  1737. /* quote ;<=>? */
  1738. if (*p >= ';' && *p <= '?')
  1739. goto need_quoting;
  1740. /* quote `[\ */
  1741. if (*p == '`')
  1742. goto need_quoting;
  1743. if (*p == '[')
  1744. goto need_quoting;
  1745. if (*p == '\\')
  1746. goto need_quoting;
  1747. /* quote {|}~ DEL and high bytes */
  1748. if (*p > 'z')
  1749. goto need_quoting;
  1750. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1751. /* TODO: maybe avoid quoting % */
  1752. p++;
  1753. }
  1754. return s;
  1755. need_quoting:
  1756. return single_quote(s);
  1757. }
  1758. /* ============ nextopt */
  1759. static char **argptr; /* argument list for builtin commands */
  1760. static char *optionarg; /* set by nextopt (like getopt) */
  1761. static char *optptr; /* used by nextopt */
  1762. /*
  1763. * XXX - should get rid of. Have all builtins use getopt(3).
  1764. * The library getopt must have the BSD extension static variable
  1765. * "optreset", otherwise it can't be used within the shell safely.
  1766. *
  1767. * Standard option processing (a la getopt) for builtin routines.
  1768. * The only argument that is passed to nextopt is the option string;
  1769. * the other arguments are unnecessary. It returns the character,
  1770. * or '\0' on end of input.
  1771. */
  1772. static int
  1773. nextopt(const char *optstring)
  1774. {
  1775. char *p;
  1776. const char *q;
  1777. char c;
  1778. p = optptr;
  1779. if (p == NULL || *p == '\0') {
  1780. /* We ate entire "-param", take next one */
  1781. p = *argptr;
  1782. if (p == NULL)
  1783. return '\0';
  1784. if (*p != '-')
  1785. return '\0';
  1786. if (*++p == '\0') /* just "-" ? */
  1787. return '\0';
  1788. argptr++;
  1789. if (LONE_DASH(p)) /* "--" ? */
  1790. return '\0';
  1791. /* p => next "-param" */
  1792. }
  1793. /* p => some option char in the middle of a "-param" */
  1794. c = *p++;
  1795. for (q = optstring; *q != c;) {
  1796. if (*q == '\0')
  1797. ash_msg_and_raise_error("illegal option -%c", c);
  1798. if (*++q == ':')
  1799. q++;
  1800. }
  1801. if (*++q == ':') {
  1802. if (*p == '\0') {
  1803. p = *argptr++;
  1804. if (p == NULL)
  1805. ash_msg_and_raise_error("no arg for -%c option", c);
  1806. }
  1807. optionarg = p;
  1808. p = NULL;
  1809. }
  1810. optptr = p;
  1811. return c;
  1812. }
  1813. /* ============ Shell variables */
  1814. struct shparam {
  1815. int nparam; /* # of positional parameters (without $0) */
  1816. #if ENABLE_ASH_GETOPTS
  1817. int optind; /* next parameter to be processed by getopts */
  1818. int optoff; /* used by getopts */
  1819. #endif
  1820. unsigned char malloced; /* if parameter list dynamically allocated */
  1821. char **p; /* parameter list */
  1822. };
  1823. /*
  1824. * Free the list of positional parameters.
  1825. */
  1826. static void
  1827. freeparam(volatile struct shparam *param)
  1828. {
  1829. if (param->malloced) {
  1830. char **ap, **ap1;
  1831. ap = ap1 = param->p;
  1832. while (*ap)
  1833. free(*ap++);
  1834. free(ap1);
  1835. }
  1836. }
  1837. #if ENABLE_ASH_GETOPTS
  1838. static void FAST_FUNC getoptsreset(const char *value);
  1839. #endif
  1840. struct var {
  1841. struct var *next; /* next entry in hash list */
  1842. int flags; /* flags are defined above */
  1843. const char *var_text; /* name=value */
  1844. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1845. /* the variable gets set/unset */
  1846. };
  1847. struct localvar {
  1848. struct localvar *next; /* next local variable in list */
  1849. struct var *vp; /* the variable that was made local */
  1850. int flags; /* saved flags */
  1851. const char *text; /* saved text */
  1852. };
  1853. /* flags */
  1854. #define VEXPORT 0x01 /* variable is exported */
  1855. #define VREADONLY 0x02 /* variable cannot be modified */
  1856. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1857. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1858. #define VSTACK 0x10 /* text is allocated on the stack */
  1859. #define VUNSET 0x20 /* the variable is not set */
  1860. #define VNOFUNC 0x40 /* don't call the callback function */
  1861. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1862. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1863. #if ENABLE_ASH_RANDOM_SUPPORT
  1864. # define VDYNAMIC 0x200 /* dynamic variable */
  1865. #else
  1866. # define VDYNAMIC 0
  1867. #endif
  1868. /* Need to be before varinit_data[] */
  1869. #if ENABLE_LOCALE_SUPPORT
  1870. static void FAST_FUNC
  1871. change_lc_all(const char *value)
  1872. {
  1873. if (value && *value != '\0')
  1874. setlocale(LC_ALL, value);
  1875. }
  1876. static void FAST_FUNC
  1877. change_lc_ctype(const char *value)
  1878. {
  1879. if (value && *value != '\0')
  1880. setlocale(LC_CTYPE, value);
  1881. }
  1882. #endif
  1883. #if ENABLE_ASH_MAIL
  1884. static void chkmail(void);
  1885. static void changemail(const char *var_value) FAST_FUNC;
  1886. #else
  1887. # define chkmail() ((void)0)
  1888. #endif
  1889. static void changepath(const char *) FAST_FUNC;
  1890. #if ENABLE_ASH_RANDOM_SUPPORT
  1891. static void change_random(const char *) FAST_FUNC;
  1892. #endif
  1893. #if BASH_EPOCH_VARS
  1894. static void change_seconds(const char *) FAST_FUNC;
  1895. static void change_realtime(const char *) FAST_FUNC;
  1896. #endif
  1897. static const struct {
  1898. int flags;
  1899. const char *var_text;
  1900. void (*var_func)(const char *) FAST_FUNC;
  1901. } varinit_data[] ALIGN_PTR = {
  1902. /*
  1903. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1904. * some environment strings may be constant.
  1905. */
  1906. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1907. #if ENABLE_ASH_MAIL
  1908. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1909. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1910. #endif
  1911. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1912. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1913. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1914. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1915. #if ENABLE_ASH_GETOPTS
  1916. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1917. #endif
  1918. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1919. { VSTRFIXED|VTEXTFIXED , NULL /* inited to funcnamevar */, NULL },
  1920. #if ENABLE_ASH_RANDOM_SUPPORT
  1921. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1922. #endif
  1923. #if BASH_EPOCH_VARS
  1924. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
  1925. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
  1926. #endif
  1927. #if ENABLE_LOCALE_SUPPORT
  1928. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1929. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1930. #endif
  1931. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1932. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1933. #endif
  1934. };
  1935. struct redirtab;
  1936. struct globals_var {
  1937. struct shparam shellparam; /* $@ current positional parameters */
  1938. struct redirtab *redirlist;
  1939. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1940. struct var *vartab[VTABSIZE];
  1941. struct var varinit[ARRAY_SIZE(varinit_data)];
  1942. int lineno;
  1943. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1944. char funcnamevar[sizeof("FUNCNAME=") + 64];
  1945. char *funcname;
  1946. unsigned trap_depth;
  1947. bool in_trap_ERR; /* ERR cannot recurse, no need to be a counter */
  1948. };
  1949. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1950. #define G_var (*ash_ptr_to_globals_var)
  1951. #define shellparam (G_var.shellparam )
  1952. //#define redirlist (G_var.redirlist )
  1953. #define preverrout_fd (G_var.preverrout_fd)
  1954. #define vartab (G_var.vartab )
  1955. #define varinit (G_var.varinit )
  1956. #define lineno (G_var.lineno )
  1957. #define linenovar (G_var.linenovar )
  1958. #define funcnamevar (G_var.funcnamevar )
  1959. #define funcname (G_var.funcname )
  1960. #define trap_depth (G_var.trap_depth )
  1961. #define in_trap_ERR (G_var.in_trap_ERR )
  1962. #define vifs varinit[0]
  1963. #if ENABLE_ASH_MAIL
  1964. # define vmail varinit[1]
  1965. # define vmpath varinit[2]
  1966. #endif
  1967. #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
  1968. #define vpath varinit[VAR_OFFSET1 + 1]
  1969. #define vps1 varinit[VAR_OFFSET1 + 2]
  1970. #define vps2 varinit[VAR_OFFSET1 + 3]
  1971. #define vps4 varinit[VAR_OFFSET1 + 4]
  1972. #if ENABLE_ASH_GETOPTS
  1973. # define voptind varinit[VAR_OFFSET1 + 5]
  1974. #endif
  1975. #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
  1976. #define vlineno varinit[VAR_OFFSET2 + 5]
  1977. #define vfuncname varinit[VAR_OFFSET2 + 6]
  1978. #if ENABLE_ASH_RANDOM_SUPPORT
  1979. # define vrandom varinit[VAR_OFFSET2 + 7]
  1980. #endif
  1981. #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
  1982. #if BASH_EPOCH_VARS
  1983. # define vepochs varinit[VAR_OFFSET3 + 7]
  1984. # define vepochr varinit[VAR_OFFSET3 + 8]
  1985. #endif
  1986. #define INIT_G_var() do { \
  1987. unsigned i; \
  1988. XZALLOC_CONST_PTR(&ash_ptr_to_globals_var, sizeof(G_var)); \
  1989. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1990. varinit[i].flags = varinit_data[i].flags; \
  1991. varinit[i].var_text = varinit_data[i].var_text; \
  1992. varinit[i].var_func = varinit_data[i].var_func; \
  1993. } \
  1994. strcpy(linenovar, "LINENO="); \
  1995. vlineno.var_text = linenovar; \
  1996. strcpy(funcnamevar, "FUNCNAME="); \
  1997. vfuncname.var_text = funcnamevar; \
  1998. } while (0)
  1999. /*
  2000. * The following macros access the values of the above variables.
  2001. * They have to skip over the name. They return the null string
  2002. * for unset variables.
  2003. */
  2004. #define ifsval() (vifs.var_text + 4)
  2005. #define ifsset() ((vifs.flags & VUNSET) == 0)
  2006. #if ENABLE_ASH_MAIL
  2007. # define mailval() (vmail.var_text + 5)
  2008. # define mpathval() (vmpath.var_text + 9)
  2009. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  2010. #endif
  2011. #define pathval() (vpath.var_text + 5)
  2012. #define ps1val() (vps1.var_text + 4)
  2013. #define ps2val() (vps2.var_text + 4)
  2014. #define ps4val() (vps4.var_text + 4)
  2015. #if ENABLE_ASH_GETOPTS
  2016. # define optindval() (voptind.var_text + 7)
  2017. #endif
  2018. #if ENABLE_ASH_GETOPTS
  2019. static void FAST_FUNC
  2020. getoptsreset(const char *value)
  2021. {
  2022. shellparam.optind = 1;
  2023. if (is_number(value))
  2024. shellparam.optind = number(value) ?: 1;
  2025. shellparam.optoff = -1;
  2026. }
  2027. #endif
  2028. /*
  2029. * Compares two strings up to the first = or '\0'. The first
  2030. * string must be terminated by '='; the second may be terminated by
  2031. * either '=' or '\0'.
  2032. */
  2033. static int
  2034. varcmp(const char *p, const char *q)
  2035. {
  2036. int c, d;
  2037. while ((c = *p) == (d = *q)) {
  2038. if (c == '\0' || c == '=')
  2039. goto out;
  2040. p++;
  2041. q++;
  2042. }
  2043. if (c == '=')
  2044. c = '\0';
  2045. if (d == '=')
  2046. d = '\0';
  2047. out:
  2048. return c - d;
  2049. }
  2050. /*
  2051. * Find the appropriate entry in the hash table from the name.
  2052. */
  2053. static struct var **
  2054. hashvar(const char *p)
  2055. {
  2056. unsigned hashval;
  2057. hashval = ((unsigned char) *p) << 4;
  2058. while (*p && *p != '=')
  2059. hashval += (unsigned char) *p++;
  2060. return &vartab[hashval % VTABSIZE];
  2061. }
  2062. static int
  2063. vpcmp(const void *a, const void *b)
  2064. {
  2065. return varcmp(*(const char **)a, *(const char **)b);
  2066. }
  2067. /*
  2068. * This routine initializes the builtin variables.
  2069. */
  2070. static void
  2071. initvar(void)
  2072. {
  2073. struct var *vp;
  2074. struct var *end;
  2075. struct var **vpp;
  2076. /*
  2077. * PS1 depends on uid
  2078. */
  2079. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2080. vps1.var_text = "PS1=\\w \\$ ";
  2081. #else
  2082. if (!geteuid())
  2083. vps1.var_text = "PS1=# ";
  2084. #endif
  2085. vp = varinit;
  2086. end = vp + ARRAY_SIZE(varinit);
  2087. do {
  2088. vpp = hashvar(vp->var_text);
  2089. vp->next = *vpp;
  2090. *vpp = vp;
  2091. } while (++vp < end);
  2092. }
  2093. static struct var **
  2094. findvar(struct var **vpp, const char *name)
  2095. {
  2096. for (; *vpp; vpp = &(*vpp)->next) {
  2097. if (varcmp((*vpp)->var_text, name) == 0) {
  2098. break;
  2099. }
  2100. }
  2101. return vpp;
  2102. }
  2103. /*
  2104. * Find the value of a variable. Returns NULL if not set.
  2105. */
  2106. static const char* FAST_FUNC
  2107. lookupvar(const char *name)
  2108. {
  2109. struct var *v;
  2110. v = *findvar(hashvar(name), name);
  2111. if (v) {
  2112. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2113. /*
  2114. * Dynamic variables are implemented roughly the same way they are
  2115. * in bash. Namely, they're "special" so long as they aren't unset.
  2116. * As soon as they're unset, they're no longer dynamic, and dynamic
  2117. * lookup will no longer happen at that point. -- PFM.
  2118. */
  2119. if (v->flags & VDYNAMIC)
  2120. v->var_func(NULL);
  2121. #endif
  2122. if (!(v->flags & VUNSET)) {
  2123. if (v->var_text == linenovar) {
  2124. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2125. } else
  2126. if (v->var_text == funcnamevar) {
  2127. safe_strncpy(funcnamevar+9, funcname ? funcname : "", sizeof(funcnamevar)-9);
  2128. }
  2129. return var_end(v->var_text);
  2130. }
  2131. }
  2132. return NULL;
  2133. }
  2134. #if ENABLE_UNICODE_SUPPORT
  2135. static void
  2136. reinit_unicode_for_ash(void)
  2137. {
  2138. /* Unicode support should be activated even if LANG is set
  2139. * _during_ shell execution, not only if it was set when
  2140. * shell was started. Therefore, re-check LANG every time:
  2141. */
  2142. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2143. || ENABLE_UNICODE_USING_LOCALE
  2144. ) {
  2145. const char *s = lookupvar("LC_ALL");
  2146. if (!s) s = lookupvar("LC_CTYPE");
  2147. if (!s) s = lookupvar("LANG");
  2148. reinit_unicode(s);
  2149. }
  2150. }
  2151. #else
  2152. # define reinit_unicode_for_ash() ((void)0)
  2153. #endif
  2154. /*
  2155. * Search the environment of a builtin command.
  2156. */
  2157. static ALWAYS_INLINE const char *
  2158. bltinlookup(const char *name)
  2159. {
  2160. return lookupvar(name);
  2161. }
  2162. /*
  2163. * Same as setvar except that the variable and value are passed in
  2164. * the first argument as name=value. Since the first argument will
  2165. * be actually stored in the table, it should not be a string that
  2166. * will go away.
  2167. * Called with interrupts off.
  2168. */
  2169. static struct var *
  2170. setvareq(char *s, int flags)
  2171. {
  2172. struct var *vp, **vpp;
  2173. vpp = hashvar(s);
  2174. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2175. vpp = findvar(vpp, s);
  2176. vp = *vpp;
  2177. if (vp) {
  2178. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2179. const char *n;
  2180. if (flags & VNOSAVE)
  2181. free(s);
  2182. n = vp->var_text;
  2183. exitstatus = 1;
  2184. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2185. }
  2186. if (flags & VNOSET)
  2187. goto out;
  2188. if (vp->var_func && !(flags & VNOFUNC))
  2189. vp->var_func(var_end(s));
  2190. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2191. free((char*)vp->var_text);
  2192. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2193. *vpp = vp->next;
  2194. free(vp);
  2195. out_free:
  2196. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2197. free(s);
  2198. goto out;
  2199. }
  2200. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2201. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2202. if (flags & VUNSET)
  2203. flags &= ~VDYNAMIC;
  2204. #endif
  2205. } else {
  2206. /* variable s is not found */
  2207. if (flags & VNOSET)
  2208. goto out;
  2209. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2210. goto out_free;
  2211. vp = ckzalloc(sizeof(*vp));
  2212. vp->next = *vpp;
  2213. /*vp->func = NULL; - ckzalloc did it */
  2214. *vpp = vp;
  2215. }
  2216. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2217. s = ckstrdup(s);
  2218. vp->var_text = s;
  2219. vp->flags = flags;
  2220. out:
  2221. return vp;
  2222. }
  2223. /*
  2224. * Set the value of a variable. The flags argument is ored with the
  2225. * flags of the variable. If val is NULL, the variable is unset.
  2226. */
  2227. static struct var *
  2228. setvar(const char *name, const char *val, int flags)
  2229. {
  2230. const char *q;
  2231. char *p;
  2232. char *nameeq;
  2233. size_t namelen;
  2234. size_t vallen;
  2235. struct var *vp;
  2236. q = endofname(name);
  2237. p = strchrnul(q, '=');
  2238. namelen = p - name;
  2239. if (!namelen || p != q)
  2240. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2241. vallen = 0;
  2242. if (val == NULL) {
  2243. flags |= VUNSET;
  2244. } else {
  2245. vallen = strlen(val);
  2246. }
  2247. INT_OFF;
  2248. nameeq = ckzalloc(namelen + vallen + 2);
  2249. p = mempcpy(nameeq, name, namelen);
  2250. if (val) {
  2251. *p++ = '=';
  2252. memcpy(p, val, vallen);
  2253. }
  2254. vp = setvareq(nameeq, flags | VNOSAVE);
  2255. INT_ON;
  2256. return vp;
  2257. }
  2258. static void FAST_FUNC
  2259. setvar0(const char *name, const char *val)
  2260. {
  2261. setvar(name, val, 0);
  2262. }
  2263. /*
  2264. * Unset the specified variable.
  2265. */
  2266. static void
  2267. unsetvar(const char *s)
  2268. {
  2269. setvar(s, NULL, 0);
  2270. }
  2271. /*
  2272. * Generate a list of variables satisfying the given conditions.
  2273. */
  2274. #if !ENABLE_FEATURE_SH_NOFORK
  2275. # define listvars(on, off, lp, end) listvars(on, off, end)
  2276. #endif
  2277. static char **
  2278. listvars(int on, int off, struct strlist *lp, char ***end)
  2279. {
  2280. struct var **vpp;
  2281. struct var *vp;
  2282. char **ep;
  2283. int mask;
  2284. STARTSTACKSTR(ep);
  2285. vpp = vartab;
  2286. mask = on | off;
  2287. do {
  2288. for (vp = *vpp; vp; vp = vp->next) {
  2289. if ((vp->flags & mask) == on) {
  2290. #if ENABLE_FEATURE_SH_NOFORK
  2291. /* If variable with the same name is both
  2292. * exported and temporarily set for a command:
  2293. * export ZVAR=5
  2294. * ZVAR=6 printenv
  2295. * then "ZVAR=6" will be both in vartab and
  2296. * lp lists. Do not pass it twice to printenv.
  2297. */
  2298. struct strlist *lp1 = lp;
  2299. while (lp1) {
  2300. if (strcmp(lp1->text, vp->var_text) == 0)
  2301. goto skip;
  2302. lp1 = lp1->next;
  2303. }
  2304. #endif
  2305. if (ep == stackstrend())
  2306. ep = growstackstr();
  2307. *ep++ = (char*)vp->var_text;
  2308. #if ENABLE_FEATURE_SH_NOFORK
  2309. skip: ;
  2310. #endif
  2311. }
  2312. }
  2313. } while (++vpp < vartab + VTABSIZE);
  2314. #if ENABLE_FEATURE_SH_NOFORK
  2315. while (lp) {
  2316. if (ep == stackstrend())
  2317. ep = growstackstr();
  2318. *ep++ = lp->text;
  2319. lp = lp->next;
  2320. }
  2321. #endif
  2322. if (ep == stackstrend())
  2323. ep = growstackstr();
  2324. if (end)
  2325. *end = ep;
  2326. *ep++ = NULL;
  2327. return grabstackstr(ep);
  2328. }
  2329. /* ============ Path search helper */
  2330. static const char *
  2331. legal_pathopt(const char *opt, const char *term, int magic)
  2332. {
  2333. switch (magic) {
  2334. case 0:
  2335. opt = NULL;
  2336. break;
  2337. case 1:
  2338. opt = prefix(opt, "builtin") ?: prefix(opt, "func");
  2339. break;
  2340. default:
  2341. opt += strcspn(opt, term);
  2342. break;
  2343. }
  2344. if (opt && *opt == '%')
  2345. opt++;
  2346. return opt;
  2347. }
  2348. /*
  2349. * The variable path (passed by reference) should be set to the start
  2350. * of the path before the first call; padvance will update
  2351. * this value as it proceeds. Successive calls to padvance will return
  2352. * the possible path expansions in sequence. If an option (indicated by
  2353. * a percent sign) appears in the path entry then the global variable
  2354. * pathopt will be set to point to it; otherwise pathopt will be set to
  2355. * NULL.
  2356. *
  2357. * If magic is 0 then pathopt recognition will be disabled. If magic is
  2358. * 1 we shall recognise %builtin/%func. Otherwise we shall accept any
  2359. * pathopt.
  2360. */
  2361. static const char *pathopt; /* set by padvance */
  2362. static int
  2363. padvance_magic(const char **path, const char *name, int magic)
  2364. {
  2365. const char *term = "%:";
  2366. const char *lpathopt;
  2367. const char *p;
  2368. char *q;
  2369. const char *start;
  2370. size_t qlen;
  2371. size_t len;
  2372. if (*path == NULL)
  2373. return -1;
  2374. lpathopt = NULL;
  2375. start = *path;
  2376. if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) {
  2377. lpathopt = start + 1;
  2378. start = p;
  2379. term = ":";
  2380. }
  2381. len = strcspn(start, term);
  2382. p = start + len;
  2383. if (*p == '%') {
  2384. size_t extra = strchrnul(p, ':') - p;
  2385. if (legal_pathopt(p + 1, term, magic))
  2386. lpathopt = p + 1;
  2387. else
  2388. len += extra;
  2389. p += extra;
  2390. }
  2391. pathopt = lpathopt;
  2392. *path = *p == ':' ? p + 1 : NULL;
  2393. /* "2" is for '/' and '\0' */
  2394. qlen = len + strlen(name) + 2;
  2395. q = growstackto(qlen);
  2396. if (len) {
  2397. q = mempcpy(q, start, len);
  2398. *q++ = '/';
  2399. }
  2400. strcpy(q, name);
  2401. return qlen;
  2402. }
  2403. static int
  2404. padvance(const char **path, const char *name)
  2405. {
  2406. return padvance_magic(path, name, 1);
  2407. }
  2408. /* ============ Prompt */
  2409. static smallint doprompt; /* if set, prompt the user */
  2410. static smallint needprompt; /* true if interactive and at start of line */
  2411. #if ENABLE_FEATURE_EDITING
  2412. static line_input_t *line_input_state;
  2413. static const char *cmdedit_prompt;
  2414. static void
  2415. putprompt(const char *s)
  2416. {
  2417. if (ENABLE_ASH_EXPAND_PRMT) {
  2418. free((char*)cmdedit_prompt);
  2419. cmdedit_prompt = ckstrdup(s);
  2420. return;
  2421. }
  2422. cmdedit_prompt = s;
  2423. }
  2424. #else
  2425. static void
  2426. putprompt(const char *s)
  2427. {
  2428. out2str(s);
  2429. }
  2430. #endif
  2431. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2432. static const char *expandstr(const char *ps, int syntax_type);
  2433. /* Values for syntax param */
  2434. #define BASESYNTAX 0 /* not in quotes */
  2435. #define DQSYNTAX 1 /* in double quotes */
  2436. #define SQSYNTAX 2 /* in single quotes */
  2437. #define ARISYNTAX 3 /* in arithmetic */
  2438. #if ENABLE_ASH_EXPAND_PRMT
  2439. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2440. #endif
  2441. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2442. /*
  2443. * called by editline -- any expansions to the prompt should be added here.
  2444. */
  2445. static void
  2446. setprompt_if(smallint do_set, int whichprompt)
  2447. {
  2448. const char *prompt;
  2449. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2450. if (!do_set)
  2451. return;
  2452. needprompt = 0;
  2453. switch (whichprompt) {
  2454. case 1:
  2455. prompt = ps1val();
  2456. break;
  2457. case 2:
  2458. prompt = ps2val();
  2459. break;
  2460. default: /* 0 */
  2461. prompt = nullstr;
  2462. }
  2463. #if ENABLE_ASH_EXPAND_PRMT
  2464. pushstackmark(&smark, stackblocksize());
  2465. putprompt(expandstr(prompt, PSSYNTAX));
  2466. popstackmark(&smark);
  2467. #else
  2468. putprompt(prompt);
  2469. #endif
  2470. }
  2471. /* ============ The cd and pwd commands */
  2472. #define CD_PHYSICAL 1
  2473. #define CD_PRINT 2
  2474. static int
  2475. cdopt(void)
  2476. {
  2477. int flags = 0;
  2478. int i, j;
  2479. j = 'L';
  2480. while ((i = nextopt("LP")) != '\0') {
  2481. if (i != j) {
  2482. flags ^= CD_PHYSICAL;
  2483. j = i;
  2484. }
  2485. }
  2486. return flags;
  2487. }
  2488. /*
  2489. * Update curdir (the name of the current directory) in response to a
  2490. * cd command.
  2491. */
  2492. static const char *
  2493. updatepwd(const char *dir)
  2494. {
  2495. char *new;
  2496. char *p;
  2497. char *cdcomppath;
  2498. const char *lim;
  2499. cdcomppath = sstrdup(dir);
  2500. STARTSTACKSTR(new);
  2501. if (*dir != '/') {
  2502. if (curdir == nullstr)
  2503. return 0;
  2504. new = stack_putstr(curdir, new);
  2505. }
  2506. new = makestrspace(strlen(dir) + 2, new);
  2507. lim = (char *)stackblock() + 1;
  2508. if (*dir != '/') {
  2509. if (new[-1] != '/')
  2510. USTPUTC('/', new);
  2511. if (new > lim && *lim == '/')
  2512. lim++;
  2513. } else {
  2514. USTPUTC('/', new);
  2515. cdcomppath++;
  2516. if (dir[1] == '/' && dir[2] != '/') {
  2517. USTPUTC('/', new);
  2518. cdcomppath++;
  2519. lim++;
  2520. }
  2521. }
  2522. p = strtok_r(cdcomppath, "/", &cdcomppath);
  2523. while (p) {
  2524. switch (*p) {
  2525. case '.':
  2526. if (p[1] == '.' && p[2] == '\0') {
  2527. while (new > lim) {
  2528. STUNPUTC(new);
  2529. if (new[-1] == '/')
  2530. break;
  2531. }
  2532. break;
  2533. }
  2534. if (p[1] == '\0')
  2535. break;
  2536. /* fall through */
  2537. default:
  2538. new = stack_putstr(p, new);
  2539. USTPUTC('/', new);
  2540. }
  2541. p = strtok_r(NULL, "/", &cdcomppath);
  2542. }
  2543. if (new > lim)
  2544. STUNPUTC(new);
  2545. *new = 0;
  2546. return stackblock();
  2547. }
  2548. /*
  2549. * Find out what the current directory is. If we already know the current
  2550. * directory, this routine returns immediately.
  2551. */
  2552. static char *
  2553. getpwd(void)
  2554. {
  2555. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2556. return dir ? dir : nullstr;
  2557. }
  2558. static void
  2559. setpwd(const char *val, int setold)
  2560. {
  2561. char *oldcur, *dir;
  2562. oldcur = dir = curdir;
  2563. if (setold) {
  2564. setvar("OLDPWD", oldcur, VEXPORT);
  2565. }
  2566. INT_OFF;
  2567. if (physdir != nullstr) {
  2568. if (physdir != oldcur)
  2569. free(physdir);
  2570. physdir = nullstr;
  2571. }
  2572. if (oldcur == val || !val) {
  2573. char *s = getpwd();
  2574. physdir = s;
  2575. if (!val)
  2576. dir = s;
  2577. } else
  2578. dir = ckstrdup(val);
  2579. if (oldcur != dir && oldcur != nullstr) {
  2580. free(oldcur);
  2581. }
  2582. curdir = dir;
  2583. INT_ON;
  2584. setvar("PWD", dir, VEXPORT);
  2585. }
  2586. static void hashcd(void);
  2587. /*
  2588. * Actually do the chdir. We also call hashcd to let other routines
  2589. * know that the current directory has changed.
  2590. */
  2591. static int
  2592. docd(const char *dest, int flags)
  2593. {
  2594. const char *dir = NULL;
  2595. int err;
  2596. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2597. INT_OFF;
  2598. if (!(flags & CD_PHYSICAL)) {
  2599. dir = updatepwd(dest);
  2600. if (dir)
  2601. dest = dir;
  2602. }
  2603. err = chdir(dest);
  2604. if (err)
  2605. goto out;
  2606. setpwd(dir, 1);
  2607. hashcd();
  2608. out:
  2609. INT_ON;
  2610. return err;
  2611. }
  2612. static int FAST_FUNC
  2613. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2614. {
  2615. const char *dest;
  2616. const char *path;
  2617. const char *p;
  2618. char c;
  2619. struct stat statb;
  2620. int flags;
  2621. int len;
  2622. flags = cdopt();
  2623. dest = *argptr;
  2624. if (!dest)
  2625. dest = bltinlookup("HOME");
  2626. else if (LONE_DASH(dest)) {
  2627. dest = bltinlookup("OLDPWD");
  2628. flags |= CD_PRINT;
  2629. }
  2630. if (!dest)
  2631. dest = nullstr;
  2632. if (*dest == '/')
  2633. goto step6;
  2634. if (*dest == '.') {
  2635. c = dest[1];
  2636. dotdot:
  2637. switch (c) {
  2638. case '\0':
  2639. case '/':
  2640. goto step6;
  2641. case '.':
  2642. c = dest[2];
  2643. if (c != '.')
  2644. goto dotdot;
  2645. }
  2646. }
  2647. if (!*dest)
  2648. dest = ".";
  2649. path = bltinlookup("CDPATH");
  2650. while (p = path, (len = padvance(&path, dest)) >= 0) {
  2651. c = *p;
  2652. p = stalloc(len);
  2653. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2654. if (c && c != ':')
  2655. flags |= CD_PRINT;
  2656. docd:
  2657. if (!docd(p, flags))
  2658. goto out;
  2659. goto err;
  2660. }
  2661. }
  2662. step6:
  2663. p = dest;
  2664. goto docd;
  2665. err:
  2666. ash_msg_and_raise_perror("can't cd to %s", dest);
  2667. /* NOTREACHED */
  2668. out:
  2669. if (flags & CD_PRINT)
  2670. out1fmt("%s\n", curdir);
  2671. return 0;
  2672. }
  2673. static int FAST_FUNC
  2674. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2675. {
  2676. int flags;
  2677. const char *dir = curdir;
  2678. flags = cdopt();
  2679. if (flags) {
  2680. if (physdir == nullstr)
  2681. setpwd(dir, 0);
  2682. dir = physdir;
  2683. }
  2684. out1fmt("%s\n", dir);
  2685. return 0;
  2686. }
  2687. /* ============ ... */
  2688. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2689. /* Syntax classes */
  2690. #define CWORD 0 /* character is nothing special */
  2691. #define CNL 1 /* newline character */
  2692. #define CBACK 2 /* a backslash character */
  2693. #define CSQUOTE 3 /* single quote */
  2694. #define CDQUOTE 4 /* double quote */
  2695. #define CENDQUOTE 5 /* a terminating quote */
  2696. #define CBQUOTE 6 /* backwards single quote */
  2697. #define CVAR 7 /* a dollar sign */
  2698. #define CENDVAR 8 /* a '}' character */
  2699. #define CLP 9 /* a left paren in arithmetic */
  2700. #define CRP 10 /* a right paren in arithmetic */
  2701. #define CENDFILE 11 /* end of file */
  2702. #define CCTL 12 /* like CWORD, except it must be escaped */
  2703. #define CSPCL 13 /* these terminate a word */
  2704. #define PEOF 256
  2705. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2706. #if ENABLE_FEATURE_SH_MATH
  2707. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2708. #else
  2709. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2710. #endif
  2711. static const uint16_t S_I_T[] ALIGN2 = {
  2712. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 0, ' ' */
  2713. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 1, \n */
  2714. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 2, !*-/:=?[]~ */
  2715. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 3, '"' */
  2716. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 4, $ */
  2717. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 5, "'" */
  2718. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 6, ( */
  2719. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 7, ) */
  2720. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 8, \ */
  2721. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 9, ` */
  2722. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 10, } */
  2723. #if !USE_SIT_FUNCTION
  2724. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 11, PEOF */
  2725. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 12, 0-9A-Za-z */
  2726. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 13, CTLESC ... */
  2727. #endif
  2728. #undef SIT_ITEM
  2729. };
  2730. /* Constants below must match table above */
  2731. enum {
  2732. CSPCL_CWORD_CWORD_CWORD , /* 0 */
  2733. CNL_CNL_CNL_CNL , /* 1 */
  2734. CWORD_CCTL_CCTL_CWORD , /* 2 */
  2735. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 3 */
  2736. CVAR_CVAR_CWORD_CVAR , /* 4 */
  2737. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 5 */
  2738. CSPCL_CWORD_CWORD_CLP , /* 6 */
  2739. CSPCL_CWORD_CWORD_CRP , /* 7 */
  2740. CBACK_CBACK_CCTL_CBACK , /* 8 */
  2741. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 9 */
  2742. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 10 */
  2743. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 11 */
  2744. CWORD_CWORD_CWORD_CWORD , /* 12 */
  2745. CCTL_CCTL_CCTL_CCTL , /* 13 */
  2746. };
  2747. /* c in SIT(c, syntax) must be an *unsigned char* or PEOF,
  2748. * caller must ensure proper cast on it if c is *char_ptr!
  2749. */
  2750. #if USE_SIT_FUNCTION
  2751. static int
  2752. SIT(int c, int syntax)
  2753. {
  2754. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2755. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2756. /*
  2757. * This causes '/' to be prepended with CTLESC in dquoted string,
  2758. * making "./file"* treated incorrectly because we feed
  2759. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2760. * The "homegrown" glob implementation is okay with that,
  2761. * but glibc one isn't. With '/' always treated as CWORD,
  2762. * both work fine.
  2763. */
  2764. static const uint8_t syntax_index_table[] ALIGN1 = {
  2765. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2766. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2767. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2768. 10, 2 /* "}~" */
  2769. };
  2770. const char *s;
  2771. int indx;
  2772. if (c == PEOF)
  2773. return CENDFILE;
  2774. /* Cast is purely for paranoia here,
  2775. * just in case someone passed signed char to us */
  2776. if ((unsigned char)c >= CTL_FIRST
  2777. && (unsigned char)c <= CTL_LAST
  2778. ) {
  2779. return CCTL;
  2780. }
  2781. s = strchrnul(spec_symbls, c);
  2782. if (*s == '\0')
  2783. return CWORD;
  2784. indx = syntax_index_table[s - spec_symbls];
  2785. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2786. }
  2787. #else /* !USE_SIT_FUNCTION */
  2788. static const uint8_t syntax_index_table[] ALIGN1 = {
  2789. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2790. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2800. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2801. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2823. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2824. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2825. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2827. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2829. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2830. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2831. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2832. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2833. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2835. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2836. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2837. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2838. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2839. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2840. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2841. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2842. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2843. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2844. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2850. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2851. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2852. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2853. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2854. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2855. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2883. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2884. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2885. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2888. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2897. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2899. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2902. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2903. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2904. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2905. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2906. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2916. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2917. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2918. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2921. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2922. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2923. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2924. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2925. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2926. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2927. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2928. #if BASH_PROCESS_SUBST
  2929. /* 137 CTLTOPROC */ CCTL_CCTL_CCTL_CCTL,
  2930. /* 138 CTLFROMPROC */ CCTL_CCTL_CCTL_CCTL,
  2931. #else
  2932. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2933. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2934. #endif
  2935. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2936. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2937. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2967. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2968. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2969. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2970. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2971. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2972. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2973. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2974. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2975. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2976. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2977. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2978. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2979. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2980. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2981. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2982. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2983. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2984. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2985. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2986. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2987. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2988. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2989. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2990. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2991. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2992. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2993. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2994. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2995. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2996. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2997. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2998. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2999. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  3000. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  3001. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  3002. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  3003. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  3004. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  3005. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  3006. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  3007. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  3008. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  3009. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  3010. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  3011. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  3012. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  3013. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  3014. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  3015. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  3016. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  3017. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  3018. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  3019. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  3020. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  3021. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  3022. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  3023. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  3024. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  3025. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  3026. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3027. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  3028. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  3029. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  3030. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  3031. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  3032. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  3033. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  3034. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  3035. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  3036. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3037. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  3038. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  3039. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  3040. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  3041. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  3042. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  3043. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  3044. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  3045. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  3046. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  3047. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  3048. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  3049. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  3050. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  3051. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  3052. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  3053. };
  3054. #if 1
  3055. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  3056. #else /* debug version, caught one signed char bug */
  3057. # define SIT(c, syntax) \
  3058. ({ \
  3059. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  3060. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3061. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  3062. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3063. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  3064. })
  3065. #endif
  3066. #endif /* !USE_SIT_FUNCTION */
  3067. /* ============ Alias handling */
  3068. #if ENABLE_ASH_ALIAS
  3069. #define ALIASINUSE 1
  3070. #define ALIASDEAD 2
  3071. struct alias {
  3072. struct alias *next;
  3073. char *name;
  3074. char *val;
  3075. int flag;
  3076. };
  3077. static struct alias **atab; // [ATABSIZE];
  3078. #define INIT_G_alias() do { \
  3079. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  3080. } while (0)
  3081. static struct alias **
  3082. __lookupalias(const char *name)
  3083. {
  3084. unsigned int hashval;
  3085. struct alias **app;
  3086. const char *p;
  3087. unsigned int ch;
  3088. p = name;
  3089. ch = (unsigned char)*p;
  3090. hashval = ch << 4;
  3091. while (ch) {
  3092. hashval += ch;
  3093. ch = (unsigned char)*++p;
  3094. }
  3095. app = &atab[hashval % ATABSIZE];
  3096. for (; *app; app = &(*app)->next) {
  3097. if (strcmp(name, (*app)->name) == 0) {
  3098. break;
  3099. }
  3100. }
  3101. return app;
  3102. }
  3103. static struct alias *
  3104. lookupalias(const char *name, int check)
  3105. {
  3106. struct alias *ap = *__lookupalias(name);
  3107. if (check && ap && (ap->flag & ALIASINUSE))
  3108. return NULL;
  3109. return ap;
  3110. }
  3111. static struct alias *
  3112. freealias(struct alias *ap)
  3113. {
  3114. struct alias *next;
  3115. if (ap->flag & ALIASINUSE) {
  3116. ap->flag |= ALIASDEAD;
  3117. return ap;
  3118. }
  3119. next = ap->next;
  3120. free(ap->name);
  3121. free(ap->val);
  3122. free(ap);
  3123. return next;
  3124. }
  3125. static void
  3126. setalias(const char *name, const char *val)
  3127. {
  3128. struct alias *ap, **app;
  3129. app = __lookupalias(name);
  3130. ap = *app;
  3131. INT_OFF;
  3132. if (ap) {
  3133. if (!(ap->flag & ALIASINUSE)) {
  3134. free(ap->val);
  3135. }
  3136. ap->val = ckstrdup(val);
  3137. ap->flag &= ~ALIASDEAD;
  3138. } else {
  3139. /* not found */
  3140. ap = ckzalloc(sizeof(struct alias));
  3141. ap->name = ckstrdup(name);
  3142. ap->val = ckstrdup(val);
  3143. /*ap->flag = 0; - ckzalloc did it */
  3144. /*ap->next = NULL;*/
  3145. *app = ap;
  3146. }
  3147. INT_ON;
  3148. }
  3149. static int
  3150. unalias(const char *name)
  3151. {
  3152. struct alias **app;
  3153. app = __lookupalias(name);
  3154. if (*app) {
  3155. INT_OFF;
  3156. *app = freealias(*app);
  3157. INT_ON;
  3158. return 0;
  3159. }
  3160. return 1;
  3161. }
  3162. static void
  3163. rmaliases(void)
  3164. {
  3165. struct alias *ap, **app;
  3166. int i;
  3167. INT_OFF;
  3168. for (i = 0; i < ATABSIZE; i++) {
  3169. app = &atab[i];
  3170. for (ap = *app; ap; ap = *app) {
  3171. *app = freealias(*app);
  3172. if (ap == *app) {
  3173. app = &ap->next;
  3174. }
  3175. }
  3176. }
  3177. INT_ON;
  3178. }
  3179. static void
  3180. printalias(const struct alias *ap)
  3181. {
  3182. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3183. }
  3184. /*
  3185. * TODO - sort output
  3186. */
  3187. static int FAST_FUNC
  3188. aliascmd(int argc UNUSED_PARAM, char **argv)
  3189. {
  3190. char *n, *v;
  3191. int ret = 0;
  3192. struct alias *ap;
  3193. if (!argv[1]) {
  3194. int i;
  3195. for (i = 0; i < ATABSIZE; i++) {
  3196. for (ap = atab[i]; ap; ap = ap->next) {
  3197. printalias(ap);
  3198. }
  3199. }
  3200. return 0;
  3201. }
  3202. while ((n = *++argv) != NULL) {
  3203. v = strchr(n+1, '=');
  3204. if (v == NULL) { /* n+1: funny ksh stuff */
  3205. ap = *__lookupalias(n);
  3206. if (ap == NULL) {
  3207. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3208. ret = 1;
  3209. } else
  3210. printalias(ap);
  3211. } else {
  3212. *v++ = '\0';
  3213. setalias(n, v);
  3214. }
  3215. }
  3216. return ret;
  3217. }
  3218. static int FAST_FUNC
  3219. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3220. {
  3221. int i;
  3222. while (nextopt("a") != '\0') {
  3223. rmaliases();
  3224. return 0;
  3225. }
  3226. for (i = 0; *argptr; argptr++) {
  3227. if (unalias(*argptr)) {
  3228. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3229. i = 1;
  3230. }
  3231. }
  3232. return i;
  3233. }
  3234. #endif /* ASH_ALIAS */
  3235. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3236. #define FORK_FG 0
  3237. #define FORK_BG 1
  3238. #define FORK_NOJOB 2
  3239. /* mode flags for showjob(s) */
  3240. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3241. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3242. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3243. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3244. /*
  3245. * A job structure contains information about a job. A job is either a
  3246. * single process or a set of processes contained in a pipeline. In the
  3247. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3248. * array of pids.
  3249. */
  3250. struct procstat {
  3251. pid_t ps_pid; /* process id */
  3252. int ps_status; /* last process status from wait() */
  3253. char *ps_cmd; /* text of command being run */
  3254. };
  3255. struct job {
  3256. struct procstat ps0; /* status of process */
  3257. struct procstat *ps; /* status of processes when more than one */
  3258. #if JOBS
  3259. int stopstatus; /* status of a stopped job */
  3260. #endif
  3261. unsigned nprocs; /* number of processes */
  3262. #define JOBRUNNING 0 /* at least one proc running */
  3263. #define JOBSTOPPED 1 /* all procs are stopped */
  3264. #define JOBDONE 2 /* all procs are completed */
  3265. unsigned
  3266. state: 8,
  3267. #if JOBS
  3268. sigint: 1, /* job was killed by SIGINT */
  3269. jobctl: 1, /* job running under job control */
  3270. #endif
  3271. waited: 1, /* true if this entry has been waited for */
  3272. used: 1, /* true if this entry is in used */
  3273. changed: 1; /* true if status has changed */
  3274. struct job *prev_job; /* previous job */
  3275. };
  3276. static struct job *makejob(/*union node *,*/ int);
  3277. static int forkshell(struct job *, union node *, int);
  3278. static int waitforjob(struct job *);
  3279. #if !JOBS
  3280. enum { doing_jobctl = 0 };
  3281. #define setjobctl(on) do {} while (0)
  3282. #else
  3283. static smallint doing_jobctl; //references:8
  3284. static void setjobctl(int);
  3285. #endif
  3286. /*
  3287. * Ignore a signal.
  3288. */
  3289. static void
  3290. ignoresig(int signo)
  3291. {
  3292. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3293. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3294. /* No, need to do it */
  3295. signal(signo, SIG_IGN);
  3296. }
  3297. sigmode[signo - 1] = S_HARD_IGN;
  3298. }
  3299. /*
  3300. * Only one usage site - in setsignal()
  3301. */
  3302. static void
  3303. signal_handler(int signo)
  3304. {
  3305. if (signo == SIGCHLD) {
  3306. got_sigchld = 1;
  3307. if (!trap[SIGCHLD])
  3308. return;
  3309. }
  3310. gotsig[signo - 1] = 1;
  3311. pending_sig = signo;
  3312. if (signo == SIGINT && !trap[SIGINT]) {
  3313. if (!suppress_int) {
  3314. pending_sig = 0;
  3315. raise_interrupt(); /* does not return */
  3316. }
  3317. pending_int = 1;
  3318. }
  3319. }
  3320. /*
  3321. * Set the signal handler for the specified signal. The routine figures
  3322. * out what it should be set to.
  3323. */
  3324. static void
  3325. setsignal(int signo)
  3326. {
  3327. char *t;
  3328. char cur_act, new_act;
  3329. struct sigaction act;
  3330. t = trap[signo];
  3331. new_act = S_DFL;
  3332. if (t != NULL) { /* trap for this sig is set */
  3333. new_act = S_CATCH;
  3334. if (t[0] == '\0') /* trap is "": ignore this sig */
  3335. new_act = S_IGN;
  3336. }
  3337. if (rootshell && new_act == S_DFL) {
  3338. switch (signo) {
  3339. case SIGINT:
  3340. if (iflag || minusc || sflag == 0)
  3341. new_act = S_CATCH;
  3342. break;
  3343. case SIGQUIT:
  3344. #if DEBUG
  3345. if (debug)
  3346. break;
  3347. #endif
  3348. /* man bash:
  3349. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3350. * commands run by bash have signal handlers
  3351. * set to the values inherited by the shell
  3352. * from its parent". */
  3353. new_act = S_IGN;
  3354. break;
  3355. case SIGTERM:
  3356. if (iflag)
  3357. new_act = S_IGN;
  3358. break;
  3359. #if JOBS
  3360. case SIGTSTP:
  3361. case SIGTTOU:
  3362. if (mflag)
  3363. new_act = S_IGN;
  3364. break;
  3365. #endif
  3366. }
  3367. }
  3368. /* if !rootshell, we reset SIGQUIT to DFL,
  3369. * whereas we have to restore it to what shell got on entry.
  3370. * This is handled by the fact that if signal was IGNored on entry,
  3371. * then cur_act is S_HARD_IGN and we never change its sigaction
  3372. * (see code below).
  3373. */
  3374. if (signo == SIGCHLD)
  3375. new_act = S_CATCH;
  3376. t = &sigmode[signo - 1];
  3377. cur_act = *t;
  3378. if (cur_act == 0) {
  3379. /* current setting is not yet known */
  3380. if (sigaction(signo, NULL, &act)) {
  3381. /* pretend it worked; maybe we should give a warning,
  3382. * but other shells don't. We don't alter sigmode,
  3383. * so we retry every time.
  3384. * btw, in Linux it never fails. --vda */
  3385. return;
  3386. }
  3387. if (act.sa_handler == SIG_IGN) {
  3388. cur_act = S_HARD_IGN;
  3389. if (mflag
  3390. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3391. ) {
  3392. cur_act = S_IGN; /* don't hard ignore these */
  3393. }
  3394. }
  3395. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3396. /* installing SIG_DFL over SIG_DFL is a no-op */
  3397. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3398. *t = S_DFL;
  3399. return;
  3400. }
  3401. }
  3402. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3403. return;
  3404. *t = new_act;
  3405. act.sa_handler = SIG_DFL;
  3406. switch (new_act) {
  3407. case S_CATCH:
  3408. act.sa_handler = signal_handler;
  3409. break;
  3410. case S_IGN:
  3411. act.sa_handler = SIG_IGN;
  3412. break;
  3413. }
  3414. /* flags and mask matter only if !DFL and !IGN, but we do it
  3415. * for all cases for more deterministic behavior:
  3416. */
  3417. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3418. sigfillset(&act.sa_mask);
  3419. sigaction_set(signo, &act);
  3420. }
  3421. /* mode flags for set_curjob */
  3422. #define CUR_DELETE 2
  3423. #define CUR_RUNNING 1
  3424. #define CUR_STOPPED 0
  3425. #if JOBS
  3426. /* pgrp of shell on invocation */
  3427. static int initialpgrp; //references:2
  3428. static int ttyfd = -1; //5
  3429. #endif
  3430. /* array of jobs */
  3431. static struct job *jobtab; //5
  3432. /* size of array */
  3433. static unsigned njobs; //4
  3434. /* current job */
  3435. static struct job *curjob; //lots
  3436. #if 0
  3437. /* Bash has a feature: it restores termios after a successful wait for
  3438. * a foreground job which had at least one stopped or sigkilled member.
  3439. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3440. * properly restoring tty state. Should we do this too?
  3441. * A reproducer: ^Z an interactive python:
  3442. *
  3443. * # python
  3444. * Python 2.7.12 (...)
  3445. * >>> ^Z
  3446. * { python leaves tty in -icanon -echo state. We do survive that... }
  3447. * [1]+ Stopped python
  3448. * { ...however, next program (python #2) does not survive it well: }
  3449. * # python
  3450. * Python 2.7.12 (...)
  3451. * >>> Traceback (most recent call last):
  3452. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3453. * File "<stdin>", line 1, in <module>
  3454. * NameError: name 'qwerty' is not defined
  3455. *
  3456. * The implementation below is modeled on bash code and seems to work.
  3457. * However, I'm not sure we should do this. For one: what if I'd fg
  3458. * the stopped python instead? It'll be confused by "restored" tty state.
  3459. */
  3460. static struct termios shell_tty_info;
  3461. static void
  3462. get_tty_state(void)
  3463. {
  3464. if (rootshell && ttyfd >= 0)
  3465. tcgetattr(ttyfd, &shell_tty_info);
  3466. }
  3467. static void
  3468. set_tty_state(void)
  3469. {
  3470. /* if (rootshell) - caller ensures this */
  3471. if (ttyfd >= 0)
  3472. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3473. }
  3474. static int
  3475. job_signal_status(struct job *jp)
  3476. {
  3477. int status;
  3478. unsigned i;
  3479. struct procstat *ps = jp->ps;
  3480. for (i = 0; i < jp->nprocs; i++) {
  3481. status = ps[i].ps_status;
  3482. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3483. return status;
  3484. }
  3485. return 0;
  3486. }
  3487. static void
  3488. restore_tty_if_stopped_or_signaled(struct job *jp)
  3489. {
  3490. //TODO: check what happens if we come from waitforjob() in expbackq()
  3491. if (rootshell) {
  3492. int s = job_signal_status(jp);
  3493. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3494. set_tty_state();
  3495. }
  3496. }
  3497. #else
  3498. # define get_tty_state() ((void)0)
  3499. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3500. #endif
  3501. static void
  3502. set_curjob(struct job *jp, unsigned mode)
  3503. {
  3504. struct job *jp1;
  3505. struct job **jpp, **curp;
  3506. /* first remove from list */
  3507. jpp = curp = &curjob;
  3508. while (1) {
  3509. jp1 = *jpp;
  3510. if (jp1 == jp)
  3511. break;
  3512. jpp = &jp1->prev_job;
  3513. }
  3514. *jpp = jp1->prev_job;
  3515. /* Then re-insert in correct position */
  3516. jpp = curp;
  3517. switch (mode) {
  3518. default:
  3519. #if DEBUG
  3520. abort();
  3521. #endif
  3522. case CUR_DELETE:
  3523. /* job being deleted */
  3524. break;
  3525. case CUR_RUNNING:
  3526. /* newly created job or backgrounded job,
  3527. * put after all stopped jobs.
  3528. */
  3529. while (1) {
  3530. jp1 = *jpp;
  3531. #if JOBS
  3532. if (!jp1 || jp1->state != JOBSTOPPED)
  3533. #endif
  3534. break;
  3535. jpp = &jp1->prev_job;
  3536. }
  3537. /* FALLTHROUGH */
  3538. #if JOBS
  3539. case CUR_STOPPED:
  3540. #endif
  3541. /* newly stopped job - becomes curjob */
  3542. jp->prev_job = *jpp;
  3543. *jpp = jp;
  3544. break;
  3545. }
  3546. }
  3547. #if JOBS || DEBUG
  3548. static int
  3549. jobno(const struct job *jp)
  3550. {
  3551. return jp - jobtab + 1;
  3552. }
  3553. #endif
  3554. /*
  3555. * Convert a job name to a job structure.
  3556. */
  3557. #if !JOBS
  3558. #define getjob(name, getctl) getjob(name)
  3559. #endif
  3560. static struct job *
  3561. getjob(const char *name, int getctl)
  3562. {
  3563. struct job *jp;
  3564. struct job *found;
  3565. const char *err_msg = "%s: no such job";
  3566. unsigned num;
  3567. int c;
  3568. const char *p;
  3569. char *(*match)(const char *, const char *);
  3570. jp = curjob;
  3571. p = name;
  3572. if (!p)
  3573. goto currentjob;
  3574. if (*p != '%')
  3575. goto err;
  3576. c = *++p;
  3577. if (!c)
  3578. goto currentjob;
  3579. if (!p[1]) {
  3580. if (c == '+' || c == '%') {
  3581. currentjob:
  3582. err_msg = "No current job";
  3583. goto check;
  3584. }
  3585. if (c == '-') {
  3586. if (jp)
  3587. jp = jp->prev_job;
  3588. err_msg = "No previous job";
  3589. check:
  3590. if (!jp)
  3591. goto err;
  3592. goto gotit;
  3593. }
  3594. }
  3595. if (is_number(p)) {
  3596. num = atoi(p);
  3597. if (num > 0 && num <= njobs) {
  3598. jp = jobtab + num - 1;
  3599. if (jp->used)
  3600. goto gotit;
  3601. goto err;
  3602. }
  3603. }
  3604. match = prefix;
  3605. if (*p == '?') {
  3606. match = strstr;
  3607. p++;
  3608. }
  3609. found = NULL;
  3610. while (jp) {
  3611. if (match(jp->ps[0].ps_cmd, p)) {
  3612. if (found)
  3613. goto err;
  3614. found = jp;
  3615. err_msg = "%s: ambiguous";
  3616. }
  3617. jp = jp->prev_job;
  3618. }
  3619. if (!found)
  3620. goto err;
  3621. jp = found;
  3622. gotit:
  3623. #if JOBS
  3624. err_msg = "job %s not created under job control";
  3625. if (getctl && jp->jobctl == 0)
  3626. goto err;
  3627. #endif
  3628. return jp;
  3629. err:
  3630. ash_msg_and_raise_error(err_msg, name);
  3631. }
  3632. /*
  3633. * Mark a job structure as unused.
  3634. */
  3635. static void
  3636. freejob(struct job *jp)
  3637. {
  3638. struct procstat *ps;
  3639. int i;
  3640. INT_OFF;
  3641. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3642. if (ps->ps_cmd != nullstr)
  3643. free(ps->ps_cmd);
  3644. }
  3645. if (jp->ps != &jp->ps0)
  3646. free(jp->ps);
  3647. jp->used = 0;
  3648. set_curjob(jp, CUR_DELETE);
  3649. INT_ON;
  3650. }
  3651. #if JOBS
  3652. static void
  3653. xtcsetpgrp(int fd, pid_t pgrp)
  3654. {
  3655. if (tcsetpgrp(fd, pgrp))
  3656. ash_msg_and_raise_perror("can't set tty process group");
  3657. }
  3658. /*
  3659. * Turn job control on and off.
  3660. *
  3661. * Note: This code assumes that the third arg to ioctl is a character
  3662. * pointer, which is true on Berkeley systems but not System V. Since
  3663. * System V doesn't have job control yet, this isn't a problem now.
  3664. *
  3665. * Called with interrupts off.
  3666. */
  3667. static void
  3668. setjobctl(int on)
  3669. {
  3670. int fd;
  3671. int pgrp;
  3672. if (on == doing_jobctl || rootshell == 0)
  3673. return;
  3674. if (on) {
  3675. int ofd;
  3676. ofd = fd = open(_PATH_TTY, O_RDWR);
  3677. if (fd < 0) {
  3678. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3679. * That sometimes helps to acquire controlling tty.
  3680. * Obviously, a workaround for bugs when someone
  3681. * failed to provide a controlling tty to bash! :) */
  3682. fd = 2;
  3683. while (!isatty(fd))
  3684. if (--fd < 0)
  3685. goto out;
  3686. }
  3687. /* fd is a tty at this point */
  3688. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3689. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3690. close(ofd);
  3691. if (fd < 0)
  3692. goto out; /* F_DUPFD failed */
  3693. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3694. close_on_exec_on(fd);
  3695. while (1) { /* while we are in the background */
  3696. pgrp = tcgetpgrp(fd);
  3697. if (pgrp < 0) {
  3698. out:
  3699. ash_msg("can't access tty; job control turned off");
  3700. mflag = on = 0;
  3701. goto close;
  3702. }
  3703. if (pgrp == getpgrp())
  3704. break;
  3705. killpg(0, SIGTTIN);
  3706. }
  3707. initialpgrp = pgrp;
  3708. setsignal(SIGTSTP);
  3709. setsignal(SIGTTOU);
  3710. setsignal(SIGTTIN);
  3711. pgrp = rootpid;
  3712. setpgid(0, pgrp);
  3713. xtcsetpgrp(fd, pgrp);
  3714. } else {
  3715. /* turning job control off */
  3716. fd = ttyfd;
  3717. pgrp = initialpgrp;
  3718. /* was xtcsetpgrp, but this can make exiting ash
  3719. * loop forever if pty is already deleted */
  3720. tcsetpgrp(fd, pgrp);
  3721. setpgid(0, pgrp);
  3722. setsignal(SIGTSTP);
  3723. setsignal(SIGTTOU);
  3724. setsignal(SIGTTIN);
  3725. close:
  3726. if (fd >= 0)
  3727. close(fd);
  3728. fd = -1;
  3729. }
  3730. ttyfd = fd;
  3731. doing_jobctl = on;
  3732. }
  3733. static int FAST_FUNC
  3734. killcmd(int argc, char **argv)
  3735. {
  3736. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3737. int i = 1;
  3738. do {
  3739. if (argv[i][0] == '%') {
  3740. /*
  3741. * "kill %N" - job kill
  3742. * Converting to pgrp / pid kill
  3743. */
  3744. struct job *jp;
  3745. char *dst;
  3746. int j, n;
  3747. jp = getjob(argv[i], 0);
  3748. /*
  3749. * In jobs started under job control, we signal
  3750. * entire process group by kill -PGRP_ID.
  3751. * This happens, f.e., in interactive shell.
  3752. *
  3753. * Otherwise, we signal each child via
  3754. * kill PID1 PID2 PID3.
  3755. * Testcases:
  3756. * sh -c 'sleep 1|sleep 1 & kill %1'
  3757. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3758. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3759. */
  3760. n = jp->nprocs; /* can't be 0 (I hope) */
  3761. if (jp->jobctl)
  3762. n = 1;
  3763. dst = alloca(n * sizeof(int)*4);
  3764. argv[i] = dst;
  3765. for (j = 0; j < n; j++) {
  3766. struct procstat *ps = &jp->ps[j];
  3767. /* Skip non-running and not-stopped members
  3768. * (i.e. dead members) of the job
  3769. */
  3770. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3771. continue;
  3772. /*
  3773. * kill_main has matching code to expect
  3774. * leading space. Needed to not confuse
  3775. * negative pids with "kill -SIGNAL_NO" syntax
  3776. */
  3777. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3778. }
  3779. *dst = '\0';
  3780. }
  3781. } while (argv[++i]);
  3782. }
  3783. return kill_main(argc, argv);
  3784. }
  3785. static void
  3786. showpipe(struct job *jp /*, FILE *out*/)
  3787. {
  3788. struct procstat *ps;
  3789. struct procstat *psend;
  3790. psend = jp->ps + jp->nprocs;
  3791. for (ps = jp->ps + 1; ps < psend; ps++)
  3792. printf(" | %s", ps->ps_cmd);
  3793. newline_and_flush(stdout);
  3794. flush_stdout_stderr();
  3795. }
  3796. static int
  3797. restartjob(struct job *jp, int mode)
  3798. {
  3799. struct procstat *ps;
  3800. int i;
  3801. int status;
  3802. pid_t pgid;
  3803. INT_OFF;
  3804. if (jp->state == JOBDONE)
  3805. goto out;
  3806. jp->state = JOBRUNNING;
  3807. pgid = jp->ps[0].ps_pid;
  3808. if (mode == FORK_FG) {
  3809. get_tty_state();
  3810. xtcsetpgrp(ttyfd, pgid);
  3811. }
  3812. killpg(pgid, SIGCONT);
  3813. ps = jp->ps;
  3814. i = jp->nprocs;
  3815. do {
  3816. if (WIFSTOPPED(ps->ps_status)) {
  3817. ps->ps_status = -1;
  3818. }
  3819. ps++;
  3820. } while (--i);
  3821. out:
  3822. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3823. INT_ON;
  3824. return status;
  3825. }
  3826. static int FAST_FUNC
  3827. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3828. {
  3829. struct job *jp;
  3830. int mode;
  3831. int retval;
  3832. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3833. nextopt(nullstr);
  3834. argv = argptr;
  3835. do {
  3836. jp = getjob(*argv, 1);
  3837. if (mode == FORK_BG) {
  3838. set_curjob(jp, CUR_RUNNING);
  3839. printf("[%d] ", jobno(jp));
  3840. }
  3841. out1str(jp->ps[0].ps_cmd);
  3842. showpipe(jp /*, stdout*/);
  3843. retval = restartjob(jp, mode);
  3844. } while (*argv && *++argv);
  3845. return retval;
  3846. }
  3847. #endif
  3848. static int
  3849. sprint_status48(char *os, int status, int sigonly)
  3850. {
  3851. char *s = os;
  3852. int st;
  3853. if (!WIFEXITED(status)) {
  3854. #if JOBS
  3855. if (WIFSTOPPED(status))
  3856. st = WSTOPSIG(status);
  3857. else
  3858. #endif
  3859. st = WTERMSIG(status);
  3860. if (sigonly) {
  3861. if (st == SIGINT || st == SIGPIPE)
  3862. goto out;
  3863. #if JOBS
  3864. if (WIFSTOPPED(status))
  3865. goto out;
  3866. #endif
  3867. }
  3868. st &= 0x7f;
  3869. s = stpncpy(s, strsignal(st), 32);
  3870. if (WCOREDUMP(status)) {
  3871. s = stpcpy(s, " (core dumped)");
  3872. }
  3873. } else if (!sigonly) {
  3874. st = WEXITSTATUS(status);
  3875. s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3876. }
  3877. out:
  3878. return s - os;
  3879. }
  3880. #define DOWAIT_NONBLOCK 0
  3881. #define DOWAIT_BLOCK 1
  3882. #define DOWAIT_BLOCK_OR_SIG 2
  3883. #if BASH_WAIT_N
  3884. # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
  3885. #endif
  3886. static int
  3887. waitproc(int block, int *status)
  3888. {
  3889. sigset_t oldmask;
  3890. int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG;
  3891. int err;
  3892. #if JOBS
  3893. if (doing_jobctl)
  3894. flags |= WUNTRACED;
  3895. #endif
  3896. do {
  3897. got_sigchld = 0;
  3898. do
  3899. err = waitpid(-1, status, flags);
  3900. while (err < 0 && errno == EINTR);
  3901. if (err || (err = -!block))
  3902. break;
  3903. sigfillset(&oldmask);
  3904. sigprocmask2(SIG_SETMASK, &oldmask); /* mask is updated */
  3905. while (!got_sigchld && !pending_sig)
  3906. sigsuspend(&oldmask);
  3907. sigprocmask(SIG_SETMASK, &oldmask, NULL);
  3908. //simpler, but unsafe: a signal can set pending_sig after check, but before pause():
  3909. //while (!got_sigchld && !pending_sig)
  3910. // pause();
  3911. } while (got_sigchld);
  3912. return err;
  3913. }
  3914. static int
  3915. waitone(int block, struct job *job)
  3916. {
  3917. int pid;
  3918. int status;
  3919. struct job *jp;
  3920. struct job *thisjob = NULL;
  3921. #if BASH_WAIT_N
  3922. bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
  3923. block = (block & ~DOWAIT_JOBSTATUS);
  3924. #endif
  3925. TRACE(("dowait(0x%x) called\n", block));
  3926. /* It's wrong to call waitpid() outside of INT_OFF region:
  3927. * signal can arrive just after syscall return and handler can
  3928. * longjmp away, losing stop/exit notification processing.
  3929. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3930. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3931. *
  3932. * However, for "wait" builtin it is wrong to simply call waitpid()
  3933. * in INT_OFF region: "wait" needs to wait for any running job
  3934. * to change state, but should exit on any trap too.
  3935. * In INT_OFF region, a signal just before syscall entry can set
  3936. * pending_sig variables, but we can't check them, and we would
  3937. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3938. *
  3939. * Because of this, we run inside INT_OFF, but use a special routine
  3940. * which combines waitpid() and sigsuspend().
  3941. * This is the reason why we need to have a handler for SIGCHLD:
  3942. * SIG_DFL handler does not wake sigsuspend().
  3943. */
  3944. INT_OFF;
  3945. pid = waitproc(block, &status);
  3946. TRACE(("wait returns pid %d, status=%d\n", pid, status));
  3947. if (pid <= 0)
  3948. goto out;
  3949. for (jp = curjob; jp; jp = jp->prev_job) {
  3950. int jobstate;
  3951. struct procstat *ps;
  3952. struct procstat *psend;
  3953. if (jp->state == JOBDONE)
  3954. continue;
  3955. jobstate = JOBDONE;
  3956. ps = jp->ps;
  3957. psend = ps + jp->nprocs;
  3958. do {
  3959. if (ps->ps_pid == pid) {
  3960. TRACE(("Job %d: changing status of proc %d "
  3961. "from 0x%x to 0x%x\n",
  3962. jobno(jp), pid, ps->ps_status, status));
  3963. ps->ps_status = status;
  3964. thisjob = jp;
  3965. }
  3966. if (ps->ps_status == -1)
  3967. jobstate = JOBRUNNING;
  3968. #if JOBS
  3969. if (jobstate == JOBRUNNING)
  3970. continue;
  3971. if (WIFSTOPPED(ps->ps_status)) {
  3972. jp->stopstatus = ps->ps_status;
  3973. jobstate = JOBSTOPPED;
  3974. }
  3975. #endif
  3976. } while (++ps < psend);
  3977. if (!thisjob)
  3978. continue;
  3979. /* Found the job where one of its processes changed its state.
  3980. * Is there at least one live and running process in this job? */
  3981. if (jobstate != JOBRUNNING) {
  3982. /* No. All live processes in the job are stopped
  3983. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3984. */
  3985. thisjob->changed = 1;
  3986. if (thisjob->state != jobstate) {
  3987. TRACE(("Job %d: changing state from %d to %d\n",
  3988. jobno(thisjob), thisjob->state, jobstate));
  3989. thisjob->state = jobstate;
  3990. #if JOBS
  3991. if (jobstate == JOBSTOPPED)
  3992. set_curjob(thisjob, CUR_STOPPED);
  3993. #endif
  3994. }
  3995. }
  3996. goto out;
  3997. }
  3998. /* The process wasn't found in job list */
  3999. out:
  4000. INT_ON;
  4001. #if BASH_WAIT_N
  4002. if (want_jobexitstatus) {
  4003. pid = -1;
  4004. if (thisjob && thisjob->state == JOBDONE)
  4005. pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
  4006. }
  4007. #endif
  4008. if (thisjob && thisjob == job) {
  4009. char s[48 + 1];
  4010. int len;
  4011. len = sprint_status48(s, status, 1);
  4012. if (len) {
  4013. s[len] = '\n';
  4014. s[len + 1] = '\0';
  4015. out2str(s);
  4016. }
  4017. }
  4018. return pid;
  4019. }
  4020. static int
  4021. dowait(int block, struct job *jp)
  4022. {
  4023. smallint gotchld = *(volatile smallint *)&got_sigchld;
  4024. int rpid;
  4025. int pid;
  4026. if (jp && jp->state != JOBRUNNING)
  4027. block = DOWAIT_NONBLOCK;
  4028. if (block == DOWAIT_NONBLOCK && !gotchld)
  4029. return 1;
  4030. rpid = 1;
  4031. do {
  4032. pid = waitone(block, jp);
  4033. rpid &= !!pid;
  4034. if (!pid || (jp && jp->state != JOBRUNNING))
  4035. block = DOWAIT_NONBLOCK;
  4036. } while (pid >= 0);
  4037. return rpid;
  4038. }
  4039. #if JOBS
  4040. static void
  4041. showjob(struct job *jp, int mode)
  4042. {
  4043. struct procstat *ps;
  4044. struct procstat *psend;
  4045. int col;
  4046. int indent_col;
  4047. char s[16 + 16 + 48];
  4048. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  4049. ps = jp->ps;
  4050. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  4051. /* just output process (group) id of pipeline */
  4052. fprintf(out, "%d\n", ps->ps_pid);
  4053. return;
  4054. }
  4055. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  4056. indent_col = col;
  4057. if (jp == curjob)
  4058. s[col - 3] = '+';
  4059. else if (curjob && jp == curjob->prev_job)
  4060. s[col - 3] = '-';
  4061. if (mode & SHOW_PIDS)
  4062. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  4063. psend = ps + jp->nprocs;
  4064. if (jp->state == JOBRUNNING) {
  4065. strcpy(s + col, "Running");
  4066. col += sizeof("Running") - 1;
  4067. } else {
  4068. int status = psend[-1].ps_status;
  4069. if (jp->state == JOBSTOPPED)
  4070. status = jp->stopstatus;
  4071. col += sprint_status48(s + col, status, 0);
  4072. }
  4073. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  4074. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  4075. * or prints several "PID | <cmdN>" lines,
  4076. * depending on SHOW_PIDS bit.
  4077. * We do not print status of individual processes
  4078. * between PID and <cmdN>. bash does it, but not very well:
  4079. * first line shows overall job status, not process status,
  4080. * making it impossible to know 1st process status.
  4081. */
  4082. goto start;
  4083. do {
  4084. /* for each process */
  4085. s[0] = '\0';
  4086. col = 33;
  4087. if (mode & SHOW_PIDS)
  4088. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  4089. start:
  4090. fprintf(out, "%s%*c%s%s",
  4091. s,
  4092. 33 - col >= 0 ? 33 - col : 0, ' ',
  4093. ps == jp->ps ? "" : "| ",
  4094. ps->ps_cmd
  4095. );
  4096. } while (++ps != psend);
  4097. newline_and_flush(out);
  4098. jp->changed = 0;
  4099. if (jp->state == JOBDONE) {
  4100. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4101. freejob(jp);
  4102. }
  4103. }
  4104. /*
  4105. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4106. * statuses have changed since the last call to showjobs.
  4107. */
  4108. static void
  4109. showjobs(int mode)
  4110. {
  4111. struct job *jp;
  4112. TRACE(("showjobs(0x%x) called\n", mode));
  4113. /* Handle all finished jobs */
  4114. dowait(DOWAIT_NONBLOCK, NULL);
  4115. for (jp = curjob; jp; jp = jp->prev_job) {
  4116. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4117. showjob(jp, mode);
  4118. }
  4119. }
  4120. }
  4121. static int FAST_FUNC
  4122. jobscmd(int argc UNUSED_PARAM, char **argv)
  4123. {
  4124. int mode, m;
  4125. mode = 0;
  4126. while ((m = nextopt("lp")) != '\0') {
  4127. if (m == 'l')
  4128. mode |= SHOW_PIDS;
  4129. else
  4130. mode |= SHOW_ONLY_PGID;
  4131. }
  4132. argv = argptr;
  4133. if (*argv) {
  4134. do
  4135. showjob(getjob(*argv, 0), mode);
  4136. while (*++argv);
  4137. } else {
  4138. showjobs(mode);
  4139. }
  4140. return 0;
  4141. }
  4142. #endif /* JOBS */
  4143. /* Called only on finished or stopped jobs (no members are running) */
  4144. static int
  4145. getstatus(struct job *job)
  4146. {
  4147. int status;
  4148. int retval;
  4149. struct procstat *ps;
  4150. /* Fetch last member's status */
  4151. ps = job->ps + job->nprocs - 1;
  4152. status = ps->ps_status;
  4153. if (pipefail) {
  4154. /* "set -o pipefail" mode: use last _nonzero_ status */
  4155. while (status == 0 && --ps >= job->ps)
  4156. status = ps->ps_status;
  4157. }
  4158. retval = WEXITSTATUS(status);
  4159. if (!WIFEXITED(status)) {
  4160. #if JOBS
  4161. retval = WSTOPSIG(status);
  4162. if (!WIFSTOPPED(status))
  4163. #endif
  4164. {
  4165. /* XXX: limits number of signals */
  4166. retval = WTERMSIG(status);
  4167. #if JOBS
  4168. if (retval == SIGINT)
  4169. job->sigint = 1;
  4170. #endif
  4171. }
  4172. retval |= 128;
  4173. }
  4174. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4175. jobno(job), job->nprocs, status, retval));
  4176. return retval;
  4177. }
  4178. static int FAST_FUNC
  4179. waitcmd(int argc UNUSED_PARAM, char **argv)
  4180. {
  4181. struct job *job;
  4182. int retval;
  4183. struct job *jp;
  4184. #if BASH_WAIT_N
  4185. int status;
  4186. char one = nextopt("n");
  4187. #else
  4188. nextopt(nullstr);
  4189. #endif
  4190. retval = 0;
  4191. argv = argptr;
  4192. if (!argv[0]) {
  4193. /* wait for all jobs / one job if -n */
  4194. for (;;) {
  4195. jp = curjob;
  4196. #if BASH_WAIT_N
  4197. if (one && !jp)
  4198. /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
  4199. retval = 127;
  4200. #endif
  4201. while (1) {
  4202. if (!jp) /* no running procs */
  4203. goto ret;
  4204. if (jp->state == JOBRUNNING)
  4205. break;
  4206. jp->waited = 1;
  4207. jp = jp->prev_job;
  4208. }
  4209. /* man bash:
  4210. * "When bash is waiting for an asynchronous command via
  4211. * the wait builtin, the reception of a signal for which a trap
  4212. * has been set will cause the wait builtin to return immediately
  4213. * with an exit status greater than 128, immediately after which
  4214. * the trap is executed."
  4215. */
  4216. #if BASH_WAIT_N
  4217. status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
  4218. #else
  4219. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4220. #endif
  4221. /* if child sends us a signal *and immediately exits*,
  4222. * dowait() returns pid > 0. Check this case,
  4223. * not "if (dowait() < 0)"!
  4224. */
  4225. if (pending_sig)
  4226. goto sigout;
  4227. #if BASH_WAIT_N
  4228. if (one) {
  4229. /* wait -n waits for one _job_, not one _process_.
  4230. * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
  4231. * should wait for 2 seconds. Not 1 or 3.
  4232. */
  4233. if (status != -1 && !WIFSTOPPED(status)) {
  4234. retval = WEXITSTATUS(status);
  4235. if (WIFSIGNALED(status))
  4236. retval = 128 | WTERMSIG(status);
  4237. goto ret;
  4238. }
  4239. }
  4240. #endif
  4241. }
  4242. }
  4243. retval = 127;
  4244. do {
  4245. if (**argv != '%') {
  4246. pid_t pid = number(*argv);
  4247. job = curjob;
  4248. while (1) {
  4249. if (!job)
  4250. goto repeat;
  4251. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4252. break;
  4253. job = job->prev_job;
  4254. }
  4255. } else {
  4256. job = getjob(*argv, 0);
  4257. }
  4258. /* loop until process terminated or stopped */
  4259. dowait(DOWAIT_BLOCK_OR_SIG, job);
  4260. if (pending_sig)
  4261. goto sigout;
  4262. job->waited = 1;
  4263. retval = getstatus(job);
  4264. repeat: ;
  4265. } while (*++argv);
  4266. ret:
  4267. return retval;
  4268. sigout:
  4269. retval = 128 | pending_sig;
  4270. return retval;
  4271. }
  4272. static struct job *
  4273. growjobtab(void)
  4274. {
  4275. size_t len;
  4276. ptrdiff_t offset;
  4277. struct job *jp, *jq;
  4278. len = njobs * sizeof(*jp);
  4279. jq = jobtab;
  4280. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4281. offset = (char *)jp - (char *)jq;
  4282. if (offset) {
  4283. /* Relocate pointers */
  4284. size_t l = len;
  4285. jq = (struct job *)((char *)jq + l);
  4286. while (l) {
  4287. l -= sizeof(*jp);
  4288. jq--;
  4289. #define joff(p) ((struct job *)((char *)(p) + l))
  4290. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4291. if (joff(jp)->ps == &jq->ps0)
  4292. jmove(joff(jp)->ps);
  4293. if (joff(jp)->prev_job)
  4294. jmove(joff(jp)->prev_job);
  4295. }
  4296. if (curjob)
  4297. jmove(curjob);
  4298. #undef joff
  4299. #undef jmove
  4300. }
  4301. njobs += 4;
  4302. jobtab = jp;
  4303. jp = (struct job *)((char *)jp + len);
  4304. jq = jp + 3;
  4305. do {
  4306. jq->used = 0;
  4307. } while (--jq >= jp);
  4308. return jp;
  4309. }
  4310. /*
  4311. * Return a new job structure.
  4312. * Called with interrupts off.
  4313. */
  4314. static struct job *
  4315. makejob(/*union node *node,*/ int nprocs)
  4316. {
  4317. int i;
  4318. struct job *jp;
  4319. for (i = njobs, jp = jobtab; ; jp++) {
  4320. if (--i < 0) {
  4321. jp = growjobtab();
  4322. break;
  4323. }
  4324. if (jp->used == 0)
  4325. break;
  4326. if (jp->state != JOBDONE || !jp->waited)
  4327. continue;
  4328. #if JOBS
  4329. if (doing_jobctl)
  4330. continue;
  4331. #endif
  4332. freejob(jp);
  4333. break;
  4334. }
  4335. memset(jp, 0, sizeof(*jp));
  4336. #if JOBS
  4337. /* jp->jobctl is a bitfield.
  4338. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4339. if (doing_jobctl)
  4340. jp->jobctl = 1;
  4341. #endif
  4342. jp->prev_job = curjob;
  4343. curjob = jp;
  4344. jp->used = 1;
  4345. jp->ps = &jp->ps0;
  4346. if (nprocs > 1) {
  4347. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4348. }
  4349. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4350. jobno(jp)));
  4351. return jp;
  4352. }
  4353. #if JOBS
  4354. /*
  4355. * Return a string identifying a command (to be printed by the
  4356. * jobs command).
  4357. */
  4358. static char *cmdnextc;
  4359. static void
  4360. cmdputs(const char *s)
  4361. {
  4362. static const char vstype[VSTYPE + 1][3] ALIGN1 = {
  4363. "", "}", "-", "+", "?", "=",
  4364. "%", "%%", "#", "##"
  4365. IF_BASH_SUBSTR(, ":")
  4366. IF_BASH_PATTERN_SUBST(, "/", "//")
  4367. };
  4368. const char *p, *str;
  4369. char cc[2];
  4370. char *nextc;
  4371. unsigned char c;
  4372. unsigned char subtype = 0;
  4373. int quoted = 0;
  4374. cc[1] = '\0';
  4375. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4376. p = s;
  4377. while ((c = *p++) != '\0') {
  4378. str = NULL;
  4379. switch (c) {
  4380. case CTLESC:
  4381. c = *p++;
  4382. break;
  4383. case CTLVAR:
  4384. subtype = *p++;
  4385. if ((subtype & VSTYPE) == VSLENGTH)
  4386. str = "${#";
  4387. else
  4388. str = "${";
  4389. goto dostr;
  4390. case CTLENDVAR:
  4391. str = "\"}";
  4392. str += !(quoted & 1);
  4393. quoted >>= 1;
  4394. subtype = 0;
  4395. goto dostr;
  4396. #if BASH_PROCESS_SUBST
  4397. case CTLBACKQ:
  4398. c = '$';
  4399. str = "(...)";
  4400. break;
  4401. case CTLTOPROC:
  4402. c = '>';
  4403. str = "(...)";
  4404. break;
  4405. case CTLFROMPROC:
  4406. c = '<';
  4407. str = "(...)";
  4408. break;
  4409. #else
  4410. case CTLBACKQ:
  4411. str = "$(...)";
  4412. goto dostr;
  4413. #endif
  4414. #if ENABLE_FEATURE_SH_MATH
  4415. case CTLARI:
  4416. str = "$((";
  4417. goto dostr;
  4418. case CTLENDARI:
  4419. str = "))";
  4420. goto dostr;
  4421. #endif
  4422. case CTLQUOTEMARK:
  4423. quoted ^= 1;
  4424. c = '"';
  4425. break;
  4426. case '=':
  4427. if (subtype == 0)
  4428. break;
  4429. if ((subtype & VSTYPE) != VSNORMAL)
  4430. quoted <<= 1;
  4431. str = vstype[subtype & VSTYPE];
  4432. if (subtype & VSNUL)
  4433. c = ':';
  4434. else
  4435. goto checkstr;
  4436. break;
  4437. case '\'':
  4438. case '\\':
  4439. case '"':
  4440. case '$':
  4441. /* These can only happen inside quotes */
  4442. cc[0] = c;
  4443. str = cc;
  4444. //FIXME:
  4445. // $ true $$ &
  4446. // $ <cr>
  4447. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4448. c = '\\';
  4449. break;
  4450. default:
  4451. break;
  4452. }
  4453. USTPUTC(c, nextc);
  4454. checkstr:
  4455. if (!str)
  4456. continue;
  4457. dostr:
  4458. while ((c = *str++) != '\0') {
  4459. USTPUTC(c, nextc);
  4460. }
  4461. } /* while *p++ not NUL */
  4462. if (quoted & 1) {
  4463. USTPUTC('"', nextc);
  4464. }
  4465. *nextc = 0;
  4466. cmdnextc = nextc;
  4467. }
  4468. /* cmdtxt() and cmdlist() call each other */
  4469. static void cmdtxt(union node *n);
  4470. static void
  4471. cmdlist(union node *np, int sep)
  4472. {
  4473. for (; np; np = np->narg.next) {
  4474. if (!sep)
  4475. cmdputs(" ");
  4476. cmdtxt(np);
  4477. if (sep && np->narg.next)
  4478. cmdputs(" ");
  4479. }
  4480. }
  4481. static void
  4482. cmdtxt(union node *n)
  4483. {
  4484. union node *np;
  4485. struct nodelist *lp;
  4486. const char *p;
  4487. if (!n)
  4488. return;
  4489. switch (n->type) {
  4490. default:
  4491. #if DEBUG
  4492. abort();
  4493. #endif
  4494. case NPIPE:
  4495. lp = n->npipe.cmdlist;
  4496. for (;;) {
  4497. cmdtxt(lp->n);
  4498. lp = lp->next;
  4499. if (!lp)
  4500. break;
  4501. cmdputs(" | ");
  4502. }
  4503. break;
  4504. case NSEMI:
  4505. p = "; ";
  4506. goto binop;
  4507. case NAND:
  4508. p = " && ";
  4509. goto binop;
  4510. case NOR:
  4511. p = " || ";
  4512. binop:
  4513. cmdtxt(n->nbinary.ch1);
  4514. cmdputs(p);
  4515. n = n->nbinary.ch2;
  4516. goto donode;
  4517. case NREDIR:
  4518. case NBACKGND:
  4519. n = n->nredir.n;
  4520. goto donode;
  4521. case NNOT:
  4522. cmdputs("!");
  4523. n = n->nnot.com;
  4524. donode:
  4525. cmdtxt(n);
  4526. break;
  4527. case NIF:
  4528. cmdputs("if ");
  4529. cmdtxt(n->nif.test);
  4530. cmdputs("; then ");
  4531. if (n->nif.elsepart) {
  4532. cmdtxt(n->nif.ifpart);
  4533. cmdputs("; else ");
  4534. n = n->nif.elsepart;
  4535. } else {
  4536. n = n->nif.ifpart;
  4537. }
  4538. p = "; fi";
  4539. goto dotail;
  4540. case NSUBSHELL:
  4541. cmdputs("(");
  4542. n = n->nredir.n;
  4543. p = ")";
  4544. goto dotail;
  4545. case NWHILE:
  4546. p = "while ";
  4547. goto until;
  4548. case NUNTIL:
  4549. p = "until ";
  4550. until:
  4551. cmdputs(p);
  4552. cmdtxt(n->nbinary.ch1);
  4553. n = n->nbinary.ch2;
  4554. p = "; done";
  4555. dodo:
  4556. cmdputs("; do ");
  4557. dotail:
  4558. cmdtxt(n);
  4559. goto dotail2;
  4560. case NFOR:
  4561. cmdputs("for ");
  4562. cmdputs(n->nfor.var);
  4563. cmdputs(" in ");
  4564. cmdlist(n->nfor.args, 1);
  4565. n = n->nfor.body;
  4566. p = "; done";
  4567. goto dodo;
  4568. case NDEFUN:
  4569. cmdputs(n->ndefun.text);
  4570. p = "() { ... }";
  4571. goto dotail2;
  4572. case NCMD:
  4573. cmdlist(n->ncmd.args, 1);
  4574. cmdlist(n->ncmd.redirect, 0);
  4575. break;
  4576. case NARG:
  4577. p = n->narg.text;
  4578. dotail2:
  4579. cmdputs(p);
  4580. break;
  4581. case NHERE:
  4582. case NXHERE:
  4583. p = "<<...";
  4584. goto dotail2;
  4585. case NCASE:
  4586. cmdputs("case ");
  4587. cmdputs(n->ncase.expr->narg.text);
  4588. cmdputs(" in ");
  4589. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4590. cmdtxt(np->nclist.pattern);
  4591. cmdputs(") ");
  4592. cmdtxt(np->nclist.body);
  4593. cmdputs(";; ");
  4594. }
  4595. p = "esac";
  4596. goto dotail2;
  4597. case NTO:
  4598. p = ">";
  4599. goto redir;
  4600. case NCLOBBER:
  4601. p = ">|";
  4602. goto redir;
  4603. case NAPPEND:
  4604. p = ">>";
  4605. goto redir;
  4606. #if BASH_REDIR_OUTPUT
  4607. case NTO2:
  4608. #endif
  4609. case NTOFD:
  4610. p = ">&";
  4611. goto redir;
  4612. case NFROM:
  4613. p = "<";
  4614. goto redir;
  4615. case NFROMFD:
  4616. p = "<&";
  4617. goto redir;
  4618. case NFROMTO:
  4619. p = "<>";
  4620. redir:
  4621. cmdputs(utoa(n->nfile.fd));
  4622. cmdputs(p);
  4623. if (n->type == NTOFD || n->type == NFROMFD) {
  4624. if (n->ndup.dupfd >= 0)
  4625. cmdputs(utoa(n->ndup.dupfd));
  4626. else
  4627. cmdputs("-");
  4628. break;
  4629. }
  4630. n = n->nfile.fname;
  4631. goto donode;
  4632. }
  4633. }
  4634. static char *
  4635. commandtext(union node *n)
  4636. {
  4637. char *name;
  4638. STARTSTACKSTR(cmdnextc);
  4639. cmdtxt(n);
  4640. name = stackblock();
  4641. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4642. return ckstrdup(name);
  4643. }
  4644. #endif /* JOBS */
  4645. /*
  4646. * Fork off a subshell. If we are doing job control, give the subshell its
  4647. * own process group. Jp is a job structure that the job is to be added to.
  4648. * N is the command that will be evaluated by the child. Both jp and n may
  4649. * be NULL. The mode parameter can be one of the following:
  4650. * FORK_FG - Fork off a foreground process.
  4651. * FORK_BG - Fork off a background process.
  4652. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4653. * process group even if job control is on.
  4654. *
  4655. * When job control is turned off, background processes have their standard
  4656. * input redirected to /dev/null (except for the second and later processes
  4657. * in a pipeline).
  4658. *
  4659. * Called with interrupts off.
  4660. */
  4661. /*
  4662. * Clear traps on a fork.
  4663. */
  4664. static void
  4665. clear_traps(void)
  4666. {
  4667. char **tp;
  4668. INT_OFF;
  4669. for (tp = trap; tp <= &trap[NTRAP_LAST]; tp++) {
  4670. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4671. if (trap_ptr == trap)
  4672. free(*tp);
  4673. /* else: it "belongs" to trap_ptr vector, don't free */
  4674. *tp = NULL;
  4675. if ((tp - trap) != 0 && (tp - trap) < NSIG)
  4676. setsignal(tp - trap);
  4677. }
  4678. }
  4679. may_have_traps = 0;
  4680. INT_ON;
  4681. }
  4682. /* Lives far away from here, needed for forkchild */
  4683. static void closescript(void);
  4684. /* Called after fork(), in child */
  4685. /* jp and n are NULL when called by openhere() for heredoc support */
  4686. static NOINLINE void
  4687. forkchild(struct job *jp, union node *n, int mode)
  4688. {
  4689. int oldlvl;
  4690. TRACE(("Child shell %d\n", getpid()));
  4691. oldlvl = shlvl;
  4692. shlvl++;
  4693. /* man bash: "Non-builtin commands run by bash have signal handlers
  4694. * set to the values inherited by the shell from its parent".
  4695. * Do we do it correctly? */
  4696. closescript();
  4697. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4698. && n && n->type == NCMD /* is it single cmd? */
  4699. /* && n->ncmd.args->type == NARG - always true? */
  4700. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4701. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4702. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4703. ) {
  4704. TRACE(("Trap hack\n"));
  4705. /* Awful hack for `trap` or $(trap).
  4706. *
  4707. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4708. * contains an example where "trap" is executed in a subshell:
  4709. *
  4710. * save_traps=$(trap)
  4711. * ...
  4712. * eval "$save_traps"
  4713. *
  4714. * Standard does not say that "trap" in subshell shall print
  4715. * parent shell's traps. It only says that its output
  4716. * must have suitable form, but then, in the above example
  4717. * (which is not supposed to be normative), it implies that.
  4718. *
  4719. * bash (and probably other shell) does implement it
  4720. * (traps are reset to defaults, but "trap" still shows them),
  4721. * but as a result, "trap" logic is hopelessly messed up:
  4722. *
  4723. * # trap
  4724. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4725. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4726. * # true | trap <--- trap is in subshell - no output (ditto)
  4727. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4728. * trap -- 'echo Ho' SIGWINCH
  4729. * # echo `(trap)` <--- in subshell in subshell - output
  4730. * trap -- 'echo Ho' SIGWINCH
  4731. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4732. * trap -- 'echo Ho' SIGWINCH
  4733. *
  4734. * The rules when to forget and when to not forget traps
  4735. * get really complex and nonsensical.
  4736. *
  4737. * Our solution: ONLY bare $(trap) or `trap` is special.
  4738. */
  4739. /* Save trap handler strings for trap builtin to print */
  4740. trap_ptr = xmemdup(trap, sizeof(trap));
  4741. /* Fall through into clearing traps */
  4742. }
  4743. clear_traps();
  4744. #if JOBS
  4745. /* do job control only in root shell */
  4746. doing_jobctl = 0;
  4747. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4748. pid_t pgrp;
  4749. if (jp->nprocs == 0)
  4750. pgrp = getpid();
  4751. else
  4752. pgrp = jp->ps[0].ps_pid;
  4753. /* this can fail because we are doing it in the parent also */
  4754. setpgid(0, pgrp);
  4755. if (mode == FORK_FG)
  4756. xtcsetpgrp(ttyfd, pgrp);
  4757. setsignal(SIGTSTP);
  4758. setsignal(SIGTTOU);
  4759. } else
  4760. #endif
  4761. if (mode == FORK_BG) {
  4762. /* man bash: "When job control is not in effect,
  4763. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4764. ignoresig(SIGINT);
  4765. ignoresig(SIGQUIT);
  4766. if (jp->nprocs == 0) {
  4767. close(0);
  4768. if (open(bb_dev_null, O_RDONLY) != 0)
  4769. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4770. }
  4771. }
  4772. if (oldlvl == 0) {
  4773. if (iflag) { /* why if iflag only? */
  4774. setsignal(SIGINT);
  4775. setsignal(SIGTERM);
  4776. }
  4777. /* man bash:
  4778. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4779. * commands run by bash have signal handlers
  4780. * set to the values inherited by the shell
  4781. * from its parent".
  4782. * Take care of the second rule: */
  4783. setsignal(SIGQUIT);
  4784. }
  4785. #if JOBS
  4786. if (n && n->type == NCMD
  4787. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4788. ) {
  4789. TRACE(("Job hack\n"));
  4790. /* "jobs": we do not want to clear job list for it,
  4791. * instead we remove only _its_ own_ job from job list.
  4792. * This makes "jobs .... | cat" more useful.
  4793. */
  4794. freejob(curjob);
  4795. return;
  4796. }
  4797. #endif
  4798. for (jp = curjob; jp; jp = jp->prev_job)
  4799. freejob(jp);
  4800. }
  4801. /* Called after fork(), in parent */
  4802. #if !JOBS
  4803. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4804. #endif
  4805. static void
  4806. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4807. {
  4808. TRACE(("In parent shell: child = %d\n", pid));
  4809. if (!jp) /* jp is NULL when called by openhere() for heredoc support */
  4810. return;
  4811. #if JOBS
  4812. if (mode != FORK_NOJOB && jp->jobctl) {
  4813. int pgrp;
  4814. if (jp->nprocs == 0)
  4815. pgrp = pid;
  4816. else
  4817. pgrp = jp->ps[0].ps_pid;
  4818. /* This can fail because we are doing it in the child also */
  4819. setpgid(pid, pgrp);
  4820. }
  4821. #endif
  4822. if (mode == FORK_BG) {
  4823. backgndpid = pid; /* set $! */
  4824. set_curjob(jp, CUR_RUNNING);
  4825. }
  4826. if (jp) {
  4827. struct procstat *ps = &jp->ps[jp->nprocs++];
  4828. ps->ps_pid = pid;
  4829. ps->ps_status = -1;
  4830. ps->ps_cmd = nullstr;
  4831. #if JOBS
  4832. if (doing_jobctl && n)
  4833. ps->ps_cmd = commandtext(n);
  4834. #endif
  4835. }
  4836. }
  4837. /* jp and n are NULL when called by openhere() for heredoc support */
  4838. static int
  4839. forkshell(struct job *jp, union node *n, int mode)
  4840. {
  4841. int pid;
  4842. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4843. pid = fork();
  4844. if (pid < 0) {
  4845. TRACE(("Fork failed, errno=%d", errno));
  4846. if (jp)
  4847. freejob(jp);
  4848. ash_msg_and_raise_perror("can't fork");
  4849. }
  4850. if (pid == 0) {
  4851. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4852. forkchild(jp, n, mode);
  4853. } else {
  4854. forkparent(jp, n, mode, pid);
  4855. }
  4856. return pid;
  4857. }
  4858. /*
  4859. * Wait for job to finish.
  4860. *
  4861. * Under job control we have the problem that while a child process
  4862. * is running interrupts generated by the user are sent to the child
  4863. * but not to the shell. This means that an infinite loop started by
  4864. * an interactive user may be hard to kill. With job control turned off,
  4865. * an interactive user may place an interactive program inside a loop.
  4866. * If the interactive program catches interrupts, the user doesn't want
  4867. * these interrupts to also abort the loop. The approach we take here
  4868. * is to have the shell ignore interrupt signals while waiting for a
  4869. * foreground process to terminate, and then send itself an interrupt
  4870. * signal if the child process was terminated by an interrupt signal.
  4871. * Unfortunately, some programs want to do a bit of cleanup and then
  4872. * exit on interrupt; unless these processes terminate themselves by
  4873. * sending a signal to themselves (instead of calling exit) they will
  4874. * confuse this approach.
  4875. *
  4876. * Called with interrupts off.
  4877. */
  4878. static int
  4879. waitforjob(struct job *jp)
  4880. {
  4881. int st;
  4882. TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0));
  4883. /* In non-interactive shells, we _can_ get
  4884. * a keyboard signal here and be EINTRed, but we just loop
  4885. * inside dowait(), waiting for command to complete.
  4886. *
  4887. * man bash:
  4888. * "If bash is waiting for a command to complete and receives
  4889. * a signal for which a trap has been set, the trap
  4890. * will not be executed until the command completes."
  4891. *
  4892. * Reality is that even if trap is not set, bash
  4893. * will not act on the signal until command completes.
  4894. * Try this. sleep5intoff.c:
  4895. * #include <signal.h>
  4896. * #include <unistd.h>
  4897. * int main() {
  4898. * sigset_t set;
  4899. * sigemptyset(&set);
  4900. * sigaddset(&set, SIGINT);
  4901. * sigaddset(&set, SIGQUIT);
  4902. * sigprocmask(SIG_BLOCK, &set, NULL);
  4903. * sleep(5);
  4904. * return 0;
  4905. * }
  4906. * $ bash -c './sleep5intoff; echo hi'
  4907. * ^C^C^C^C <--- pressing ^C once a second
  4908. * $ _
  4909. * $ bash -c './sleep5intoff; echo hi'
  4910. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4911. * $ _
  4912. */
  4913. dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp);
  4914. if (!jp)
  4915. return exitstatus;
  4916. st = getstatus(jp);
  4917. #if JOBS
  4918. if (jp->jobctl) {
  4919. xtcsetpgrp(ttyfd, rootpid);
  4920. restore_tty_if_stopped_or_signaled(jp);
  4921. /*
  4922. * This is truly gross.
  4923. * If we're doing job control, then we did a TIOCSPGRP which
  4924. * caused us (the shell) to no longer be in the controlling
  4925. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4926. * intuit from the subprocess exit status whether a SIGINT
  4927. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4928. */
  4929. if (jp->sigint) /* TODO: do the same with all signals */
  4930. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4931. }
  4932. if (jp->state == JOBDONE)
  4933. #endif
  4934. freejob(jp);
  4935. return st;
  4936. }
  4937. /*
  4938. * return 1 if there are stopped jobs, otherwise 0
  4939. */
  4940. static int
  4941. stoppedjobs(void)
  4942. {
  4943. struct job *jp;
  4944. int retval;
  4945. retval = 0;
  4946. if (!iflag || job_warning)
  4947. goto out;
  4948. jp = curjob;
  4949. if (jp && jp->state == JOBSTOPPED) {
  4950. out2str("You have stopped jobs.\n");
  4951. job_warning = 2;
  4952. retval++;
  4953. }
  4954. out:
  4955. return retval;
  4956. }
  4957. /*
  4958. * Code for dealing with input/output redirection.
  4959. */
  4960. #undef EMPTY
  4961. #undef CLOSED
  4962. #define EMPTY -2 /* marks an unused slot in redirtab */
  4963. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4964. /*
  4965. * Handle here documents. Normally we fork off a process to write the
  4966. * data to a pipe. If the document is short, we can stuff the data in
  4967. * the pipe without forking.
  4968. */
  4969. /* openhere needs this forward reference */
  4970. static void expandhere(union node *arg);
  4971. static int
  4972. openhere(union node *redir)
  4973. {
  4974. char *p;
  4975. int pip[2];
  4976. size_t len = 0;
  4977. if (pipe(pip) < 0)
  4978. ash_msg_and_raise_perror("can't create pipe");
  4979. p = redir->nhere.doc->narg.text;
  4980. if (redir->type == NXHERE) {
  4981. expandhere(redir->nhere.doc);
  4982. p = stackblock();
  4983. }
  4984. len = strlen(p);
  4985. if (len <= PIPE_BUF) {
  4986. xwrite(pip[1], p, len);
  4987. goto out;
  4988. }
  4989. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4990. /* child */
  4991. close(pip[0]);
  4992. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4993. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4994. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4995. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4996. signal(SIGPIPE, SIG_DFL);
  4997. xwrite(pip[1], p, len);
  4998. _exit(EXIT_SUCCESS);
  4999. }
  5000. out:
  5001. close(pip[1]);
  5002. return pip[0];
  5003. }
  5004. static int
  5005. openredirect(union node *redir)
  5006. {
  5007. struct stat sb;
  5008. char *fname;
  5009. int f;
  5010. switch (redir->nfile.type) {
  5011. /* Can't happen, our single caller does this itself */
  5012. // case NTOFD:
  5013. // case NFROMFD:
  5014. // return -1;
  5015. case NHERE:
  5016. case NXHERE:
  5017. return openhere(redir);
  5018. }
  5019. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  5020. * allocated space. Do it only when we know it is safe.
  5021. */
  5022. fname = redir->nfile.expfname;
  5023. switch (redir->nfile.type) {
  5024. default:
  5025. #if DEBUG
  5026. abort();
  5027. #endif
  5028. case NFROM:
  5029. f = open(fname, O_RDONLY);
  5030. if (f < 0)
  5031. goto eopen;
  5032. break;
  5033. case NFROMTO:
  5034. f = open(fname, O_RDWR|O_CREAT, 0666);
  5035. if (f < 0)
  5036. goto ecreate;
  5037. break;
  5038. case NTO:
  5039. #if BASH_REDIR_OUTPUT
  5040. case NTO2:
  5041. #endif
  5042. /* Take care of noclobber mode. */
  5043. if (Cflag) {
  5044. if (stat(fname, &sb) < 0) {
  5045. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  5046. if (f < 0)
  5047. goto ecreate;
  5048. } else if (!S_ISREG(sb.st_mode)) {
  5049. f = open(fname, O_WRONLY, 0666);
  5050. if (f < 0)
  5051. goto ecreate;
  5052. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  5053. close(f);
  5054. errno = EEXIST;
  5055. goto ecreate;
  5056. }
  5057. } else {
  5058. errno = EEXIST;
  5059. goto ecreate;
  5060. }
  5061. break;
  5062. }
  5063. /* FALLTHROUGH */
  5064. case NCLOBBER:
  5065. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  5066. if (f < 0)
  5067. goto ecreate;
  5068. break;
  5069. case NAPPEND:
  5070. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  5071. if (f < 0)
  5072. goto ecreate;
  5073. break;
  5074. }
  5075. return f;
  5076. ecreate:
  5077. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  5078. eopen:
  5079. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  5080. }
  5081. /*
  5082. * Copy a file descriptor to be >= 10. Throws exception on error.
  5083. */
  5084. static int
  5085. savefd(int from)
  5086. {
  5087. int newfd;
  5088. int err;
  5089. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  5090. err = newfd < 0 ? errno : 0;
  5091. if (err != EBADF) {
  5092. if (err)
  5093. ash_msg_and_raise_perror("%d", from);
  5094. close(from);
  5095. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5096. close_on_exec_on(newfd);
  5097. }
  5098. return newfd;
  5099. }
  5100. static int
  5101. dup2_or_raise(int from, int to)
  5102. {
  5103. int newfd;
  5104. newfd = (from != to) ? dup2(from, to) : to;
  5105. if (newfd < 0) {
  5106. /* Happens when source fd is not open: try "echo >&99" */
  5107. ash_msg_and_raise_perror("%d", from);
  5108. }
  5109. return newfd;
  5110. }
  5111. static int
  5112. dup_CLOEXEC(int fd, int avoid_fd)
  5113. {
  5114. int newfd;
  5115. repeat:
  5116. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5117. if (newfd >= 0) {
  5118. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  5119. close_on_exec_on(newfd);
  5120. } else { /* newfd < 0 */
  5121. if (errno == EBUSY)
  5122. goto repeat;
  5123. if (errno == EINTR)
  5124. goto repeat;
  5125. }
  5126. return newfd;
  5127. }
  5128. static int
  5129. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5130. {
  5131. int newfd;
  5132. repeat:
  5133. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5134. if (newfd < 0) {
  5135. if (errno == EBUSY)
  5136. goto repeat;
  5137. if (errno == EINTR)
  5138. goto repeat;
  5139. /* fd was not open? */
  5140. if (errno == EBADF)
  5141. return fd;
  5142. ash_msg_and_raise_perror("%d", newfd);
  5143. }
  5144. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5145. close_on_exec_on(newfd);
  5146. close(fd);
  5147. return newfd;
  5148. }
  5149. /* Struct def and variable are moved down to the first usage site */
  5150. struct squirrel {
  5151. int orig_fd;
  5152. int moved_to;
  5153. };
  5154. struct redirtab {
  5155. struct redirtab *next;
  5156. int pair_count;
  5157. struct squirrel two_fd[];
  5158. };
  5159. #define redirlist (G_var.redirlist)
  5160. static void
  5161. add_squirrel_closed(struct redirtab *sq, int fd)
  5162. {
  5163. int i;
  5164. if (!sq)
  5165. return;
  5166. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5167. /* If we collide with an already moved fd... */
  5168. if (fd == sq->two_fd[i].orig_fd) {
  5169. /* Examples:
  5170. * "echo 3>FILE 3>&- 3>FILE"
  5171. * "echo 3>&- 3>FILE"
  5172. * No need for last redirect to insert
  5173. * another "need to close 3" indicator.
  5174. */
  5175. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5176. return;
  5177. }
  5178. }
  5179. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5180. sq->two_fd[i].orig_fd = fd;
  5181. sq->two_fd[i].moved_to = CLOSED;
  5182. }
  5183. static int
  5184. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5185. {
  5186. int i, new_fd;
  5187. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5188. avoid_fd = 9;
  5189. #if JOBS
  5190. if (fd == ttyfd) {
  5191. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5192. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5193. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5194. return 1; /* "we closed fd" */
  5195. }
  5196. #endif
  5197. /* Are we called from redirect(0)? E.g. redirect
  5198. * in a forked child. No need to save fds,
  5199. * we aren't going to use them anymore, ok to trash.
  5200. */
  5201. if (!sq)
  5202. return 0;
  5203. /* If this one of script's fds? */
  5204. if (fd != 0) {
  5205. struct parsefile *pf = g_parsefile;
  5206. while (pf) {
  5207. /* We skip fd == 0 case because of the following:
  5208. * $ ash # running ash interactively
  5209. * $ . ./script.sh
  5210. * and in script.sh: "exec 9>&0".
  5211. * Even though top-level pf_fd _is_ 0,
  5212. * it's still ok to use it: "read" builtin uses it,
  5213. * why should we cripple "exec" builtin?
  5214. */
  5215. if (fd == pf->pf_fd) {
  5216. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5217. return 1; /* "we closed fd" */
  5218. }
  5219. pf = pf->prev;
  5220. }
  5221. }
  5222. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5223. /* First: do we collide with some already moved fds? */
  5224. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5225. /* If we collide with an already moved fd... */
  5226. if (fd == sq->two_fd[i].moved_to) {
  5227. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5228. sq->two_fd[i].moved_to = new_fd;
  5229. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5230. if (new_fd < 0) /* what? */
  5231. xfunc_die();
  5232. return 0; /* "we did not close fd" */
  5233. }
  5234. if (fd == sq->two_fd[i].orig_fd) {
  5235. /* Example: echo Hello >/dev/null 1>&2 */
  5236. TRACE(("redirect_fd %d: already moved\n", fd));
  5237. return 0; /* "we did not close fd" */
  5238. }
  5239. }
  5240. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5241. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5242. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5243. if (new_fd < 0) {
  5244. if (errno != EBADF)
  5245. xfunc_die();
  5246. /* new_fd = CLOSED; - already is -1 */
  5247. }
  5248. sq->two_fd[i].moved_to = new_fd;
  5249. sq->two_fd[i].orig_fd = fd;
  5250. /* if we move stderr, let "set -x" code know */
  5251. if (fd == preverrout_fd)
  5252. preverrout_fd = new_fd;
  5253. return 0; /* "we did not close fd" */
  5254. }
  5255. static int
  5256. internally_opened_fd(int fd, struct redirtab *sq)
  5257. {
  5258. int i;
  5259. #if JOBS
  5260. if (fd == ttyfd)
  5261. return 1;
  5262. #endif
  5263. /* If this one of script's fds? */
  5264. if (fd != 0) {
  5265. struct parsefile *pf = g_parsefile;
  5266. while (pf) {
  5267. if (fd == pf->pf_fd)
  5268. return 1;
  5269. pf = pf->prev;
  5270. }
  5271. }
  5272. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5273. if (fd == sq->two_fd[i].moved_to)
  5274. return 1;
  5275. }
  5276. return 0;
  5277. }
  5278. /*
  5279. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5280. * old file descriptors are stashed away so that the redirection can be
  5281. * undone by calling popredir.
  5282. */
  5283. /* flags passed to redirect */
  5284. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5285. static void
  5286. redirect(union node *redir, int flags)
  5287. {
  5288. struct redirtab *sv;
  5289. if (!redir)
  5290. return;
  5291. sv = NULL;
  5292. INT_OFF;
  5293. if (flags & REDIR_PUSH)
  5294. sv = redirlist;
  5295. do {
  5296. int fd;
  5297. int newfd;
  5298. int close_fd;
  5299. int closed;
  5300. fd = redir->nfile.fd;
  5301. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5302. //bb_error_msg("doing %d > %d", fd, newfd);
  5303. newfd = redir->ndup.dupfd;
  5304. close_fd = -1;
  5305. } else {
  5306. newfd = openredirect(redir); /* always >= 0 */
  5307. if (fd == newfd) {
  5308. /* open() gave us precisely the fd we wanted.
  5309. * This means that this fd was not busy
  5310. * (not opened to anywhere).
  5311. * Remember to close it on restore:
  5312. */
  5313. add_squirrel_closed(sv, fd);
  5314. continue;
  5315. }
  5316. close_fd = newfd;
  5317. }
  5318. if (fd == newfd)
  5319. continue;
  5320. /* if "N>FILE": move newfd to fd */
  5321. /* if "N>&M": dup newfd to fd */
  5322. /* if "N>&-": close fd (newfd is -1) */
  5323. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5324. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5325. if (newfd == -1) {
  5326. /* "N>&-" means "close me" */
  5327. if (!closed) {
  5328. /* ^^^ optimization: saving may already
  5329. * have closed it. If not... */
  5330. close(fd);
  5331. }
  5332. } else {
  5333. /* if newfd is a script fd or saved fd, simulate EBADF */
  5334. if (internally_opened_fd(newfd, sv)) {
  5335. errno = EBADF;
  5336. ash_msg_and_raise_perror("%d", newfd);
  5337. }
  5338. dup2_or_raise(newfd, fd);
  5339. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5340. close(close_fd);
  5341. #if BASH_REDIR_OUTPUT
  5342. if (redir->nfile.type == NTO2 && fd == 1) {
  5343. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5344. fd = 2;
  5345. newfd = 1;
  5346. close_fd = -1;
  5347. goto redirect_more;
  5348. }
  5349. #endif
  5350. }
  5351. } while ((redir = redir->nfile.next) != NULL);
  5352. INT_ON;
  5353. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5354. #define REDIR_SAVEFD2 0
  5355. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5356. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5357. // not only for calls with flags containing REDIR_SAVEFD2.
  5358. // We do this unconditionally (see save_fd_on_redirect()).
  5359. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5360. // preverrout_fd = copied_fd2;
  5361. }
  5362. static int
  5363. redirectsafe(union node *redir, int flags)
  5364. {
  5365. int err;
  5366. volatile int saveint;
  5367. struct jmploc *volatile savehandler = exception_handler;
  5368. struct jmploc jmploc;
  5369. SAVE_INT(saveint);
  5370. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5371. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5372. if (!err) {
  5373. exception_handler = &jmploc;
  5374. redirect(redir, flags);
  5375. }
  5376. exception_handler = savehandler;
  5377. if (err && exception_type != EXERROR)
  5378. longjmp(exception_handler->loc, 1);
  5379. RESTORE_INT(saveint);
  5380. return err;
  5381. }
  5382. #if BASH_PROCESS_SUBST
  5383. static void
  5384. pushfd(int fd)
  5385. {
  5386. struct redirtab *sv;
  5387. sv = ckzalloc(sizeof(*sv) + sizeof(sv->two_fd[0]));
  5388. sv->pair_count = 1;
  5389. sv->two_fd[0].orig_fd = fd;
  5390. sv->two_fd[0].moved_to = CLOSED;
  5391. sv->next = redirlist;
  5392. redirlist = sv;
  5393. }
  5394. #endif
  5395. static struct redirtab*
  5396. pushredir(union node *redir)
  5397. {
  5398. struct redirtab *sv;
  5399. int i;
  5400. if (!redir)
  5401. return redirlist;
  5402. i = 0;
  5403. do {
  5404. i++;
  5405. #if BASH_REDIR_OUTPUT
  5406. if (redir->nfile.type == NTO2)
  5407. i++;
  5408. #endif
  5409. redir = redir->nfile.next;
  5410. } while (redir);
  5411. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5412. sv->pair_count = i;
  5413. while (--i >= 0)
  5414. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5415. sv->next = redirlist;
  5416. redirlist = sv;
  5417. return sv->next;
  5418. }
  5419. /*
  5420. * Undo the effects of the last redirection.
  5421. */
  5422. static void
  5423. popredir(int drop)
  5424. {
  5425. struct redirtab *rp;
  5426. int i;
  5427. if (redirlist == NULL)
  5428. return;
  5429. INT_OFF;
  5430. rp = redirlist;
  5431. for (i = 0; i < rp->pair_count; i++) {
  5432. int fd = rp->two_fd[i].orig_fd;
  5433. int copy = rp->two_fd[i].moved_to;
  5434. if (copy == CLOSED) {
  5435. if (!drop)
  5436. close(fd);
  5437. continue;
  5438. }
  5439. if (copy != EMPTY) {
  5440. if (!drop) {
  5441. /*close(fd);*/
  5442. dup2_or_raise(copy, fd);
  5443. }
  5444. close(copy);
  5445. }
  5446. }
  5447. redirlist = rp->next;
  5448. free(rp);
  5449. INT_ON;
  5450. }
  5451. static void
  5452. unwindredir(struct redirtab *stop)
  5453. {
  5454. while (redirlist != stop)
  5455. popredir(/*drop:*/ 0);
  5456. }
  5457. /* ============ Routines to expand arguments to commands
  5458. *
  5459. * We have to deal with backquotes, shell variables, and file metacharacters.
  5460. */
  5461. #if ENABLE_FEATURE_SH_MATH
  5462. static arith_t
  5463. ash_arith(const char *s)
  5464. {
  5465. arith_state_t math_state;
  5466. arith_t result;
  5467. math_state.lookupvar = lookupvar;
  5468. math_state.setvar = setvar0;
  5469. //math_state.endofname = endofname;
  5470. INT_OFF;
  5471. result = arith(&math_state, s);
  5472. if (math_state.errmsg)
  5473. ash_msg_and_raise_error(math_state.errmsg);
  5474. INT_ON;
  5475. return result;
  5476. }
  5477. #endif
  5478. #if BASH_SUBSTR
  5479. # if ENABLE_FEATURE_SH_MATH
  5480. static int substr_atoi(const char *s)
  5481. {
  5482. arith_t t = ash_arith(s);
  5483. if (sizeof(t) > sizeof(int)) {
  5484. /* clamp very large or very large negative nums for ${v:N:M}:
  5485. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5486. */
  5487. if (t > INT_MAX)
  5488. t = INT_MAX;
  5489. if (t < INT_MIN)
  5490. t = INT_MIN;
  5491. }
  5492. return t;
  5493. }
  5494. # else
  5495. # define substr_atoi(s) number(s)
  5496. # endif
  5497. #endif
  5498. /*
  5499. * expandarg flags
  5500. */
  5501. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5502. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5503. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5504. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5505. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5506. * POSIX says for this case:
  5507. * Pathname expansion shall not be performed on the word by a
  5508. * non-interactive shell; an interactive shell may perform it, but shall
  5509. * do so only when the expansion would result in one word.
  5510. * Currently, our code complies to the above rule by never globbing
  5511. * redirection filenames.
  5512. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5513. * (this means that on a typical Linux distro, bash almost always
  5514. * performs globbing, and thus diverges from what we do).
  5515. */
  5516. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5517. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5518. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5519. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5520. #define EXP_KEEPNUL 0x200 /* do not skip NUL characters */
  5521. #define EXP_DISCARD 0x400 /* discard result of expansion */
  5522. /*
  5523. * rmescape() flags
  5524. */
  5525. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5526. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5527. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5528. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5529. /* Add CTLESC when necessary. */
  5530. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5531. /*
  5532. * Structure specifying which parts of the string should be searched
  5533. * for IFS characters.
  5534. */
  5535. struct ifsregion {
  5536. struct ifsregion *next; /* next region in list */
  5537. int begoff; /* offset of start of region */
  5538. int endoff; /* offset of end of region */
  5539. int nulonly; /* search for nul bytes only */
  5540. };
  5541. struct arglist {
  5542. struct strlist *list;
  5543. struct strlist **lastp;
  5544. };
  5545. /* output of current string */
  5546. static char *expdest;
  5547. /* list of back quote expressions */
  5548. static struct nodelist *argbackq;
  5549. /* first struct in list of ifs regions */
  5550. static struct ifsregion ifsfirst;
  5551. /* last struct in list */
  5552. static struct ifsregion *ifslastp;
  5553. /* holds expanded arg list */
  5554. static struct arglist exparg;
  5555. /*
  5556. * Break the argument string into pieces based upon IFS and add the
  5557. * strings to the argument list. The regions of the string to be
  5558. * searched for IFS characters have been stored by recordregion.
  5559. */
  5560. static void
  5561. ifsbreakup(char *string, struct arglist *arglist)
  5562. {
  5563. struct ifsregion *ifsp;
  5564. struct strlist *sp;
  5565. char *start;
  5566. char *p;
  5567. char *q;
  5568. const char *ifs, *realifs;
  5569. int ifsspc;
  5570. int nulonly;
  5571. start = string;
  5572. if (ifslastp != NULL) {
  5573. ifsspc = 0;
  5574. nulonly = 0;
  5575. realifs = ifsset() ? ifsval() : defifs;
  5576. ifsp = &ifsfirst;
  5577. do {
  5578. int afternul;
  5579. p = string + ifsp->begoff;
  5580. afternul = nulonly;
  5581. nulonly = ifsp->nulonly;
  5582. ifs = nulonly ? nullstr : realifs;
  5583. ifsspc = 0;
  5584. while (p < string + ifsp->endoff) {
  5585. q = p;
  5586. if ((unsigned char)*p == CTLESC)
  5587. p++;
  5588. if (!strchr(ifs, *p)) {
  5589. p++;
  5590. continue;
  5591. }
  5592. if (!(afternul || nulonly))
  5593. ifsspc = (strchr(defifs, *p) != NULL);
  5594. /* Ignore IFS whitespace at start */
  5595. if (q == start && ifsspc) {
  5596. p++;
  5597. start = p;
  5598. continue;
  5599. }
  5600. *q = '\0';
  5601. sp = stzalloc(sizeof(*sp));
  5602. sp->text = start;
  5603. *arglist->lastp = sp;
  5604. arglist->lastp = &sp->next;
  5605. p++;
  5606. if (!nulonly) {
  5607. for (;;) {
  5608. if (p >= string + ifsp->endoff) {
  5609. break;
  5610. }
  5611. q = p;
  5612. if ((unsigned char)*p == CTLESC)
  5613. p++;
  5614. if (strchr(ifs, *p) == NULL) {
  5615. p = q;
  5616. break;
  5617. }
  5618. if (strchr(defifs, *p) == NULL) {
  5619. if (ifsspc) {
  5620. p++;
  5621. ifsspc = 0;
  5622. } else {
  5623. p = q;
  5624. break;
  5625. }
  5626. } else
  5627. p++;
  5628. }
  5629. }
  5630. start = p;
  5631. } /* while */
  5632. ifsp = ifsp->next;
  5633. } while (ifsp != NULL);
  5634. if (nulonly)
  5635. goto add;
  5636. }
  5637. if (!*start)
  5638. return;
  5639. add:
  5640. sp = stzalloc(sizeof(*sp));
  5641. sp->text = start;
  5642. *arglist->lastp = sp;
  5643. arglist->lastp = &sp->next;
  5644. }
  5645. static void
  5646. ifsfree(void)
  5647. {
  5648. struct ifsregion *p = ifsfirst.next;
  5649. if (!p)
  5650. goto out;
  5651. INT_OFF;
  5652. do {
  5653. struct ifsregion *ifsp;
  5654. ifsp = p->next;
  5655. free(p);
  5656. p = ifsp;
  5657. } while (p);
  5658. ifsfirst.next = NULL;
  5659. INT_ON;
  5660. out:
  5661. ifslastp = NULL;
  5662. }
  5663. static size_t
  5664. esclen(const char *start, const char *p)
  5665. {
  5666. size_t esc = 0;
  5667. while (p > start && (unsigned char)*--p == CTLESC) {
  5668. esc++;
  5669. }
  5670. return esc;
  5671. }
  5672. /*
  5673. * Remove any CTLESC characters from a string.
  5674. */
  5675. #if !BASH_PATTERN_SUBST
  5676. #define rmescapes(str, flag, slash_position) \
  5677. rmescapes(str, flag)
  5678. #endif
  5679. static char *
  5680. rmescapes(char *str, int flag, int *slash_position)
  5681. {
  5682. static const char qchars[] ALIGN1 = {
  5683. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5684. char *p, *q, *r;
  5685. unsigned protect_against_glob;
  5686. unsigned globbing;
  5687. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5688. if (!p)
  5689. return str;
  5690. q = p;
  5691. r = str;
  5692. if (flag & RMESCAPE_ALLOC) {
  5693. size_t len = p - str;
  5694. size_t fulllen = len + strlen(p) + 1;
  5695. if (flag & RMESCAPE_GROW) {
  5696. int strloc = str - (char *)stackblock();
  5697. r = makestrspace(fulllen, expdest);
  5698. /* p and str may be invalidated by makestrspace */
  5699. str = (char *)stackblock() + strloc;
  5700. p = str + len;
  5701. } else if (flag & RMESCAPE_HEAP) {
  5702. r = ckmalloc(fulllen);
  5703. } else {
  5704. r = stalloc(fulllen);
  5705. }
  5706. q = r;
  5707. if (len > 0) {
  5708. q = (char *)mempcpy(q, str, len);
  5709. }
  5710. }
  5711. globbing = flag & RMESCAPE_GLOB;
  5712. protect_against_glob = globbing;
  5713. while (*p) {
  5714. if ((unsigned char)*p == CTLQUOTEMARK) {
  5715. // Note: protect_against_glob only affect whether
  5716. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5717. p++;
  5718. protect_against_glob = globbing;
  5719. continue;
  5720. }
  5721. if (*p == '\\') {
  5722. /* naked back slash */
  5723. protect_against_glob = 0;
  5724. goto copy;
  5725. }
  5726. if ((unsigned char)*p == CTLESC) {
  5727. p++;
  5728. #if DEBUG
  5729. if (*p == '\0')
  5730. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5731. #endif
  5732. if (protect_against_glob) {
  5733. /*
  5734. * We used to trust glob() and fnmatch() to eat
  5735. * superfluous escapes (\z where z has no
  5736. * special meaning anyway). But this causes
  5737. * bugs such as string of one greek letter rho
  5738. * (unicode-encoded as two bytes "cf,81")
  5739. * getting encoded as "cf,CTLESC,81"
  5740. * and here, converted to "cf,\,81" -
  5741. * which does not go well with some flavors
  5742. * of fnmatch() in unicode locales
  5743. * (for example, glibc <= 2.22).
  5744. *
  5745. * Lets add "\" only on the chars which need it.
  5746. * Testcases for less obvious chars are shown.
  5747. */
  5748. if (*p == '*'
  5749. || *p == '?'
  5750. || *p == '['
  5751. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5752. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5753. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5754. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5755. /* Some libc support [^negate], that's why "^" also needs love */
  5756. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5757. ) {
  5758. *q++ = '\\';
  5759. }
  5760. }
  5761. }
  5762. #if BASH_PATTERN_SUBST
  5763. else if (slash_position && p == str + *slash_position) {
  5764. /* stop handling globbing */
  5765. globbing = 0;
  5766. *slash_position = q - r;
  5767. slash_position = NULL;
  5768. }
  5769. #endif
  5770. protect_against_glob = globbing;
  5771. copy:
  5772. *q++ = *p++;
  5773. }
  5774. *q = '\0';
  5775. if (flag & RMESCAPE_GROW) {
  5776. expdest = r;
  5777. STADJUST(q - r + 1, expdest);
  5778. }
  5779. return r;
  5780. }
  5781. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5782. /*
  5783. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5784. *
  5785. * Returns an stalloced string.
  5786. */
  5787. static char *
  5788. preglob(const char *pattern, int flag)
  5789. {
  5790. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5791. }
  5792. /*
  5793. * Put a string on the stack.
  5794. */
  5795. static size_t
  5796. memtodest(const char *p, size_t len, int flags)
  5797. {
  5798. int syntax = flags & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5799. char *q;
  5800. char *s;
  5801. if (!len)
  5802. return 0;
  5803. q = makestrspace(len * 2, expdest);
  5804. s = q;
  5805. do {
  5806. unsigned char c = *p++;
  5807. if (c) {
  5808. if (flags & QUOTES_ESC) {
  5809. int n = SIT(c, syntax);
  5810. if (n == CCTL
  5811. || ((flags & EXP_QUOTED) && n == CBACK)
  5812. ) {
  5813. USTPUTC(CTLESC, q);
  5814. }
  5815. }
  5816. } else if (!(flags & EXP_KEEPNUL))
  5817. continue;
  5818. USTPUTC(c, q);
  5819. } while (--len);
  5820. expdest = q;
  5821. return q - s;
  5822. }
  5823. static size_t
  5824. strtodest(const char *p, int flags)
  5825. {
  5826. size_t len = strlen(p);
  5827. memtodest(p, len, flags);
  5828. return len;
  5829. }
  5830. /*
  5831. * Our own itoa().
  5832. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5833. */
  5834. static int
  5835. cvtnum(arith_t num, int flags)
  5836. {
  5837. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5838. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5839. int len = (sizeof(arith_t) >= 4) ? sizeof(arith_t) * 3 : sizeof(arith_t) * 3 + 2;
  5840. char buf[len];
  5841. len = fmtstr(buf, len, ARITH_FMT, num);
  5842. return memtodest(buf, len, flags);
  5843. }
  5844. /*
  5845. * Record the fact that we have to scan this region of the
  5846. * string for IFS characters.
  5847. */
  5848. static void
  5849. recordregion(int start, int end, int nulonly)
  5850. {
  5851. struct ifsregion *ifsp;
  5852. if (ifslastp == NULL) {
  5853. ifsp = &ifsfirst;
  5854. } else {
  5855. INT_OFF;
  5856. ifsp = ckzalloc(sizeof(*ifsp));
  5857. /*ifsp->next = NULL; - ckzalloc did it */
  5858. ifslastp->next = ifsp;
  5859. INT_ON;
  5860. }
  5861. ifslastp = ifsp;
  5862. ifslastp->begoff = start;
  5863. ifslastp->endoff = end;
  5864. ifslastp->nulonly = nulonly;
  5865. }
  5866. static void
  5867. removerecordregions(int endoff)
  5868. {
  5869. if (ifslastp == NULL)
  5870. return;
  5871. if (ifsfirst.endoff > endoff) {
  5872. while (ifsfirst.next) {
  5873. struct ifsregion *ifsp;
  5874. INT_OFF;
  5875. ifsp = ifsfirst.next->next;
  5876. free(ifsfirst.next);
  5877. ifsfirst.next = ifsp;
  5878. INT_ON;
  5879. }
  5880. if (ifsfirst.begoff > endoff) {
  5881. ifslastp = NULL;
  5882. } else {
  5883. ifslastp = &ifsfirst;
  5884. ifsfirst.endoff = endoff;
  5885. }
  5886. return;
  5887. }
  5888. ifslastp = &ifsfirst;
  5889. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5890. ifslastp = ifslastp->next;
  5891. while (ifslastp->next) {
  5892. struct ifsregion *ifsp;
  5893. INT_OFF;
  5894. ifsp = ifslastp->next->next;
  5895. free(ifslastp->next);
  5896. ifslastp->next = ifsp;
  5897. INT_ON;
  5898. }
  5899. if (ifslastp->endoff > endoff)
  5900. ifslastp->endoff = endoff;
  5901. }
  5902. static char *
  5903. exptilde(char *startp, int flag)
  5904. {
  5905. unsigned char c;
  5906. char *name;
  5907. struct passwd *pw;
  5908. const char *home;
  5909. char *p;
  5910. p = startp;
  5911. name = p + 1;
  5912. while ((c = *++p) != '\0') {
  5913. switch (c) {
  5914. case CTLESC:
  5915. return startp;
  5916. case CTLQUOTEMARK:
  5917. return startp;
  5918. case ':':
  5919. if (flag & EXP_VARTILDE)
  5920. goto done;
  5921. break;
  5922. case '/':
  5923. case CTLENDVAR:
  5924. goto done;
  5925. }
  5926. }
  5927. done:
  5928. if (flag & EXP_DISCARD)
  5929. goto out;
  5930. *p = '\0';
  5931. if (*name == '\0') {
  5932. home = lookupvar("HOME");
  5933. } else {
  5934. pw = getpwnam(name);
  5935. if (pw == NULL)
  5936. goto lose;
  5937. home = pw->pw_dir;
  5938. }
  5939. *p = c;
  5940. if (!home)
  5941. goto lose;
  5942. strtodest(home, flag | EXP_QUOTED);
  5943. out:
  5944. return p;
  5945. lose:
  5946. return startp;
  5947. }
  5948. /*
  5949. * Execute a command inside back quotes. If it's a builtin command, we
  5950. * want to save its output in a block obtained from malloc. Otherwise
  5951. * we fork off a subprocess and get the output of the command via a pipe.
  5952. * Should be called with interrupts off.
  5953. */
  5954. struct backcmd { /* result of evalbackcmd */
  5955. int fd; /* file descriptor to read from */
  5956. int nleft; /* number of chars in buffer */
  5957. char *buf; /* buffer */
  5958. struct job *jp; /* job structure for command */
  5959. };
  5960. /* These forward decls are needed to use "eval" code for backticks handling: */
  5961. /* flags in argument to evaltree */
  5962. #define EV_EXIT 01 /* exit after evaluating tree */
  5963. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5964. static int evaltree(union node *, int);
  5965. /* An evaltree() which is known to never return.
  5966. * Used to use an alias:
  5967. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5968. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5969. */
  5970. static ALWAYS_INLINE NORETURN void
  5971. evaltreenr(union node *n, int flags)
  5972. {
  5973. evaltree(n, flags);
  5974. bb_unreachable(abort());
  5975. /* NOTREACHED */
  5976. }
  5977. static void FAST_FUNC
  5978. evalbackcmd(union node *n, struct backcmd *result
  5979. IF_BASH_PROCESS_SUBST(, int ctl))
  5980. {
  5981. int pip[2];
  5982. struct job *jp;
  5983. #if BASH_PROCESS_SUBST
  5984. /* determine end of pipe used by parent (ip) and child (ic) */
  5985. const int ip = (ctl == CTLTOPROC);
  5986. const int ic = !(ctl == CTLTOPROC);
  5987. #else
  5988. const int ctl = CTLBACKQ;
  5989. const int ip = 0;
  5990. const int ic = 1;
  5991. #endif
  5992. result->fd = -1;
  5993. result->buf = NULL;
  5994. result->nleft = 0;
  5995. result->jp = NULL;
  5996. if (n == NULL) {
  5997. goto out;
  5998. }
  5999. if (pipe(pip) < 0)
  6000. ash_msg_and_raise_perror("can't create pipe");
  6001. /* process substitution uses NULL job/node, like openhere() */
  6002. jp = (ctl == CTLBACKQ) ? makejob(/*n,*/ 1) : NULL;
  6003. if (forkshell(jp, (ctl == CTLBACKQ) ? n : NULL, FORK_NOJOB) == 0) {
  6004. /* child */
  6005. FORCE_INT_ON;
  6006. close(pip[ip]);
  6007. /* ic is index of child end of pipe *and* fd to connect it to */
  6008. if (pip[ic] != ic) {
  6009. /*close(ic);*/
  6010. dup2_or_raise(pip[ic], ic);
  6011. close(pip[ic]);
  6012. }
  6013. /* TODO: eflag clearing makes the following not abort:
  6014. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  6015. * which is what bash does (unless it is in POSIX mode).
  6016. * dash deleted "eflag = 0" line in the commit
  6017. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  6018. * [EVAL] Don't clear eflag in evalbackcmd
  6019. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  6020. */
  6021. eflag = 0;
  6022. ifsfree();
  6023. evaltreenr(n, EV_EXIT);
  6024. /* NOTREACHED */
  6025. }
  6026. /* parent */
  6027. #if BASH_PROCESS_SUBST
  6028. if (ctl != CTLBACKQ) {
  6029. int fd = fcntl(pip[ip], F_DUPFD, 64);
  6030. if (fd > 0) {
  6031. close(pip[ip]);
  6032. pip[ip] = fd;
  6033. }
  6034. pushfd(pip[ip]);
  6035. }
  6036. #endif
  6037. close(pip[ic]);
  6038. result->fd = pip[ip];
  6039. result->jp = jp;
  6040. out:
  6041. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  6042. result->fd, result->buf, result->nleft, result->jp));
  6043. }
  6044. /*
  6045. * Expand stuff in backwards quotes.
  6046. */
  6047. static void
  6048. expbackq(union node *cmd, int flag IF_BASH_PROCESS_SUBST(, int ctl))
  6049. {
  6050. #if !BASH_PROCESS_SUBST
  6051. const int ctl = CTLBACKQ;
  6052. #endif
  6053. struct backcmd in;
  6054. int i;
  6055. char buf[128];
  6056. char *p;
  6057. char *dest;
  6058. int startloc;
  6059. struct stackmark smark;
  6060. if (flag & EXP_DISCARD)
  6061. goto out;
  6062. INT_OFF;
  6063. startloc = expdest - (char *)stackblock();
  6064. pushstackmark(&smark, startloc);
  6065. evalbackcmd(cmd, &in IF_BASH_PROCESS_SUBST(, ctl));
  6066. popstackmark(&smark);
  6067. if (ctl != CTLBACKQ) {
  6068. sprintf(buf, DEV_FD_PREFIX"%d", in.fd);
  6069. strtodest(buf, BASESYNTAX);
  6070. goto done;
  6071. }
  6072. p = in.buf;
  6073. i = in.nleft;
  6074. if (i == 0)
  6075. goto read;
  6076. for (;;) {
  6077. memtodest(p, i, flag);
  6078. read:
  6079. if (in.fd < 0)
  6080. break;
  6081. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  6082. TRACE(("expbackq: read returns %d\n", i));
  6083. if (i <= 0)
  6084. break;
  6085. p = buf;
  6086. }
  6087. free(in.buf);
  6088. if (in.fd >= 0) {
  6089. close(in.fd);
  6090. back_exitstatus = waitforjob(in.jp);
  6091. }
  6092. done:
  6093. INT_ON;
  6094. /* Eat all trailing newlines */
  6095. dest = expdest;
  6096. for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';)
  6097. STUNPUTC(dest);
  6098. expdest = dest;
  6099. if (!(flag & EXP_QUOTED))
  6100. recordregion(startloc, dest - (char *)stackblock(), 0);
  6101. TRACE(("evalbackq: size:%d:'%.*s'\n",
  6102. (int)((dest - (char *)stackblock()) - startloc),
  6103. (int)((dest - (char *)stackblock()) - startloc),
  6104. stackblock() + startloc));
  6105. out:
  6106. argbackq = argbackq->next;
  6107. }
  6108. /* expari needs it */
  6109. static char *argstr(char *p, int flag);
  6110. #if ENABLE_FEATURE_SH_MATH
  6111. /*
  6112. * Expand arithmetic expression. Backup to start of expression,
  6113. * evaluate, place result in (backed up) result, adjust string position.
  6114. */
  6115. static char *
  6116. expari(char *start, int flag)
  6117. {
  6118. struct stackmark sm;
  6119. int begoff;
  6120. int endoff;
  6121. int len;
  6122. arith_t result;
  6123. char *p;
  6124. p = stackblock();
  6125. begoff = expdest - p;
  6126. p = argstr(start, flag & EXP_DISCARD);
  6127. if (flag & EXP_DISCARD)
  6128. goto out;
  6129. start = stackblock();
  6130. endoff = expdest - start;
  6131. start += begoff;
  6132. STADJUST(start - expdest, expdest);
  6133. removerecordregions(begoff);
  6134. if (flag & QUOTES_ESC)
  6135. rmescapes(start, 0, NULL);
  6136. pushstackmark(&sm, endoff);
  6137. result = ash_arith(start);
  6138. popstackmark(&sm);
  6139. len = cvtnum(result, flag);
  6140. if (!(flag & EXP_QUOTED))
  6141. recordregion(begoff, begoff + len, 0);
  6142. out:
  6143. return p;
  6144. }
  6145. #endif
  6146. /* argstr needs it */
  6147. static char *evalvar(char *p, int flags);
  6148. /*
  6149. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  6150. * characters to allow for further processing. Otherwise treat
  6151. * $@ like $* since no splitting will be performed.
  6152. */
  6153. static char *
  6154. argstr(char *p, int flag)
  6155. {
  6156. static const char spclchars[] ALIGN1 = {
  6157. '=',
  6158. ':',
  6159. CTLQUOTEMARK,
  6160. CTLENDVAR,
  6161. CTLESC,
  6162. CTLVAR,
  6163. CTLBACKQ,
  6164. #if BASH_PROCESS_SUBST
  6165. CTLTOPROC,
  6166. CTLFROMPROC,
  6167. #endif
  6168. #if ENABLE_FEATURE_SH_MATH
  6169. CTLARI,
  6170. CTLENDARI,
  6171. #endif
  6172. '\0'
  6173. };
  6174. const char *reject = spclchars;
  6175. int breakall = (flag & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6176. int inquotes;
  6177. size_t length;
  6178. int startloc;
  6179. reject += !!(flag & EXP_VARTILDE2);
  6180. reject += flag & EXP_VARTILDE ? 0 : 2;
  6181. inquotes = 0;
  6182. length = 0;
  6183. if (flag & EXP_TILDE) {
  6184. flag &= ~EXP_TILDE;
  6185. tilde:
  6186. if (*p == '~')
  6187. p = exptilde(p, flag);
  6188. }
  6189. start:
  6190. startloc = expdest - (char *)stackblock();
  6191. for (;;) {
  6192. int end;
  6193. unsigned char c;
  6194. length += strcspn(p + length, reject);
  6195. end = 0;
  6196. c = p[length];
  6197. if (!(c & 0x80)
  6198. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6199. || c == CTLENDVAR
  6200. ) {
  6201. /*
  6202. * c == '=' || c == ':' || c == '\0' ||
  6203. * c == CTLENDARI || c == CTLENDVAR
  6204. */
  6205. length++;
  6206. /* c == '\0' || c == CTLENDARI || c == CTLENDVAR */
  6207. end = !!((c - 1) & 0x80);
  6208. }
  6209. if (length > 0 && !(flag & EXP_DISCARD)) {
  6210. int newloc;
  6211. char *q;
  6212. q = stnputs(p, length, expdest);
  6213. q[-1] &= end - 1;
  6214. expdest = q - (flag & EXP_WORD ? end : 0);
  6215. newloc = q - (char *)stackblock() - end;
  6216. if (breakall && !inquotes && newloc > startloc) {
  6217. recordregion(startloc, newloc, 0);
  6218. }
  6219. startloc = newloc;
  6220. }
  6221. p += length + 1;
  6222. length = 0;
  6223. if (end)
  6224. break;
  6225. switch (c) {
  6226. case '=':
  6227. flag |= EXP_VARTILDE2;
  6228. reject++;
  6229. /* fall through */
  6230. case ':':
  6231. /*
  6232. * sort of a hack - expand tildes in variable
  6233. * assignments (after the first '=' and after ':'s).
  6234. */
  6235. if (*--p == '~') {
  6236. goto tilde;
  6237. }
  6238. continue;
  6239. case CTLQUOTEMARK:
  6240. /* "$@" syntax adherence hack */
  6241. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6242. p = evalvar(p + 1, flag | EXP_QUOTED) + 1;
  6243. goto start;
  6244. }
  6245. inquotes ^= EXP_QUOTED;
  6246. addquote:
  6247. if (flag & QUOTES_ESC) {
  6248. p--;
  6249. length++;
  6250. startloc++;
  6251. }
  6252. break;
  6253. case CTLESC:
  6254. startloc++;
  6255. length++;
  6256. goto addquote;
  6257. case CTLVAR:
  6258. TRACE(("argstr: evalvar('%s')\n", p));
  6259. p = evalvar(p, flag | inquotes);
  6260. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6261. goto start;
  6262. #if BASH_PROCESS_SUBST
  6263. case CTLTOPROC:
  6264. case CTLFROMPROC:
  6265. #endif
  6266. case CTLBACKQ:
  6267. expbackq(argbackq->n, flag | inquotes IF_BASH_PROCESS_SUBST(, c));
  6268. goto start;
  6269. #if ENABLE_FEATURE_SH_MATH
  6270. case CTLARI:
  6271. p = expari(p, flag | inquotes);
  6272. goto start;
  6273. #endif
  6274. }
  6275. }
  6276. return p - 1;
  6277. }
  6278. static char *
  6279. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6280. char *pattern, int quotes, int zero)
  6281. {
  6282. char *loc, *loc2;
  6283. char c;
  6284. loc = startp;
  6285. loc2 = rmesc;
  6286. do {
  6287. int match;
  6288. const char *s = loc2;
  6289. c = *loc2;
  6290. if (zero) {
  6291. *loc2 = '\0';
  6292. s = rmesc;
  6293. }
  6294. match = pmatch(pattern, s);
  6295. *loc2 = c;
  6296. if (match)
  6297. return loc;
  6298. if (quotes && (unsigned char)*loc == CTLESC)
  6299. loc++;
  6300. loc++;
  6301. loc2++;
  6302. } while (c);
  6303. return NULL;
  6304. }
  6305. static char *
  6306. scanright(char *startp, char *rmesc, char *rmescend,
  6307. char *pattern, int quotes, int match_at_start)
  6308. {
  6309. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6310. int try2optimize = match_at_start;
  6311. #endif
  6312. int esc = 0;
  6313. char *loc;
  6314. char *loc2;
  6315. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6316. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6317. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6318. * Logic:
  6319. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6320. * and on each iteration they go back two/one char until they reach the beginning.
  6321. * We try to match "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6322. * If one of these matches, return pointer past last matched char in startp.
  6323. */
  6324. /* TODO: document in what other circumstances we are called. */
  6325. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6326. int match;
  6327. char c = *loc2;
  6328. const char *s = loc2;
  6329. if (match_at_start) {
  6330. *loc2 = '\0';
  6331. s = rmesc;
  6332. }
  6333. match = pmatch(pattern, s);
  6334. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6335. *loc2 = c;
  6336. if (match)
  6337. return loc;
  6338. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6339. if (try2optimize) {
  6340. /* Maybe we can optimize this:
  6341. * if pattern ends with unescaped *, we can avoid checking
  6342. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6343. * it won't match truncated "raw_value_of_" strings too.
  6344. */
  6345. unsigned plen = strlen(pattern);
  6346. /* Does it end with "*"? */
  6347. if (plen != 0 && pattern[--plen] == '*') {
  6348. /* "xxxx*" is not escaped */
  6349. /* "xxx\*" is escaped */
  6350. /* "xx\\*" is not escaped */
  6351. /* "x\\\*" is escaped */
  6352. int slashes = 0;
  6353. while (plen != 0 && pattern[--plen] == '\\')
  6354. slashes++;
  6355. if (!(slashes & 1))
  6356. break; /* ends with unescaped "*" */
  6357. }
  6358. try2optimize = 0;
  6359. }
  6360. #endif
  6361. loc--;
  6362. if (quotes) {
  6363. if (--esc < 0) {
  6364. esc = esclen(startp, loc);
  6365. }
  6366. if (esc % 2) {
  6367. esc--;
  6368. loc--;
  6369. }
  6370. }
  6371. }
  6372. return NULL;
  6373. }
  6374. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6375. static void
  6376. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6377. {
  6378. const char *msg;
  6379. const char *tail;
  6380. tail = nullstr;
  6381. msg = "parameter not set";
  6382. if (umsg) {
  6383. if ((unsigned char)*end == CTLENDVAR) {
  6384. if (varflags & VSNUL)
  6385. tail = " or null";
  6386. } else {
  6387. msg = umsg;
  6388. }
  6389. }
  6390. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6391. }
  6392. static char *
  6393. subevalvar(char *start, char *str, int strloc,
  6394. int startloc, int varflags, int flag)
  6395. {
  6396. int subtype = varflags & VSTYPE;
  6397. int quotes = flag & QUOTES_ESC;
  6398. char *startp;
  6399. char *loc;
  6400. char *rmesc, *rmescend;
  6401. long amount;
  6402. int resetloc;
  6403. int argstr_flags;
  6404. IF_BASH_PATTERN_SUBST(int workloc;)
  6405. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6406. IF_BASH_PATTERN_SUBST(char *repl;)
  6407. int zero;
  6408. char *(*scan)(char*, char*, char*, char*, int, int);
  6409. char *p;
  6410. //bb_error_msg("subevalvar(start:'%s',str:'%s',strloc:%d,startloc:%d,varflags:%x,quotes:%d)",
  6411. // start, str, strloc, startloc, varflags, quotes);
  6412. #if BASH_PATTERN_SUBST
  6413. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6414. * argstr() call expands possible variable references in pattern:
  6415. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6416. */
  6417. repl = NULL;
  6418. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6419. /* Find '/' and replace with NUL */
  6420. repl = start;
  6421. /* The pattern can't be empty.
  6422. * IOW: if the first char after "${v//" is a slash,
  6423. * it does not terminate the pattern - it's the first char of the pattern:
  6424. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6425. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6426. */
  6427. if (*repl == '/')
  6428. repl++;
  6429. for (;;) {
  6430. if (*repl == '\0') {
  6431. repl = NULL;
  6432. break;
  6433. }
  6434. if (*repl == '/') {
  6435. *repl = '\0';
  6436. break;
  6437. }
  6438. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6439. if ((unsigned char)*repl == CTLESC && repl[1])
  6440. repl++;
  6441. repl++;
  6442. }
  6443. }
  6444. #endif
  6445. argstr_flags = (flag & EXP_DISCARD) | EXP_TILDE;
  6446. if (!str
  6447. #if BASH_SUBSTR
  6448. && subtype != VSSUBSTR
  6449. #endif
  6450. ) {
  6451. /* EXP_CASE keeps CTLESC's */
  6452. argstr_flags |= EXP_CASE;
  6453. }
  6454. p = argstr(start, argstr_flags);
  6455. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6456. #if BASH_PATTERN_SUBST
  6457. slash_pos = -1;
  6458. if (repl) {
  6459. slash_pos = expdest - ((char *)stackblock() + strloc);
  6460. if (!(flag & EXP_DISCARD))
  6461. STPUTC('/', expdest);
  6462. //bb_error_msg("repl+1:'%s'", repl + 1);
  6463. p = argstr(repl + 1, (flag & EXP_DISCARD) | EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6464. *repl = '/';
  6465. }
  6466. #endif
  6467. if (flag & EXP_DISCARD)
  6468. return p;
  6469. startp = (char *)stackblock() + startloc;
  6470. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6471. switch (subtype) {
  6472. case VSASSIGN:
  6473. setvar0(str, startp);
  6474. loc = startp;
  6475. goto out;
  6476. case VSQUESTION:
  6477. varunset(start, str, startp, varflags);
  6478. /* NOTREACHED */
  6479. #if BASH_SUBSTR
  6480. case VSSUBSTR: {
  6481. int pos, len, orig_len;
  6482. char *colon;
  6483. char *vstr;
  6484. loc = vstr = stackblock() + strloc;
  6485. /* Read POS in ${var:POS:LEN} */
  6486. colon = strchr(loc, ':');
  6487. if (colon) *colon = '\0';
  6488. pos = substr_atoi(loc);
  6489. if (colon) *colon = ':';
  6490. /* Read LEN in ${var:POS:LEN} */
  6491. len = vstr - startp - 1;
  6492. /* *loc != '\0', guaranteed by parser */
  6493. if (quotes) {
  6494. char *ptr;
  6495. /* Adjust the length by the number of escapes */
  6496. for (ptr = startp; ptr < (vstr - 1); ptr++) {
  6497. if ((unsigned char)*ptr == CTLESC) {
  6498. len--;
  6499. ptr++;
  6500. }
  6501. }
  6502. }
  6503. orig_len = len;
  6504. if (*loc++ == ':') {
  6505. /* ${var::LEN} */
  6506. len = substr_atoi(loc);
  6507. } else {
  6508. /* Skip POS in ${var:POS:LEN} */
  6509. len = orig_len;
  6510. while (*loc && *loc != ':')
  6511. loc++;
  6512. if (*loc++ == ':')
  6513. len = substr_atoi(loc);
  6514. }
  6515. if (pos < 0) {
  6516. /* ${VAR:$((-n)):l} starts n chars from the end */
  6517. pos = orig_len + pos;
  6518. }
  6519. if ((unsigned)pos >= orig_len) {
  6520. /* apart from obvious ${VAR:999999:l},
  6521. * covers ${VAR:$((-9999999)):l} - result is ""
  6522. * (bash compat)
  6523. */
  6524. pos = 0;
  6525. len = 0;
  6526. }
  6527. if (len < 0) {
  6528. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6529. len = (orig_len - pos) + len;
  6530. }
  6531. if ((unsigned)len > (orig_len - pos))
  6532. len = orig_len - pos;
  6533. if (!quotes) {
  6534. loc = mempcpy(startp, startp + pos, len);
  6535. } else {
  6536. for (vstr = startp; pos != 0; pos--) {
  6537. if ((unsigned char)*vstr == CTLESC)
  6538. vstr++;
  6539. vstr++;
  6540. }
  6541. for (loc = startp; len != 0; len--) {
  6542. if ((unsigned char)*vstr == CTLESC)
  6543. *loc++ = *vstr++;
  6544. *loc++ = *vstr++;
  6545. }
  6546. }
  6547. *loc = '\0';
  6548. goto out;
  6549. }
  6550. #endif /* BASH_SUBSTR */
  6551. }
  6552. resetloc = expdest - (char *)stackblock();
  6553. #if BASH_PATTERN_SUBST
  6554. repl = NULL;
  6555. /* We'll comeback here if we grow the stack while handling
  6556. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6557. * stack will need rebasing, and we'll need to remove our work
  6558. * areas each time
  6559. */
  6560. restart:
  6561. #endif
  6562. amount = expdest - ((char *)stackblock() + resetloc);
  6563. STADJUST(-amount, expdest);
  6564. startp = (char *)stackblock() + startloc;
  6565. rmesc = startp;
  6566. rmescend = (char *)stackblock() + strloc;
  6567. //bb_error_msg("str7:'%s'", rmescend);
  6568. if (quotes) {
  6569. //TODO: how to handle slash_pos here if string changes (shortens?)
  6570. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6571. if (rmesc != startp) {
  6572. rmescend = expdest;
  6573. startp = (char *)stackblock() + startloc;
  6574. }
  6575. }
  6576. rmescend--;
  6577. str = (char *)stackblock() + strloc;
  6578. /*
  6579. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6580. * The result is a_\_z_c (not a\_\_z_c)!
  6581. *
  6582. * The search pattern and replace string treat backslashes differently!
  6583. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6584. * and string. It's only used on the first call.
  6585. */
  6586. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6587. rmescapes(str, RMESCAPE_GLOB,
  6588. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6589. );
  6590. #if BASH_PATTERN_SUBST
  6591. workloc = expdest - (char *)stackblock();
  6592. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6593. size_t no_meta_len, first_escaped;
  6594. int len;
  6595. char *idx, *end;
  6596. if (!repl) {
  6597. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6598. repl = nullstr;
  6599. if (slash_pos >= 0) {
  6600. repl = str + slash_pos;
  6601. *repl++ = '\0';
  6602. }
  6603. }
  6604. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6605. /* If there's no pattern to match, return the expansion unmolested */
  6606. if (str[0] == '\0')
  6607. goto out1;
  6608. first_escaped = (str[0] == '\\' && str[1]);
  6609. /* "first_escaped" trick allows to treat e.g. "\*no_glob_chars"
  6610. * as literal too (as it is semi-common, and easy to accomodate
  6611. * by just using str + 1).
  6612. */
  6613. no_meta_len = strpbrk(str + first_escaped * 2, "*?[\\") ? 0 : strlen(str);
  6614. len = 0;
  6615. idx = startp;
  6616. end = str - 1;
  6617. while (idx <= end) {
  6618. try_to_match:
  6619. if (no_meta_len == 0) {
  6620. /* pattern has meta chars, have to glob */
  6621. loc = scanright(idx, rmesc, rmescend, str, quotes, /*match_at_start:*/ 1);
  6622. } else {
  6623. /* Testcase for very slow replace (performs about 22k replaces):
  6624. * x=::::::::::::::::::::::
  6625. * 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}
  6626. * echo "${x//:/|}"
  6627. * To test "first_escaped" logic, replace : with *.
  6628. */
  6629. if (strncmp(rmesc, str + first_escaped, no_meta_len - first_escaped) != 0)
  6630. goto no_match;
  6631. loc = idx;
  6632. if (!quotes) {
  6633. loc += no_meta_len - first_escaped;
  6634. } else {
  6635. size_t n = no_meta_len - first_escaped;
  6636. do {
  6637. if ((unsigned char)*loc == CTLESC)
  6638. loc++;
  6639. loc++;
  6640. } while (--n != 0);
  6641. }
  6642. }
  6643. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6644. if (!loc) {
  6645. char *restart_detect;
  6646. no_match:
  6647. /* No match, advance */
  6648. restart_detect = stackblock();
  6649. skip_matching:
  6650. if (idx >= end)
  6651. break;
  6652. STPUTC(*idx, expdest);
  6653. if (quotes && (unsigned char)*idx == CTLESC) {
  6654. idx++;
  6655. len++;
  6656. STPUTC(*idx, expdest);
  6657. }
  6658. if (stackblock() != restart_detect)
  6659. goto restart;
  6660. idx++;
  6661. len++;
  6662. rmesc++;
  6663. /* continue; - prone to quadratic behavior, smarter code: */
  6664. if (str[0] == '*') {
  6665. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6666. * it would never match "ong_string" etc, no point in trying.
  6667. */
  6668. goto skip_matching;
  6669. }
  6670. goto try_to_match;
  6671. }
  6672. if (subtype == VSREPLACEALL) {
  6673. while (idx < loc) {
  6674. if (quotes && (unsigned char)*idx == CTLESC)
  6675. idx++;
  6676. idx++;
  6677. rmesc++;
  6678. }
  6679. } else {
  6680. idx = loc;
  6681. }
  6682. //bb_error_msg("repl:'%s'", repl);
  6683. for (loc = (char*)repl; *loc; loc++) {
  6684. char *restart_detect = stackblock();
  6685. if (quotes && *loc == '\\') {
  6686. STPUTC(CTLESC, expdest);
  6687. len++;
  6688. }
  6689. STPUTC(*loc, expdest);
  6690. if (stackblock() != restart_detect)
  6691. goto restart;
  6692. len++;
  6693. }
  6694. if (subtype == VSREPLACE) {
  6695. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6696. while (*idx) {
  6697. char *restart_detect = stackblock();
  6698. STPUTC(*idx, expdest);
  6699. if (stackblock() != restart_detect)
  6700. goto restart;
  6701. len++;
  6702. idx++;
  6703. }
  6704. break;
  6705. }
  6706. }
  6707. /* We've put the replaced text into a buffer at workloc, now
  6708. * move it to the right place and adjust the stack.
  6709. */
  6710. STPUTC('\0', expdest);
  6711. startp = (char *)stackblock() + startloc;
  6712. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6713. //bb_error_msg("startp:'%s'", startp);
  6714. loc = startp + len;
  6715. goto out;
  6716. }
  6717. #endif /* BASH_PATTERN_SUBST */
  6718. subtype -= VSTRIMRIGHT;
  6719. #if DEBUG
  6720. if (subtype < 0 || subtype > 7)
  6721. abort();
  6722. #endif
  6723. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6724. zero = subtype >> 1;
  6725. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6726. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6727. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6728. if (loc) {
  6729. if (zero) {
  6730. memmove(startp, loc, str - loc);
  6731. loc = startp + (str - loc) - 1;
  6732. }
  6733. *loc = '\0';
  6734. } else
  6735. loc = str - 1;
  6736. out:
  6737. amount = loc - expdest;
  6738. STADJUST(amount, expdest);
  6739. #if BASH_PATTERN_SUBST
  6740. out1:
  6741. #endif
  6742. /* Remove any recorded regions beyond start of variable */
  6743. removerecordregions(startloc);
  6744. return p;
  6745. }
  6746. /*
  6747. * Add the value of a specialized variable to the stack string.
  6748. * name parameter (examples):
  6749. * ash -c 'echo $1' name:'1='
  6750. * ash -c 'echo $qwe' name:'qwe='
  6751. * ash -c 'echo $$' name:'$='
  6752. * ash -c 'echo ${$}' name:'$='
  6753. * ash -c 'echo ${$##q}' name:'$=q'
  6754. * ash -c 'echo ${#$}' name:'$='
  6755. * note: examples with bad shell syntax:
  6756. * ash -c 'echo ${#$1}' name:'$=1'
  6757. * ash -c 'echo ${#1#}' name:'1=#'
  6758. */
  6759. static NOINLINE ssize_t
  6760. varvalue(char *name, int varflags, int flags, int quoted)
  6761. {
  6762. const char *p;
  6763. int num;
  6764. int i;
  6765. ssize_t len = 0;
  6766. int sep;
  6767. int subtype = varflags & VSTYPE;
  6768. int discard = (subtype == VSPLUS || subtype == VSLENGTH) | (flags & EXP_DISCARD);
  6769. if (!subtype) {
  6770. if (discard)
  6771. return -1;
  6772. raise_error_syntax("bad substitution");
  6773. }
  6774. flags |= EXP_KEEPNUL;
  6775. flags &= discard ? ~QUOTES_ESC : ~0;
  6776. sep = (flags & EXP_FULL) << CHAR_BIT;
  6777. switch (*name) {
  6778. case '$':
  6779. num = rootpid;
  6780. goto numvar;
  6781. case '?':
  6782. num = exitstatus;
  6783. goto numvar;
  6784. case '#':
  6785. num = shellparam.nparam;
  6786. goto numvar;
  6787. case '!':
  6788. num = backgndpid;
  6789. if (num == 0)
  6790. return -1;
  6791. numvar:
  6792. len = cvtnum(num, flags);
  6793. goto check_1char_name;
  6794. case '-':
  6795. expdest = makestrspace(NOPTS, expdest);
  6796. for (i = NOPTS - 1; i >= 0; i--) {
  6797. if (optlist[i] && optletters(i)) {
  6798. USTPUTC(optletters(i), expdest);
  6799. len++;
  6800. }
  6801. }
  6802. check_1char_name:
  6803. #if 0
  6804. /* handles cases similar to ${#$1} */
  6805. if (name[2] != '\0')
  6806. raise_error_syntax("bad substitution");
  6807. #endif
  6808. break;
  6809. case '@':
  6810. if (quoted && sep)
  6811. goto param;
  6812. /* fall through */
  6813. case '*': {
  6814. char **ap;
  6815. char sepc;
  6816. char c;
  6817. /* We will set c to 0 or ~0 depending on whether
  6818. * we're doing field splitting. We won't do field
  6819. * splitting if either we're quoted or sep is zero.
  6820. *
  6821. * Instead of testing (quoted || !sep) the following
  6822. * trick optimises away any branches by using the
  6823. * fact that EXP_QUOTED (which is the only bit that
  6824. * can be set in quoted) is the same as EXP_FULL <<
  6825. * CHAR_BIT (which is the only bit that can be set
  6826. * in sep).
  6827. */
  6828. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6829. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6830. #endif
  6831. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6832. sep &= ~quoted;
  6833. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6834. param:
  6835. sepc = sep;
  6836. ap = shellparam.p;
  6837. if (!ap)
  6838. return -1;
  6839. while ((p = *ap++) != NULL) {
  6840. len += strtodest(p, flags);
  6841. if (*ap && sep) {
  6842. len++;
  6843. memtodest(&sepc, 1, flags);
  6844. }
  6845. }
  6846. break;
  6847. } /* case '*' */
  6848. case '0':
  6849. case '1':
  6850. case '2':
  6851. case '3':
  6852. case '4':
  6853. case '5':
  6854. case '6':
  6855. case '7':
  6856. case '8':
  6857. case '9':
  6858. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6859. if (num < 0 || num > shellparam.nparam)
  6860. return -1;
  6861. p = num ? shellparam.p[num - 1] : arg0;
  6862. goto value;
  6863. default:
  6864. /* NB: name has form "VAR=..." */
  6865. p = lookupvar(name);
  6866. value:
  6867. if (!p)
  6868. return -1;
  6869. len = strtodest(p, flags);
  6870. #if ENABLE_UNICODE_SUPPORT
  6871. if (subtype == VSLENGTH && len > 0) {
  6872. reinit_unicode_for_ash();
  6873. if (unicode_status == UNICODE_ON) {
  6874. STADJUST(-len, expdest);
  6875. discard = 0;
  6876. len = unicode_strlen(p);
  6877. }
  6878. }
  6879. #endif
  6880. break;
  6881. }
  6882. if (discard)
  6883. STADJUST(-len, expdest);
  6884. return len;
  6885. }
  6886. /*
  6887. * Expand a variable, and return a pointer to the next character in the
  6888. * input string.
  6889. */
  6890. static char *
  6891. evalvar(char *p, int flag)
  6892. {
  6893. char varflags;
  6894. char subtype;
  6895. char *var;
  6896. int patloc;
  6897. int startloc;
  6898. ssize_t varlen;
  6899. int discard;
  6900. int quoted;
  6901. varflags = (unsigned char) *p++;
  6902. subtype = varflags & VSTYPE;
  6903. quoted = flag & EXP_QUOTED;
  6904. var = p;
  6905. startloc = expdest - (char *)stackblock();
  6906. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6907. again:
  6908. varlen = varvalue(var, varflags, flag, quoted);
  6909. if (varflags & VSNUL)
  6910. varlen--;
  6911. discard = varlen < 0 ? EXP_DISCARD : 0;
  6912. switch (subtype) {
  6913. case VSPLUS:
  6914. discard ^= EXP_DISCARD;
  6915. /* fall through */
  6916. case 0:
  6917. case VSMINUS:
  6918. p = argstr(p, flag | EXP_TILDE | EXP_WORD | (discard ^ EXP_DISCARD));
  6919. goto record;
  6920. case VSASSIGN:
  6921. case VSQUESTION:
  6922. p = subevalvar(p, var, 0, startloc, varflags,
  6923. (flag & ~QUOTES_ESC) | (discard ^ EXP_DISCARD));
  6924. if ((flag | ~discard) & EXP_DISCARD)
  6925. goto record;
  6926. varflags &= ~VSNUL;
  6927. subtype = VSNORMAL;
  6928. goto again;
  6929. }
  6930. if ((discard & ~flag) && uflag)
  6931. varunset(p, var, 0, 0);
  6932. if (subtype == VSLENGTH) {
  6933. p++;
  6934. if (flag & EXP_DISCARD)
  6935. return p;
  6936. cvtnum(varlen > 0 ? varlen : 0, flag);
  6937. goto really_record;
  6938. }
  6939. if (subtype == VSNORMAL)
  6940. goto record;
  6941. #if DEBUG
  6942. switch (subtype) {
  6943. case VSTRIMLEFT:
  6944. case VSTRIMLEFTMAX:
  6945. case VSTRIMRIGHT:
  6946. case VSTRIMRIGHTMAX:
  6947. #if BASH_SUBSTR
  6948. case VSSUBSTR:
  6949. #endif
  6950. #if BASH_PATTERN_SUBST
  6951. case VSREPLACE:
  6952. case VSREPLACEALL:
  6953. #endif
  6954. break;
  6955. default:
  6956. abort();
  6957. }
  6958. #endif
  6959. flag |= discard;
  6960. if (!(flag & EXP_DISCARD)) {
  6961. /*
  6962. * Terminate the string and start recording the pattern
  6963. * right after it
  6964. */
  6965. STPUTC('\0', expdest);
  6966. }
  6967. patloc = expdest - (char *)stackblock();
  6968. p = subevalvar(p, NULL, patloc, startloc, varflags, flag);
  6969. record:
  6970. if ((flag | discard) & EXP_DISCARD)
  6971. return p;
  6972. really_record:
  6973. if (quoted) {
  6974. quoted = *var == '@' && shellparam.nparam;
  6975. if (!quoted)
  6976. return p;
  6977. }
  6978. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6979. return p;
  6980. }
  6981. /*
  6982. * Add a file name to the list.
  6983. */
  6984. static void
  6985. addfname(const char *name)
  6986. {
  6987. struct strlist *sp;
  6988. sp = stzalloc(sizeof(*sp));
  6989. sp->text = sstrdup(name);
  6990. *exparg.lastp = sp;
  6991. exparg.lastp = &sp->next;
  6992. }
  6993. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6994. static int
  6995. hasmeta(const char *p)
  6996. {
  6997. static const char chars[] ALIGN1 = {
  6998. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6999. };
  7000. for (;;) {
  7001. p = strpbrk(p, chars);
  7002. if (!p)
  7003. break;
  7004. switch ((unsigned char)*p) {
  7005. case CTLQUOTEMARK:
  7006. for (;;) {
  7007. p++;
  7008. if ((unsigned char)*p == CTLQUOTEMARK)
  7009. break;
  7010. if ((unsigned char)*p == CTLESC)
  7011. p++;
  7012. if (*p == '\0') /* huh? */
  7013. return 0;
  7014. }
  7015. break;
  7016. case '\\':
  7017. case CTLESC:
  7018. p++;
  7019. if (*p == '\0')
  7020. return 0;
  7021. break;
  7022. case '[':
  7023. if (!strchr(p + 1, ']')) {
  7024. /* It's not a properly closed [] pattern,
  7025. * but other metas may follow. Continue checking.
  7026. * my[file* _is_ globbed by bash
  7027. * and matches filenames like "my[file1".
  7028. */
  7029. break;
  7030. }
  7031. /* fallthrough */
  7032. default:
  7033. /* case '*': */
  7034. /* case '?': */
  7035. return 1;
  7036. }
  7037. p++;
  7038. }
  7039. return 0;
  7040. }
  7041. /* If we want to use glob() from libc... */
  7042. #if !ENABLE_ASH_INTERNAL_GLOB
  7043. /* Add the result of glob() to the list */
  7044. static void
  7045. addglob(const glob_t *pglob)
  7046. {
  7047. char **p = pglob->gl_pathv;
  7048. do {
  7049. addfname(*p);
  7050. } while (*++p);
  7051. }
  7052. static void
  7053. expandmeta(struct strlist *str /*, int flag*/)
  7054. {
  7055. /* TODO - EXP_REDIR */
  7056. while (str) {
  7057. char *p;
  7058. glob_t pglob;
  7059. int i;
  7060. if (fflag)
  7061. goto nometa;
  7062. if (!hasmeta(str->text))
  7063. goto nometa;
  7064. INT_OFF;
  7065. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7066. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  7067. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  7068. //
  7069. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  7070. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  7071. // Which means you need to unescape the string, right? Not so fast:
  7072. // if there _is_ a file named "file\?" (with backslash), it is returned
  7073. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  7074. // You DON'T KNOW by looking at the result whether you need to unescape it.
  7075. //
  7076. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  7077. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  7078. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  7079. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  7080. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  7081. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  7082. i = glob(p, 0, NULL, &pglob);
  7083. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  7084. if (p != str->text)
  7085. free(p);
  7086. switch (i) {
  7087. case 0:
  7088. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  7089. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  7090. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  7091. goto nometa2;
  7092. #endif
  7093. addglob(&pglob);
  7094. globfree(&pglob);
  7095. INT_ON;
  7096. break;
  7097. case GLOB_NOMATCH:
  7098. //nometa2:
  7099. globfree(&pglob);
  7100. INT_ON;
  7101. nometa:
  7102. *exparg.lastp = str;
  7103. rmescapes(str->text, 0, NULL);
  7104. exparg.lastp = &str->next;
  7105. break;
  7106. default: /* GLOB_NOSPACE */
  7107. globfree(&pglob);
  7108. INT_ON;
  7109. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  7110. }
  7111. str = str->next;
  7112. }
  7113. }
  7114. #else
  7115. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  7116. /*
  7117. * Do metacharacter (i.e. *, ?, [...]) expansion.
  7118. */
  7119. typedef struct exp_t {
  7120. char *dir;
  7121. unsigned dir_max;
  7122. } exp_t;
  7123. static void
  7124. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  7125. {
  7126. #define expdir exp->dir
  7127. #define expdir_max exp->dir_max
  7128. char *enddir = expdir + expdir_len;
  7129. char *p;
  7130. const char *cp;
  7131. char *start;
  7132. char *endname;
  7133. int metaflag;
  7134. struct stat statb;
  7135. DIR *dirp;
  7136. struct dirent *dp;
  7137. int atend;
  7138. int matchdot;
  7139. int esc;
  7140. metaflag = 0;
  7141. start = name;
  7142. for (p = name; esc = 0, *p; p += esc + 1) {
  7143. if (*p == '*' || *p == '?')
  7144. metaflag = 1;
  7145. else if (*p == '[') {
  7146. char *q = p + 1;
  7147. if (*q == '!')
  7148. q++;
  7149. for (;;) {
  7150. if (*q == '\\')
  7151. q++;
  7152. if (*q == '/' || *q == '\0')
  7153. break;
  7154. if (*++q == ']') {
  7155. metaflag = 1;
  7156. break;
  7157. }
  7158. }
  7159. } else {
  7160. if (*p == '\\' && p[1])
  7161. esc++;
  7162. if (p[esc] == '/') {
  7163. if (metaflag)
  7164. break;
  7165. start = p + esc + 1;
  7166. }
  7167. }
  7168. }
  7169. if (metaflag == 0) { /* we've reached the end of the file name */
  7170. if (!expdir_len)
  7171. return;
  7172. p = name;
  7173. do {
  7174. if (*p == '\\' && p[1])
  7175. p++;
  7176. *enddir++ = *p;
  7177. } while (*p++);
  7178. if (lstat(expdir, &statb) == 0)
  7179. addfname(expdir);
  7180. return;
  7181. }
  7182. endname = p;
  7183. if (name < start) {
  7184. p = name;
  7185. do {
  7186. if (*p == '\\' && p[1])
  7187. p++;
  7188. *enddir++ = *p++;
  7189. } while (p < start);
  7190. }
  7191. *enddir = '\0';
  7192. cp = expdir;
  7193. expdir_len = enddir - cp;
  7194. if (!expdir_len)
  7195. cp = ".";
  7196. dirp = opendir(cp);
  7197. if (dirp == NULL)
  7198. return;
  7199. if (*endname == 0) {
  7200. atend = 1;
  7201. } else {
  7202. atend = 0;
  7203. *endname = '\0';
  7204. endname += esc + 1;
  7205. }
  7206. name_len -= endname - name;
  7207. matchdot = 0;
  7208. p = start;
  7209. if (*p == '\\')
  7210. p++;
  7211. if (*p == '.')
  7212. matchdot++;
  7213. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7214. if (dp->d_name[0] == '.' && !matchdot)
  7215. continue;
  7216. if (pmatch(start, dp->d_name)) {
  7217. if (atend) {
  7218. strcpy(enddir, dp->d_name);
  7219. addfname(expdir);
  7220. } else {
  7221. unsigned offset;
  7222. unsigned len;
  7223. p = stpcpy(enddir, dp->d_name);
  7224. *p = '/';
  7225. offset = p - expdir + 1;
  7226. len = offset + name_len + NAME_MAX;
  7227. if (len > expdir_max) {
  7228. len += PATH_MAX;
  7229. expdir = ckrealloc(expdir, len);
  7230. expdir_max = len;
  7231. }
  7232. expmeta(exp, endname, name_len, offset);
  7233. enddir = expdir + expdir_len;
  7234. }
  7235. }
  7236. }
  7237. closedir(dirp);
  7238. if (!atend)
  7239. endname[-esc - 1] = esc ? '\\' : '/';
  7240. #undef expdir
  7241. #undef expdir_max
  7242. }
  7243. static struct strlist *
  7244. msort(struct strlist *list, int len)
  7245. {
  7246. struct strlist *p, *q = NULL;
  7247. struct strlist **lpp;
  7248. int half;
  7249. int n;
  7250. if (len <= 1)
  7251. return list;
  7252. half = len >> 1;
  7253. p = list;
  7254. for (n = half; --n >= 0;) {
  7255. q = p;
  7256. p = p->next;
  7257. }
  7258. q->next = NULL; /* terminate first half of list */
  7259. q = msort(list, half); /* sort first half of list */
  7260. p = msort(p, len - half); /* sort second half */
  7261. lpp = &list;
  7262. for (;;) {
  7263. #if ENABLE_LOCALE_SUPPORT
  7264. if (strcoll(p->text, q->text) < 0)
  7265. #else
  7266. if (strcmp(p->text, q->text) < 0)
  7267. #endif
  7268. {
  7269. *lpp = p;
  7270. lpp = &p->next;
  7271. p = *lpp;
  7272. if (p == NULL) {
  7273. *lpp = q;
  7274. break;
  7275. }
  7276. } else {
  7277. *lpp = q;
  7278. lpp = &q->next;
  7279. q = *lpp;
  7280. if (q == NULL) {
  7281. *lpp = p;
  7282. break;
  7283. }
  7284. }
  7285. }
  7286. return list;
  7287. }
  7288. /*
  7289. * Sort the results of file name expansion. It calculates the number of
  7290. * strings to sort and then calls msort (short for merge sort) to do the
  7291. * work.
  7292. */
  7293. static struct strlist *
  7294. expsort(struct strlist *str)
  7295. {
  7296. int len;
  7297. struct strlist *sp;
  7298. len = 0;
  7299. for (sp = str; sp; sp = sp->next)
  7300. len++;
  7301. return msort(str, len);
  7302. }
  7303. static void
  7304. expandmeta(struct strlist *str /*, int flag*/)
  7305. {
  7306. /* TODO - EXP_REDIR */
  7307. while (str) {
  7308. exp_t exp;
  7309. struct strlist **savelastp;
  7310. struct strlist *sp;
  7311. char *p;
  7312. unsigned len;
  7313. if (fflag)
  7314. goto nometa;
  7315. if (!hasmeta(str->text))
  7316. goto nometa;
  7317. savelastp = exparg.lastp;
  7318. INT_OFF;
  7319. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7320. len = strlen(p);
  7321. exp.dir_max = len + PATH_MAX;
  7322. exp.dir = ckmalloc(exp.dir_max);
  7323. expmeta(&exp, p, len, 0);
  7324. free(exp.dir);
  7325. if (p != str->text)
  7326. free(p);
  7327. INT_ON;
  7328. if (exparg.lastp == savelastp) {
  7329. /*
  7330. * no matches
  7331. */
  7332. nometa:
  7333. *exparg.lastp = str;
  7334. rmescapes(str->text, 0, NULL);
  7335. exparg.lastp = &str->next;
  7336. } else {
  7337. *exparg.lastp = NULL;
  7338. *savelastp = sp = expsort(*savelastp);
  7339. while (sp->next != NULL)
  7340. sp = sp->next;
  7341. exparg.lastp = &sp->next;
  7342. }
  7343. str = str->next;
  7344. }
  7345. }
  7346. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7347. /*
  7348. * Perform variable substitution and command substitution on an argument,
  7349. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7350. * perform splitting and file name expansion. When arglist is NULL, perform
  7351. * here document expansion.
  7352. */
  7353. static void
  7354. expandarg(union node *arg, struct arglist *arglist, int flag)
  7355. {
  7356. struct strlist *sp;
  7357. char *p;
  7358. argbackq = arg->narg.backquote;
  7359. STARTSTACKSTR(expdest);
  7360. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7361. argstr(arg->narg.text, flag);
  7362. if (arglist == NULL) {
  7363. /* here document expanded */
  7364. goto out;
  7365. }
  7366. p = grabstackstr(expdest);
  7367. TRACE(("expandarg: p:'%s'\n", p));
  7368. exparg.lastp = &exparg.list;
  7369. /*
  7370. * TODO - EXP_REDIR
  7371. */
  7372. if (flag & EXP_FULL) {
  7373. ifsbreakup(p, &exparg);
  7374. *exparg.lastp = NULL;
  7375. exparg.lastp = &exparg.list;
  7376. expandmeta(exparg.list /*, flag*/);
  7377. } else {
  7378. sp = stzalloc(sizeof(*sp));
  7379. sp->text = p;
  7380. *exparg.lastp = sp;
  7381. exparg.lastp = &sp->next;
  7382. }
  7383. *exparg.lastp = NULL;
  7384. if (exparg.list) {
  7385. *arglist->lastp = exparg.list;
  7386. arglist->lastp = exparg.lastp;
  7387. }
  7388. out:
  7389. ifsfree();
  7390. }
  7391. /*
  7392. * Expand shell variables and backquotes inside a here document.
  7393. */
  7394. static void
  7395. expandhere(union node *arg)
  7396. {
  7397. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7398. }
  7399. /*
  7400. * Returns true if the pattern matches the string.
  7401. */
  7402. static int
  7403. patmatch(char *pattern, const char *string)
  7404. {
  7405. char *p = preglob(pattern, 0);
  7406. int r = pmatch(p, string);
  7407. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7408. return r;
  7409. }
  7410. /*
  7411. * See if a pattern matches in a case statement.
  7412. */
  7413. static int
  7414. casematch(union node *pattern, char *val)
  7415. {
  7416. struct stackmark smark;
  7417. int result;
  7418. setstackmark(&smark);
  7419. argbackq = pattern->narg.backquote;
  7420. STARTSTACKSTR(expdest);
  7421. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7422. ifsfree();
  7423. result = patmatch(stackblock(), val);
  7424. popstackmark(&smark);
  7425. return result;
  7426. }
  7427. /* ============ find_command */
  7428. struct builtincmd {
  7429. const char *name;
  7430. int (*builtin)(int, char **) FAST_FUNC;
  7431. /* unsigned flags; */
  7432. };
  7433. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7434. /* "regular" builtins always take precedence over commands,
  7435. * regardless of PATH=....%builtin... position */
  7436. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7437. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7438. struct cmdentry {
  7439. smallint cmdtype; /* CMDxxx */
  7440. union param {
  7441. int index;
  7442. /* index >= 0 for commands without path (slashes) */
  7443. /* (TODO: what exactly does the value mean? PATH position?) */
  7444. /* index == -1 for commands with slashes */
  7445. /* index == (-2 - applet_no) for NOFORK applets */
  7446. const struct builtincmd *cmd;
  7447. struct funcnode *func;
  7448. } u;
  7449. };
  7450. /* values of cmdtype */
  7451. #define CMDUNKNOWN -1 /* no entry in table for command */
  7452. #define CMDNORMAL 0 /* command is an executable program */
  7453. #define CMDFUNCTION 1 /* command is a shell function */
  7454. #define CMDBUILTIN 2 /* command is a shell builtin */
  7455. /* action to find_command() */
  7456. #define DO_ERR 0x01 /* prints errors */
  7457. #define DO_ABS 0x02 /* checks absolute paths */
  7458. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7459. #define DO_ALTPATH 0x08 /* using alternate path */
  7460. #define DO_REGBLTIN 0x10 /* regular built-ins and functions only */
  7461. static void find_command(char *, struct cmdentry *, int, const char *);
  7462. /* ============ Hashing commands */
  7463. /*
  7464. * When commands are first encountered, they are entered in a hash table.
  7465. * This ensures that a full path search will not have to be done for them
  7466. * on each invocation.
  7467. *
  7468. * We should investigate converting to a linear search, even though that
  7469. * would make the command name "hash" a misnomer.
  7470. */
  7471. struct tblentry {
  7472. struct tblentry *next; /* next entry in hash chain */
  7473. union param param; /* definition of builtin function */
  7474. smallint cmdtype; /* CMDxxx */
  7475. char rehash; /* if set, cd done since entry created */
  7476. char cmdname[1]; /* name of command */
  7477. };
  7478. static struct tblentry **cmdtable;
  7479. #define INIT_G_cmdtable() do { \
  7480. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7481. } while (0)
  7482. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7483. static void
  7484. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7485. {
  7486. #if ENABLE_FEATURE_SH_STANDALONE
  7487. if (applet_no >= 0) {
  7488. if (APPLET_IS_NOEXEC(applet_no)) {
  7489. clearenv();
  7490. while (*envp)
  7491. putenv(*envp++);
  7492. popredir(/*drop:*/ 1);
  7493. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7494. }
  7495. /* re-exec ourselves with the new arguments */
  7496. execve(bb_busybox_exec_path, argv, envp);
  7497. /* If they called chroot or otherwise made the binary no longer
  7498. * executable, fall through */
  7499. }
  7500. #endif
  7501. repeat:
  7502. #ifdef SYSV
  7503. do {
  7504. execve(cmd, argv, envp);
  7505. } while (errno == EINTR);
  7506. #else
  7507. execve(cmd, argv, envp);
  7508. #endif
  7509. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7510. /* Run "cmd" as a shell script:
  7511. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7512. * "If the execve() function fails with ENOEXEC, the shell
  7513. * shall execute a command equivalent to having a shell invoked
  7514. * with the command name as its first operand,
  7515. * with any remaining arguments passed to the new shell"
  7516. *
  7517. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7518. * just call ourselves.
  7519. *
  7520. * Note that bash reads ~80 chars of the file, and if it sees
  7521. * a zero byte before it sees newline, it doesn't try to
  7522. * interpret it, but fails with "cannot execute binary file"
  7523. * message and exit code 126. For one, this prevents attempts
  7524. * to interpret foreign ELF binaries as shell scripts.
  7525. */
  7526. argv[0] = (char*) cmd;
  7527. cmd = bb_busybox_exec_path;
  7528. /* NB: this is only possible because all callers of shellexec()
  7529. * ensure that the argv[-1] slot exists!
  7530. */
  7531. argv--;
  7532. argv[0] = (char*) "ash";
  7533. goto repeat;
  7534. }
  7535. }
  7536. /*
  7537. * Exec a program. Never returns. If you change this routine, you may
  7538. * have to change the find_command routine as well.
  7539. * argv[-1] must exist and be writable! See tryexec() for why.
  7540. */
  7541. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7542. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7543. {
  7544. char *cmdname;
  7545. int e;
  7546. char **envp;
  7547. int exerrno;
  7548. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7549. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7550. if (strchr(prog, '/') != NULL
  7551. #if ENABLE_FEATURE_SH_STANDALONE
  7552. || (applet_no = find_applet_by_name(prog)) >= 0
  7553. #endif
  7554. ) {
  7555. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7556. if (applet_no >= 0) {
  7557. /* We tried execing ourself, but it didn't work.
  7558. * Maybe /proc/self/exe doesn't exist?
  7559. * Try $PATH search.
  7560. */
  7561. goto try_PATH;
  7562. }
  7563. e = errno;
  7564. } else {
  7565. try_PATH:
  7566. e = ENOENT;
  7567. while (padvance(&path, argv[0]) >= 0) {
  7568. cmdname = stackblock();
  7569. if (--idx < 0 && pathopt == NULL) {
  7570. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7571. if (errno != ENOENT && errno != ENOTDIR)
  7572. e = errno;
  7573. }
  7574. }
  7575. }
  7576. /* Map to POSIX errors */
  7577. switch (e) {
  7578. default:
  7579. exerrno = 126;
  7580. break;
  7581. case ELOOP:
  7582. case ENAMETOOLONG:
  7583. case ENOENT:
  7584. case ENOTDIR:
  7585. exerrno = 127;
  7586. break;
  7587. }
  7588. exitstatus = exerrno;
  7589. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7590. prog, e, suppress_int));
  7591. ash_msg_and_raise(EXEND, "%s: %s", prog, errmsg(e, "not found"));
  7592. /* NOTREACHED */
  7593. }
  7594. static void
  7595. printentry(struct tblentry *cmdp)
  7596. {
  7597. int idx;
  7598. const char *path;
  7599. char *name;
  7600. idx = cmdp->param.index;
  7601. path = pathval();
  7602. do {
  7603. padvance(&path, cmdp->cmdname);
  7604. } while (--idx >= 0);
  7605. name = stackblock();
  7606. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7607. }
  7608. /*
  7609. * Clear out command entries.
  7610. */
  7611. static void
  7612. clearcmdentry(void)
  7613. {
  7614. struct tblentry **tblp;
  7615. struct tblentry **pp;
  7616. struct tblentry *cmdp;
  7617. INT_OFF;
  7618. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7619. pp = tblp;
  7620. while ((cmdp = *pp) != NULL) {
  7621. if (cmdp->cmdtype == CMDNORMAL
  7622. || (cmdp->cmdtype == CMDBUILTIN
  7623. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7624. && builtinloc > 0
  7625. )
  7626. ) {
  7627. *pp = cmdp->next;
  7628. free(cmdp);
  7629. } else {
  7630. pp = &cmdp->next;
  7631. }
  7632. }
  7633. }
  7634. INT_ON;
  7635. }
  7636. /*
  7637. * Locate a command in the command hash table. If "add" is nonzero,
  7638. * add the command to the table if it is not already present. The
  7639. * variable "lastcmdentry" is set to point to the address of the link
  7640. * pointing to the entry, so that delete_cmd_entry can delete the
  7641. * entry.
  7642. *
  7643. * Interrupts must be off if called with add != 0.
  7644. */
  7645. static struct tblentry **lastcmdentry;
  7646. static struct tblentry *
  7647. cmdlookup(const char *name, int add)
  7648. {
  7649. unsigned int hashval;
  7650. const char *p;
  7651. struct tblentry *cmdp;
  7652. struct tblentry **pp;
  7653. p = name;
  7654. hashval = (unsigned char)*p << 4;
  7655. while (*p)
  7656. hashval += (unsigned char)*p++;
  7657. hashval &= 0x7FFF;
  7658. pp = &cmdtable[hashval % CMDTABLESIZE];
  7659. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7660. if (strcmp(cmdp->cmdname, name) == 0)
  7661. break;
  7662. pp = &cmdp->next;
  7663. }
  7664. if (add && cmdp == NULL) {
  7665. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7666. + strlen(name)
  7667. /* + 1 - already done because
  7668. * tblentry::cmdname is char[1] */);
  7669. /*cmdp->next = NULL; - ckzalloc did it */
  7670. cmdp->cmdtype = CMDUNKNOWN;
  7671. strcpy(cmdp->cmdname, name);
  7672. }
  7673. lastcmdentry = pp;
  7674. return cmdp;
  7675. }
  7676. /*
  7677. * Delete the command entry returned on the last lookup.
  7678. */
  7679. static void
  7680. delete_cmd_entry(void)
  7681. {
  7682. struct tblentry *cmdp;
  7683. INT_OFF;
  7684. cmdp = *lastcmdentry;
  7685. *lastcmdentry = cmdp->next;
  7686. if (cmdp->cmdtype == CMDFUNCTION)
  7687. freefunc(cmdp->param.func);
  7688. free(cmdp);
  7689. INT_ON;
  7690. }
  7691. /*
  7692. * Add a new command entry, replacing any existing command entry for
  7693. * the same name - except special builtins.
  7694. */
  7695. static void
  7696. addcmdentry(char *name, struct cmdentry *entry)
  7697. {
  7698. struct tblentry *cmdp;
  7699. cmdp = cmdlookup(name, 1);
  7700. if (cmdp->cmdtype == CMDFUNCTION) {
  7701. freefunc(cmdp->param.func);
  7702. }
  7703. cmdp->cmdtype = entry->cmdtype;
  7704. cmdp->param = entry->u;
  7705. cmdp->rehash = 0;
  7706. }
  7707. static int FAST_FUNC
  7708. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7709. {
  7710. struct tblentry **pp;
  7711. struct tblentry *cmdp;
  7712. int c;
  7713. struct cmdentry entry;
  7714. char *name;
  7715. if (nextopt("r") != '\0') {
  7716. clearcmdentry();
  7717. return 0;
  7718. }
  7719. if (*argptr == NULL) {
  7720. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7721. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7722. if (cmdp->cmdtype == CMDNORMAL)
  7723. printentry(cmdp);
  7724. }
  7725. }
  7726. return 0;
  7727. }
  7728. c = 0;
  7729. while ((name = *argptr) != NULL) {
  7730. cmdp = cmdlookup(name, 0);
  7731. if (cmdp != NULL
  7732. && (cmdp->cmdtype == CMDNORMAL
  7733. || (cmdp->cmdtype == CMDBUILTIN
  7734. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7735. && builtinloc > 0
  7736. )
  7737. )
  7738. ) {
  7739. delete_cmd_entry();
  7740. }
  7741. find_command(name, &entry, DO_ERR, pathval());
  7742. if (entry.cmdtype == CMDUNKNOWN)
  7743. c = 1;
  7744. argptr++;
  7745. }
  7746. return c;
  7747. }
  7748. /*
  7749. * Called when a cd is done. Marks all commands so the next time they
  7750. * are executed they will be rehashed.
  7751. */
  7752. static void
  7753. hashcd(void)
  7754. {
  7755. struct tblentry **pp;
  7756. struct tblentry *cmdp;
  7757. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7758. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7759. if (cmdp->cmdtype == CMDNORMAL
  7760. || (cmdp->cmdtype == CMDBUILTIN
  7761. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7762. && builtinloc > 0)
  7763. ) {
  7764. cmdp->rehash = 1;
  7765. }
  7766. }
  7767. }
  7768. }
  7769. /*
  7770. * Fix command hash table when PATH changed.
  7771. * Called before PATH is changed. The argument is the new value of PATH;
  7772. * pathval() still returns the old value at this point.
  7773. * Called with interrupts off.
  7774. */
  7775. static void FAST_FUNC
  7776. changepath(const char *newval)
  7777. {
  7778. const char *new;
  7779. int idx;
  7780. int bltin;
  7781. new = newval;
  7782. idx = 0;
  7783. bltin = -1;
  7784. for (;;) {
  7785. if (*new == '%' && prefix(new + 1, "builtin")) {
  7786. bltin = idx;
  7787. break;
  7788. }
  7789. new = strchr(new, ':');
  7790. if (!new)
  7791. break;
  7792. idx++;
  7793. new++;
  7794. }
  7795. builtinloc = bltin;
  7796. clearcmdentry();
  7797. }
  7798. enum {
  7799. TEOF,
  7800. TNL,
  7801. TREDIR,
  7802. TWORD,
  7803. TSEMI,
  7804. TBACKGND,
  7805. TAND,
  7806. TOR,
  7807. TPIPE,
  7808. TLP,
  7809. TRP,
  7810. TENDCASE,
  7811. TENDBQUOTE,
  7812. TNOT,
  7813. TCASE,
  7814. TDO,
  7815. TDONE,
  7816. TELIF,
  7817. TELSE,
  7818. TESAC,
  7819. TFI,
  7820. TFOR,
  7821. #if BASH_FUNCTION
  7822. TFUNCTION,
  7823. #endif
  7824. TIF,
  7825. TIN,
  7826. TTHEN,
  7827. TUNTIL,
  7828. TWHILE,
  7829. TBEGIN,
  7830. TEND
  7831. };
  7832. typedef smallint token_id_t;
  7833. /* Nth bit indicates if token marks the end of a list */
  7834. enum {
  7835. tokendlist = 0
  7836. /* 0 */ | (1u << TEOF)
  7837. /* 1 */ | (0u << TNL)
  7838. /* 2 */ | (0u << TREDIR)
  7839. /* 3 */ | (0u << TWORD)
  7840. /* 4 */ | (0u << TSEMI)
  7841. /* 5 */ | (0u << TBACKGND)
  7842. /* 6 */ | (0u << TAND)
  7843. /* 7 */ | (0u << TOR)
  7844. /* 8 */ | (0u << TPIPE)
  7845. /* 9 */ | (0u << TLP)
  7846. /* 10 */ | (1u << TRP)
  7847. /* 11 */ | (1u << TENDCASE)
  7848. /* 12 */ | (1u << TENDBQUOTE)
  7849. /* 13 */ | (0u << TNOT)
  7850. /* 14 */ | (0u << TCASE)
  7851. /* 15 */ | (1u << TDO)
  7852. /* 16 */ | (1u << TDONE)
  7853. /* 17 */ | (1u << TELIF)
  7854. /* 18 */ | (1u << TELSE)
  7855. /* 19 */ | (1u << TESAC)
  7856. /* 20 */ | (1u << TFI)
  7857. /* 21 */ | (0u << TFOR)
  7858. #if BASH_FUNCTION
  7859. /* 22 */ | (0u << TFUNCTION)
  7860. #endif
  7861. /* 23 */ | (0u << TIF)
  7862. /* 24 */ | (0u << TIN)
  7863. /* 25 */ | (1u << TTHEN)
  7864. /* 26 */ | (0u << TUNTIL)
  7865. /* 27 */ | (0u << TWHILE)
  7866. /* 28 */ | (0u << TBEGIN)
  7867. /* 29 */ | (1u << TEND)
  7868. , /* thus far 29 bits used */
  7869. };
  7870. static const char *const tokname_array[] ALIGN_PTR = {
  7871. "end of file",
  7872. "newline",
  7873. "redirection",
  7874. "word",
  7875. ";",
  7876. "&",
  7877. "&&",
  7878. "||",
  7879. "|",
  7880. "(",
  7881. ")",
  7882. ";;",
  7883. "`",
  7884. #define KWDOFFSET 13
  7885. /* the following are keywords */
  7886. "!",
  7887. "case",
  7888. "do",
  7889. "done",
  7890. "elif",
  7891. "else",
  7892. "esac",
  7893. "fi",
  7894. "for",
  7895. #if BASH_FUNCTION
  7896. "function",
  7897. #endif
  7898. "if",
  7899. "in",
  7900. "then",
  7901. "until",
  7902. "while",
  7903. "{",
  7904. "}",
  7905. };
  7906. /* Wrapper around strcmp for qsort/bsearch/... */
  7907. static int
  7908. pstrcmp(const void *a, const void *b)
  7909. {
  7910. return strcmp((char*)a, *(char**)b);
  7911. }
  7912. static const char *const *
  7913. findkwd(const char *s)
  7914. {
  7915. return bsearch(s, tokname_array + KWDOFFSET,
  7916. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7917. sizeof(tokname_array[0]), pstrcmp);
  7918. }
  7919. /*
  7920. * Locate and print what a word is...
  7921. */
  7922. static int
  7923. describe_command(char *command, const char *path, int describe_command_verbose)
  7924. {
  7925. struct cmdentry entry;
  7926. #if ENABLE_ASH_ALIAS
  7927. const struct alias *ap;
  7928. #endif
  7929. path = path ? path : pathval();
  7930. if (describe_command_verbose) {
  7931. out1str(command);
  7932. }
  7933. /* First look at the keywords */
  7934. if (findkwd(command)) {
  7935. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7936. goto out;
  7937. }
  7938. #if ENABLE_ASH_ALIAS
  7939. /* Then look at the aliases */
  7940. ap = lookupalias(command, 0);
  7941. if (ap != NULL) {
  7942. if (!describe_command_verbose) {
  7943. out1str("alias ");
  7944. printalias(ap);
  7945. return 0;
  7946. }
  7947. out1fmt(" is an alias for %s", ap->val);
  7948. goto out;
  7949. }
  7950. #endif
  7951. /* Brute force */
  7952. find_command(command, &entry, DO_ABS, path);
  7953. switch (entry.cmdtype) {
  7954. case CMDNORMAL: {
  7955. int j = entry.u.index;
  7956. char *p;
  7957. if (j < 0) {
  7958. p = command;
  7959. } else {
  7960. do {
  7961. padvance(&path, command);
  7962. } while (--j >= 0);
  7963. p = stackblock();
  7964. }
  7965. if (describe_command_verbose) {
  7966. out1fmt(" is %s", p);
  7967. } else {
  7968. out1str(p);
  7969. }
  7970. break;
  7971. }
  7972. case CMDFUNCTION:
  7973. if (describe_command_verbose) {
  7974. /*out1str(" is a shell function");*/
  7975. out1str(" is a function"); /* bash says this */
  7976. } else {
  7977. out1str(command);
  7978. }
  7979. break;
  7980. case CMDBUILTIN:
  7981. if (describe_command_verbose) {
  7982. out1fmt(" is a %sshell builtin",
  7983. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7984. "special " : nullstr
  7985. );
  7986. } else {
  7987. out1str(command);
  7988. }
  7989. break;
  7990. default:
  7991. if (describe_command_verbose) {
  7992. out1str(": not found\n");
  7993. }
  7994. return 127;
  7995. }
  7996. out:
  7997. out1str("\n");
  7998. return 0;
  7999. }
  8000. static int FAST_FUNC
  8001. typecmd(int argc UNUSED_PARAM, char **argv)
  8002. {
  8003. int i = 1;
  8004. int err = 0;
  8005. int verbose = 1;
  8006. /* type -p ... ? (we don't bother checking for 'p') */
  8007. if (argv[1] && argv[1][0] == '-') {
  8008. i++;
  8009. verbose = 0;
  8010. }
  8011. while (argv[i]) {
  8012. err |= describe_command(argv[i++], NULL, verbose);
  8013. }
  8014. return err;
  8015. }
  8016. static struct strlist *
  8017. fill_arglist(struct arglist *arglist, union node **argpp)
  8018. {
  8019. struct strlist **lastp = arglist->lastp;
  8020. union node *argp;
  8021. while ((argp = *argpp) != NULL) {
  8022. expandarg(argp, arglist, EXP_FULL | EXP_TILDE);
  8023. *argpp = argp->narg.next;
  8024. if (*lastp)
  8025. break;
  8026. }
  8027. return *lastp;
  8028. }
  8029. #if ENABLE_ASH_CMDCMD
  8030. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  8031. static int
  8032. parse_command_args(struct arglist *arglist, union node **argpp, const char **path)
  8033. {
  8034. struct strlist *sp = arglist->list;
  8035. char *cp, c;
  8036. for (;;) {
  8037. sp = sp->next ? sp->next : fill_arglist(arglist, argpp);
  8038. if (!sp)
  8039. return 0;
  8040. cp = sp->text;
  8041. if (*cp++ != '-')
  8042. break;
  8043. c = *cp++;
  8044. if (!c)
  8045. break;
  8046. if (c == '-' && !*cp) {
  8047. if (!sp->next && !fill_arglist(arglist, argpp))
  8048. return 0;
  8049. sp = sp->next;
  8050. break;
  8051. }
  8052. do {
  8053. switch (c) {
  8054. case 'p':
  8055. *path = bb_default_path;
  8056. break;
  8057. default:
  8058. /* run 'typecmd' for other options */
  8059. return 0;
  8060. }
  8061. c = *cp++;
  8062. } while (c);
  8063. }
  8064. arglist->list = sp;
  8065. return DO_NOFUNC;
  8066. }
  8067. static int FAST_FUNC
  8068. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8069. {
  8070. char *cmd;
  8071. int c;
  8072. enum {
  8073. VERIFY_BRIEF = 1,
  8074. VERIFY_VERBOSE = 2,
  8075. } verify = 0;
  8076. const char *path = NULL;
  8077. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  8078. * never reaches this function.
  8079. */
  8080. while ((c = nextopt("pvV")) != '\0')
  8081. if (c == 'V')
  8082. verify |= VERIFY_VERBOSE;
  8083. else if (c == 'v')
  8084. /*verify |= VERIFY_BRIEF*/;
  8085. #if DEBUG
  8086. else if (c != 'p')
  8087. abort();
  8088. #endif
  8089. else
  8090. path = bb_default_path;
  8091. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  8092. cmd = *argptr;
  8093. if (/*verify && */ cmd)
  8094. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  8095. return 0;
  8096. }
  8097. #endif
  8098. /*static int funcblocksize; // size of structures in function */
  8099. /*static int funcstringsize; // size of strings in node */
  8100. static void *funcblock; /* block to allocate function from */
  8101. static char *funcstring_end; /* end of block to allocate strings from */
  8102. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  8103. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  8104. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  8105. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  8106. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  8107. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  8108. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8109. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8110. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8111. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  8112. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8113. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8114. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  8115. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  8116. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  8117. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  8118. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  8119. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8120. #if BASH_REDIR_OUTPUT
  8121. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  8122. #endif
  8123. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  8124. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  8125. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8126. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  8127. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8128. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8129. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8130. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8131. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  8132. };
  8133. static int calcsize(int funcblocksize, union node *n);
  8134. static int
  8135. sizenodelist(int funcblocksize, struct nodelist *lp)
  8136. {
  8137. while (lp) {
  8138. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  8139. funcblocksize = calcsize(funcblocksize, lp->n);
  8140. lp = lp->next;
  8141. }
  8142. return funcblocksize;
  8143. }
  8144. static int
  8145. calcsize(int funcblocksize, union node *n)
  8146. {
  8147. if (n == NULL)
  8148. return funcblocksize;
  8149. funcblocksize += nodesize[n->type];
  8150. switch (n->type) {
  8151. case NCMD:
  8152. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  8153. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  8154. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  8155. break;
  8156. case NPIPE:
  8157. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  8158. break;
  8159. case NREDIR:
  8160. case NBACKGND:
  8161. case NSUBSHELL:
  8162. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  8163. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  8164. break;
  8165. case NAND:
  8166. case NOR:
  8167. case NSEMI:
  8168. case NWHILE:
  8169. case NUNTIL:
  8170. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  8171. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  8172. break;
  8173. case NIF:
  8174. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  8175. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  8176. funcblocksize = calcsize(funcblocksize, n->nif.test);
  8177. break;
  8178. case NFOR:
  8179. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  8180. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  8181. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  8182. break;
  8183. case NCASE:
  8184. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  8185. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  8186. break;
  8187. case NCLIST:
  8188. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  8189. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  8190. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  8191. break;
  8192. case NDEFUN:
  8193. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8194. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8195. break;
  8196. case NARG:
  8197. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8198. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8199. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8200. break;
  8201. case NTO:
  8202. #if BASH_REDIR_OUTPUT
  8203. case NTO2:
  8204. #endif
  8205. case NCLOBBER:
  8206. case NFROM:
  8207. case NFROMTO:
  8208. case NAPPEND:
  8209. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8210. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8211. break;
  8212. case NTOFD:
  8213. case NFROMFD:
  8214. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8215. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8216. break;
  8217. case NHERE:
  8218. case NXHERE:
  8219. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8220. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8221. break;
  8222. case NNOT:
  8223. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8224. break;
  8225. };
  8226. return funcblocksize;
  8227. }
  8228. static char *
  8229. nodeckstrdup(char *s)
  8230. {
  8231. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8232. return strcpy(funcstring_end, s);
  8233. }
  8234. static union node *copynode(union node *);
  8235. static struct nodelist *
  8236. copynodelist(struct nodelist *lp)
  8237. {
  8238. struct nodelist *start;
  8239. struct nodelist **lpp;
  8240. lpp = &start;
  8241. while (lp) {
  8242. *lpp = funcblock;
  8243. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8244. (*lpp)->n = copynode(lp->n);
  8245. lp = lp->next;
  8246. lpp = &(*lpp)->next;
  8247. }
  8248. *lpp = NULL;
  8249. return start;
  8250. }
  8251. static union node *
  8252. copynode(union node *n)
  8253. {
  8254. union node *new;
  8255. if (n == NULL)
  8256. return NULL;
  8257. new = funcblock;
  8258. funcblock = (char *) funcblock + nodesize[n->type];
  8259. switch (n->type) {
  8260. case NCMD:
  8261. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8262. new->ncmd.args = copynode(n->ncmd.args);
  8263. new->ncmd.assign = copynode(n->ncmd.assign);
  8264. new->ncmd.linno = n->ncmd.linno;
  8265. break;
  8266. case NPIPE:
  8267. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8268. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8269. break;
  8270. case NREDIR:
  8271. case NBACKGND:
  8272. case NSUBSHELL:
  8273. new->nredir.redirect = copynode(n->nredir.redirect);
  8274. new->nredir.n = copynode(n->nredir.n);
  8275. new->nredir.linno = n->nredir.linno;
  8276. break;
  8277. case NAND:
  8278. case NOR:
  8279. case NSEMI:
  8280. case NWHILE:
  8281. case NUNTIL:
  8282. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8283. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8284. break;
  8285. case NIF:
  8286. new->nif.elsepart = copynode(n->nif.elsepart);
  8287. new->nif.ifpart = copynode(n->nif.ifpart);
  8288. new->nif.test = copynode(n->nif.test);
  8289. break;
  8290. case NFOR:
  8291. new->nfor.var = nodeckstrdup(n->nfor.var);
  8292. new->nfor.body = copynode(n->nfor.body);
  8293. new->nfor.args = copynode(n->nfor.args);
  8294. new->nfor.linno = n->nfor.linno;
  8295. break;
  8296. case NCASE:
  8297. new->ncase.cases = copynode(n->ncase.cases);
  8298. new->ncase.expr = copynode(n->ncase.expr);
  8299. new->ncase.linno = n->ncase.linno;
  8300. break;
  8301. case NCLIST:
  8302. new->nclist.body = copynode(n->nclist.body);
  8303. new->nclist.pattern = copynode(n->nclist.pattern);
  8304. new->nclist.next = copynode(n->nclist.next);
  8305. break;
  8306. case NDEFUN:
  8307. new->ndefun.body = copynode(n->ndefun.body);
  8308. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8309. new->ndefun.linno = n->ndefun.linno;
  8310. break;
  8311. case NARG:
  8312. new->narg.backquote = copynodelist(n->narg.backquote);
  8313. new->narg.text = nodeckstrdup(n->narg.text);
  8314. new->narg.next = copynode(n->narg.next);
  8315. break;
  8316. case NTO:
  8317. #if BASH_REDIR_OUTPUT
  8318. case NTO2:
  8319. #endif
  8320. case NCLOBBER:
  8321. case NFROM:
  8322. case NFROMTO:
  8323. case NAPPEND:
  8324. new->nfile.fname = copynode(n->nfile.fname);
  8325. new->nfile.fd = n->nfile.fd;
  8326. new->nfile.next = copynode(n->nfile.next);
  8327. break;
  8328. case NTOFD:
  8329. case NFROMFD:
  8330. new->ndup.vname = copynode(n->ndup.vname);
  8331. new->ndup.dupfd = n->ndup.dupfd;
  8332. new->ndup.fd = n->ndup.fd;
  8333. new->ndup.next = copynode(n->ndup.next);
  8334. break;
  8335. case NHERE:
  8336. case NXHERE:
  8337. new->nhere.doc = copynode(n->nhere.doc);
  8338. new->nhere.fd = n->nhere.fd;
  8339. new->nhere.next = copynode(n->nhere.next);
  8340. break;
  8341. case NNOT:
  8342. new->nnot.com = copynode(n->nnot.com);
  8343. break;
  8344. };
  8345. new->type = n->type;
  8346. return new;
  8347. }
  8348. /*
  8349. * Make a copy of a parse tree.
  8350. */
  8351. static struct funcnode *
  8352. copyfunc(union node *n)
  8353. {
  8354. struct funcnode *f;
  8355. size_t blocksize;
  8356. /*funcstringsize = 0;*/
  8357. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8358. f = ckzalloc(blocksize /* + funcstringsize */);
  8359. funcblock = (char *) f + offsetof(struct funcnode, n);
  8360. funcstring_end = (char *) f + blocksize;
  8361. copynode(n);
  8362. /* f->count = 0; - ckzalloc did it */
  8363. return f;
  8364. }
  8365. /*
  8366. * Define a shell function.
  8367. */
  8368. static void
  8369. defun(union node *func)
  8370. {
  8371. struct cmdentry entry;
  8372. INT_OFF;
  8373. entry.cmdtype = CMDFUNCTION;
  8374. entry.u.func = copyfunc(func);
  8375. addcmdentry(func->ndefun.text, &entry);
  8376. INT_ON;
  8377. }
  8378. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8379. #define SKIPBREAK (1 << 0)
  8380. #define SKIPCONT (1 << 1)
  8381. #define SKIPFUNC (1 << 2)
  8382. #define SKIPFUNCDEF (1 << 3)
  8383. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8384. static int skipcount; /* number of levels to skip */
  8385. static int loopnest; /* current loop nesting level */
  8386. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8387. /* Forward decl way out to parsing code - dotrap needs it */
  8388. static int evalstring(char *s, int flags);
  8389. /* Called to execute a trap.
  8390. * Single callsite - at the end of evaltree().
  8391. * If we return non-zero, evaltree raises EXEXIT exception.
  8392. *
  8393. * Perhaps we should avoid entering new trap handlers
  8394. * while we are executing a trap handler. [is it a TODO?]
  8395. */
  8396. static void
  8397. dotrap(void)
  8398. {
  8399. uint8_t *g;
  8400. int sig;
  8401. int status, last_status;
  8402. if (!pending_sig)
  8403. return;
  8404. status = savestatus;
  8405. last_status = status;
  8406. if (status < 0) {
  8407. status = exitstatus;
  8408. savestatus = status;
  8409. }
  8410. pending_sig = 0;
  8411. barrier();
  8412. TRACE(("dotrap entered\n"));
  8413. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8414. char *p;
  8415. if (!*g)
  8416. continue;
  8417. if (evalskip) {
  8418. pending_sig = sig;
  8419. break;
  8420. }
  8421. p = trap[sig];
  8422. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8423. * don't upset it by resetting gotsig[SIGINT-1] */
  8424. if (sig == SIGINT && !p)
  8425. continue;
  8426. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8427. *g = 0;
  8428. if (!p)
  8429. continue;
  8430. trap_depth++;
  8431. evalstring(p, 0);
  8432. trap_depth--;
  8433. if (evalskip != SKIPFUNC)
  8434. exitstatus = status;
  8435. }
  8436. savestatus = last_status;
  8437. TRACE(("dotrap returns\n"));
  8438. }
  8439. /* forward declarations - evaluation is fairly recursive business... */
  8440. static int evalloop(union node *, int);
  8441. static int evalfor(union node *, int);
  8442. static int evalcase(union node *, int);
  8443. static int evalsubshell(union node *, int);
  8444. static void expredir(union node *);
  8445. static int evalpipe(union node *, int);
  8446. static int evalcommand(union node *, int);
  8447. static int evalbltin(const struct builtincmd *, int, char **, int);
  8448. static void prehash(union node *);
  8449. /*
  8450. * Evaluate a parse tree. The value is left in the global variable
  8451. * exitstatus.
  8452. */
  8453. static int
  8454. evaltree(union node *n, int flags)
  8455. {
  8456. int checkexit = 0;
  8457. int (*evalfn)(union node *, int);
  8458. struct stackmark smark;
  8459. int status = 0;
  8460. setstackmark(&smark);
  8461. if (nflag)
  8462. goto out;
  8463. if (n == NULL) {
  8464. TRACE(("evaltree(NULL) called\n"));
  8465. goto out;
  8466. }
  8467. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8468. dotrap();
  8469. switch (n->type) {
  8470. default:
  8471. #if DEBUG
  8472. out1fmt("Node type = %d\n", n->type);
  8473. fflush_all();
  8474. break;
  8475. #endif
  8476. case NNOT:
  8477. status = !evaltree(n->nnot.com, EV_TESTED);
  8478. goto setstatus;
  8479. case NREDIR:
  8480. errlinno = lineno = n->nredir.linno;
  8481. expredir(n->nredir.redirect);
  8482. pushredir(n->nredir.redirect);
  8483. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8484. if (!status) {
  8485. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8486. }
  8487. if (n->nredir.redirect)
  8488. popredir(/*drop:*/ 0);
  8489. goto setstatus;
  8490. case NCMD:
  8491. evalfn = evalcommand;
  8492. checkexit:
  8493. checkexit = ~flags & EV_TESTED;
  8494. goto calleval;
  8495. case NFOR:
  8496. evalfn = evalfor;
  8497. goto calleval;
  8498. case NWHILE:
  8499. case NUNTIL:
  8500. evalfn = evalloop;
  8501. goto calleval;
  8502. case NSUBSHELL:
  8503. case NBACKGND:
  8504. evalfn = evalsubshell;
  8505. goto checkexit;
  8506. case NPIPE:
  8507. evalfn = evalpipe;
  8508. goto checkexit;
  8509. case NCASE:
  8510. evalfn = evalcase;
  8511. goto calleval;
  8512. case NAND:
  8513. case NOR:
  8514. case NSEMI: {
  8515. #if NAND + 1 != NOR
  8516. #error NAND + 1 != NOR
  8517. #endif
  8518. #if NOR + 1 != NSEMI
  8519. #error NOR + 1 != NSEMI
  8520. #endif
  8521. unsigned is_or = n->type - NAND;
  8522. status = evaltree(
  8523. n->nbinary.ch1,
  8524. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8525. );
  8526. if ((!status) == is_or || evalskip)
  8527. break;
  8528. n = n->nbinary.ch2;
  8529. evaln:
  8530. evalfn = evaltree;
  8531. calleval:
  8532. status = evalfn(n, flags);
  8533. goto setstatus;
  8534. }
  8535. case NIF:
  8536. status = evaltree(n->nif.test, EV_TESTED);
  8537. if (evalskip)
  8538. break;
  8539. if (!status) {
  8540. n = n->nif.ifpart;
  8541. goto evaln;
  8542. } else if (n->nif.elsepart) {
  8543. n = n->nif.elsepart;
  8544. goto evaln;
  8545. }
  8546. status = 0;
  8547. goto setstatus;
  8548. case NDEFUN:
  8549. defun(n);
  8550. /* Not necessary. To test it:
  8551. * "false; f() { qwerty; }; echo $?" should print 0.
  8552. */
  8553. /* status = 0; */
  8554. setstatus:
  8555. exitstatus = status;
  8556. break;
  8557. }
  8558. out:
  8559. /* Order of checks below is important:
  8560. * signal handlers trigger before exit caused by "set -e".
  8561. */
  8562. dotrap();
  8563. if (checkexit && status) {
  8564. if (trap[NTRAP_ERR] && !in_trap_ERR) {
  8565. int err;
  8566. struct jmploc *volatile savehandler = exception_handler;
  8567. struct jmploc jmploc;
  8568. in_trap_ERR = 1;
  8569. trap_depth++;
  8570. err = setjmp(jmploc.loc);
  8571. if (!err) {
  8572. exception_handler = &jmploc;
  8573. savestatus = exitstatus;
  8574. evalstring(trap[NTRAP_ERR], 0);
  8575. }
  8576. trap_depth--;
  8577. in_trap_ERR = 0;
  8578. exception_handler = savehandler;
  8579. if (err && exception_type != EXERROR)
  8580. longjmp(exception_handler->loc, 1);
  8581. exitstatus = savestatus;
  8582. }
  8583. if (eflag)
  8584. goto exexit;
  8585. }
  8586. if (flags & EV_EXIT) {
  8587. exexit:
  8588. raise_exception(EXEND);
  8589. }
  8590. popstackmark(&smark);
  8591. TRACE(("leaving evaltree (no interrupts)\n"));
  8592. return exitstatus;
  8593. }
  8594. static int
  8595. skiploop(void)
  8596. {
  8597. int skip = evalskip;
  8598. switch (skip) {
  8599. case 0:
  8600. break;
  8601. case SKIPBREAK:
  8602. case SKIPCONT:
  8603. if (--skipcount <= 0) {
  8604. evalskip = 0;
  8605. break;
  8606. }
  8607. skip = SKIPBREAK;
  8608. break;
  8609. }
  8610. return skip;
  8611. }
  8612. static int
  8613. evalloop(union node *n, int flags)
  8614. {
  8615. int skip;
  8616. int status;
  8617. loopnest++;
  8618. status = 0;
  8619. flags &= EV_TESTED;
  8620. do {
  8621. int i;
  8622. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8623. skip = skiploop();
  8624. if (skip == SKIPFUNC)
  8625. status = i;
  8626. if (skip)
  8627. continue;
  8628. if (n->type != NWHILE)
  8629. i = !i;
  8630. if (i != 0)
  8631. break;
  8632. status = evaltree(n->nbinary.ch2, flags);
  8633. skip = skiploop();
  8634. } while (!(skip & ~SKIPCONT));
  8635. loopnest--;
  8636. return status;
  8637. }
  8638. static int
  8639. evalfor(union node *n, int flags)
  8640. {
  8641. struct arglist arglist;
  8642. union node *argp;
  8643. struct strlist *sp;
  8644. int status = 0;
  8645. errlinno = lineno = n->ncase.linno;
  8646. arglist.list = NULL;
  8647. arglist.lastp = &arglist.list;
  8648. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8649. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8650. }
  8651. *arglist.lastp = NULL;
  8652. loopnest++;
  8653. flags &= EV_TESTED;
  8654. for (sp = arglist.list; sp; sp = sp->next) {
  8655. setvar0(n->nfor.var, sp->text);
  8656. status = evaltree(n->nfor.body, flags);
  8657. if (skiploop() & ~SKIPCONT)
  8658. break;
  8659. }
  8660. loopnest--;
  8661. return status;
  8662. }
  8663. static int
  8664. evalcase(union node *n, int flags)
  8665. {
  8666. union node *cp;
  8667. union node *patp;
  8668. struct arglist arglist;
  8669. int status = 0;
  8670. errlinno = lineno = n->ncase.linno;
  8671. arglist.list = NULL;
  8672. arglist.lastp = &arglist.list;
  8673. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8674. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8675. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8676. if (casematch(patp, arglist.list->text)) {
  8677. /* Ensure body is non-empty as otherwise
  8678. * EV_EXIT may prevent us from setting the
  8679. * exit status.
  8680. */
  8681. if (evalskip == 0 && cp->nclist.body) {
  8682. status = evaltree(cp->nclist.body, flags);
  8683. }
  8684. goto out;
  8685. }
  8686. }
  8687. }
  8688. out:
  8689. return status;
  8690. }
  8691. /*
  8692. * Kick off a subshell to evaluate a tree.
  8693. */
  8694. static int
  8695. evalsubshell(union node *n, int flags)
  8696. {
  8697. struct job *jp;
  8698. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8699. int status;
  8700. errlinno = lineno = n->nredir.linno;
  8701. expredir(n->nredir.redirect);
  8702. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8703. goto nofork;
  8704. INT_OFF;
  8705. if (backgnd == FORK_FG)
  8706. get_tty_state();
  8707. jp = makejob(/*n,*/ 1);
  8708. if (forkshell(jp, n, backgnd) == 0) {
  8709. /* child */
  8710. INT_ON;
  8711. flags |= EV_EXIT;
  8712. if (backgnd)
  8713. flags &= ~EV_TESTED;
  8714. nofork:
  8715. redirect(n->nredir.redirect, 0);
  8716. evaltreenr(n->nredir.n, flags);
  8717. /* never returns */
  8718. }
  8719. /* parent */
  8720. status = 0;
  8721. if (backgnd == FORK_FG)
  8722. status = waitforjob(jp);
  8723. INT_ON;
  8724. return status;
  8725. }
  8726. /*
  8727. * Compute the names of the files in a redirection list.
  8728. */
  8729. static void fixredir(union node *, const char *, int);
  8730. static void
  8731. expredir(union node *n)
  8732. {
  8733. union node *redir;
  8734. for (redir = n; redir; redir = redir->nfile.next) {
  8735. struct arglist fn;
  8736. fn.list = NULL;
  8737. fn.lastp = &fn.list;
  8738. switch (redir->type) {
  8739. case NFROMTO:
  8740. case NFROM:
  8741. case NTO:
  8742. #if BASH_REDIR_OUTPUT
  8743. case NTO2:
  8744. #endif
  8745. case NCLOBBER:
  8746. case NAPPEND:
  8747. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8748. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8749. #if BASH_REDIR_OUTPUT
  8750. store_expfname:
  8751. #endif
  8752. #if 0
  8753. // By the design of stack allocator, the loop of this kind:
  8754. // while true; do while true; do break; done </dev/null; done
  8755. // will look like a memory leak: ash plans to free expfname's
  8756. // of "/dev/null" as soon as it finishes running the loop
  8757. // (in this case, never).
  8758. // This "fix" is wrong:
  8759. if (redir->nfile.expfname)
  8760. stunalloc(redir->nfile.expfname);
  8761. // It results in corrupted state of stacked allocations.
  8762. #endif
  8763. redir->nfile.expfname = fn.list->text;
  8764. break;
  8765. case NFROMFD:
  8766. case NTOFD: /* >& */
  8767. if (redir->ndup.vname) {
  8768. expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
  8769. if (fn.list == NULL)
  8770. ash_msg_and_raise_error("redir error");
  8771. #if BASH_REDIR_OUTPUT
  8772. if (!isdigit_str9(fn.list->text)) {
  8773. /* >&file, not >&fd */
  8774. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8775. ash_msg_and_raise_error("redir error");
  8776. redir->type = NTO2;
  8777. goto store_expfname;
  8778. }
  8779. #endif
  8780. fixredir(redir, fn.list->text, 1);
  8781. }
  8782. break;
  8783. }
  8784. }
  8785. }
  8786. /*
  8787. * Evaluate a pipeline. All the processes in the pipeline are children
  8788. * of the process creating the pipeline. (This differs from some versions
  8789. * of the shell, which make the last process in a pipeline the parent
  8790. * of all the rest.)
  8791. */
  8792. static int
  8793. evalpipe(union node *n, int flags)
  8794. {
  8795. struct job *jp;
  8796. struct nodelist *lp;
  8797. int pipelen;
  8798. int prevfd;
  8799. int pip[2];
  8800. int status = 0;
  8801. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8802. pipelen = 0;
  8803. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8804. pipelen++;
  8805. flags |= EV_EXIT;
  8806. INT_OFF;
  8807. if (n->npipe.pipe_backgnd == 0)
  8808. get_tty_state();
  8809. jp = makejob(/*n,*/ pipelen);
  8810. prevfd = -1;
  8811. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8812. prehash(lp->n);
  8813. pip[1] = -1;
  8814. if (lp->next) {
  8815. if (pipe(pip) < 0) {
  8816. close(prevfd);
  8817. ash_msg_and_raise_perror("can't create pipe");
  8818. }
  8819. }
  8820. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8821. /* child */
  8822. INT_ON;
  8823. if (pip[1] >= 0) {
  8824. close(pip[0]);
  8825. }
  8826. if (prevfd > 0) {
  8827. dup2(prevfd, 0);
  8828. close(prevfd);
  8829. }
  8830. if (pip[1] > 1) {
  8831. dup2(pip[1], 1);
  8832. close(pip[1]);
  8833. }
  8834. evaltreenr(lp->n, flags);
  8835. /* never returns */
  8836. }
  8837. /* parent */
  8838. if (prevfd >= 0)
  8839. close(prevfd);
  8840. prevfd = pip[0];
  8841. /* Don't want to trigger debugging */
  8842. if (pip[1] != -1)
  8843. close(pip[1]);
  8844. }
  8845. if (n->npipe.pipe_backgnd == 0) {
  8846. status = waitforjob(jp);
  8847. TRACE(("evalpipe: job done exit status %d\n", status));
  8848. }
  8849. INT_ON;
  8850. return status;
  8851. }
  8852. /* setinteractive needs this forward reference */
  8853. #if EDITING_HAS_get_exe_name
  8854. static const char *get_builtin_name(int i) FAST_FUNC;
  8855. #endif
  8856. /*
  8857. * Controls whether the shell is interactive or not.
  8858. */
  8859. static void
  8860. setinteractive(int on)
  8861. {
  8862. static smallint is_interactive;
  8863. if (++on == is_interactive)
  8864. return;
  8865. is_interactive = on;
  8866. setsignal(SIGINT);
  8867. setsignal(SIGQUIT);
  8868. setsignal(SIGTERM);
  8869. if (is_interactive > 1) {
  8870. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8871. /* Looks like they want an interactive shell */
  8872. static smallint did_banner;
  8873. if (!did_banner) {
  8874. /* note: ash and hush share this string */
  8875. out1fmt("\n\n%s %s\n"
  8876. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8877. "\n",
  8878. bb_banner,
  8879. "built-in shell (ash)"
  8880. );
  8881. did_banner = 1;
  8882. }
  8883. #endif
  8884. #if ENABLE_FEATURE_EDITING
  8885. if (!line_input_state) {
  8886. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  8887. # if EDITING_HAS_get_exe_name
  8888. line_input_state->get_exe_name = get_builtin_name;
  8889. # endif
  8890. }
  8891. #endif
  8892. }
  8893. }
  8894. static void
  8895. optschanged(void)
  8896. {
  8897. #if DEBUG
  8898. opentrace();
  8899. #endif
  8900. setinteractive(iflag);
  8901. setjobctl(mflag);
  8902. #if ENABLE_FEATURE_EDITING_VI
  8903. if (line_input_state) {
  8904. if (viflag)
  8905. line_input_state->flags |= VI_MODE;
  8906. else
  8907. line_input_state->flags &= ~VI_MODE;
  8908. }
  8909. #else
  8910. viflag = 0; /* forcibly keep the option off */
  8911. #endif
  8912. }
  8913. struct localvar_list {
  8914. struct localvar_list *next;
  8915. struct localvar *lv;
  8916. };
  8917. static struct localvar_list *localvar_stack;
  8918. /*
  8919. * Called after a function returns.
  8920. * Interrupts must be off.
  8921. */
  8922. static void
  8923. poplocalvars(int keep)
  8924. {
  8925. struct localvar_list *ll;
  8926. struct localvar *lvp, *next;
  8927. struct var *vp;
  8928. INT_OFF;
  8929. ll = localvar_stack;
  8930. localvar_stack = ll->next;
  8931. next = ll->lv;
  8932. free(ll);
  8933. while ((lvp = next) != NULL) {
  8934. next = lvp->next;
  8935. vp = lvp->vp;
  8936. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8937. if (keep) {
  8938. int bits = VSTRFIXED;
  8939. if (lvp->flags != VUNSET) {
  8940. if (vp->var_text == lvp->text)
  8941. bits |= VTEXTFIXED;
  8942. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8943. free((char*)lvp->text);
  8944. }
  8945. vp->flags &= ~bits;
  8946. vp->flags |= (lvp->flags & bits);
  8947. if ((vp->flags &
  8948. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8949. unsetvar(vp->var_text);
  8950. } else if (vp == NULL) { /* $- saved */
  8951. memcpy(optlist, lvp->text, sizeof(optlist));
  8952. free((char*)lvp->text);
  8953. optschanged();
  8954. } else if (lvp->flags == VUNSET) {
  8955. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8956. unsetvar(vp->var_text);
  8957. } else {
  8958. if (vp->var_func)
  8959. vp->var_func(var_end(lvp->text));
  8960. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8961. free((char*)vp->var_text);
  8962. vp->flags = lvp->flags;
  8963. vp->var_text = lvp->text;
  8964. }
  8965. free(lvp);
  8966. }
  8967. INT_ON;
  8968. }
  8969. /*
  8970. * Create a new localvar environment.
  8971. */
  8972. static struct localvar_list *
  8973. pushlocalvars(int push)
  8974. {
  8975. struct localvar_list *ll;
  8976. struct localvar_list *top;
  8977. top = localvar_stack;
  8978. if (!push)
  8979. goto out;
  8980. INT_OFF;
  8981. ll = ckzalloc(sizeof(*ll));
  8982. /*ll->lv = NULL; - zalloc did it */
  8983. ll->next = top;
  8984. localvar_stack = ll;
  8985. INT_ON;
  8986. out:
  8987. return top;
  8988. }
  8989. static void
  8990. unwindlocalvars(struct localvar_list *stop)
  8991. {
  8992. while (localvar_stack != stop)
  8993. poplocalvars(0);
  8994. }
  8995. static int
  8996. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8997. {
  8998. volatile struct shparam saveparam;
  8999. struct jmploc *volatile savehandler;
  9000. struct jmploc jmploc;
  9001. int e;
  9002. int savelineno;
  9003. int savefuncline;
  9004. char *savefuncname;
  9005. char *savetrap = NULL;
  9006. if (!Eflag) {
  9007. savetrap = trap[NTRAP_ERR];
  9008. trap[NTRAP_ERR] = NULL;
  9009. }
  9010. savelineno = lineno;
  9011. saveparam = shellparam;
  9012. savefuncline = funcline;
  9013. savefuncname = funcname;
  9014. savehandler = exception_handler;
  9015. e = setjmp(jmploc.loc);
  9016. if (e) {
  9017. goto funcdone;
  9018. }
  9019. INT_OFF;
  9020. exception_handler = &jmploc;
  9021. shellparam.malloced = 0;
  9022. func->count++;
  9023. funcname = func->n.ndefun.text;
  9024. funcline = func->n.ndefun.linno;
  9025. INT_ON;
  9026. shellparam.nparam = argc - 1;
  9027. shellparam.p = argv + 1;
  9028. #if ENABLE_ASH_GETOPTS
  9029. shellparam.optind = 1;
  9030. shellparam.optoff = -1;
  9031. #endif
  9032. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  9033. funcdone:
  9034. INT_OFF;
  9035. funcname = savefuncname;
  9036. if (savetrap) {
  9037. if (!trap[NTRAP_ERR])
  9038. trap[NTRAP_ERR] = savetrap;
  9039. else
  9040. free(savetrap);
  9041. }
  9042. funcline = savefuncline;
  9043. lineno = savelineno;
  9044. freefunc(func);
  9045. freeparam(&shellparam);
  9046. shellparam = saveparam;
  9047. exception_handler = savehandler;
  9048. INT_ON;
  9049. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  9050. return e;
  9051. }
  9052. /*
  9053. * Make a variable a local variable. When a variable is made local, it's
  9054. * value and flags are saved in a localvar structure. The saved values
  9055. * will be restored when the shell function returns. We handle the name
  9056. * "-" as a special case: it makes changes to "set +-options" local
  9057. * (options will be restored on return from the function).
  9058. */
  9059. static void
  9060. mklocal(char *name, int flags)
  9061. {
  9062. struct localvar *lvp;
  9063. struct var **vpp;
  9064. struct var *vp;
  9065. char *eq = strchr(name, '=');
  9066. INT_OFF;
  9067. /* Cater for duplicate "local". Examples:
  9068. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  9069. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  9070. */
  9071. lvp = localvar_stack->lv;
  9072. while (lvp) {
  9073. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  9074. if (eq)
  9075. setvareq(name, 0);
  9076. /* else:
  9077. * it's a duplicate "local VAR" declaration, do nothing
  9078. */
  9079. goto ret;
  9080. }
  9081. lvp = lvp->next;
  9082. }
  9083. lvp = ckzalloc(sizeof(*lvp));
  9084. if (LONE_DASH(name)) {
  9085. char *p;
  9086. p = ckmalloc(sizeof(optlist));
  9087. lvp->text = memcpy(p, optlist, sizeof(optlist));
  9088. vp = NULL;
  9089. } else {
  9090. vpp = hashvar(name);
  9091. vp = *findvar(vpp, name);
  9092. if (vp == NULL) {
  9093. /* variable did not exist yet */
  9094. if (eq)
  9095. vp = setvareq(name, VSTRFIXED | flags);
  9096. else
  9097. vp = setvar(name, NULL, VSTRFIXED | flags);
  9098. lvp->flags = VUNSET;
  9099. } else {
  9100. lvp->text = vp->var_text;
  9101. lvp->flags = vp->flags;
  9102. /* make sure neither "struct var" nor string gets freed
  9103. * during (un)setting:
  9104. */
  9105. vp->flags |= VSTRFIXED|VTEXTFIXED;
  9106. if (eq)
  9107. setvareq(name, flags);
  9108. else
  9109. /* "local VAR" unsets VAR: */
  9110. setvar0(name, NULL);
  9111. }
  9112. }
  9113. lvp->vp = vp;
  9114. lvp->next = localvar_stack->lv;
  9115. localvar_stack->lv = lvp;
  9116. ret:
  9117. INT_ON;
  9118. }
  9119. /*
  9120. * The "local" command.
  9121. */
  9122. static int FAST_FUNC
  9123. localcmd(int argc UNUSED_PARAM, char **argv)
  9124. {
  9125. char *name;
  9126. if (!localvar_stack)
  9127. ash_msg_and_raise_error("not in a function");
  9128. argv = argptr;
  9129. while ((name = *argv++) != NULL) {
  9130. mklocal(name, 0);
  9131. }
  9132. return 0;
  9133. }
  9134. static int FAST_FUNC
  9135. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9136. {
  9137. return 1;
  9138. }
  9139. static int FAST_FUNC
  9140. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9141. {
  9142. return 0;
  9143. }
  9144. static int FAST_FUNC
  9145. execcmd(int argc UNUSED_PARAM, char **argv)
  9146. {
  9147. optionarg = NULL;
  9148. while (nextopt("a:") != '\0')
  9149. /* nextopt() sets optionarg to "-a ARGV0" */;
  9150. argv = argptr;
  9151. if (argv[0]) {
  9152. char *prog;
  9153. iflag = 0; /* exit on error */
  9154. mflag = 0;
  9155. optschanged();
  9156. /* We should set up signals for "exec CMD"
  9157. * the same way as for "CMD" without "exec".
  9158. * But optschanged->setinteractive->setsignal
  9159. * still thought we are a root shell. Therefore, for example,
  9160. * SIGQUIT is still set to IGN. Fix it:
  9161. */
  9162. shlvl++;
  9163. setsignal(SIGQUIT);
  9164. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  9165. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  9166. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  9167. prog = argv[0];
  9168. if (optionarg)
  9169. argv[0] = optionarg;
  9170. shellexec(prog, argv, pathval(), 0);
  9171. /* NOTREACHED */
  9172. }
  9173. return 0;
  9174. }
  9175. /*
  9176. * The return command.
  9177. */
  9178. static int FAST_FUNC
  9179. returncmd(int argc UNUSED_PARAM, char **argv)
  9180. {
  9181. int skip;
  9182. int status;
  9183. /*
  9184. * If called outside a function, do what ksh does;
  9185. * skip the rest of the file.
  9186. */
  9187. if (argv[1]) {
  9188. skip = SKIPFUNC;
  9189. status = number(argv[1]);
  9190. } else {
  9191. skip = SKIPFUNCDEF;
  9192. status = exitstatus;
  9193. }
  9194. evalskip = skip;
  9195. return status;
  9196. }
  9197. /* Forward declarations for builtintab[] */
  9198. static int breakcmd(int, char **) FAST_FUNC;
  9199. static int dotcmd(int, char **) FAST_FUNC;
  9200. static int evalcmd(int, char **, int) FAST_FUNC;
  9201. static int exitcmd(int, char **) FAST_FUNC;
  9202. static int exportcmd(int, char **) FAST_FUNC;
  9203. #if ENABLE_ASH_GETOPTS
  9204. static int getoptscmd(int, char **) FAST_FUNC;
  9205. #endif
  9206. #if ENABLE_ASH_HELP
  9207. static int helpcmd(int, char **) FAST_FUNC;
  9208. #endif
  9209. #if MAX_HISTORY
  9210. static int historycmd(int, char **) FAST_FUNC;
  9211. #endif
  9212. #if ENABLE_FEATURE_SH_MATH
  9213. static int letcmd(int, char **) FAST_FUNC;
  9214. #endif
  9215. static int readcmd(int, char **) FAST_FUNC;
  9216. static int setcmd(int, char **) FAST_FUNC;
  9217. static int shiftcmd(int, char **) FAST_FUNC;
  9218. static int timescmd(int, char **) FAST_FUNC;
  9219. static int trapcmd(int, char **) FAST_FUNC;
  9220. static int umaskcmd(int, char **) FAST_FUNC;
  9221. static int unsetcmd(int, char **) FAST_FUNC;
  9222. static int ulimitcmd(int, char **) FAST_FUNC;
  9223. #define BUILTIN_NOSPEC "0"
  9224. #define BUILTIN_SPECIAL "1"
  9225. #define BUILTIN_REGULAR "2"
  9226. #define BUILTIN_SPEC_REG "3"
  9227. #define BUILTIN_ASSIGN "4"
  9228. #define BUILTIN_SPEC_ASSG "5"
  9229. #define BUILTIN_REG_ASSG "6"
  9230. #define BUILTIN_SPEC_REG_ASSG "7"
  9231. /* Stubs for calling non-FAST_FUNC's */
  9232. #if ENABLE_ASH_ECHO
  9233. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  9234. #endif
  9235. #if ENABLE_ASH_PRINTF
  9236. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  9237. #endif
  9238. #if ENABLE_ASH_TEST || BASH_TEST2
  9239. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  9240. #endif
  9241. /* Keep these in proper order since it is searched via bsearch() */
  9242. static const struct builtincmd builtintab[] = {
  9243. { BUILTIN_SPEC_REG "." , dotcmd },
  9244. { BUILTIN_SPEC_REG ":" , truecmd },
  9245. #if ENABLE_ASH_TEST
  9246. { BUILTIN_REGULAR "[" , testcmd },
  9247. #endif
  9248. #if BASH_TEST2
  9249. { BUILTIN_REGULAR "[[" , testcmd },
  9250. #endif
  9251. #if ENABLE_ASH_ALIAS
  9252. { BUILTIN_REG_ASSG "alias" , aliascmd },
  9253. #endif
  9254. #if JOBS
  9255. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  9256. #endif
  9257. { BUILTIN_SPEC_REG "break" , breakcmd },
  9258. { BUILTIN_REGULAR "cd" , cdcmd },
  9259. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9260. #if ENABLE_ASH_CMDCMD
  9261. { BUILTIN_REGULAR "command" , commandcmd },
  9262. #endif
  9263. { BUILTIN_SPEC_REG "continue", breakcmd },
  9264. #if ENABLE_ASH_ECHO
  9265. { BUILTIN_REGULAR "echo" , echocmd },
  9266. #endif
  9267. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9268. { BUILTIN_SPEC_REG "exec" , execcmd },
  9269. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9270. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9271. { BUILTIN_REGULAR "false" , falsecmd },
  9272. #if JOBS
  9273. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9274. #endif
  9275. #if ENABLE_ASH_GETOPTS
  9276. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9277. #endif
  9278. { BUILTIN_REGULAR "hash" , hashcmd },
  9279. #if ENABLE_ASH_HELP
  9280. { BUILTIN_NOSPEC "help" , helpcmd },
  9281. #endif
  9282. #if MAX_HISTORY
  9283. { BUILTIN_NOSPEC "history" , historycmd },
  9284. #endif
  9285. #if JOBS
  9286. { BUILTIN_REGULAR "jobs" , jobscmd },
  9287. { BUILTIN_REGULAR "kill" , killcmd },
  9288. #endif
  9289. #if ENABLE_FEATURE_SH_MATH
  9290. { BUILTIN_NOSPEC "let" , letcmd },
  9291. #endif
  9292. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9293. #if ENABLE_ASH_PRINTF
  9294. { BUILTIN_REGULAR "printf" , printfcmd },
  9295. #endif
  9296. { BUILTIN_REGULAR "pwd" , pwdcmd },
  9297. { BUILTIN_REGULAR "read" , readcmd },
  9298. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9299. { BUILTIN_SPEC_REG "return" , returncmd },
  9300. { BUILTIN_SPEC_REG "set" , setcmd },
  9301. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9302. #if BASH_SOURCE
  9303. { BUILTIN_SPEC_REG "source" , dotcmd },
  9304. #endif
  9305. #if ENABLE_ASH_TEST
  9306. { BUILTIN_REGULAR "test" , testcmd },
  9307. #endif
  9308. { BUILTIN_SPEC_REG "times" , timescmd },
  9309. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9310. { BUILTIN_REGULAR "true" , truecmd },
  9311. { BUILTIN_REGULAR "type" , typecmd },
  9312. { BUILTIN_REGULAR "ulimit" , ulimitcmd },
  9313. { BUILTIN_REGULAR "umask" , umaskcmd },
  9314. #if ENABLE_ASH_ALIAS
  9315. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9316. #endif
  9317. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9318. { BUILTIN_REGULAR "wait" , waitcmd },
  9319. };
  9320. /* Should match the above table! */
  9321. #define COMMANDCMD (builtintab + \
  9322. /* . : */ 2 + \
  9323. /* [ */ 1 * ENABLE_ASH_TEST + \
  9324. /* [[ */ 1 * BASH_TEST2 + \
  9325. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9326. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9327. /* break cd cddir */ 3)
  9328. #define EVALCMD (COMMANDCMD + \
  9329. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9330. /* continue */ 1 + \
  9331. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9332. 0)
  9333. #define EXECCMD (EVALCMD + \
  9334. /* eval */ 1)
  9335. /*
  9336. * Search the table of builtin commands.
  9337. */
  9338. static int
  9339. pstrcmp1(const void *a, const void *b)
  9340. {
  9341. return strcmp((char*)a, *(char**)b + 1);
  9342. }
  9343. static struct builtincmd *
  9344. find_builtin(const char *name)
  9345. {
  9346. struct builtincmd *bp;
  9347. bp = bsearch(
  9348. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9349. pstrcmp1
  9350. );
  9351. return bp;
  9352. }
  9353. #if EDITING_HAS_get_exe_name
  9354. static const char * FAST_FUNC
  9355. get_builtin_name(int i)
  9356. {
  9357. return /*i >= 0 &&*/ i < ARRAY_SIZE(builtintab) ? builtintab[i].name + 1 : NULL;
  9358. }
  9359. #endif
  9360. /*
  9361. * Execute a simple command.
  9362. */
  9363. static void unwindfiles(struct parsefile *stop);
  9364. static int
  9365. isassignment(const char *p)
  9366. {
  9367. const char *q = endofname(p);
  9368. if (p == q)
  9369. return 0;
  9370. return *q == '=';
  9371. }
  9372. static int FAST_FUNC
  9373. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9374. {
  9375. /* Preserve exitstatus of a previous possible redirection
  9376. * as POSIX mandates */
  9377. return back_exitstatus;
  9378. }
  9379. static int
  9380. evalcommand(union node *cmd, int flags)
  9381. {
  9382. static const struct builtincmd null_bltin = {
  9383. BUILTIN_REGULAR "", bltincmd
  9384. };
  9385. struct localvar_list *localvar_stop;
  9386. struct parsefile *file_stop;
  9387. struct redirtab *redir_stop;
  9388. union node *argp;
  9389. struct arglist arglist;
  9390. struct arglist varlist;
  9391. char **argv;
  9392. int argc;
  9393. struct strlist *osp;
  9394. const struct strlist *sp;
  9395. struct cmdentry cmdentry;
  9396. struct job *jp;
  9397. char *lastarg;
  9398. const char *path;
  9399. int spclbltin;
  9400. int cmd_flag;
  9401. int status;
  9402. char **nargv;
  9403. smallint cmd_is_exec;
  9404. int vflags;
  9405. int vlocal;
  9406. errlinno = lineno = cmd->ncmd.linno;
  9407. /* First expand the arguments. */
  9408. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9409. #if BASH_PROCESS_SUBST
  9410. redir_stop = redirlist;
  9411. #endif
  9412. file_stop = g_parsefile;
  9413. back_exitstatus = 0;
  9414. cmdentry.cmdtype = CMDBUILTIN;
  9415. cmdentry.u.cmd = &null_bltin;
  9416. varlist.lastp = &varlist.list;
  9417. *varlist.lastp = NULL;
  9418. arglist.lastp = &arglist.list;
  9419. *arglist.lastp = NULL;
  9420. cmd_flag = 0;
  9421. cmd_is_exec = 0;
  9422. spclbltin = -1;
  9423. vflags = 0;
  9424. vlocal = 0;
  9425. path = NULL;
  9426. argc = 0;
  9427. argp = cmd->ncmd.args;
  9428. osp = fill_arglist(&arglist, &argp);
  9429. if (osp) {
  9430. int pseudovarflag = 0;
  9431. for (;;) {
  9432. find_command(arglist.list->text, &cmdentry,
  9433. cmd_flag | DO_REGBLTIN, pathval());
  9434. vlocal++;
  9435. /* implement bltin and command here */
  9436. if (cmdentry.cmdtype != CMDBUILTIN)
  9437. break;
  9438. pseudovarflag = IS_BUILTIN_ASSIGN(cmdentry.u.cmd);
  9439. if (spclbltin < 0) {
  9440. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9441. vlocal = !spclbltin;
  9442. }
  9443. cmd_is_exec = cmdentry.u.cmd == EXECCMD;
  9444. #if ENABLE_ASH_CMDCMD
  9445. if (cmdentry.u.cmd != COMMANDCMD)
  9446. break;
  9447. cmd_flag = parse_command_args(&arglist, &argp, &path);
  9448. if (!cmd_flag)
  9449. #endif
  9450. break;
  9451. }
  9452. for (; argp; argp = argp->narg.next)
  9453. expandarg(argp, &arglist,
  9454. pseudovarflag &&
  9455. isassignment(argp->narg.text) ?
  9456. EXP_VARTILDE : EXP_FULL | EXP_TILDE);
  9457. for (sp = arglist.list; sp; sp = sp->next)
  9458. argc++;
  9459. if (cmd_is_exec && argc > 1)
  9460. vflags = VEXPORT;
  9461. }
  9462. localvar_stop = pushlocalvars(vlocal);
  9463. /* Reserve one extra spot at the front for shellexec. */
  9464. nargv = stalloc(sizeof(char *) * (argc + 2));
  9465. argv = ++nargv;
  9466. for (sp = arglist.list; sp; sp = sp->next) {
  9467. TRACE(("evalcommand arg: %s\n", sp->text));
  9468. *nargv++ = sp->text;
  9469. }
  9470. *nargv = NULL;
  9471. lastarg = NULL;
  9472. if (iflag && funcline == 0 && argc > 0)
  9473. lastarg = nargv[-1];
  9474. expredir(cmd->ncmd.redirect);
  9475. #if !BASH_PROCESS_SUBST
  9476. redir_stop = pushredir(cmd->ncmd.redirect);
  9477. #else
  9478. pushredir(cmd->ncmd.redirect);
  9479. #endif
  9480. preverrout_fd = 2;
  9481. if (BASH_XTRACEFD && xflag) {
  9482. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9483. * we do not emulate this. We only use its value.
  9484. */
  9485. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9486. if (xtracefd && is_number(xtracefd))
  9487. preverrout_fd = atoi(xtracefd);
  9488. }
  9489. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9490. if (status) {
  9491. bail:
  9492. exitstatus = status;
  9493. /* We have a redirection error. */
  9494. if (spclbltin > 0)
  9495. raise_exception(EXERROR);
  9496. goto out;
  9497. }
  9498. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9499. struct strlist **spp;
  9500. spp = varlist.lastp;
  9501. expandarg(argp, &varlist, EXP_VARTILDE);
  9502. if (vlocal)
  9503. mklocal((*spp)->text, VEXPORT);
  9504. else
  9505. setvareq((*spp)->text, vflags);
  9506. }
  9507. /* Print the command if xflag is set. */
  9508. if (xflag && !inps4) {
  9509. const char *pfx = "";
  9510. inps4 = 1;
  9511. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9512. inps4 = 0;
  9513. sp = varlist.list;
  9514. while (sp) {
  9515. char *varval = sp->text;
  9516. char *eq = strchrnul(varval, '=');
  9517. if (*eq)
  9518. eq++;
  9519. fdprintf(preverrout_fd, "%s%.*s%s",
  9520. pfx,
  9521. (int)(eq - varval), varval,
  9522. maybe_single_quote(eq)
  9523. );
  9524. sp = sp->next;
  9525. pfx = " ";
  9526. }
  9527. sp = arglist.list;
  9528. while (sp) {
  9529. fdprintf(preverrout_fd, "%s%s",
  9530. pfx,
  9531. /* always quote if matches reserved word: */
  9532. findkwd(sp->text)
  9533. ? single_quote(sp->text)
  9534. : maybe_single_quote(sp->text)
  9535. );
  9536. sp = sp->next;
  9537. pfx = " ";
  9538. }
  9539. safe_write(preverrout_fd, "\n", 1);
  9540. }
  9541. /* Now locate the command. */
  9542. if (cmdentry.cmdtype != CMDBUILTIN
  9543. || !(IS_BUILTIN_REGULAR(cmdentry.u.cmd))
  9544. ) {
  9545. path = path ? path : pathval();
  9546. find_command(argv[0], &cmdentry, cmd_flag | DO_ERR, path);
  9547. }
  9548. jp = NULL;
  9549. /* Execute the command. */
  9550. switch (cmdentry.cmdtype) {
  9551. case CMDUNKNOWN:
  9552. status = 127;
  9553. flush_stdout_stderr();
  9554. goto bail;
  9555. default: {
  9556. #if ENABLE_FEATURE_SH_STANDALONE \
  9557. && ENABLE_FEATURE_SH_NOFORK \
  9558. && NUM_APPLETS > 1
  9559. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9560. * around run_nofork_applet() call.
  9561. * (2) Should this check also be done in forkshell()?
  9562. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9563. */
  9564. /* find_command() encodes applet_no as (-2 - applet_no) */
  9565. int applet_no = (- cmdentry.u.index - 2);
  9566. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9567. char **sv_environ;
  9568. INT_OFF;
  9569. sv_environ = environ;
  9570. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9571. /*
  9572. * Run <applet>_main().
  9573. * Signals (^C) can't interrupt here.
  9574. * Otherwise we can mangle stdio or malloc internal state.
  9575. * This makes applets which can run for a long time
  9576. * and/or wait for user input ineligible for NOFORK:
  9577. * for example, "yes" or "rm" (rm -i waits for input).
  9578. */
  9579. exitstatus = run_nofork_applet(applet_no, argv);
  9580. environ = sv_environ;
  9581. /*
  9582. * Try enabling NOFORK for "yes" applet.
  9583. * ^C _will_ stop it (write returns EINTR),
  9584. * but this causes stdout FILE to be stuck
  9585. * and needing clearerr(). What if other applets
  9586. * also can get EINTRs? Do we need to switch
  9587. * our signals to SA_RESTART?
  9588. */
  9589. /*clearerr(stdout);*/
  9590. INT_ON;
  9591. break;
  9592. }
  9593. #endif
  9594. /* Can we avoid forking? For example, very last command
  9595. * in a script or a subshell does not need forking,
  9596. * we can just exec it.
  9597. */
  9598. if (!(flags & EV_EXIT) || may_have_traps) {
  9599. /* No, forking off a child is necessary */
  9600. INT_OFF;
  9601. get_tty_state();
  9602. jp = makejob(/*cmd,*/ 1);
  9603. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9604. /* parent */
  9605. break;
  9606. }
  9607. /* child */
  9608. FORCE_INT_ON;
  9609. /* fall through to exec'ing external program */
  9610. }
  9611. shellexec(argv[0], argv, path, cmdentry.u.index);
  9612. /* NOTREACHED */
  9613. } /* default */
  9614. case CMDBUILTIN:
  9615. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)
  9616. && !(exception_type == EXERROR && spclbltin <= 0)
  9617. ) {
  9618. raise:
  9619. longjmp(exception_handler->loc, 1);
  9620. }
  9621. break;
  9622. case CMDFUNCTION:
  9623. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9624. goto raise;
  9625. break;
  9626. } /* switch */
  9627. status = waitforjob(jp);
  9628. if (jp)
  9629. TRACE(("forked child exited with %d\n", status));
  9630. FORCE_INT_ON;
  9631. out:
  9632. if (cmd->ncmd.redirect)
  9633. popredir(/*drop:*/ cmd_is_exec);
  9634. unwindredir(redir_stop);
  9635. unwindfiles(file_stop);
  9636. unwindlocalvars(localvar_stop);
  9637. if (lastarg) {
  9638. /* dsl: I think this is intended to be used to support
  9639. * '_' in 'vi' command mode during line editing...
  9640. * However I implemented that within libedit itself.
  9641. */
  9642. setvar0("_", lastarg);
  9643. }
  9644. return status;
  9645. }
  9646. static int
  9647. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9648. {
  9649. char *volatile savecmdname;
  9650. struct jmploc *volatile savehandler;
  9651. struct jmploc jmploc;
  9652. int status;
  9653. int i;
  9654. savecmdname = commandname;
  9655. savehandler = exception_handler;
  9656. i = setjmp(jmploc.loc);
  9657. if (i)
  9658. goto cmddone;
  9659. exception_handler = &jmploc;
  9660. commandname = argv[0];
  9661. argptr = argv + 1;
  9662. optptr = NULL; /* initialize nextopt */
  9663. if (cmd == EVALCMD)
  9664. status = evalcmd(argc, argv, flags);
  9665. else
  9666. status = (*cmd->builtin)(argc, argv);
  9667. flush_stdout_stderr();
  9668. status |= ferror(stdout);
  9669. exitstatus = status;
  9670. cmddone:
  9671. clearerr(stdout);
  9672. commandname = savecmdname;
  9673. exception_handler = savehandler;
  9674. return i;
  9675. }
  9676. static int
  9677. goodname(const char *p)
  9678. {
  9679. return endofname(p)[0] == '\0';
  9680. }
  9681. /*
  9682. * Search for a command. This is called before we fork so that the
  9683. * location of the command will be available in the parent as well as
  9684. * the child. The check for "goodname" is an overly conservative
  9685. * check that the name will not be subject to expansion.
  9686. */
  9687. static void
  9688. prehash(union node *n)
  9689. {
  9690. struct cmdentry entry;
  9691. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9692. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9693. }
  9694. /* ============ Builtin commands
  9695. *
  9696. * Builtin commands whose functions are closely tied to evaluation
  9697. * are implemented here.
  9698. */
  9699. /*
  9700. * Handle break and continue commands. Break, continue, and return are
  9701. * all handled by setting the evalskip flag. The evaluation routines
  9702. * above all check this flag, and if it is set they start skipping
  9703. * commands rather than executing them. The variable skipcount is
  9704. * the number of loops to break/continue, or the number of function
  9705. * levels to return. (The latter is always 1.) It should probably
  9706. * be an error to break out of more loops than exist, but it isn't
  9707. * in the standard shell so we don't make it one here.
  9708. */
  9709. static int FAST_FUNC
  9710. breakcmd(int argc UNUSED_PARAM, char **argv)
  9711. {
  9712. int n = argv[1] ? number(argv[1]) : 1;
  9713. if (n <= 0)
  9714. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9715. if (n > loopnest)
  9716. n = loopnest;
  9717. if (n > 0) {
  9718. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9719. skipcount = n;
  9720. }
  9721. return 0;
  9722. }
  9723. /*
  9724. * This implements the input routines used by the parser.
  9725. */
  9726. enum {
  9727. INPUT_PUSH_FILE = 1,
  9728. INPUT_NOFILE_OK = 2,
  9729. };
  9730. static smallint checkkwd;
  9731. /* values of checkkwd variable */
  9732. #define CHKALIAS 0x1
  9733. #define CHKKWD 0x2
  9734. #define CHKNL 0x4
  9735. #define CHKEOFMARK 0x8
  9736. /*
  9737. * Push a string back onto the input at this current parsefile level.
  9738. * We handle aliases this way.
  9739. */
  9740. #if !ENABLE_ASH_ALIAS
  9741. #define pushstring(s, ap) pushstring(s)
  9742. #endif
  9743. static void
  9744. pushstring(char *s, struct alias *ap)
  9745. {
  9746. struct strpush *sp;
  9747. int len;
  9748. len = strlen(s);
  9749. INT_OFF;
  9750. if (g_parsefile->strpush || g_parsefile->spfree) {
  9751. sp = ckzalloc(sizeof(*sp));
  9752. sp->prev = g_parsefile->strpush;
  9753. } else {
  9754. sp = &(g_parsefile->basestrpush);
  9755. }
  9756. g_parsefile->strpush = sp;
  9757. sp->prev_string = g_parsefile->next_to_pgetc;
  9758. sp->prev_left_in_line = g_parsefile->left_in_line;
  9759. sp->unget = g_parsefile->unget;
  9760. sp->spfree = g_parsefile->spfree;
  9761. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9762. #if ENABLE_ASH_ALIAS
  9763. sp->ap = ap;
  9764. if (ap) {
  9765. ap->flag |= ALIASINUSE;
  9766. sp->string = s;
  9767. }
  9768. #endif
  9769. g_parsefile->next_to_pgetc = s;
  9770. g_parsefile->left_in_line = len;
  9771. g_parsefile->unget = 0;
  9772. g_parsefile->spfree = NULL;
  9773. INT_ON;
  9774. }
  9775. static void popstring(void)
  9776. {
  9777. struct strpush *sp = g_parsefile->strpush;
  9778. INT_OFF;
  9779. #if ENABLE_ASH_ALIAS
  9780. if (sp->ap) {
  9781. if (g_parsefile->next_to_pgetc[-1] == ' '
  9782. || g_parsefile->next_to_pgetc[-1] == '\t'
  9783. ) {
  9784. checkkwd |= CHKALIAS;
  9785. }
  9786. if (sp->string != sp->ap->val) {
  9787. free(sp->string);
  9788. }
  9789. }
  9790. #endif
  9791. g_parsefile->next_to_pgetc = sp->prev_string;
  9792. g_parsefile->left_in_line = sp->prev_left_in_line;
  9793. g_parsefile->unget = sp->unget;
  9794. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9795. g_parsefile->strpush = sp->prev;
  9796. g_parsefile->spfree = sp;
  9797. INT_ON;
  9798. }
  9799. static int
  9800. preadfd(void)
  9801. {
  9802. int nr;
  9803. char *buf = g_parsefile->buf;
  9804. g_parsefile->next_to_pgetc = buf;
  9805. #if ENABLE_FEATURE_EDITING
  9806. /* retry: */
  9807. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9808. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9809. else {
  9810. # if ENABLE_ASH_IDLE_TIMEOUT
  9811. int timeout = -1;
  9812. const char *tmout_var = lookupvar("TMOUT");
  9813. if (tmout_var) {
  9814. timeout = atoi(tmout_var) * 1000;
  9815. if (timeout <= 0)
  9816. timeout = -1;
  9817. }
  9818. line_input_state->timeout = timeout;
  9819. # endif
  9820. # if ENABLE_FEATURE_TAB_COMPLETION
  9821. line_input_state->path_lookup = pathval();
  9822. # endif
  9823. reinit_unicode_for_ash();
  9824. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9825. if (nr == 0) {
  9826. /* ^C pressed, "convert" to SIGINT */
  9827. write(STDOUT_FILENO, "^C", 2);
  9828. raise(SIGINT);
  9829. if (trap[SIGINT]) {
  9830. buf[0] = '\n';
  9831. buf[1] = '\0';
  9832. return 1;
  9833. }
  9834. exitstatus = 128 + SIGINT;
  9835. return -1;
  9836. }
  9837. if (nr < 0) {
  9838. if (errno == 0) {
  9839. /* Ctrl+D pressed */
  9840. nr = 0;
  9841. }
  9842. # if ENABLE_ASH_IDLE_TIMEOUT
  9843. else if (errno == EAGAIN && timeout > 0) {
  9844. puts("\007timed out waiting for input: auto-logout");
  9845. exitshell();
  9846. }
  9847. # endif
  9848. }
  9849. }
  9850. #else
  9851. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9852. #endif
  9853. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9854. if (nr < 0) {
  9855. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9856. int flags = fcntl(0, F_GETFL);
  9857. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9858. flags &= ~O_NONBLOCK;
  9859. if (fcntl(0, F_SETFL, flags) >= 0) {
  9860. out2str("sh: turning off NDELAY mode\n");
  9861. goto retry;
  9862. }
  9863. }
  9864. }
  9865. }
  9866. #endif
  9867. return nr;
  9868. }
  9869. /*
  9870. * Refill the input buffer and return the next input character:
  9871. *
  9872. * 1) If a string was pushed back on the input, pop it;
  9873. * 2) If we are reading from a string we can't refill the buffer, return EOF.
  9874. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9875. * 4) Process input up to the next newline, deleting nul characters.
  9876. */
  9877. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9878. #define pgetc_debug(...) ((void)0)
  9879. static int __pgetc(void);
  9880. static int
  9881. preadbuffer(void)
  9882. {
  9883. char *q;
  9884. int more;
  9885. if (unlikely(g_parsefile->strpush)) {
  9886. popstring();
  9887. return __pgetc();
  9888. }
  9889. if (g_parsefile->buf == NULL) {
  9890. pgetc_debug("preadbuffer PEOF1");
  9891. return PEOF;
  9892. }
  9893. more = g_parsefile->left_in_buffer;
  9894. if (more <= 0) {
  9895. flush_stdout_stderr();
  9896. again:
  9897. more = preadfd();
  9898. if (more <= 0) {
  9899. g_parsefile->left_in_buffer = g_parsefile->left_in_line = 0;
  9900. pgetc_debug("preadbuffer PEOF2");
  9901. return PEOF;
  9902. }
  9903. }
  9904. /* Find out where's the end of line.
  9905. * Set g_parsefile->left_in_line
  9906. * and g_parsefile->left_in_buffer acordingly.
  9907. * NUL chars are deleted.
  9908. */
  9909. q = g_parsefile->next_to_pgetc;
  9910. for (;;) {
  9911. char c;
  9912. more--;
  9913. c = *q;
  9914. if (c == '\0') {
  9915. memmove(q, q + 1, more);
  9916. } else {
  9917. q++;
  9918. if (c == '\n') {
  9919. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9920. break;
  9921. }
  9922. }
  9923. if (more <= 0) {
  9924. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9925. if (g_parsefile->left_in_line < 0)
  9926. goto again;
  9927. break;
  9928. }
  9929. }
  9930. g_parsefile->left_in_buffer = more;
  9931. if (vflag) {
  9932. char save = *q;
  9933. *q = '\0';
  9934. out2str(g_parsefile->next_to_pgetc);
  9935. *q = save;
  9936. }
  9937. pgetc_debug("preadbuffer at %d:%p'%s'",
  9938. g_parsefile->left_in_line,
  9939. g_parsefile->next_to_pgetc,
  9940. g_parsefile->next_to_pgetc);
  9941. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9942. }
  9943. static void
  9944. nlprompt(void)
  9945. {
  9946. if (trap_depth == 0)
  9947. g_parsefile->linno++;
  9948. setprompt_if(doprompt, 2);
  9949. }
  9950. static void
  9951. nlnoprompt(void)
  9952. {
  9953. if (trap_depth == 0)
  9954. g_parsefile->linno++;
  9955. needprompt = doprompt;
  9956. }
  9957. static void freestrings(struct strpush *sp)
  9958. {
  9959. INT_OFF;
  9960. do {
  9961. struct strpush *psp;
  9962. #if ENABLE_ASH_ALIAS
  9963. if (sp->ap) {
  9964. sp->ap->flag &= ~ALIASINUSE;
  9965. if (sp->ap->flag & ALIASDEAD) {
  9966. unalias(sp->ap->name);
  9967. }
  9968. }
  9969. #endif
  9970. psp = sp;
  9971. sp = sp->spfree;
  9972. if (psp != &(g_parsefile->basestrpush))
  9973. free(psp);
  9974. } while (sp);
  9975. g_parsefile->spfree = NULL;
  9976. INT_ON;
  9977. }
  9978. static int __pgetc(void)
  9979. {
  9980. int c;
  9981. pgetc_debug("pgetc at %d:%p'%s'",
  9982. g_parsefile->left_in_line,
  9983. g_parsefile->next_to_pgetc,
  9984. g_parsefile->next_to_pgetc);
  9985. if (g_parsefile->unget)
  9986. return g_parsefile->lastc[--g_parsefile->unget];
  9987. if (--g_parsefile->left_in_line >= 0)
  9988. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9989. else
  9990. c = preadbuffer();
  9991. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9992. g_parsefile->lastc[0] = c;
  9993. return c;
  9994. }
  9995. /*
  9996. * Read a character from the script, returning PEOF on end of file.
  9997. * Nul characters in the input are silently discarded.
  9998. */
  9999. static int pgetc(void)
  10000. {
  10001. struct strpush *sp = g_parsefile->spfree;
  10002. if (unlikely(sp))
  10003. freestrings(sp);
  10004. return __pgetc();
  10005. }
  10006. /*
  10007. * Undo a call to pgetc. Only two characters may be pushed back.
  10008. * PEOF may be pushed back.
  10009. */
  10010. static void
  10011. pungetc(void)
  10012. {
  10013. g_parsefile->unget++;
  10014. }
  10015. /* This one eats backslash+newline */
  10016. static int
  10017. pgetc_eatbnl(void)
  10018. {
  10019. int c;
  10020. while ((c = pgetc()) == '\\') {
  10021. if (pgetc() != '\n') {
  10022. pungetc();
  10023. break;
  10024. }
  10025. nlprompt();
  10026. }
  10027. return c;
  10028. }
  10029. struct synstack {
  10030. smalluint syntax;
  10031. uint8_t innerdq :1;
  10032. uint8_t varpushed :1;
  10033. uint8_t dblquote :1;
  10034. int varnest; /* levels of variables expansion */
  10035. int dqvarnest; /* levels of variables expansion within double quotes */
  10036. int parenlevel; /* levels of parens in arithmetic */
  10037. struct synstack *prev;
  10038. struct synstack *next;
  10039. };
  10040. static int
  10041. pgetc_top(struct synstack *stack)
  10042. {
  10043. return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
  10044. }
  10045. static void
  10046. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  10047. {
  10048. memset(next, 0, sizeof(*next));
  10049. next->syntax = syntax;
  10050. next->next = *stack;
  10051. (*stack)->prev = next;
  10052. *stack = next;
  10053. }
  10054. static ALWAYS_INLINE void
  10055. synstack_pop(struct synstack **stack)
  10056. {
  10057. *stack = (*stack)->next;
  10058. }
  10059. /*
  10060. * To handle the "." command, a stack of input files is used. Pushfile
  10061. * adds a new entry to the stack and popfile restores the previous level.
  10062. */
  10063. static void
  10064. pushfile(void)
  10065. {
  10066. struct parsefile *pf;
  10067. pf = ckzalloc(sizeof(*pf));
  10068. pf->prev = g_parsefile;
  10069. pf->pf_fd = -1;
  10070. /*pf->strpush = NULL; - ckzalloc did it */
  10071. /*pf->spfree = NULL;*/
  10072. /*pf->basestrpush.prev = NULL;*/
  10073. /*pf->unget = 0;*/
  10074. g_parsefile = pf;
  10075. }
  10076. static void
  10077. popfile(void)
  10078. {
  10079. struct parsefile *pf = g_parsefile;
  10080. if (pf == &basepf)
  10081. return;
  10082. INT_OFF;
  10083. if (pf->pf_fd >= 0)
  10084. close(pf->pf_fd);
  10085. free(pf->buf);
  10086. if (g_parsefile->spfree)
  10087. freestrings(g_parsefile->spfree);
  10088. while (pf->strpush) {
  10089. popstring();
  10090. freestrings(g_parsefile->spfree);
  10091. }
  10092. g_parsefile = pf->prev;
  10093. free(pf);
  10094. INT_ON;
  10095. }
  10096. static void
  10097. unwindfiles(struct parsefile *stop)
  10098. {
  10099. while (g_parsefile != stop)
  10100. popfile();
  10101. }
  10102. /*
  10103. * Return to top level.
  10104. */
  10105. static void
  10106. popallfiles(void)
  10107. {
  10108. unwindfiles(&basepf);
  10109. }
  10110. /*
  10111. * Close the file(s) that the shell is reading commands from. Called
  10112. * after a fork is done.
  10113. */
  10114. static void
  10115. closescript(void)
  10116. {
  10117. popallfiles();
  10118. if (g_parsefile->pf_fd > 0) {
  10119. close(g_parsefile->pf_fd);
  10120. g_parsefile->pf_fd = 0;
  10121. }
  10122. }
  10123. /*
  10124. * Like setinputfile, but takes an open file descriptor. Call this with
  10125. * interrupts off.
  10126. */
  10127. static void
  10128. setinputfd(int fd, int push)
  10129. {
  10130. if (push) {
  10131. pushfile();
  10132. g_parsefile->buf = NULL;
  10133. }
  10134. g_parsefile->pf_fd = fd;
  10135. if (g_parsefile->buf == NULL)
  10136. g_parsefile->buf = ckmalloc(IBUFSIZ);
  10137. g_parsefile->left_in_buffer = 0;
  10138. g_parsefile->left_in_line = 0;
  10139. g_parsefile->linno = 1;
  10140. }
  10141. /*
  10142. * Set the input to take input from a file. If push is set, push the
  10143. * old input onto the stack first.
  10144. */
  10145. static int
  10146. setinputfile(const char *fname, int flags)
  10147. {
  10148. int fd;
  10149. INT_OFF;
  10150. fd = open(fname, O_RDONLY | O_CLOEXEC);
  10151. if (fd < 0) {
  10152. if (flags & INPUT_NOFILE_OK)
  10153. goto out;
  10154. exitstatus = 127;
  10155. ash_msg_and_raise_perror("can't open '%s'", fname);
  10156. }
  10157. if (fd < 10)
  10158. fd = savefd(fd);
  10159. else if (O_CLOEXEC == 0) /* old libc */
  10160. close_on_exec_on(fd);
  10161. setinputfd(fd, flags & INPUT_PUSH_FILE);
  10162. out:
  10163. INT_ON;
  10164. return fd;
  10165. }
  10166. /*
  10167. * Like setinputfile, but takes input from a string.
  10168. */
  10169. static void
  10170. setinputstring(char *string)
  10171. {
  10172. INT_OFF;
  10173. pushfile();
  10174. g_parsefile->next_to_pgetc = string;
  10175. g_parsefile->left_in_line = strlen(string);
  10176. g_parsefile->buf = NULL;
  10177. g_parsefile->linno = lineno;
  10178. INT_ON;
  10179. }
  10180. /*
  10181. * Routines to check for mail.
  10182. */
  10183. #if ENABLE_ASH_MAIL
  10184. /* Hash of mtimes of mailboxes */
  10185. static unsigned mailtime_hash;
  10186. /* Set if MAIL or MAILPATH is changed. */
  10187. static smallint mail_var_path_changed;
  10188. /*
  10189. * Print appropriate message(s) if mail has arrived.
  10190. * If mail_var_path_changed is set,
  10191. * then the value of MAIL has mail_var_path_changed,
  10192. * so we just update the values.
  10193. */
  10194. static void
  10195. chkmail(void)
  10196. {
  10197. const char *mpath;
  10198. char *p;
  10199. char *q;
  10200. unsigned new_hash;
  10201. struct stackmark smark;
  10202. struct stat statb;
  10203. setstackmark(&smark);
  10204. mpath = mpathset() ? mpathval() : mailval();
  10205. new_hash = 0;
  10206. for (;;) {
  10207. int len;
  10208. len = padvance_magic(&mpath, nullstr, 2);
  10209. if (!len)
  10210. break;
  10211. p = stackblock();
  10212. break;
  10213. if (*p == '\0')
  10214. continue;
  10215. for (q = p; *q; q++)
  10216. continue;
  10217. #if DEBUG
  10218. if (q[-1] != '/')
  10219. abort();
  10220. #endif
  10221. q[-1] = '\0'; /* delete trailing '/' */
  10222. if (stat(p, &statb) < 0) {
  10223. continue;
  10224. }
  10225. /* Very simplistic "hash": just a sum of all mtimes */
  10226. new_hash += (unsigned)statb.st_mtime;
  10227. }
  10228. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  10229. if (mailtime_hash != 0)
  10230. out2str("you have mail\n");
  10231. mailtime_hash = new_hash;
  10232. }
  10233. mail_var_path_changed = 0;
  10234. popstackmark(&smark);
  10235. }
  10236. static void FAST_FUNC
  10237. changemail(const char *val UNUSED_PARAM)
  10238. {
  10239. mail_var_path_changed = 1;
  10240. }
  10241. #endif /* ASH_MAIL */
  10242. /* ============ ??? */
  10243. /*
  10244. * Set the shell parameters.
  10245. */
  10246. static void
  10247. setparam(char **argv)
  10248. {
  10249. char **newparam;
  10250. char **ap;
  10251. int nparam;
  10252. for (nparam = 0; argv[nparam]; nparam++)
  10253. continue;
  10254. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10255. while (*argv) {
  10256. *ap++ = ckstrdup(*argv++);
  10257. }
  10258. *ap = NULL;
  10259. freeparam(&shellparam);
  10260. shellparam.malloced = 1;
  10261. shellparam.nparam = nparam;
  10262. shellparam.p = newparam;
  10263. #if ENABLE_ASH_GETOPTS
  10264. shellparam.optind = 1;
  10265. shellparam.optoff = -1;
  10266. #endif
  10267. }
  10268. /*
  10269. * Process shell options. The global variable argptr contains a pointer
  10270. * to the argument list; we advance it past the options.
  10271. *
  10272. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10273. * For a non-interactive shell, an error condition encountered
  10274. * by a special built-in ... shall cause the shell to write a diagnostic message
  10275. * to standard error and exit as shown in the following table:
  10276. * Error Special Built-In
  10277. * ...
  10278. * Utility syntax error (option or operand error) Shall exit
  10279. * ...
  10280. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10281. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10282. * and shell continues), and people rely on this behavior!
  10283. * Testcase:
  10284. * set -o barfoo 2>/dev/null
  10285. * echo $?
  10286. *
  10287. * Oh well. Let's mimic that.
  10288. */
  10289. static int
  10290. plus_minus_o(char *name, int val)
  10291. {
  10292. int i;
  10293. if (name) {
  10294. for (i = 0; i < NOPTS; i++) {
  10295. if (strcmp(name, optnames(i)) == 0) {
  10296. optlist[i] = val;
  10297. return 0;
  10298. }
  10299. }
  10300. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10301. return 1;
  10302. }
  10303. for (i = 0; i < NOPTS; i++) {
  10304. if (optnames(i)[0] == '\0')
  10305. continue;
  10306. if (val) {
  10307. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10308. } else {
  10309. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10310. }
  10311. }
  10312. return 0;
  10313. }
  10314. static void
  10315. setoption(int flag, int val)
  10316. {
  10317. int i;
  10318. for (i = 0; i < NOPTS; i++) {
  10319. if (optletters(i) == flag && optnames(i)[0] != '\0') {
  10320. optlist[i] = val;
  10321. return;
  10322. }
  10323. }
  10324. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10325. /* NOTREACHED */
  10326. }
  10327. /* If login_sh is not NULL, we are called to parse command line opts,
  10328. * not "set -opts"
  10329. */
  10330. static int
  10331. options(int *login_sh)
  10332. {
  10333. char *p;
  10334. int val;
  10335. int c;
  10336. if (login_sh)
  10337. minusc = NULL;
  10338. while ((p = *argptr) != NULL) {
  10339. c = *p++;
  10340. if (c != '-' && c != '+')
  10341. break;
  10342. argptr++;
  10343. val = 0; /* val = 0 if c == '+' */
  10344. if (c == '-') {
  10345. val = 1;
  10346. if (p[0] == '\0' || LONE_DASH(p)) {
  10347. if (!login_sh) {
  10348. /* "-" means turn off -x and -v */
  10349. if (p[0] == '\0')
  10350. xflag = vflag = 0;
  10351. /* "--" means reset params */
  10352. else if (*argptr == NULL)
  10353. setparam(argptr);
  10354. }
  10355. break; /* "-" or "--" terminates options */
  10356. }
  10357. }
  10358. /* first char was + or - */
  10359. while ((c = *p++) != '\0') {
  10360. if (login_sh) {
  10361. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10362. if (c == 'c') {
  10363. minusc = p; /* command is after shell args */
  10364. cflag = 1;
  10365. continue;
  10366. }
  10367. if (c == 's') { /* -s, +s */
  10368. sflag = 1;
  10369. continue;
  10370. }
  10371. if (c == 'i') { /* -i, +i */
  10372. iflag = 1;
  10373. continue;
  10374. }
  10375. if (c == 'l') {
  10376. *login_sh = 1; /* -l or +l == --login */
  10377. continue;
  10378. }
  10379. /* bash does not accept +-login, we also won't */
  10380. if (val && (c == '-')) { /* long options */
  10381. if (strcmp(p, "login") == 0) {
  10382. *login_sh = 1;
  10383. }
  10384. break;
  10385. }
  10386. }
  10387. if (c == 'o') {
  10388. if (plus_minus_o(*argptr, val)) {
  10389. /* it already printed err message */
  10390. return 1; /* error */
  10391. }
  10392. if (*argptr)
  10393. argptr++;
  10394. } else {
  10395. setoption(c, val);
  10396. }
  10397. }
  10398. }
  10399. return 0;
  10400. }
  10401. /*
  10402. * The shift builtin command.
  10403. */
  10404. static int FAST_FUNC
  10405. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10406. {
  10407. int n;
  10408. char **ap1, **ap2;
  10409. n = 1;
  10410. if (argv[1])
  10411. n = number(argv[1]);
  10412. if (n > shellparam.nparam)
  10413. return 1;
  10414. INT_OFF;
  10415. shellparam.nparam -= n;
  10416. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10417. if (shellparam.malloced)
  10418. free(*ap1);
  10419. }
  10420. ap2 = shellparam.p;
  10421. while ((*ap2++ = *ap1++) != NULL)
  10422. continue;
  10423. #if ENABLE_ASH_GETOPTS
  10424. shellparam.optind = 1;
  10425. shellparam.optoff = -1;
  10426. #endif
  10427. INT_ON;
  10428. return 0;
  10429. }
  10430. /*
  10431. * POSIX requires that 'set' (but not export or readonly) output the
  10432. * variables in lexicographic order - by the locale's collating order (sigh).
  10433. * Maybe we could keep them in an ordered balanced binary tree
  10434. * instead of hashed lists.
  10435. * For now just roll 'em through qsort for printing...
  10436. */
  10437. static int
  10438. showvars(const char *sep_prefix, int on, int off)
  10439. {
  10440. const char *sep;
  10441. char **ep, **epend;
  10442. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10443. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10444. sep = *sep_prefix ? " " : sep_prefix;
  10445. for (; ep < epend; ep++) {
  10446. const char *p;
  10447. const char *q;
  10448. p = endofname(*ep);
  10449. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10450. * makes "export -p" to have output not suitable for "eval":
  10451. * import os
  10452. * os.environ["test-test"]="test"
  10453. * if os.fork() == 0:
  10454. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10455. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10456. */
  10457. q = nullstr;
  10458. if (*p == '=')
  10459. q = single_quote(++p);
  10460. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10461. }
  10462. return 0;
  10463. }
  10464. /*
  10465. * The set command builtin.
  10466. */
  10467. static int FAST_FUNC
  10468. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10469. {
  10470. int retval;
  10471. if (!argv[1])
  10472. return showvars(nullstr, 0, VUNSET);
  10473. INT_OFF;
  10474. retval = options(/*login_sh:*/ NULL);
  10475. if (retval == 0) { /* if no parse error... */
  10476. optschanged();
  10477. if (*argptr != NULL) {
  10478. setparam(argptr);
  10479. }
  10480. }
  10481. INT_ON;
  10482. return retval;
  10483. }
  10484. #if ENABLE_ASH_RANDOM_SUPPORT
  10485. static void FAST_FUNC
  10486. change_random(const char *value)
  10487. {
  10488. uint32_t t;
  10489. if (value == NULL) {
  10490. /* "get", generate */
  10491. t = next_random(&random_gen);
  10492. /* set without recursion */
  10493. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10494. vrandom.flags &= ~VNOFUNC;
  10495. } else {
  10496. /* set/reset */
  10497. t = strtoul(value, NULL, 10);
  10498. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10499. }
  10500. }
  10501. #endif
  10502. #if BASH_EPOCH_VARS
  10503. static void FAST_FUNC
  10504. change_epoch(struct var *vepoch, const char *fmt)
  10505. {
  10506. struct timeval tv;
  10507. char buffer[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
  10508. xgettimeofday(&tv);
  10509. sprintf(buffer, fmt, (unsigned long long)tv.tv_sec, (unsigned)tv.tv_usec);
  10510. setvar(vepoch->var_text, buffer, VNOFUNC);
  10511. vepoch->flags &= ~VNOFUNC;
  10512. }
  10513. static void FAST_FUNC
  10514. change_seconds(const char *value UNUSED_PARAM)
  10515. {
  10516. change_epoch(&vepochs, "%llu");
  10517. }
  10518. static void FAST_FUNC
  10519. change_realtime(const char *value UNUSED_PARAM)
  10520. {
  10521. change_epoch(&vepochr, "%llu.%06u");
  10522. }
  10523. #endif
  10524. #if ENABLE_ASH_GETOPTS
  10525. static int
  10526. getopts(char *optstr, char *optvar, char **optfirst)
  10527. {
  10528. char *p, *q;
  10529. char c = '?';
  10530. int done = 0;
  10531. char sbuf[2];
  10532. char **optnext;
  10533. int ind = shellparam.optind;
  10534. int off = shellparam.optoff;
  10535. sbuf[1] = '\0';
  10536. shellparam.optind = -1;
  10537. optnext = optfirst + ind - 1;
  10538. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10539. p = NULL;
  10540. else
  10541. p = optnext[-1] + off;
  10542. if (p == NULL || *p == '\0') {
  10543. /* Current word is done, advance */
  10544. p = *optnext;
  10545. if (p == NULL || *p != '-' || *++p == '\0') {
  10546. atend:
  10547. unsetvar("OPTARG");
  10548. p = NULL;
  10549. done = 1;
  10550. goto out;
  10551. }
  10552. optnext++;
  10553. if (LONE_DASH(p)) /* check for "--" */
  10554. goto atend;
  10555. }
  10556. c = *p++;
  10557. for (q = optstr; *q != c;) {
  10558. if (*q == '\0') {
  10559. /* OPTERR is a bashism */
  10560. const char *cp = lookupvar("OPTERR");
  10561. if ((cp && LONE_CHAR(cp, '0'))
  10562. || (optstr[0] == ':')
  10563. ) {
  10564. sbuf[0] = c;
  10565. /*sbuf[1] = '\0'; - already is */
  10566. setvar0("OPTARG", sbuf);
  10567. } else {
  10568. fprintf(stderr, "Illegal option -%c\n", c);
  10569. unsetvar("OPTARG");
  10570. }
  10571. c = '?';
  10572. goto out;
  10573. }
  10574. if (*++q == ':')
  10575. q++;
  10576. }
  10577. if (*++q == ':') {
  10578. if (*p == '\0' && (p = *optnext) == NULL) {
  10579. /* OPTERR is a bashism */
  10580. const char *cp = lookupvar("OPTERR");
  10581. if ((cp && LONE_CHAR(cp, '0'))
  10582. || (optstr[0] == ':')
  10583. ) {
  10584. sbuf[0] = c;
  10585. /*sbuf[1] = '\0'; - already is */
  10586. setvar0("OPTARG", sbuf);
  10587. c = ':';
  10588. } else {
  10589. fprintf(stderr, "No arg for -%c option\n", c);
  10590. unsetvar("OPTARG");
  10591. c = '?';
  10592. }
  10593. goto out;
  10594. }
  10595. if (p == *optnext)
  10596. optnext++;
  10597. setvar0("OPTARG", p);
  10598. p = NULL;
  10599. } else
  10600. setvar0("OPTARG", nullstr);
  10601. out:
  10602. ind = optnext - optfirst + 1;
  10603. setvar("OPTIND", itoa(ind), VNOFUNC);
  10604. sbuf[0] = c;
  10605. /*sbuf[1] = '\0'; - already is */
  10606. setvar0(optvar, sbuf);
  10607. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10608. shellparam.optind = ind;
  10609. return done;
  10610. }
  10611. /*
  10612. * The getopts builtin. Shellparam.optnext points to the next argument
  10613. * to be processed. Shellparam.optptr points to the next character to
  10614. * be processed in the current argument. If shellparam.optnext is NULL,
  10615. * then it's the first time getopts has been called.
  10616. */
  10617. static int FAST_FUNC
  10618. getoptscmd(int argc, char **argv)
  10619. {
  10620. char **optbase;
  10621. if (argc < 3)
  10622. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10623. if (argc == 3) {
  10624. optbase = shellparam.p;
  10625. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10626. shellparam.optind = 1;
  10627. shellparam.optoff = -1;
  10628. }
  10629. } else {
  10630. optbase = &argv[3];
  10631. if ((unsigned)shellparam.optind > argc - 2) {
  10632. shellparam.optind = 1;
  10633. shellparam.optoff = -1;
  10634. }
  10635. }
  10636. return getopts(argv[1], argv[2], optbase);
  10637. }
  10638. #endif /* ASH_GETOPTS */
  10639. /* ============ Shell parser */
  10640. struct heredoc {
  10641. struct heredoc *next; /* next here document in list */
  10642. union node *here; /* redirection node */
  10643. char *eofmark; /* string indicating end of input */
  10644. smallint striptabs; /* if set, strip leading tabs */
  10645. };
  10646. static smallint tokpushback; /* last token pushed back */
  10647. static smallint quoteflag; /* set if (part of) last token was quoted */
  10648. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10649. static struct heredoc *heredoclist; /* list of here documents to read */
  10650. static char *wordtext; /* text of last word returned by readtoken */
  10651. static struct nodelist *backquotelist;
  10652. static union node *redirnode;
  10653. static struct heredoc *heredoc;
  10654. static const char *
  10655. tokname(char *buf, int tok)
  10656. {
  10657. if (tok < TSEMI)
  10658. return tokname_array[tok];
  10659. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10660. return buf;
  10661. }
  10662. /* raise_error_unexpected_syntax:
  10663. * Called when an unexpected token is read during the parse. The argument
  10664. * is the token that is expected, or -1 if more than one type of token can
  10665. * occur at this point.
  10666. */
  10667. static void raise_error_unexpected_syntax(int) NORETURN;
  10668. static void
  10669. raise_error_unexpected_syntax(int token)
  10670. {
  10671. char msg[64];
  10672. char buf[16];
  10673. int l;
  10674. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10675. if (token >= 0)
  10676. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10677. raise_error_syntax(msg);
  10678. /* NOTREACHED */
  10679. }
  10680. /* parsing is heavily cross-recursive, need these forward decls */
  10681. static union node *andor(void);
  10682. static union node *pipeline(void);
  10683. static union node *parse_command(void);
  10684. static void parseheredoc(void);
  10685. static int readtoken(void);
  10686. static union node *
  10687. list(int nlflag)
  10688. {
  10689. int chknl = nlflag & 1 ? 0 : CHKNL;
  10690. union node *n1, *n2, *n3;
  10691. int tok;
  10692. n1 = NULL;
  10693. for (;;) {
  10694. checkkwd = chknl | CHKKWD | CHKALIAS;
  10695. tok = readtoken();
  10696. switch (tok) {
  10697. case TNL:
  10698. parseheredoc();
  10699. return n1;
  10700. case TEOF:
  10701. if (!n1 && !chknl)
  10702. n1 = NODE_EOF;
  10703. out_eof:
  10704. parseheredoc();
  10705. tokpushback++;
  10706. lasttoken = TEOF;
  10707. return n1;
  10708. }
  10709. tokpushback++;
  10710. if (nlflag == 2 && ((1 << tok) & tokendlist))
  10711. return n1;
  10712. nlflag |= 2;
  10713. n2 = andor();
  10714. tok = readtoken();
  10715. if (tok == TBACKGND) {
  10716. if (n2->type == NPIPE) {
  10717. n2->npipe.pipe_backgnd = 1;
  10718. } else {
  10719. if (n2->type != NREDIR) {
  10720. n3 = stzalloc(sizeof(struct nredir));
  10721. n3->nredir.n = n2;
  10722. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10723. n2 = n3;
  10724. }
  10725. n2->type = NBACKGND;
  10726. }
  10727. }
  10728. if (n1 == NULL) {
  10729. n1 = n2;
  10730. } else {
  10731. n3 = stzalloc(sizeof(struct nbinary));
  10732. n3->type = NSEMI;
  10733. n3->nbinary.ch1 = n1;
  10734. n3->nbinary.ch2 = n2;
  10735. n1 = n3;
  10736. }
  10737. switch (tok) {
  10738. case TEOF:
  10739. goto out_eof;
  10740. case TNL:
  10741. tokpushback = 1;
  10742. /* fall through */
  10743. case TBACKGND:
  10744. case TSEMI:
  10745. break;
  10746. default:
  10747. if (!chknl)
  10748. raise_error_unexpected_syntax(-1);
  10749. tokpushback = 1;
  10750. return n1;
  10751. }
  10752. }
  10753. }
  10754. static union node *
  10755. andor(void)
  10756. {
  10757. union node *n1, *n2, *n3;
  10758. int t;
  10759. n1 = pipeline();
  10760. for (;;) {
  10761. t = readtoken();
  10762. if (t == TAND) {
  10763. t = NAND;
  10764. } else if (t == TOR) {
  10765. t = NOR;
  10766. } else {
  10767. tokpushback = 1;
  10768. return n1;
  10769. }
  10770. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10771. n2 = pipeline();
  10772. n3 = stzalloc(sizeof(struct nbinary));
  10773. n3->type = t;
  10774. n3->nbinary.ch1 = n1;
  10775. n3->nbinary.ch2 = n2;
  10776. n1 = n3;
  10777. }
  10778. }
  10779. static union node *
  10780. pipeline(void)
  10781. {
  10782. union node *n1, *n2, *pipenode;
  10783. struct nodelist *lp, *prev;
  10784. int negate;
  10785. negate = 0;
  10786. TRACE(("pipeline: entered\n"));
  10787. if (readtoken() == TNOT) {
  10788. negate = !negate;
  10789. checkkwd = CHKKWD | CHKALIAS;
  10790. } else
  10791. tokpushback = 1;
  10792. n1 = parse_command();
  10793. if (readtoken() == TPIPE) {
  10794. pipenode = stzalloc(sizeof(struct npipe));
  10795. pipenode->type = NPIPE;
  10796. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10797. lp = stzalloc(sizeof(struct nodelist));
  10798. pipenode->npipe.cmdlist = lp;
  10799. lp->n = n1;
  10800. do {
  10801. prev = lp;
  10802. lp = stzalloc(sizeof(struct nodelist));
  10803. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10804. lp->n = parse_command();
  10805. prev->next = lp;
  10806. } while (readtoken() == TPIPE);
  10807. lp->next = NULL;
  10808. n1 = pipenode;
  10809. }
  10810. tokpushback = 1;
  10811. if (negate) {
  10812. n2 = stzalloc(sizeof(struct nnot));
  10813. n2->type = NNOT;
  10814. n2->nnot.com = n1;
  10815. return n2;
  10816. }
  10817. return n1;
  10818. }
  10819. static union node *
  10820. makename(void)
  10821. {
  10822. union node *n;
  10823. n = stzalloc(sizeof(struct narg));
  10824. n->type = NARG;
  10825. /*n->narg.next = NULL; - stzalloc did it */
  10826. n->narg.text = wordtext;
  10827. n->narg.backquote = backquotelist;
  10828. return n;
  10829. }
  10830. static void
  10831. fixredir(union node *n, const char *text, int err)
  10832. {
  10833. int fd;
  10834. TRACE(("Fix redir %s %d\n", text, err));
  10835. if (!err)
  10836. n->ndup.vname = NULL;
  10837. fd = bb_strtou(text, NULL, 10);
  10838. if (!errno && fd >= 0)
  10839. n->ndup.dupfd = fd;
  10840. else if (LONE_DASH(text))
  10841. n->ndup.dupfd = -1;
  10842. else {
  10843. if (err)
  10844. raise_error_syntax("bad fd number");
  10845. n->ndup.vname = makename();
  10846. }
  10847. }
  10848. static void
  10849. parsefname(void)
  10850. {
  10851. union node *n = redirnode;
  10852. if (n->type == NHERE)
  10853. checkkwd = CHKEOFMARK;
  10854. if (readtoken() != TWORD)
  10855. raise_error_unexpected_syntax(-1);
  10856. if (n->type == NHERE) {
  10857. struct heredoc *here = heredoc;
  10858. struct heredoc *p;
  10859. if (quoteflag == 0)
  10860. n->type = NXHERE;
  10861. TRACE(("Here document %d\n", n->type));
  10862. rmescapes(wordtext, 0, NULL);
  10863. here->eofmark = wordtext;
  10864. here->next = NULL;
  10865. if (heredoclist == NULL)
  10866. heredoclist = here;
  10867. else {
  10868. for (p = heredoclist; p->next; p = p->next)
  10869. continue;
  10870. p->next = here;
  10871. }
  10872. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10873. fixredir(n, wordtext, 0);
  10874. } else {
  10875. n->nfile.fname = makename();
  10876. }
  10877. }
  10878. static union node *
  10879. simplecmd(void)
  10880. {
  10881. union node *args, **app;
  10882. union node *n = NULL;
  10883. union node *vars, **vpp;
  10884. union node **rpp, *redir;
  10885. int savecheckkwd;
  10886. int savelinno;
  10887. #if BASH_TEST2
  10888. smallint double_brackets_flag = 0;
  10889. #endif
  10890. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10891. args = NULL;
  10892. app = &args;
  10893. vars = NULL;
  10894. vpp = &vars;
  10895. redir = NULL;
  10896. rpp = &redir;
  10897. savecheckkwd = CHKALIAS;
  10898. savelinno = g_parsefile->linno;
  10899. for (;;) {
  10900. int t;
  10901. checkkwd = savecheckkwd;
  10902. t = readtoken();
  10903. switch (t) {
  10904. #if BASH_FUNCTION
  10905. case TFUNCTION:
  10906. if (readtoken() != TWORD)
  10907. raise_error_unexpected_syntax(TWORD);
  10908. tokpushback = 1;
  10909. function_flag = 1;
  10910. break;
  10911. #endif
  10912. #if BASH_TEST2
  10913. case TAND: /* "&&" */
  10914. case TOR: /* "||" */
  10915. if (!double_brackets_flag) {
  10916. tokpushback = 1;
  10917. goto out;
  10918. }
  10919. /* pass "&&" or "||" to [[ ]] as literal args */
  10920. wordtext = (char *) (t == TAND ? "&&" : "||");
  10921. #endif
  10922. case TWORD:
  10923. n = stzalloc(sizeof(struct narg));
  10924. n->type = NARG;
  10925. /*n->narg.next = NULL; - stzalloc did it */
  10926. n->narg.text = wordtext;
  10927. #if BASH_TEST2
  10928. if (strcmp("[[", wordtext) == 0)
  10929. double_brackets_flag = 1;
  10930. else if (strcmp("]]", wordtext) == 0)
  10931. double_brackets_flag = 0;
  10932. #endif
  10933. n->narg.backquote = backquotelist;
  10934. if (savecheckkwd && isassignment(wordtext)) {
  10935. *vpp = n;
  10936. vpp = &n->narg.next;
  10937. } else {
  10938. *app = n;
  10939. app = &n->narg.next;
  10940. savecheckkwd = 0;
  10941. }
  10942. #if BASH_FUNCTION
  10943. if (function_flag) {
  10944. checkkwd = CHKNL | CHKKWD;
  10945. t = readtoken();
  10946. tokpushback = 1;
  10947. switch (t) {
  10948. case TBEGIN:
  10949. case TIF:
  10950. case TCASE:
  10951. case TUNTIL:
  10952. case TWHILE:
  10953. case TFOR:
  10954. goto do_func;
  10955. case TLP:
  10956. function_flag = 0;
  10957. break;
  10958. # if BASH_TEST2
  10959. case TWORD:
  10960. if (strcmp("[[", wordtext) == 0)
  10961. goto do_func;
  10962. /* fall through */
  10963. # endif
  10964. default:
  10965. raise_error_unexpected_syntax(-1);
  10966. }
  10967. }
  10968. #endif
  10969. break;
  10970. case TREDIR:
  10971. *rpp = n = redirnode;
  10972. rpp = &n->nfile.next;
  10973. parsefname(); /* read name of redirection file */
  10974. break;
  10975. case TLP:
  10976. IF_BASH_FUNCTION(do_func:)
  10977. if (args && app == &args->narg.next
  10978. && !vars && !redir
  10979. ) {
  10980. struct builtincmd *bcmd;
  10981. const char *name;
  10982. /* We have a function */
  10983. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10984. raise_error_unexpected_syntax(TRP);
  10985. name = n->narg.text;
  10986. if (!goodname(name)
  10987. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10988. ) {
  10989. raise_error_syntax("bad function name");
  10990. }
  10991. n->type = NDEFUN;
  10992. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10993. n->ndefun.text = n->narg.text;
  10994. n->ndefun.linno = g_parsefile->linno;
  10995. n->ndefun.body = parse_command();
  10996. return n;
  10997. }
  10998. IF_BASH_FUNCTION(function_flag = 0;)
  10999. /* fall through */
  11000. default:
  11001. tokpushback = 1;
  11002. goto out;
  11003. }
  11004. }
  11005. out:
  11006. *app = NULL;
  11007. *vpp = NULL;
  11008. *rpp = NULL;
  11009. n = stzalloc(sizeof(struct ncmd));
  11010. if (NCMD != 0)
  11011. n->type = NCMD;
  11012. n->ncmd.linno = savelinno;
  11013. n->ncmd.args = args;
  11014. n->ncmd.assign = vars;
  11015. n->ncmd.redirect = redir;
  11016. return n;
  11017. }
  11018. static union node *
  11019. parse_command(void)
  11020. {
  11021. union node *n1, *n2;
  11022. union node *ap, **app;
  11023. union node *cp, **cpp;
  11024. union node *redir, **rpp;
  11025. union node **rpp2;
  11026. int t;
  11027. int savelinno;
  11028. redir = NULL;
  11029. rpp2 = &redir;
  11030. savelinno = g_parsefile->linno;
  11031. switch (readtoken()) {
  11032. default:
  11033. raise_error_unexpected_syntax(-1);
  11034. /* NOTREACHED */
  11035. case TIF:
  11036. n1 = stzalloc(sizeof(struct nif));
  11037. n1->type = NIF;
  11038. n1->nif.test = list(0);
  11039. if (readtoken() != TTHEN)
  11040. raise_error_unexpected_syntax(TTHEN);
  11041. n1->nif.ifpart = list(0);
  11042. n2 = n1;
  11043. while (readtoken() == TELIF) {
  11044. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  11045. n2 = n2->nif.elsepart;
  11046. n2->type = NIF;
  11047. n2->nif.test = list(0);
  11048. if (readtoken() != TTHEN)
  11049. raise_error_unexpected_syntax(TTHEN);
  11050. n2->nif.ifpart = list(0);
  11051. }
  11052. if (lasttoken == TELSE)
  11053. n2->nif.elsepart = list(0);
  11054. else {
  11055. n2->nif.elsepart = NULL;
  11056. tokpushback = 1;
  11057. }
  11058. t = TFI;
  11059. break;
  11060. case TWHILE:
  11061. case TUNTIL: {
  11062. int got;
  11063. n1 = stzalloc(sizeof(struct nbinary));
  11064. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  11065. n1->nbinary.ch1 = list(0);
  11066. got = readtoken();
  11067. if (got != TDO) {
  11068. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  11069. got == TWORD ? wordtext : ""));
  11070. raise_error_unexpected_syntax(TDO);
  11071. }
  11072. n1->nbinary.ch2 = list(0);
  11073. t = TDONE;
  11074. break;
  11075. }
  11076. case TFOR:
  11077. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  11078. raise_error_syntax("bad for loop variable");
  11079. n1 = stzalloc(sizeof(struct nfor));
  11080. n1->type = NFOR;
  11081. n1->nfor.linno = savelinno;
  11082. n1->nfor.var = wordtext;
  11083. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11084. if (readtoken() == TIN) {
  11085. app = &ap;
  11086. while (readtoken() == TWORD) {
  11087. n2 = stzalloc(sizeof(struct narg));
  11088. n2->type = NARG;
  11089. /*n2->narg.next = NULL; - stzalloc did it */
  11090. n2->narg.text = wordtext;
  11091. n2->narg.backquote = backquotelist;
  11092. *app = n2;
  11093. app = &n2->narg.next;
  11094. }
  11095. *app = NULL;
  11096. n1->nfor.args = ap;
  11097. if (lasttoken != TNL && lasttoken != TSEMI)
  11098. raise_error_unexpected_syntax(-1);
  11099. } else {
  11100. n2 = stzalloc(sizeof(struct narg));
  11101. n2->type = NARG;
  11102. /*n2->narg.next = NULL; - stzalloc did it */
  11103. n2->narg.text = (char *)dolatstr;
  11104. /*n2->narg.backquote = NULL;*/
  11105. n1->nfor.args = n2;
  11106. /*
  11107. * Newline or semicolon here is optional (but note
  11108. * that the original Bourne shell only allowed NL).
  11109. */
  11110. if (lasttoken != TSEMI)
  11111. tokpushback = 1;
  11112. }
  11113. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11114. if (readtoken() != TDO)
  11115. raise_error_unexpected_syntax(TDO);
  11116. n1->nfor.body = list(0);
  11117. t = TDONE;
  11118. break;
  11119. case TCASE:
  11120. n1 = stzalloc(sizeof(struct ncase));
  11121. n1->type = NCASE;
  11122. n1->ncase.linno = savelinno;
  11123. if (readtoken() != TWORD)
  11124. raise_error_unexpected_syntax(TWORD);
  11125. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  11126. n2->type = NARG;
  11127. /*n2->narg.next = NULL; - stzalloc did it */
  11128. n2->narg.text = wordtext;
  11129. n2->narg.backquote = backquotelist;
  11130. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11131. if (readtoken() != TIN)
  11132. raise_error_unexpected_syntax(TIN);
  11133. cpp = &n1->ncase.cases;
  11134. next_case:
  11135. checkkwd = CHKNL | CHKKWD;
  11136. t = readtoken();
  11137. while (t != TESAC) {
  11138. if (lasttoken == TLP)
  11139. readtoken();
  11140. *cpp = cp = stzalloc(sizeof(struct nclist));
  11141. cp->type = NCLIST;
  11142. app = &cp->nclist.pattern;
  11143. for (;;) {
  11144. *app = ap = stzalloc(sizeof(struct narg));
  11145. ap->type = NARG;
  11146. /*ap->narg.next = NULL; - stzalloc did it */
  11147. ap->narg.text = wordtext;
  11148. ap->narg.backquote = backquotelist;
  11149. if (readtoken() != TPIPE)
  11150. break;
  11151. app = &ap->narg.next;
  11152. readtoken();
  11153. }
  11154. //ap->narg.next = NULL;
  11155. if (lasttoken != TRP)
  11156. raise_error_unexpected_syntax(TRP);
  11157. cp->nclist.body = list(2);
  11158. cpp = &cp->nclist.next;
  11159. checkkwd = CHKNL | CHKKWD;
  11160. t = readtoken();
  11161. if (t != TESAC) {
  11162. if (t != TENDCASE)
  11163. raise_error_unexpected_syntax(TENDCASE);
  11164. goto next_case;
  11165. }
  11166. }
  11167. *cpp = NULL;
  11168. goto redir;
  11169. case TLP:
  11170. n1 = stzalloc(sizeof(struct nredir));
  11171. n1->type = NSUBSHELL;
  11172. n1->nredir.linno = savelinno;
  11173. n1->nredir.n = list(0);
  11174. /*n1->nredir.redirect = NULL; - stzalloc did it */
  11175. t = TRP;
  11176. break;
  11177. case TBEGIN:
  11178. n1 = list(0);
  11179. t = TEND;
  11180. break;
  11181. IF_BASH_FUNCTION(case TFUNCTION:)
  11182. case TWORD:
  11183. case TREDIR:
  11184. tokpushback = 1;
  11185. return simplecmd();
  11186. }
  11187. if (readtoken() != t)
  11188. raise_error_unexpected_syntax(t);
  11189. redir:
  11190. /* Now check for redirection which may follow command */
  11191. checkkwd = CHKKWD | CHKALIAS;
  11192. rpp = rpp2;
  11193. while (readtoken() == TREDIR) {
  11194. *rpp = n2 = redirnode;
  11195. rpp = &n2->nfile.next;
  11196. parsefname();
  11197. }
  11198. tokpushback = 1;
  11199. *rpp = NULL;
  11200. if (redir) {
  11201. if (n1->type != NSUBSHELL) {
  11202. n2 = stzalloc(sizeof(struct nredir));
  11203. n2->type = NREDIR;
  11204. n2->nredir.linno = savelinno;
  11205. n2->nredir.n = n1;
  11206. n1 = n2;
  11207. }
  11208. n1->nredir.redirect = redir;
  11209. }
  11210. return n1;
  11211. }
  11212. #if BASH_DOLLAR_SQUOTE
  11213. static int
  11214. decode_dollar_squote(void)
  11215. {
  11216. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  11217. int c, cnt;
  11218. char *p;
  11219. char buf[4];
  11220. c = pgetc();
  11221. p = strchr(C_escapes, c);
  11222. if (p) {
  11223. buf[0] = c;
  11224. p = buf;
  11225. cnt = 3;
  11226. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  11227. do {
  11228. c = pgetc();
  11229. *++p = c;
  11230. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  11231. pungetc();
  11232. } else if (c == 'x') { /* \xHH */
  11233. do {
  11234. c = pgetc();
  11235. *++p = c;
  11236. } while (isxdigit(c) && --cnt);
  11237. pungetc();
  11238. if (cnt == 3) { /* \x but next char is "bad" */
  11239. c = 'x';
  11240. goto unrecognized;
  11241. }
  11242. } else { /* simple seq like \\ or \t */
  11243. p++;
  11244. }
  11245. *p = '\0';
  11246. p = buf;
  11247. c = bb_process_escape_sequence((void*)&p);
  11248. } else { /* unrecognized "\z": print both chars unless ' or " */
  11249. if (c != '\'' && c != '"') {
  11250. unrecognized:
  11251. c |= 0x100; /* "please encode \, then me" */
  11252. }
  11253. }
  11254. return c;
  11255. }
  11256. #endif
  11257. /* Used by expandstr to get here-doc like behaviour. */
  11258. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  11259. static ALWAYS_INLINE int
  11260. realeofmark(const char *eofmark)
  11261. {
  11262. return eofmark && eofmark != FAKEEOFMARK;
  11263. }
  11264. /*
  11265. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  11266. * is not NULL, read a here document. In the latter case, eofmark is the
  11267. * word which marks the end of the document and striptabs is true if
  11268. * leading tabs should be stripped from the document. The argument c
  11269. * is the first character of the input token or document.
  11270. *
  11271. * Because C does not have internal subroutines, I have simulated them
  11272. * using goto's to implement the subroutine linkage. The following macros
  11273. * will run code that appears at the end of readtoken1.
  11274. */
  11275. #define CHECKEND() {goto checkend; checkend_return:;}
  11276. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  11277. #define PARSESUB() {goto parsesub; parsesub_return:;}
  11278. #define PARSEBACKQOLD() {style = OLD; goto parsebackq; parsebackq_oldreturn:;}
  11279. #define PARSEBACKQNEW() {style = NEW; goto parsebackq; parsebackq_newreturn:;}
  11280. #define PARSEPROCSUB() {style = PSUB; goto parsebackq; parsebackq_psreturn:;}
  11281. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  11282. static int
  11283. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  11284. {
  11285. /* NB: syntax parameter fits into smallint */
  11286. /* c parameter is an unsigned char or PEOF */
  11287. char *out;
  11288. size_t len;
  11289. struct nodelist *bqlist;
  11290. smallint quotef;
  11291. smallint style;
  11292. enum { OLD, NEW, PSUB };
  11293. #define oldstyle (style == OLD)
  11294. smallint pssyntax; /* we are expanding a prompt string */
  11295. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  11296. /* syntax stack */
  11297. struct synstack synbase = { };
  11298. struct synstack *synstack = &synbase;
  11299. #if ENABLE_ASH_EXPAND_PRMT
  11300. pssyntax = (syntax == PSSYNTAX);
  11301. if (pssyntax)
  11302. syntax = DQSYNTAX;
  11303. #else
  11304. pssyntax = 0; /* constant */
  11305. #endif
  11306. synstack->syntax = syntax;
  11307. if (syntax == DQSYNTAX)
  11308. synstack->dblquote = 1;
  11309. quotef = 0;
  11310. bqlist = NULL;
  11311. STARTSTACKSTR(out);
  11312. loop:
  11313. /* For each line, until end of word */
  11314. CHECKEND(); /* set c to PEOF if at end of here document */
  11315. for (;;) { /* until end of line or end of word */
  11316. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11317. switch (SIT(c, synstack->syntax)) {
  11318. case CNL: /* '\n' */
  11319. if (synstack->syntax == BASESYNTAX
  11320. && !synstack->varnest
  11321. ) {
  11322. goto endword; /* exit outer loop */
  11323. }
  11324. USTPUTC(c, out);
  11325. nlprompt();
  11326. c = pgetc_top(synstack);
  11327. goto loop; /* continue outer loop */
  11328. case CWORD:
  11329. USTPUTC(c, out);
  11330. break;
  11331. case CCTL:
  11332. #if BASH_DOLLAR_SQUOTE
  11333. if (c == '\\' && bash_dollar_squote) {
  11334. c = decode_dollar_squote();
  11335. if (c == '\0') {
  11336. /* skip $'\000', $'\x00' (like bash) */
  11337. break;
  11338. }
  11339. if (c & 0x100) {
  11340. /* Unknown escape. Encode as '\z' */
  11341. c = (unsigned char)c;
  11342. if (eofmark == NULL || synstack->dblquote)
  11343. USTPUTC(CTLESC, out);
  11344. USTPUTC('\\', out);
  11345. }
  11346. }
  11347. #endif
  11348. if (!eofmark || synstack->dblquote || synstack->varnest)
  11349. USTPUTC(CTLESC, out);
  11350. USTPUTC(c, out);
  11351. break;
  11352. case CBACK: /* backslash */
  11353. c = pgetc();
  11354. if (c == PEOF) {
  11355. USTPUTC(CTLESC, out);
  11356. USTPUTC('\\', out);
  11357. pungetc();
  11358. } else {
  11359. if (pssyntax && c == '$') {
  11360. USTPUTC(CTLESC, out);
  11361. USTPUTC('\\', out);
  11362. }
  11363. /* Backslash is retained if we are in "str"
  11364. * and next char isn't dquote-special.
  11365. */
  11366. if (synstack->dblquote
  11367. && c != '\\'
  11368. && c != '`'
  11369. && c != '$'
  11370. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11371. && (c != '}' || !synstack->varnest)
  11372. ) {
  11373. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11374. USTPUTC('\\', out);
  11375. }
  11376. USTPUTC(CTLESC, out);
  11377. USTPUTC(c, out);
  11378. quotef = 1;
  11379. }
  11380. break;
  11381. case CSQUOTE:
  11382. synstack->syntax = SQSYNTAX;
  11383. quotemark:
  11384. if (eofmark == NULL) {
  11385. USTPUTC(CTLQUOTEMARK, out);
  11386. }
  11387. break;
  11388. case CDQUOTE:
  11389. synstack->syntax = DQSYNTAX;
  11390. synstack->dblquote = 1;
  11391. toggledq:
  11392. if (synstack->varnest)
  11393. synstack->innerdq ^= 1;
  11394. goto quotemark;
  11395. case CENDQUOTE:
  11396. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11397. if (eofmark != NULL && synstack->varnest == 0) {
  11398. USTPUTC(c, out);
  11399. break;
  11400. }
  11401. if (synstack->dqvarnest == 0) {
  11402. synstack->syntax = BASESYNTAX;
  11403. synstack->dblquote = 0;
  11404. }
  11405. quotef = 1;
  11406. if (c == '"')
  11407. goto toggledq;
  11408. goto quotemark;
  11409. case CVAR: /* '$' */
  11410. PARSESUB(); /* parse substitution */
  11411. break;
  11412. case CENDVAR: /* '}' */
  11413. if (!synstack->innerdq && synstack->varnest > 0) {
  11414. if (!--synstack->varnest && synstack->varpushed)
  11415. synstack_pop(&synstack);
  11416. else if (synstack->dqvarnest > 0)
  11417. synstack->dqvarnest--;
  11418. c = CTLENDVAR;
  11419. }
  11420. USTPUTC(c, out);
  11421. break;
  11422. #if ENABLE_FEATURE_SH_MATH
  11423. case CLP: /* '(' in arithmetic */
  11424. synstack->parenlevel++;
  11425. USTPUTC(c, out);
  11426. break;
  11427. case CRP: /* ')' in arithmetic */
  11428. if (synstack->parenlevel > 0) {
  11429. synstack->parenlevel--;
  11430. } else {
  11431. if (pgetc_eatbnl() == ')') {
  11432. c = CTLENDARI;
  11433. synstack_pop(&synstack);
  11434. } else {
  11435. /*
  11436. * unbalanced parens
  11437. * (don't 2nd guess - no error)
  11438. */
  11439. pungetc();
  11440. }
  11441. }
  11442. USTPUTC(c, out);
  11443. break;
  11444. #endif
  11445. case CBQUOTE: /* '`' */
  11446. if (checkkwd & CHKEOFMARK) {
  11447. quotef = 1;
  11448. USTPUTC('`', out);
  11449. break;
  11450. }
  11451. PARSEBACKQOLD();
  11452. break;
  11453. case CENDFILE:
  11454. goto endword; /* exit outer loop */
  11455. default:
  11456. if (synstack->varnest == 0) {
  11457. #if BASH_REDIR_OUTPUT
  11458. if (c == '&') {
  11459. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11460. if (pgetc() == '>')
  11461. c = 0x100 + '>'; /* flag &> */
  11462. pungetc();
  11463. }
  11464. #endif
  11465. #if BASH_PROCESS_SUBST
  11466. if (c == '<' || c == '>') {
  11467. if (pgetc() == '(') {
  11468. PARSEPROCSUB();
  11469. break;
  11470. }
  11471. pungetc();
  11472. }
  11473. #endif
  11474. goto endword; /* exit outer loop */
  11475. }
  11476. USTPUTC(c, out);
  11477. }
  11478. c = pgetc_top(synstack);
  11479. } /* for (;;) */
  11480. endword:
  11481. #if ENABLE_FEATURE_SH_MATH
  11482. if (synstack->syntax == ARISYNTAX)
  11483. raise_error_syntax("missing '))'");
  11484. #endif
  11485. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11486. raise_error_syntax("unterminated quoted string");
  11487. if (synstack->varnest != 0) {
  11488. /* { */
  11489. raise_error_syntax("missing '}'");
  11490. }
  11491. USTPUTC('\0', out);
  11492. len = out - (char *)stackblock();
  11493. out = stackblock();
  11494. if (eofmark == NULL) {
  11495. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11496. && quotef == 0
  11497. ) {
  11498. if (isdigit_str9(out)) {
  11499. PARSEREDIR(); /* passed as params: out, c */
  11500. lasttoken = TREDIR;
  11501. return lasttoken;
  11502. }
  11503. /* else: non-number X seen, interpret it
  11504. * as "NNNX>file" = "NNNX >file" */
  11505. }
  11506. pungetc();
  11507. }
  11508. quoteflag = quotef;
  11509. backquotelist = bqlist;
  11510. grabstackblock(len);
  11511. wordtext = out;
  11512. lasttoken = TWORD;
  11513. return lasttoken;
  11514. /* end of readtoken routine */
  11515. /*
  11516. * Check to see whether we are at the end of the here document. When this
  11517. * is called, c is set to the first character of the next input line. If
  11518. * we are at the end of the here document, this routine sets the c to PEOF.
  11519. */
  11520. checkend: {
  11521. if (realeofmark(eofmark)) {
  11522. int markloc;
  11523. char *p;
  11524. if (striptabs) {
  11525. while (c == '\t')
  11526. c = pgetc();
  11527. }
  11528. markloc = out - (char *)stackblock();
  11529. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11530. if (c != *p)
  11531. goto more_heredoc;
  11532. /* FIXME: fails for backslash-newlined terminator:
  11533. * cat <<EOF
  11534. * ...
  11535. * EO\
  11536. * F
  11537. * (see heredoc_bkslash_newline2.tests)
  11538. */
  11539. c = pgetc();
  11540. }
  11541. if (c == '\n' || c == PEOF) {
  11542. c = PEOF;
  11543. if (trap_depth == 0)
  11544. g_parsefile->linno++;
  11545. needprompt = doprompt;
  11546. } else {
  11547. int len_here;
  11548. more_heredoc:
  11549. p = (char *)stackblock() + markloc + 1;
  11550. len_here = out - p;
  11551. if (len_here) {
  11552. len_here -= (c >= PEOF);
  11553. c = p[-1];
  11554. if (len_here) {
  11555. char *str;
  11556. str = alloca(len_here + 1);
  11557. *(char *)mempcpy(str, p, len_here) = '\0';
  11558. pushstring(str, NULL);
  11559. }
  11560. }
  11561. }
  11562. STADJUST((char *)stackblock() + markloc - out, out);
  11563. }
  11564. goto checkend_return;
  11565. }
  11566. /*
  11567. * Parse a redirection operator. The variable "out" points to a string
  11568. * specifying the fd to be redirected. The variable "c" contains the
  11569. * first character of the redirection operator.
  11570. */
  11571. parseredir: {
  11572. /* out is already checked to be a valid number or "" */
  11573. int fd = (*out == '\0' ? -1 : atoi(out));
  11574. union node *np;
  11575. np = stzalloc(sizeof(struct nfile));
  11576. if (c == '>') {
  11577. np->nfile.fd = 1;
  11578. c = pgetc_eatbnl();
  11579. if (c == '>')
  11580. np->type = NAPPEND;
  11581. else if (c == '|')
  11582. np->type = NCLOBBER;
  11583. else if (c == '&')
  11584. np->type = NTOFD;
  11585. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11586. else {
  11587. np->type = NTO;
  11588. pungetc();
  11589. }
  11590. }
  11591. #if BASH_REDIR_OUTPUT
  11592. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11593. np->nfile.fd = 1;
  11594. pgetc(); /* this is '>', no need to check */
  11595. np->type = NTO2;
  11596. }
  11597. #endif
  11598. else { /* c == '<' */
  11599. /*np->nfile.fd = 0; - stzalloc did it */
  11600. c = pgetc_eatbnl();
  11601. switch (c) {
  11602. case '<':
  11603. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11604. np = stzalloc(sizeof(struct nhere));
  11605. /*np->nfile.fd = 0; - stzalloc did it */
  11606. }
  11607. np->type = NHERE;
  11608. heredoc = stzalloc(sizeof(struct heredoc));
  11609. heredoc->here = np;
  11610. c = pgetc_eatbnl();
  11611. if (c == '-') {
  11612. heredoc->striptabs = 1;
  11613. } else {
  11614. /*heredoc->striptabs = 0; - stzalloc did it */
  11615. pungetc();
  11616. }
  11617. break;
  11618. case '&':
  11619. np->type = NFROMFD;
  11620. break;
  11621. case '>':
  11622. np->type = NFROMTO;
  11623. break;
  11624. default:
  11625. np->type = NFROM;
  11626. pungetc();
  11627. break;
  11628. }
  11629. }
  11630. if (fd >= 0)
  11631. np->nfile.fd = fd;
  11632. redirnode = np;
  11633. goto parseredir_return;
  11634. }
  11635. /*
  11636. * Parse a substitution. At this point, we have read the dollar sign
  11637. * and nothing else.
  11638. */
  11639. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11640. * (assuming ascii char codes, as the original implementation did) */
  11641. #define is_special(c) \
  11642. (((unsigned)(c) - 33 < 32) \
  11643. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11644. parsesub: {
  11645. unsigned char subtype;
  11646. int typeloc;
  11647. c = pgetc_eatbnl();
  11648. if ((checkkwd & CHKEOFMARK)
  11649. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11650. ) {
  11651. #if BASH_DOLLAR_SQUOTE
  11652. if (synstack->syntax != DQSYNTAX && c == '\'')
  11653. bash_dollar_squote = 1;
  11654. else
  11655. #endif
  11656. USTPUTC('$', out);
  11657. pungetc();
  11658. } else if (c == '(') {
  11659. /* $(command) or $((arith)) */
  11660. if (pgetc_eatbnl() == '(') {
  11661. #if ENABLE_FEATURE_SH_MATH
  11662. PARSEARITH();
  11663. #else
  11664. raise_error_syntax("support for $((arith)) is disabled");
  11665. #endif
  11666. } else {
  11667. pungetc();
  11668. PARSEBACKQNEW();
  11669. }
  11670. } else {
  11671. /* $VAR, $<specialchar>, ${...}, or PEOF */
  11672. smalluint newsyn = synstack->syntax;
  11673. USTPUTC(CTLVAR, out);
  11674. typeloc = out - (char *)stackblock();
  11675. STADJUST(1, out);
  11676. subtype = VSNORMAL;
  11677. if (c == '{') {
  11678. c = pgetc_eatbnl();
  11679. subtype = 0;
  11680. }
  11681. varname:
  11682. if (is_name(c)) {
  11683. /* $[{[#]]NAME[}] */
  11684. do {
  11685. STPUTC(c, out);
  11686. c = pgetc_eatbnl();
  11687. } while (is_in_name(c));
  11688. } else if (isdigit(c)) {
  11689. /* $[{[#]]NUM[}] */
  11690. do {
  11691. STPUTC(c, out);
  11692. c = pgetc_eatbnl();
  11693. } while ((subtype == 0 || subtype == VSLENGTH) && isdigit(c));
  11694. } else if (c != '}') {
  11695. /* $[{[#]]<specialchar>[}] */
  11696. int cc = c;
  11697. c = pgetc_eatbnl();
  11698. if (!subtype && cc == '#') {
  11699. subtype = VSLENGTH;
  11700. if (c == '_' || isalnum(c))
  11701. goto varname;
  11702. cc = c;
  11703. c = pgetc_eatbnl();
  11704. if (cc == '}' || c != '}') {
  11705. pungetc();
  11706. subtype = 0;
  11707. c = cc;
  11708. cc = '#';
  11709. }
  11710. }
  11711. if (!is_special(cc)) {
  11712. if (subtype == VSLENGTH)
  11713. subtype = 0;
  11714. goto badsub;
  11715. }
  11716. USTPUTC(cc, out);
  11717. } else
  11718. goto badsub;
  11719. if (subtype == 0) {
  11720. static const char types[] ALIGN1 = "}-+?=";
  11721. /* ${VAR...} but not $VAR or ${#VAR} */
  11722. /* c == first char after VAR */
  11723. int cc = c;
  11724. switch (c) {
  11725. case ':':
  11726. c = pgetc_eatbnl();
  11727. #if BASH_SUBSTR
  11728. /* This check is only needed to not misinterpret
  11729. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11730. * constructs.
  11731. */
  11732. if (!strchr(types, c)) {
  11733. subtype = VSSUBSTR;
  11734. pungetc();
  11735. break; /* "goto badsub" is bigger (!) */
  11736. }
  11737. #endif
  11738. subtype = VSNUL;
  11739. /*FALLTHROUGH*/
  11740. default: {
  11741. const char *p = strchr(types, c);
  11742. if (p == NULL)
  11743. break;
  11744. subtype |= p - types + VSNORMAL;
  11745. break;
  11746. }
  11747. case '%':
  11748. case '#':
  11749. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11750. c = pgetc_eatbnl();
  11751. if (c == cc)
  11752. subtype++;
  11753. else
  11754. pungetc();
  11755. newsyn = BASESYNTAX;
  11756. break;
  11757. #if BASH_PATTERN_SUBST
  11758. case '/':
  11759. /* ${v/[/]pattern/repl} */
  11760. //TODO: encode pattern and repl separately.
  11761. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11762. // are broken (should print "ONE")
  11763. subtype = VSREPLACE;
  11764. newsyn = BASESYNTAX;
  11765. c = pgetc_eatbnl();
  11766. if (c != '/')
  11767. goto badsub;
  11768. subtype++; /* VSREPLACEALL */
  11769. break;
  11770. #endif
  11771. }
  11772. } else {
  11773. if (subtype == VSLENGTH && c != '}')
  11774. subtype = 0;
  11775. badsub:
  11776. pungetc();
  11777. }
  11778. if (newsyn == ARISYNTAX)
  11779. newsyn = DQSYNTAX;
  11780. if ((newsyn != synstack->syntax || synstack->innerdq)
  11781. && subtype != VSNORMAL
  11782. ) {
  11783. synstack_push(&synstack,
  11784. synstack->prev ?: alloca(sizeof(*synstack)),
  11785. newsyn);
  11786. synstack->varpushed = 1;
  11787. synstack->dblquote = newsyn != BASESYNTAX;
  11788. }
  11789. ((unsigned char *)stackblock())[typeloc] = subtype;
  11790. if (subtype != VSNORMAL) {
  11791. synstack->varnest++;
  11792. if (synstack->dblquote)
  11793. synstack->dqvarnest++;
  11794. }
  11795. STPUTC('=', out);
  11796. }
  11797. goto parsesub_return;
  11798. }
  11799. /*
  11800. * Called to parse command substitutions. Newstyle is set if the command
  11801. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11802. * list of commands (passed by reference), and savelen is the number of
  11803. * characters on the top of the stack which must be preserved.
  11804. */
  11805. parsebackq: {
  11806. struct nodelist **nlpp;
  11807. union node *n;
  11808. char *str;
  11809. size_t savelen;
  11810. struct heredoc *saveheredoclist;
  11811. smallint saveprompt = 0;
  11812. str = NULL;
  11813. savelen = out - (char *)stackblock();
  11814. if (savelen > 0) {
  11815. /*
  11816. * FIXME: this can allocate very large block on stack and SEGV.
  11817. * Example:
  11818. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11819. * allocates 100kb for every command subst. With about
  11820. * a hundred command substitutions stack overflows.
  11821. * With larger prepended string, SEGV happens sooner.
  11822. */
  11823. str = alloca(savelen);
  11824. memcpy(str, stackblock(), savelen);
  11825. }
  11826. if (oldstyle) {
  11827. /* We must read until the closing backquote, giving special
  11828. * treatment to some slashes, and then push the string and
  11829. * reread it as input, interpreting it normally.
  11830. */
  11831. char *pout;
  11832. size_t psavelen;
  11833. char *pstr;
  11834. STARTSTACKSTR(pout);
  11835. for (;;) {
  11836. int pc;
  11837. setprompt_if(needprompt, 2);
  11838. pc = pgetc_eatbnl();
  11839. switch (pc) {
  11840. case '`':
  11841. goto done;
  11842. case '\\':
  11843. pc = pgetc(); /* not pgetc_eatbnl! */
  11844. if (pc != '\\' && pc != '`' && pc != '$'
  11845. && (!synstack->dblquote || pc != '"')
  11846. ) {
  11847. STPUTC('\\', pout);
  11848. }
  11849. break;
  11850. case PEOF:
  11851. raise_error_syntax("EOF in backquote substitution");
  11852. case '\n':
  11853. nlnoprompt();
  11854. break;
  11855. default:
  11856. break;
  11857. }
  11858. STPUTC(pc, pout);
  11859. }
  11860. done:
  11861. STPUTC('\0', pout);
  11862. psavelen = pout - (char *)stackblock();
  11863. if (psavelen > 0) {
  11864. pstr = grabstackstr(pout);
  11865. setinputstring(pstr);
  11866. }
  11867. }
  11868. nlpp = &bqlist;
  11869. while (*nlpp)
  11870. nlpp = &(*nlpp)->next;
  11871. *nlpp = stzalloc(sizeof(**nlpp));
  11872. /* (*nlpp)->next = NULL; - stzalloc did it */
  11873. saveheredoclist = heredoclist;
  11874. heredoclist = NULL;
  11875. if (oldstyle) {
  11876. saveprompt = doprompt;
  11877. doprompt = 0;
  11878. }
  11879. n = list(2);
  11880. if (oldstyle)
  11881. doprompt = saveprompt;
  11882. else {
  11883. if (readtoken() != TRP)
  11884. raise_error_unexpected_syntax(TRP);
  11885. setinputstring(nullstr);
  11886. }
  11887. parseheredoc();
  11888. heredoclist = saveheredoclist;
  11889. (*nlpp)->n = n;
  11890. /* Start reading from old file again. */
  11891. popfile();
  11892. /* Ignore any pushed back tokens left from the backquote parsing. */
  11893. if (oldstyle)
  11894. tokpushback = 0;
  11895. out = growstackto(savelen + 1);
  11896. if (str) {
  11897. memcpy(out, str, savelen);
  11898. STADJUST(savelen, out);
  11899. }
  11900. #if BASH_PROCESS_SUBST
  11901. if (style == PSUB)
  11902. USTPUTC(c == '<' ? CTLFROMPROC : CTLTOPROC, out);
  11903. else
  11904. #endif
  11905. USTPUTC(CTLBACKQ, out);
  11906. if (oldstyle)
  11907. goto parsebackq_oldreturn;
  11908. #if BASH_PROCESS_SUBST
  11909. else if (style == PSUB)
  11910. goto parsebackq_psreturn;
  11911. #endif
  11912. goto parsebackq_newreturn;
  11913. }
  11914. #if ENABLE_FEATURE_SH_MATH
  11915. /*
  11916. * Parse an arithmetic expansion (indicate start of one and set state)
  11917. */
  11918. parsearith: {
  11919. synstack_push(&synstack,
  11920. synstack->prev ?: alloca(sizeof(*synstack)),
  11921. ARISYNTAX);
  11922. synstack->dblquote = 1;
  11923. USTPUTC(CTLARI, out);
  11924. goto parsearith_return;
  11925. }
  11926. #endif
  11927. } /* end of readtoken */
  11928. /*
  11929. * Read the next input token.
  11930. * If the token is a word, we set backquotelist to the list of cmds in
  11931. * backquotes. We set quoteflag to true if any part of the word was
  11932. * quoted.
  11933. * If the token is TREDIR, then we set redirnode to a structure containing
  11934. * the redirection.
  11935. *
  11936. * [Change comment: here documents and internal procedures]
  11937. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11938. * word parsing code into a separate routine. In this case, readtoken
  11939. * doesn't need to have any internal procedures, but parseword does.
  11940. * We could also make parseoperator in essence the main routine, and
  11941. * have parseword (readtoken1?) handle both words and redirection.]
  11942. */
  11943. #define NEW_xxreadtoken
  11944. #ifdef NEW_xxreadtoken
  11945. /* singles must be first! */
  11946. static const char xxreadtoken_chars[7] ALIGN1 = {
  11947. '\n', '(', ')', /* singles */
  11948. '&', '|', ';', /* doubles */
  11949. 0
  11950. };
  11951. #define xxreadtoken_singles 3
  11952. #define xxreadtoken_doubles 3
  11953. static const char xxreadtoken_tokens[] ALIGN1 = {
  11954. TNL, TLP, TRP, /* only single occurrence allowed */
  11955. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11956. TEOF, /* corresponds to trailing nul */
  11957. TAND, TOR, TENDCASE /* if double occurrence */
  11958. };
  11959. static int
  11960. xxreadtoken(void)
  11961. {
  11962. int c;
  11963. if (tokpushback) {
  11964. tokpushback = 0;
  11965. return lasttoken;
  11966. }
  11967. setprompt_if(needprompt, 2);
  11968. for (;;) { /* until token or start of word found */
  11969. c = pgetc_eatbnl();
  11970. if (c == ' ' || c == '\t')
  11971. continue;
  11972. if (c == '#') {
  11973. while ((c = pgetc()) != '\n' && c != PEOF)
  11974. continue;
  11975. pungetc();
  11976. } else if (c == '\\') {
  11977. break; /* return readtoken1(...) */
  11978. } else {
  11979. const char *p;
  11980. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11981. if (c != PEOF) {
  11982. if (c == '\n') {
  11983. nlnoprompt();
  11984. }
  11985. p = strchr(xxreadtoken_chars, c);
  11986. if (p == NULL)
  11987. break; /* return readtoken1(...) */
  11988. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11989. int cc = pgetc_eatbnl();
  11990. if (cc == c) { /* double occurrence? */
  11991. p += xxreadtoken_doubles + 1;
  11992. } else {
  11993. pungetc();
  11994. #if BASH_REDIR_OUTPUT
  11995. if (c == '&' && cc == '>') /* &> */
  11996. break; /* return readtoken1(...) */
  11997. #endif
  11998. }
  11999. }
  12000. }
  12001. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  12002. return lasttoken;
  12003. }
  12004. } /* for (;;) */
  12005. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  12006. }
  12007. #else /* old xxreadtoken */
  12008. #define RETURN(token) return lasttoken = token
  12009. static int
  12010. xxreadtoken(void)
  12011. {
  12012. int c;
  12013. if (tokpushback) {
  12014. tokpushback = 0;
  12015. return lasttoken;
  12016. }
  12017. setprompt_if(needprompt, 2);
  12018. for (;;) { /* until token or start of word found */
  12019. c = pgetc_eatbnl();
  12020. switch (c) {
  12021. case ' ': case '\t':
  12022. continue;
  12023. case '#':
  12024. while ((c = pgetc()) != '\n' && c != PEOF)
  12025. continue;
  12026. pungetc();
  12027. continue;
  12028. case '\n':
  12029. nlnoprompt();
  12030. RETURN(TNL);
  12031. case PEOF:
  12032. RETURN(TEOF);
  12033. case '&':
  12034. if (pgetc_eatbnl() == '&')
  12035. RETURN(TAND);
  12036. pungetc();
  12037. RETURN(TBACKGND);
  12038. case '|':
  12039. if (pgetc_eatbnl() == '|')
  12040. RETURN(TOR);
  12041. pungetc();
  12042. RETURN(TPIPE);
  12043. case ';':
  12044. if (pgetc_eatbnl() == ';')
  12045. RETURN(TENDCASE);
  12046. pungetc();
  12047. RETURN(TSEMI);
  12048. case '(':
  12049. RETURN(TLP);
  12050. case ')':
  12051. RETURN(TRP);
  12052. }
  12053. break;
  12054. }
  12055. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  12056. #undef RETURN
  12057. }
  12058. #endif /* old xxreadtoken */
  12059. static int
  12060. readtoken(void)
  12061. {
  12062. int t;
  12063. int kwd = checkkwd;
  12064. #if DEBUG
  12065. smallint alreadyseen = tokpushback;
  12066. #endif
  12067. #if ENABLE_ASH_ALIAS
  12068. top:
  12069. #endif
  12070. t = xxreadtoken();
  12071. /*
  12072. * eat newlines
  12073. */
  12074. if (kwd & CHKNL) {
  12075. while (t == TNL) {
  12076. parseheredoc();
  12077. checkkwd = 0;
  12078. t = xxreadtoken();
  12079. }
  12080. }
  12081. kwd |= checkkwd;
  12082. checkkwd = 0;
  12083. if (t != TWORD || quoteflag) {
  12084. goto out;
  12085. }
  12086. /*
  12087. * check for keywords
  12088. */
  12089. if (kwd & CHKKWD) {
  12090. const char *const *pp;
  12091. pp = findkwd(wordtext);
  12092. if (pp) {
  12093. lasttoken = t = pp - tokname_array;
  12094. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  12095. goto out;
  12096. }
  12097. }
  12098. if (kwd & CHKALIAS) {
  12099. #if ENABLE_ASH_ALIAS
  12100. struct alias *ap;
  12101. ap = lookupalias(wordtext, 1);
  12102. if (ap != NULL) {
  12103. if (*ap->val) {
  12104. pushstring(ap->val, ap);
  12105. }
  12106. goto top;
  12107. }
  12108. #endif
  12109. }
  12110. out:
  12111. #if DEBUG
  12112. if (!alreadyseen)
  12113. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  12114. else
  12115. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  12116. #endif
  12117. return t;
  12118. }
  12119. /*
  12120. * Read and parse a command. Returns NODE_EOF on end of file.
  12121. * (NULL is a valid parse tree indicating a blank line.)
  12122. */
  12123. static union node *
  12124. parsecmd(int interact)
  12125. {
  12126. tokpushback = 0;
  12127. checkkwd = 0;
  12128. heredoclist = 0;
  12129. doprompt = interact;
  12130. setprompt_if(doprompt, doprompt);
  12131. needprompt = 0;
  12132. return list(1);
  12133. }
  12134. /*
  12135. * Input any here documents.
  12136. */
  12137. static void
  12138. parseheredoc(void)
  12139. {
  12140. struct heredoc *here;
  12141. union node *n;
  12142. here = heredoclist;
  12143. heredoclist = NULL;
  12144. while (here) {
  12145. tokpushback = 0;
  12146. setprompt_if(needprompt, 2);
  12147. if (here->here->type == NHERE)
  12148. readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
  12149. else
  12150. readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
  12151. n = stzalloc(sizeof(struct narg));
  12152. n->narg.type = NARG;
  12153. /*n->narg.next = NULL; - stzalloc did it */
  12154. n->narg.text = wordtext;
  12155. n->narg.backquote = backquotelist;
  12156. here->here->nhere.doc = n;
  12157. here = here->next;
  12158. }
  12159. }
  12160. static const char *
  12161. expandstr(const char *ps, int syntax_type)
  12162. {
  12163. struct parsefile *file_stop;
  12164. struct jmploc *volatile savehandler;
  12165. struct heredoc *saveheredoclist;
  12166. const char *result;
  12167. int saveprompt;
  12168. struct jmploc jmploc;
  12169. union node n;
  12170. int err;
  12171. file_stop = g_parsefile;
  12172. /* XXX Fix (char *) cast. */
  12173. setinputstring((char *)ps);
  12174. saveheredoclist = heredoclist;
  12175. heredoclist = NULL;
  12176. saveprompt = doprompt;
  12177. doprompt = 0;
  12178. result = ps;
  12179. savehandler = exception_handler;
  12180. err = setjmp(jmploc.loc);
  12181. if (err)
  12182. goto out;
  12183. /* readtoken1() might die horribly.
  12184. * Try a prompt with syntactically wrong command:
  12185. * PS1='$(date "+%H:%M:%S) > '
  12186. */
  12187. exception_handler = &jmploc;
  12188. readtoken1(pgetc_eatbnl(), syntax_type, FAKEEOFMARK, 0);
  12189. n.narg.type = NARG;
  12190. n.narg.next = NULL;
  12191. n.narg.text = wordtext;
  12192. n.narg.backquote = backquotelist;
  12193. /* expandarg() might fail too:
  12194. * PS1='$((123+))'
  12195. */
  12196. expandarg(&n, NULL, EXP_QUOTED);
  12197. result = stackblock();
  12198. out:
  12199. exception_handler = savehandler;
  12200. if (err && exception_type != EXERROR)
  12201. longjmp(exception_handler->loc, 1);
  12202. doprompt = saveprompt;
  12203. /* Try: PS1='`xxx(`' */
  12204. unwindfiles(file_stop);
  12205. heredoclist = saveheredoclist;
  12206. return result;
  12207. }
  12208. static inline int
  12209. parser_eof(void)
  12210. {
  12211. return tokpushback && lasttoken == TEOF;
  12212. }
  12213. /*
  12214. * Execute a command or commands contained in a string.
  12215. */
  12216. static int
  12217. evalstring(char *s, int flags)
  12218. {
  12219. struct jmploc *volatile savehandler;
  12220. struct jmploc jmploc;
  12221. int ex;
  12222. union node *n;
  12223. struct stackmark smark;
  12224. int status;
  12225. s = sstrdup(s);
  12226. setinputstring(s);
  12227. setstackmark(&smark);
  12228. status = 0;
  12229. /* On exception inside execution loop, we must popfile().
  12230. * Try interactively:
  12231. * readonly a=a
  12232. * command eval "a=b" # throws "is read only" error
  12233. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  12234. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  12235. */
  12236. savehandler = exception_handler;
  12237. ex = setjmp(jmploc.loc);
  12238. if (ex)
  12239. goto out;
  12240. exception_handler = &jmploc;
  12241. while ((n = parsecmd(0)) != NODE_EOF) {
  12242. int i;
  12243. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  12244. if (n)
  12245. status = i;
  12246. popstackmark(&smark);
  12247. if (evalskip)
  12248. break;
  12249. }
  12250. out:
  12251. popstackmark(&smark);
  12252. popfile();
  12253. stunalloc(s);
  12254. exception_handler = savehandler;
  12255. if (ex)
  12256. longjmp(exception_handler->loc, ex);
  12257. return status;
  12258. }
  12259. /*
  12260. * The eval command.
  12261. */
  12262. static int FAST_FUNC
  12263. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  12264. {
  12265. char *p;
  12266. char *concat;
  12267. if (argv[1]) {
  12268. p = argv[1];
  12269. argv += 2;
  12270. if (argv[0]) {
  12271. STARTSTACKSTR(concat);
  12272. for (;;) {
  12273. concat = stack_putstr(p, concat);
  12274. p = *argv++;
  12275. if (p == NULL)
  12276. break;
  12277. STPUTC(' ', concat);
  12278. }
  12279. STPUTC('\0', concat);
  12280. p = grabstackstr(concat);
  12281. }
  12282. return evalstring(p, flags & EV_TESTED);
  12283. }
  12284. return 0;
  12285. }
  12286. /*
  12287. * Read and execute commands.
  12288. * "Top" is nonzero for the top level command loop;
  12289. * it turns on prompting if the shell is interactive.
  12290. */
  12291. static int
  12292. cmdloop(int top)
  12293. {
  12294. union node *n;
  12295. struct stackmark smark;
  12296. int inter;
  12297. int status = 0;
  12298. int numeof = 0;
  12299. TRACE(("cmdloop(%d) called\n", top));
  12300. for (;;) {
  12301. int skip;
  12302. setstackmark(&smark);
  12303. #if JOBS
  12304. if (doing_jobctl)
  12305. showjobs(SHOW_CHANGED|SHOW_STDERR);
  12306. #endif
  12307. inter = 0;
  12308. if (iflag && top) {
  12309. inter++;
  12310. chkmail();
  12311. }
  12312. n = parsecmd(inter);
  12313. #if DEBUG
  12314. if (DEBUG > 2 && debug && (n != NODE_EOF))
  12315. showtree(n);
  12316. #endif
  12317. if (n == NODE_EOF) {
  12318. if (!top || numeof >= 50)
  12319. break;
  12320. if (!stoppedjobs()) {
  12321. if (!iflag)
  12322. break;
  12323. if (!Iflag) {
  12324. newline_and_flush(stderr);
  12325. break;
  12326. }
  12327. /* "set -o ignoreeof" active, do not exit command loop on ^D */
  12328. out2str("\nUse \"exit\" to leave shell.\n");
  12329. }
  12330. numeof++;
  12331. } else {
  12332. int i;
  12333. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12334. job_warning >>= 1;
  12335. numeof = 0;
  12336. i = evaltree(n, 0);
  12337. if (n)
  12338. status = i;
  12339. }
  12340. popstackmark(&smark);
  12341. skip = evalskip;
  12342. if (skip) {
  12343. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  12344. break;
  12345. }
  12346. }
  12347. return status;
  12348. }
  12349. /*
  12350. * Take commands from a file. To be compatible we should do a path
  12351. * search for the file, which is necessary to find sub-commands.
  12352. */
  12353. static char *
  12354. find_dot_file(char *basename)
  12355. {
  12356. char *fullname;
  12357. const char *path = pathval();
  12358. struct stat statb;
  12359. int len;
  12360. /* don't try this for absolute or relative paths */
  12361. if (strchr(basename, '/'))
  12362. return basename;
  12363. while ((len = padvance(&path, basename)) >= 0) {
  12364. fullname = stackblock();
  12365. if ((!pathopt || *pathopt == 'f')
  12366. && !stat(fullname, &statb) && S_ISREG(statb.st_mode)
  12367. ) {
  12368. /* This will be freed by the caller. */
  12369. return stalloc(len);
  12370. }
  12371. }
  12372. /* not found in PATH */
  12373. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12374. return basename;
  12375. #else
  12376. ash_msg_and_raise_error("%s: not found", basename);
  12377. /* NOTREACHED */
  12378. #endif
  12379. }
  12380. static int FAST_FUNC
  12381. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12382. {
  12383. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12384. int status = 0;
  12385. char *fullname;
  12386. char **argv;
  12387. char *args_need_save;
  12388. volatile struct shparam saveparam;
  12389. //???
  12390. // struct strlist *sp;
  12391. // for (sp = cmdenviron; sp; sp = sp->next)
  12392. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12393. nextopt(nullstr); /* handle possible "--" */
  12394. argv = argptr;
  12395. if (!argv[0]) {
  12396. /* bash says: "bash: .: filename argument required" */
  12397. return 2; /* bash compat */
  12398. }
  12399. /* This aborts if file isn't found, which is POSIXly correct.
  12400. * bash returns exitcode 1 instead.
  12401. */
  12402. fullname = find_dot_file(argv[0]);
  12403. argv++;
  12404. args_need_save = argv[0];
  12405. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12406. int argc;
  12407. saveparam = shellparam;
  12408. shellparam.malloced = 0;
  12409. argc = 1;
  12410. while (argv[argc])
  12411. argc++;
  12412. shellparam.nparam = argc;
  12413. shellparam.p = argv;
  12414. };
  12415. /* This aborts if file can't be opened, which is POSIXly correct.
  12416. * bash returns exitcode 1 instead.
  12417. */
  12418. setinputfile(fullname, INPUT_PUSH_FILE);
  12419. commandname = fullname;
  12420. status = cmdloop(0);
  12421. popfile();
  12422. if (args_need_save) {
  12423. freeparam(&shellparam);
  12424. shellparam = saveparam;
  12425. };
  12426. return status;
  12427. }
  12428. static int FAST_FUNC
  12429. exitcmd(int argc UNUSED_PARAM, char **argv)
  12430. {
  12431. if (stoppedjobs())
  12432. return 0;
  12433. if (argv[1])
  12434. savestatus = number(argv[1]);
  12435. //TODO: this script
  12436. // trap 'echo trap:$FUNCNAME' EXIT
  12437. // f() { exit; }
  12438. // f
  12439. //prints "trap:f" in bash. We can call exitshell() here to achieve this.
  12440. //For now, keeping dash code:
  12441. raise_exception(EXEXIT);
  12442. /* NOTREACHED */
  12443. }
  12444. /*
  12445. * Read a file containing shell functions.
  12446. */
  12447. static void
  12448. readcmdfile(char *name)
  12449. {
  12450. setinputfile(name, INPUT_PUSH_FILE);
  12451. cmdloop(0);
  12452. popfile();
  12453. }
  12454. /* ============ find_command inplementation */
  12455. /*
  12456. * Resolve a command name. If you change this routine, you may have to
  12457. * change the shellexec routine as well.
  12458. */
  12459. static void
  12460. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12461. {
  12462. struct tblentry *cmdp;
  12463. int idx;
  12464. int prev;
  12465. char *fullname;
  12466. struct stat statb;
  12467. int e;
  12468. int updatetbl;
  12469. struct builtincmd *bcmd;
  12470. int len;
  12471. /* If name contains a slash, don't use PATH or hash table */
  12472. if (strchr(name, '/') != NULL) {
  12473. entry->u.index = -1;
  12474. if (act & DO_ABS) {
  12475. while (stat(name, &statb) < 0) {
  12476. #ifdef SYSV
  12477. if (errno == EINTR)
  12478. continue;
  12479. #endif
  12480. entry->cmdtype = CMDUNKNOWN;
  12481. return;
  12482. }
  12483. }
  12484. entry->cmdtype = CMDNORMAL;
  12485. return;
  12486. }
  12487. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12488. updatetbl = (path == pathval());
  12489. if (!updatetbl)
  12490. act |= DO_ALTPATH;
  12491. /* If name is in the table, check answer will be ok */
  12492. cmdp = cmdlookup(name, 0);
  12493. if (cmdp != NULL) {
  12494. int bit;
  12495. switch (cmdp->cmdtype) {
  12496. default:
  12497. #if DEBUG
  12498. abort();
  12499. #endif
  12500. case CMDNORMAL:
  12501. bit = DO_ALTPATH | DO_REGBLTIN;
  12502. break;
  12503. case CMDFUNCTION:
  12504. bit = DO_NOFUNC;
  12505. break;
  12506. case CMDBUILTIN:
  12507. bit = IS_BUILTIN_REGULAR(cmdp->param.cmd) ? 0 : DO_REGBLTIN;
  12508. break;
  12509. }
  12510. if (act & bit) {
  12511. if (act & bit & DO_REGBLTIN)
  12512. goto fail;
  12513. updatetbl = 0;
  12514. cmdp = NULL;
  12515. } else if (cmdp->rehash == 0)
  12516. /* if not invalidated by cd, we're done */
  12517. goto success;
  12518. }
  12519. /* If %builtin not in path, check for builtin next */
  12520. bcmd = find_builtin(name);
  12521. if (bcmd) {
  12522. if (IS_BUILTIN_REGULAR(bcmd))
  12523. goto builtin_success;
  12524. if (act & DO_ALTPATH)
  12525. goto builtin_success;
  12526. if (builtinloc <= 0)
  12527. goto builtin_success;
  12528. }
  12529. if (act & DO_REGBLTIN)
  12530. goto fail;
  12531. #if ENABLE_FEATURE_SH_STANDALONE
  12532. {
  12533. int applet_no = find_applet_by_name(name);
  12534. if (applet_no >= 0) {
  12535. entry->cmdtype = CMDNORMAL;
  12536. entry->u.index = -2 - applet_no;
  12537. return;
  12538. }
  12539. }
  12540. #endif
  12541. /* We have to search path. */
  12542. prev = -1; /* where to start */
  12543. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12544. if (cmdp->cmdtype == CMDBUILTIN)
  12545. prev = builtinloc;
  12546. else
  12547. prev = cmdp->param.index;
  12548. }
  12549. e = ENOENT;
  12550. idx = -1;
  12551. loop:
  12552. while ((len = padvance(&path, name)) >= 0) {
  12553. const char *lpathopt = pathopt;
  12554. fullname = stackblock();
  12555. idx++;
  12556. if (lpathopt) {
  12557. if (*lpathopt == 'b') {
  12558. if (bcmd)
  12559. goto builtin_success;
  12560. continue;
  12561. } else if (!(act & DO_NOFUNC)) {
  12562. /* handled below */
  12563. } else {
  12564. /* ignore unimplemented options */
  12565. continue;
  12566. }
  12567. }
  12568. /* if rehash, don't redo absolute path names */
  12569. if (fullname[0] == '/' && idx <= prev) {
  12570. if (idx < prev)
  12571. continue;
  12572. TRACE(("searchexec \"%s\": no change\n", name));
  12573. goto success;
  12574. }
  12575. while (stat(fullname, &statb) < 0) {
  12576. #ifdef SYSV
  12577. if (errno == EINTR)
  12578. continue;
  12579. #endif
  12580. if (errno != ENOENT && errno != ENOTDIR)
  12581. e = errno;
  12582. goto loop;
  12583. }
  12584. e = EACCES; /* if we fail, this will be the error */
  12585. if (!S_ISREG(statb.st_mode))
  12586. continue;
  12587. if (lpathopt) { /* this is a %func directory */
  12588. stalloc(len);
  12589. /* NB: stalloc will return space pointed by fullname
  12590. * (because we don't have any intervening allocations
  12591. * between stunalloc above and this stalloc) */
  12592. readcmdfile(fullname);
  12593. cmdp = cmdlookup(name, 0);
  12594. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12595. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12596. stunalloc(fullname);
  12597. goto success;
  12598. }
  12599. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12600. if (!updatetbl) {
  12601. entry->cmdtype = CMDNORMAL;
  12602. entry->u.index = idx;
  12603. return;
  12604. }
  12605. INT_OFF;
  12606. cmdp = cmdlookup(name, 1);
  12607. cmdp->cmdtype = CMDNORMAL;
  12608. cmdp->param.index = idx;
  12609. INT_ON;
  12610. goto success;
  12611. }
  12612. /* We failed. If there was an entry for this command, delete it */
  12613. if (cmdp && updatetbl)
  12614. delete_cmd_entry();
  12615. if (act & DO_ERR) {
  12616. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12617. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12618. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12619. char *argv[3];
  12620. argv[0] = (char*) "command_not_found_handle";
  12621. argv[1] = name;
  12622. argv[2] = NULL;
  12623. evalfun(hookp->param.func, 2, argv, 0);
  12624. entry->cmdtype = CMDUNKNOWN;
  12625. return;
  12626. }
  12627. #endif
  12628. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12629. }
  12630. fail:
  12631. entry->cmdtype = CMDUNKNOWN;
  12632. return;
  12633. builtin_success:
  12634. if (!updatetbl) {
  12635. entry->cmdtype = CMDBUILTIN;
  12636. entry->u.cmd = bcmd;
  12637. return;
  12638. }
  12639. INT_OFF;
  12640. cmdp = cmdlookup(name, 1);
  12641. cmdp->cmdtype = CMDBUILTIN;
  12642. cmdp->param.cmd = bcmd;
  12643. INT_ON;
  12644. success:
  12645. cmdp->rehash = 0;
  12646. entry->cmdtype = cmdp->cmdtype;
  12647. entry->u = cmdp->param;
  12648. }
  12649. /*
  12650. * The trap builtin.
  12651. */
  12652. static int FAST_FUNC
  12653. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12654. {
  12655. char *action;
  12656. char **ap;
  12657. int signo, exitcode;
  12658. nextopt(nullstr);
  12659. ap = argptr;
  12660. if (!*ap) {
  12661. for (signo = 0; signo <= NTRAP_LAST; signo++) {
  12662. char *tr = trap_ptr[signo];
  12663. if (tr) {
  12664. /* note: bash adds "SIG", but only if invoked
  12665. * as "bash". If called as "sh", or if set -o posix,
  12666. * then it prints short signal names.
  12667. * We are printing short names: */
  12668. out1fmt("trap -- %s %s\n",
  12669. single_quote(tr),
  12670. (signo == NTRAP_ERR) ? "ERR" : get_signame(signo));
  12671. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12672. * In this case, we will exit very soon, no need to free(). */
  12673. /* if (trap_ptr != trap && tp[0]) */
  12674. /* free(tr); */
  12675. }
  12676. }
  12677. /*
  12678. if (trap_ptr != trap) {
  12679. free(trap_ptr);
  12680. trap_ptr = trap;
  12681. }
  12682. */
  12683. return 0;
  12684. }
  12685. /* Why the second check?
  12686. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12687. * In this case, NUM is signal no, not an action.
  12688. */
  12689. action = NULL;
  12690. if (ap[1] && !is_number(ap[0]))
  12691. action = *ap++;
  12692. exitcode = 0;
  12693. while (*ap) {
  12694. signo = strcmp(*ap, "ERR") == 0 ? NTRAP_ERR : get_signum(*ap);
  12695. if (signo < 0) {
  12696. /* Mimic bash message exactly */
  12697. ash_msg("%s: invalid signal specification", *ap);
  12698. exitcode = 1;
  12699. goto next;
  12700. }
  12701. INT_OFF;
  12702. if (action) {
  12703. if (LONE_DASH(action))
  12704. action = NULL;
  12705. else {
  12706. if (action[0]) /* not NULL and not "" and not "-" */
  12707. may_have_traps = 1;
  12708. action = ckstrdup(action);
  12709. }
  12710. }
  12711. free(trap[signo]);
  12712. trap[signo] = action;
  12713. if (signo != 0 && signo < NSIG)
  12714. setsignal(signo);
  12715. INT_ON;
  12716. next:
  12717. ap++;
  12718. }
  12719. return exitcode;
  12720. }
  12721. /* ============ Builtins */
  12722. #if ENABLE_ASH_HELP
  12723. static int FAST_FUNC
  12724. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12725. {
  12726. unsigned col;
  12727. unsigned i;
  12728. out1fmt(
  12729. "Built-in commands:\n"
  12730. "------------------\n");
  12731. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12732. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12733. builtintab[i].name + 1);
  12734. if (col > 60) {
  12735. out1fmt("\n");
  12736. col = 0;
  12737. }
  12738. }
  12739. # if ENABLE_FEATURE_SH_STANDALONE
  12740. {
  12741. const char *a = applet_names;
  12742. while (*a) {
  12743. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12744. if (col > 60) {
  12745. out1fmt("\n");
  12746. col = 0;
  12747. }
  12748. while (*a++ != '\0')
  12749. continue;
  12750. }
  12751. }
  12752. # endif
  12753. newline_and_flush(stdout);
  12754. return EXIT_SUCCESS;
  12755. }
  12756. #endif
  12757. #if MAX_HISTORY
  12758. static int FAST_FUNC
  12759. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12760. {
  12761. show_history(line_input_state);
  12762. return EXIT_SUCCESS;
  12763. }
  12764. #endif
  12765. /*
  12766. * The export and readonly commands.
  12767. */
  12768. static int FAST_FUNC
  12769. exportcmd(int argc UNUSED_PARAM, char **argv)
  12770. {
  12771. struct var *vp;
  12772. char *name;
  12773. const char *p;
  12774. char **aptr;
  12775. char opt;
  12776. int flag;
  12777. int flag_off;
  12778. /* "readonly" in bash accepts, but ignores -n.
  12779. * We do the same: it saves a conditional in nextopt's param.
  12780. */
  12781. flag_off = 0;
  12782. while ((opt = nextopt("np")) != '\0') {
  12783. if (opt == 'n')
  12784. flag_off = VEXPORT;
  12785. }
  12786. flag = VEXPORT;
  12787. if (argv[0][0] == 'r') {
  12788. flag = VREADONLY;
  12789. flag_off = 0; /* readonly ignores -n */
  12790. }
  12791. flag_off = ~flag_off;
  12792. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12793. {
  12794. aptr = argptr;
  12795. name = *aptr;
  12796. if (name) {
  12797. do {
  12798. p = strchr(name, '=');
  12799. if (p != NULL) {
  12800. p++;
  12801. } else {
  12802. vp = *findvar(hashvar(name), name);
  12803. if (vp) {
  12804. vp->flags = ((vp->flags | flag) & flag_off);
  12805. continue;
  12806. }
  12807. }
  12808. setvar(name, p, (flag & flag_off));
  12809. } while ((name = *++aptr) != NULL);
  12810. return 0;
  12811. }
  12812. }
  12813. /* No arguments. Show the list of exported or readonly vars.
  12814. * -n is ignored.
  12815. */
  12816. showvars(argv[0], flag, 0);
  12817. return 0;
  12818. }
  12819. /*
  12820. * Delete a function if it exists.
  12821. */
  12822. static void
  12823. unsetfunc(const char *name)
  12824. {
  12825. struct tblentry *cmdp;
  12826. cmdp = cmdlookup(name, 0);
  12827. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12828. delete_cmd_entry();
  12829. }
  12830. /*
  12831. * The unset builtin command. We unset the function before we unset the
  12832. * variable to allow a function to be unset when there is a readonly variable
  12833. * with the same name.
  12834. */
  12835. static int FAST_FUNC
  12836. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12837. {
  12838. char **ap;
  12839. int i;
  12840. int flag = 0;
  12841. while ((i = nextopt("vf")) != 0) {
  12842. flag = i;
  12843. }
  12844. for (ap = argptr; *ap; ap++) {
  12845. if (flag != 'f') {
  12846. unsetvar(*ap);
  12847. continue;
  12848. }
  12849. if (flag != 'v')
  12850. unsetfunc(*ap);
  12851. }
  12852. return 0;
  12853. }
  12854. static const unsigned char timescmd_str[] ALIGN1 = {
  12855. ' ', offsetof(struct tms, tms_utime),
  12856. '\n', offsetof(struct tms, tms_stime),
  12857. ' ', offsetof(struct tms, tms_cutime),
  12858. '\n', offsetof(struct tms, tms_cstime),
  12859. 0
  12860. };
  12861. static int FAST_FUNC
  12862. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12863. {
  12864. unsigned clk_tck;
  12865. const unsigned char *p;
  12866. struct tms buf;
  12867. clk_tck = bb_clk_tck();
  12868. times(&buf);
  12869. p = timescmd_str;
  12870. do {
  12871. unsigned sec, frac;
  12872. unsigned long t;
  12873. t = *(clock_t *)(((char *) &buf) + p[1]);
  12874. sec = t / clk_tck;
  12875. frac = t % clk_tck;
  12876. out1fmt("%um%u.%03us%c",
  12877. sec / 60, sec % 60,
  12878. (frac * 1000) / clk_tck,
  12879. p[0]);
  12880. p += 2;
  12881. } while (*p);
  12882. return 0;
  12883. }
  12884. #if ENABLE_FEATURE_SH_MATH
  12885. /*
  12886. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12887. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12888. *
  12889. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12890. */
  12891. static int FAST_FUNC
  12892. letcmd(int argc UNUSED_PARAM, char **argv)
  12893. {
  12894. arith_t i;
  12895. argv++;
  12896. if (!*argv)
  12897. ash_msg_and_raise_error("expression expected");
  12898. do {
  12899. i = ash_arith(*argv);
  12900. } while (*++argv);
  12901. return !i;
  12902. }
  12903. #endif
  12904. /*
  12905. * The read builtin. Options:
  12906. * -r Do not interpret '\' specially
  12907. * -s Turn off echo (tty only)
  12908. * -n NCHARS Read NCHARS max
  12909. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12910. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12911. * -u FD Read from given FD instead of fd 0
  12912. * -d DELIM End on DELIM char, not newline
  12913. * This uses unbuffered input, which may be avoidable in some cases.
  12914. * TODO: bash also has:
  12915. * -a ARRAY Read into array[0],[1],etc
  12916. * -e Use line editing (tty only)
  12917. */
  12918. static int FAST_FUNC
  12919. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12920. {
  12921. struct builtin_read_params params;
  12922. const char *r;
  12923. int i;
  12924. memset(&params, 0, sizeof(params));
  12925. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12926. switch (i) {
  12927. case 'p':
  12928. params.opt_p = optionarg;
  12929. break;
  12930. case 'n':
  12931. params.opt_n = optionarg;
  12932. break;
  12933. case 's':
  12934. params.read_flags |= BUILTIN_READ_SILENT;
  12935. break;
  12936. case 't':
  12937. params.opt_t = optionarg;
  12938. break;
  12939. case 'r':
  12940. params.read_flags |= BUILTIN_READ_RAW;
  12941. break;
  12942. case 'u':
  12943. params.opt_u = optionarg;
  12944. break;
  12945. #if BASH_READ_D
  12946. case 'd':
  12947. params.opt_d = optionarg;
  12948. break;
  12949. #endif
  12950. default:
  12951. break;
  12952. }
  12953. }
  12954. if (!ENABLE_ASH_BASH_COMPAT && !argptr) {
  12955. bb_simple_error_msg("read: need variable name");
  12956. return 1;
  12957. }
  12958. params.argv = argptr;
  12959. params.setvar = setvar0;
  12960. params.ifs = bltinlookup("IFS"); /* can be NULL */
  12961. /* "read -s" needs to save/restore termios, can't allow ^C
  12962. * to jump out of it.
  12963. */
  12964. again:
  12965. INT_OFF;
  12966. r = shell_builtin_read(&params);
  12967. INT_ON;
  12968. if ((uintptr_t)r == 1 && errno == EINTR) {
  12969. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12970. * Correct behavior is to not exit "read"
  12971. */
  12972. if (pending_sig == 0)
  12973. goto again;
  12974. }
  12975. if ((uintptr_t)r > 1)
  12976. ash_msg_and_raise_error(r);
  12977. return (uintptr_t)r;
  12978. }
  12979. static int FAST_FUNC
  12980. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12981. {
  12982. static const char permuser[3] ALIGN1 = "ogu";
  12983. mode_t mask;
  12984. int symbolic_mode = 0;
  12985. while (nextopt("S") != '\0') {
  12986. symbolic_mode = 1;
  12987. }
  12988. INT_OFF;
  12989. mask = umask(0);
  12990. umask(mask);
  12991. INT_ON;
  12992. if (*argptr == NULL) {
  12993. if (symbolic_mode) {
  12994. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12995. char *p = buf;
  12996. int i;
  12997. i = 2;
  12998. for (;;) {
  12999. *p++ = ',';
  13000. *p++ = permuser[i];
  13001. *p++ = '=';
  13002. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  13003. if (!(mask & 0400)) *p++ = 'r';
  13004. if (!(mask & 0200)) *p++ = 'w';
  13005. if (!(mask & 0100)) *p++ = 'x';
  13006. mask <<= 3;
  13007. if (--i < 0)
  13008. break;
  13009. }
  13010. *p = '\0';
  13011. puts(buf + 1);
  13012. } else {
  13013. out1fmt("%04o\n", mask);
  13014. }
  13015. } else {
  13016. char *modestr = *argptr;
  13017. /* numeric umasks are taken as-is */
  13018. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  13019. if (!isdigit(modestr[0]))
  13020. mask ^= 0777;
  13021. mask = bb_parse_mode(modestr, mask);
  13022. if ((unsigned)mask > 0777) {
  13023. ash_msg_and_raise_error("illegal mode: %s", modestr);
  13024. }
  13025. if (!isdigit(modestr[0]))
  13026. mask ^= 0777;
  13027. umask(mask);
  13028. }
  13029. return 0;
  13030. }
  13031. static int FAST_FUNC
  13032. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  13033. {
  13034. return shell_builtin_ulimit(argv);
  13035. }
  13036. /* ============ main() and helpers */
  13037. /*
  13038. * This routine is called when an error or an interrupt occurs in an
  13039. * interactive shell and control is returned to the main command loop
  13040. * but prior to exitshell.
  13041. */
  13042. static void
  13043. exitreset(void)
  13044. {
  13045. /* from eval.c: */
  13046. if (savestatus >= 0) {
  13047. if (exception_type == EXEXIT || evalskip == SKIPFUNCDEF)
  13048. exitstatus = savestatus;
  13049. savestatus = -1;
  13050. }
  13051. evalskip = 0;
  13052. loopnest = 0;
  13053. inps4 = 0;
  13054. /* from expand.c: */
  13055. ifsfree();
  13056. /* from redir.c: */
  13057. unwindredir(NULL);
  13058. }
  13059. /*
  13060. * This routine is called when an error or an interrupt occurs in an
  13061. * interactive shell and control is returned to the main command loop.
  13062. * (In dash, this function is auto-generated by build machinery).
  13063. */
  13064. static void
  13065. reset(void)
  13066. {
  13067. /* from input.c: */
  13068. g_parsefile->left_in_buffer = 0;
  13069. g_parsefile->left_in_line = 0; /* clear input buffer */
  13070. g_parsefile->unget = 0;
  13071. popallfiles();
  13072. /* from var.c: */
  13073. unwindlocalvars(NULL);
  13074. }
  13075. /*
  13076. * Called to exit the shell.
  13077. */
  13078. static void
  13079. exitshell(void)
  13080. {
  13081. struct jmploc loc;
  13082. char *p;
  13083. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  13084. save_history(line_input_state); /* may be NULL */
  13085. #endif
  13086. savestatus = exitstatus;
  13087. TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
  13088. if (setjmp(loc.loc))
  13089. goto out;
  13090. exception_handler = &loc;
  13091. p = trap[0];
  13092. if (p) {
  13093. trap[0] = NULL;
  13094. evalskip = 0;
  13095. trap_depth++;
  13096. evalstring(p, 0);
  13097. trap_depth--;
  13098. evalskip = SKIPFUNCDEF;
  13099. /*free(p); - we'll exit soon */
  13100. }
  13101. out:
  13102. exitreset();
  13103. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  13104. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  13105. */
  13106. setjobctl(0);
  13107. flush_stdout_stderr();
  13108. _exit(exitstatus);
  13109. /* NOTREACHED */
  13110. }
  13111. /* Don't inline: conserve stack of caller from having our locals too */
  13112. static NOINLINE void
  13113. init(void)
  13114. {
  13115. /* we will never free this */
  13116. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  13117. basepf.linno = 1;
  13118. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  13119. setsignal(SIGCHLD);
  13120. {
  13121. char **envp;
  13122. const char *p;
  13123. initvar();
  13124. for (envp = environ; envp && *envp; envp++) {
  13125. /* Used to have
  13126. * p = endofname(*envp);
  13127. * if (p != *envp && *p == '=') {
  13128. * here to weed out badly-named variables, but this breaks
  13129. * scenarios where people do want them passed to children:
  13130. * import os
  13131. * os.environ["test-test"]="test"
  13132. * if os.fork() == 0:
  13133. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  13134. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  13135. */
  13136. if (strchr(*envp, '=')) {
  13137. setvareq(*envp, VEXPORT|VTEXTFIXED);
  13138. }
  13139. }
  13140. setvareq((char*)defifsvar, VTEXTFIXED);
  13141. setvareq((char*)defoptindvar, VTEXTFIXED);
  13142. setvar0("PPID", utoa(getppid()));
  13143. #if BASH_SHLVL_VAR
  13144. p = lookupvar("SHLVL");
  13145. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  13146. #endif
  13147. #if BASH_HOSTNAME_VAR
  13148. if (!lookupvar("HOSTNAME")) {
  13149. struct utsname uts;
  13150. uname(&uts);
  13151. setvar0("HOSTNAME", uts.nodename);
  13152. }
  13153. #endif
  13154. p = lookupvar("PWD");
  13155. if (p) {
  13156. struct stat st1, st2;
  13157. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  13158. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  13159. ) {
  13160. p = NULL;
  13161. }
  13162. }
  13163. setpwd(p, 0);
  13164. }
  13165. }
  13166. //usage:#define ash_trivial_usage
  13167. //usage: "[-il] [-|+Cabefmnuvx] [-|+o OPT]... [-c 'SCRIPT' [ARG0 ARGS] | FILE ARGS | -s ARGS]"
  13168. //////// comes from ^^^^^^^^^^optletters
  13169. //usage:#define ash_full_usage "\n\n"
  13170. //usage: "Unix shell interpreter"
  13171. /*
  13172. * Process the shell command line arguments.
  13173. */
  13174. static int
  13175. procargs(char **argv)
  13176. {
  13177. int i;
  13178. const char *xminusc;
  13179. char **xargv;
  13180. int login_sh;
  13181. xargv = argv;
  13182. login_sh = xargv[0] && xargv[0][0] == '-';
  13183. #if NUM_SCRIPTS > 0
  13184. if (minusc)
  13185. goto setarg0;
  13186. #endif
  13187. arg0 = xargv[0];
  13188. /* if (xargv[0]) - mmm, this is always true! */
  13189. xargv++;
  13190. argptr = xargv;
  13191. for (i = 0; i < NOPTS; i++)
  13192. optlist[i] = 2;
  13193. if (options(&login_sh)) {
  13194. /* it already printed err message */
  13195. raise_exception(EXERROR);
  13196. }
  13197. xargv = argptr;
  13198. xminusc = minusc;
  13199. if (*xargv == NULL) {
  13200. if (xminusc)
  13201. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  13202. sflag = 1;
  13203. }
  13204. if (iflag == 2 /* no explicit -i given */
  13205. && sflag == 1 /* -s given (or implied) */
  13206. && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
  13207. && isatty(0) && isatty(1) /* we are on tty */
  13208. ) {
  13209. iflag = 1;
  13210. }
  13211. if (mflag == 2)
  13212. mflag = iflag;
  13213. /* Unset options which weren't explicitly set or unset */
  13214. for (i = 0; i < NOPTS; i++)
  13215. optlist[i] &= 1; /* same effect as "if (optlist[i] == 2) optlist[i] = 0;" */
  13216. #if DEBUG == 2
  13217. debug = 1;
  13218. #endif
  13219. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  13220. if (xminusc) {
  13221. minusc = *xargv++;
  13222. if (*xargv)
  13223. goto setarg0;
  13224. } else if (!sflag) {
  13225. setinputfile(*xargv, 0);
  13226. setarg0:
  13227. arg0 = *xargv++;
  13228. commandname = arg0;
  13229. }
  13230. shellparam.p = xargv;
  13231. #if ENABLE_ASH_GETOPTS
  13232. shellparam.optind = 1;
  13233. shellparam.optoff = -1;
  13234. #endif
  13235. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  13236. while (*xargv) {
  13237. shellparam.nparam++;
  13238. xargv++;
  13239. }
  13240. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  13241. * Try:
  13242. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  13243. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  13244. * NB: must do it before setting up signals (in optschanged())
  13245. * and reading .profile etc (after we return from here):
  13246. */
  13247. if (iflag)
  13248. signal(SIGHUP, SIG_DFL);
  13249. optschanged();
  13250. return login_sh;
  13251. }
  13252. /*
  13253. * Read /etc/profile, ~/.profile, $ENV.
  13254. */
  13255. static void
  13256. read_profile(const char *name)
  13257. {
  13258. name = expandstr(name, DQSYNTAX);
  13259. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  13260. return;
  13261. cmdloop(0);
  13262. popfile();
  13263. }
  13264. #if PROFILE
  13265. static short profile_buf[16384];
  13266. extern int etext();
  13267. #endif
  13268. /*
  13269. * Main routine. We initialize things, parse the arguments, execute
  13270. * profiles if we're a login shell, and then call cmdloop to execute
  13271. * commands. The setjmp call sets up the location to jump to when an
  13272. * exception occurs. When an exception occurs the variable "state"
  13273. * is used to figure out how far we had gotten.
  13274. */
  13275. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13276. #if NUM_SCRIPTS > 0
  13277. int ash_main(int argc, char **argv)
  13278. #else
  13279. int ash_main(int argc UNUSED_PARAM, char **argv)
  13280. #endif
  13281. /* note: 'argc' is used only if embedded scripts are enabled */
  13282. {
  13283. volatile smallint state;
  13284. struct jmploc jmploc;
  13285. struct stackmark smark;
  13286. int login_sh;
  13287. /* Initialize global data */
  13288. INIT_G_misc();
  13289. INIT_G_memstack();
  13290. INIT_G_var();
  13291. #if ENABLE_ASH_ALIAS
  13292. INIT_G_alias();
  13293. #endif
  13294. INIT_G_cmdtable();
  13295. #if PROFILE
  13296. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  13297. #endif
  13298. state = 0;
  13299. if (setjmp(jmploc.loc)) {
  13300. smallint e;
  13301. smallint s;
  13302. exitreset();
  13303. e = exception_type;
  13304. s = state;
  13305. if (e == EXEND || e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  13306. exitshell();
  13307. }
  13308. reset();
  13309. if (e == EXINT) {
  13310. newline_and_flush(stderr);
  13311. }
  13312. popstackmark(&smark);
  13313. FORCE_INT_ON; /* enable interrupts */
  13314. if (s == 1)
  13315. goto state1;
  13316. if (s == 2)
  13317. goto state2;
  13318. if (s == 3)
  13319. goto state3;
  13320. goto state4;
  13321. }
  13322. exception_handler = &jmploc;
  13323. rootpid = getpid();
  13324. init();
  13325. setstackmark(&smark);
  13326. #if NUM_SCRIPTS > 0
  13327. if (argc < 0)
  13328. /* Non-NULL minusc tells procargs that an embedded script is being run */
  13329. minusc = get_script_content(-argc - 1);
  13330. #endif
  13331. login_sh = procargs(argv);
  13332. #if DEBUG
  13333. TRACE(("Shell args: "));
  13334. trace_puts_args(argv);
  13335. #endif
  13336. if (login_sh) {
  13337. const char *hp;
  13338. state = 1;
  13339. read_profile("/etc/profile");
  13340. state1:
  13341. state = 2;
  13342. hp = lookupvar("HOME");
  13343. if (hp)
  13344. read_profile("$HOME/.profile");
  13345. }
  13346. state2:
  13347. state = 3;
  13348. if (iflag
  13349. #ifndef linux
  13350. && getuid() == geteuid() && getgid() == getegid()
  13351. #endif
  13352. ) {
  13353. const char *shinit = lookupvar("ENV");
  13354. if (shinit != NULL && *shinit != '\0')
  13355. read_profile(shinit);
  13356. }
  13357. popstackmark(&smark);
  13358. state3:
  13359. state = 4;
  13360. if (minusc) {
  13361. /* evalstring pushes parsefile stack.
  13362. * Ensure we don't falsely claim that 0 (stdin)
  13363. * is one of stacked source fds.
  13364. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13365. // if (!sflag) g_parsefile->pf_fd = -1;
  13366. // ^^ not necessary since now we special-case fd 0
  13367. // in save_fd_on_redirect()
  13368. lineno = 0; // bash compat
  13369. // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
  13370. // The above makes
  13371. // ash -sc 'echo $-'
  13372. // continue reading input from stdin after running 'echo'.
  13373. // bash does not do this: it prints "hBcs" and exits.
  13374. evalstring(minusc, EV_EXIT);
  13375. }
  13376. if (sflag || minusc == NULL) {
  13377. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13378. if (line_input_state) {
  13379. const char *hp = lookupvar("HISTFILE");
  13380. if (!hp) {
  13381. hp = lookupvar("HOME");
  13382. if (hp) {
  13383. INT_OFF;
  13384. hp = concat_path_file(hp, ".ash_history");
  13385. setvar0("HISTFILE", hp);
  13386. free((char*)hp);
  13387. INT_ON;
  13388. hp = lookupvar("HISTFILE");
  13389. }
  13390. }
  13391. if (hp)
  13392. line_input_state->hist_file = xstrdup(hp);
  13393. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13394. hp = lookupvar("HISTFILESIZE");
  13395. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13396. # endif
  13397. }
  13398. #endif
  13399. state4: /* XXX ??? - why isn't this before the "if" statement */
  13400. cmdloop(1);
  13401. }
  13402. #if PROFILE
  13403. monitor(0);
  13404. #endif
  13405. #ifdef GPROF
  13406. {
  13407. extern void _mcleanup(void);
  13408. _mcleanup();
  13409. }
  13410. #endif
  13411. TRACE(("End of main reached\n"));
  13412. exitshell();
  13413. /* NOTREACHED */
  13414. }
  13415. /*-
  13416. * Copyright (c) 1989, 1991, 1993, 1994
  13417. * The Regents of the University of California. All rights reserved.
  13418. *
  13419. * This code is derived from software contributed to Berkeley by
  13420. * Kenneth Almquist.
  13421. *
  13422. * Redistribution and use in source and binary forms, with or without
  13423. * modification, are permitted provided that the following conditions
  13424. * are met:
  13425. * 1. Redistributions of source code must retain the above copyright
  13426. * notice, this list of conditions and the following disclaimer.
  13427. * 2. Redistributions in binary form must reproduce the above copyright
  13428. * notice, this list of conditions and the following disclaimer in the
  13429. * documentation and/or other materials provided with the distribution.
  13430. * 3. Neither the name of the University nor the names of its contributors
  13431. * may be used to endorse or promote products derived from this software
  13432. * without specific prior written permission.
  13433. *
  13434. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13435. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13436. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13437. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13438. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13439. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13440. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13441. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13442. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13443. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13444. * SUCH DAMAGE.
  13445. */