ash.c 321 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321
  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 ASH
  19. //config: bool "ash (78 kb)"
  20. //config: default y
  21. //config: depends on !NOMMU
  22. //config: help
  23. //config: The most complete and most pedantically correct shell included with
  24. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  25. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  26. //config: (written by Kenneth Almquist) from NetBSD.
  27. //config:
  28. //config:# ash options
  29. //config:# note: Don't remove !NOMMU part in the next line; it would break
  30. //config:# menuconfig's indenting.
  31. //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
  32. //config:
  33. //config:config ASH_OPTIMIZE_FOR_SIZE
  34. //config: bool "Optimize for size instead of speed"
  35. //config: default y
  36. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  37. //config:
  38. //config:config ASH_INTERNAL_GLOB
  39. //config: bool "Use internal glob() implementation"
  40. //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
  41. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  42. //config: help
  43. //config: Do not use glob() function from libc, use internal implementation.
  44. //config: Use this if you are getting "glob.h: No such file or directory"
  45. //config: or similar build errors.
  46. //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
  47. //config: which would break ash if you select N here.
  48. //config:
  49. //config:config ASH_BASH_COMPAT
  50. //config: bool "bash-compatible extensions"
  51. //config: default y
  52. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  53. //config:
  54. //config:config ASH_BASH_SOURCE_CURDIR
  55. //config: bool "'source' and '.' builtins search current directory after $PATH"
  56. //config: default n # do not encourage non-standard behavior
  57. //config: depends on ASH_BASH_COMPAT
  58. //config: help
  59. //config: This is not compliant with standards. Avoid if possible.
  60. //config:
  61. //config:config ASH_BASH_NOT_FOUND_HOOK
  62. //config: bool "command_not_found_handle hook support"
  63. //config: default y
  64. //config: depends on ASH_BASH_COMPAT
  65. //config: help
  66. //config: Enable support for the 'command_not_found_handle' hook function,
  67. //config: from GNU bash, which allows for alternative command not found
  68. //config: handling.
  69. //config:
  70. //config:config ASH_JOB_CONTROL
  71. //config: bool "Job control"
  72. //config: default y
  73. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  74. //config:
  75. //config:config ASH_ALIAS
  76. //config: bool "Alias support"
  77. //config: default y
  78. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  79. //config:
  80. //config:config ASH_RANDOM_SUPPORT
  81. //config: bool "Pseudorandom generator and $RANDOM variable"
  82. //config: default y
  83. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  84. //config: help
  85. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  86. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  87. //config: You can reset the generator by using a specified start value.
  88. //config: After "unset RANDOM" the generator will switch off and this
  89. //config: variable will no longer have special treatment.
  90. //config:
  91. //config:config ASH_EXPAND_PRMT
  92. //config: bool "Expand prompt string"
  93. //config: default y
  94. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  95. //config: help
  96. //config: $PS# may contain volatile content, such as backquote commands.
  97. //config: This option recreates the prompt string from the environment
  98. //config: variable each time it is displayed.
  99. //config:
  100. //config:config ASH_IDLE_TIMEOUT
  101. //config: bool "Idle timeout variable $TMOUT"
  102. //config: default y
  103. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  104. //config: help
  105. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  106. //config:
  107. //config:config ASH_MAIL
  108. //config: bool "Check for new mail in interactive shell"
  109. //config: default y
  110. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  111. //config: help
  112. //config: Enable "check for new mail" function:
  113. //config: if set, $MAIL file and $MAILPATH list of files
  114. //config: are checked for mtime changes, and "you have mail"
  115. //config: message is printed if change is detected.
  116. //config:
  117. //config:config ASH_ECHO
  118. //config: bool "echo builtin"
  119. //config: default y
  120. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  121. //config:
  122. //config:config ASH_PRINTF
  123. //config: bool "printf builtin"
  124. //config: default y
  125. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  126. //config:
  127. //config:config ASH_TEST
  128. //config: bool "test builtin"
  129. //config: default y
  130. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  131. //config:
  132. //config:config ASH_HELP
  133. //config: bool "help builtin"
  134. //config: default y
  135. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  136. //config:
  137. //config:config ASH_GETOPTS
  138. //config: bool "getopts builtin"
  139. //config: default y
  140. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  141. //config:
  142. //config:config ASH_CMDCMD
  143. //config: bool "command builtin"
  144. //config: default y
  145. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  146. //config: help
  147. //config: Enable support for the 'command' builtin, which allows
  148. //config: you to run the specified command or builtin,
  149. //config: even when there is a function with the same name.
  150. //config:
  151. //config:endif # ash options
  152. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  153. // APPLET_ODDNAME:name main location suid_type help
  154. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  155. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  156. //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
  157. //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  158. //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  159. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  160. /*
  161. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  162. * DEBUG=2 to compile in and turn on debugging.
  163. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  164. * debugging info is written to ./trace, quit signal generates core dump.
  165. */
  166. #define DEBUG 0
  167. /* Tweak debug output verbosity here */
  168. #define DEBUG_TIME 0
  169. #define DEBUG_PID 1
  170. #define DEBUG_SIG 1
  171. #define DEBUG_INTONOFF 0
  172. #define PROFILE 0
  173. #define JOBS ENABLE_ASH_JOB_CONTROL
  174. #include <fnmatch.h>
  175. #include <sys/times.h>
  176. #include <sys/utsname.h> /* for setting $HOSTNAME */
  177. #include "busybox.h" /* for applet_names */
  178. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
  179. # include "embedded_scripts.h"
  180. #else
  181. # define NUM_SCRIPTS 0
  182. #endif
  183. /* So far, all bash compat is controlled by one config option */
  184. /* Separate defines document which part of code implements what */
  185. /* function keyword */
  186. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  187. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  188. /* &>file */
  189. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  190. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  191. /* $'...' */
  192. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  193. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  194. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  195. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  196. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  197. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  198. /* BASH_TEST2: [[ EXPR ]]
  199. * Status of [[ support:
  200. * We replace && and || with -a and -o
  201. * TODO:
  202. * singleword+noglob expansion:
  203. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  204. * [[ /bin/n* ]]; echo 0:$?
  205. * -a/-o are not AND/OR ops! (they are just strings)
  206. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  207. * = is glob match operator, not equality operator: STR = GLOB
  208. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  209. * == same as =
  210. * add =~ regex match operator: STR =~ REGEX
  211. */
  212. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  213. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  214. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  215. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  216. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  217. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  218. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  219. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  220. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  221. /* Bionic at least up to version 24 has no glob() */
  222. # undef ENABLE_ASH_INTERNAL_GLOB
  223. # define ENABLE_ASH_INTERNAL_GLOB 1
  224. #endif
  225. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  226. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  227. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  228. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  229. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  230. # error fails to match dirname, subsequently not expanding <pattern> in it.
  231. // Testcase:
  232. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  233. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  234. #endif
  235. #if !ENABLE_ASH_INTERNAL_GLOB
  236. # include <glob.h>
  237. #endif
  238. #include "unicode.h"
  239. #include "shell_common.h"
  240. #if ENABLE_FEATURE_SH_MATH
  241. # include "math.h"
  242. #else
  243. typedef long arith_t;
  244. # define ARITH_FMT "%ld"
  245. #endif
  246. #if ENABLE_ASH_RANDOM_SUPPORT
  247. # include "random.h"
  248. #else
  249. # define CLEAR_RANDOM_T(rnd) ((void)0)
  250. #endif
  251. #include "NUM_APPLETS.h"
  252. #if NUM_APPLETS == 1
  253. /* STANDALONE does not make sense, and won't compile */
  254. # undef CONFIG_FEATURE_SH_STANDALONE
  255. # undef ENABLE_FEATURE_SH_STANDALONE
  256. # undef IF_FEATURE_SH_STANDALONE
  257. # undef IF_NOT_FEATURE_SH_STANDALONE
  258. # define ENABLE_FEATURE_SH_STANDALONE 0
  259. # define IF_FEATURE_SH_STANDALONE(...)
  260. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  261. #endif
  262. #ifndef F_DUPFD_CLOEXEC
  263. # define F_DUPFD_CLOEXEC F_DUPFD
  264. #endif
  265. #ifndef O_CLOEXEC
  266. # define O_CLOEXEC 0
  267. #endif
  268. #ifndef PIPE_BUF
  269. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  270. #endif
  271. #if !BB_MMU
  272. # error "Do not even bother, ash will not run on NOMMU machine"
  273. #endif
  274. /* We use a trick to have more optimized code (fewer pointer reloads):
  275. * ash.c: extern struct globals *const ash_ptr_to_globals;
  276. * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
  277. * This way, compiler in ash.c knows the pointer can not change.
  278. *
  279. * However, this may break on weird arches or toolchains. In this case,
  280. * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
  281. * this optimization.
  282. */
  283. #ifndef BB_GLOBAL_CONST
  284. # define BB_GLOBAL_CONST const
  285. #endif
  286. /* ============ Hash table sizes. Configurable. */
  287. #define VTABSIZE 39
  288. #define ATABSIZE 39
  289. #define CMDTABLESIZE 31 /* should be prime */
  290. /* ============ Shell options */
  291. static const char *const optletters_optnames[] = {
  292. "e" "errexit",
  293. "f" "noglob",
  294. "I" "ignoreeof",
  295. "i" "interactive",
  296. "m" "monitor",
  297. "n" "noexec",
  298. "s" "stdin",
  299. "x" "xtrace",
  300. "v" "verbose",
  301. "C" "noclobber",
  302. "a" "allexport",
  303. "b" "notify",
  304. "u" "nounset",
  305. "\0" "vi"
  306. #if BASH_PIPEFAIL
  307. ,"\0" "pipefail"
  308. #endif
  309. #if DEBUG
  310. ,"\0" "nolog"
  311. ,"\0" "debug"
  312. #endif
  313. };
  314. #define optletters(n) optletters_optnames[n][0]
  315. #define optnames(n) (optletters_optnames[n] + 1)
  316. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  317. /* ============ Misc data */
  318. #define msg_illnum "Illegal number: %s"
  319. /*
  320. * We enclose jmp_buf in a structure so that we can declare pointers to
  321. * jump locations. The global variable handler contains the location to
  322. * jump to when an exception occurs, and the global variable exception_type
  323. * contains a code identifying the exception. To implement nested
  324. * exception handlers, the user should save the value of handler on entry
  325. * to an inner scope, set handler to point to a jmploc structure for the
  326. * inner scope, and restore handler on exit from the scope.
  327. */
  328. struct jmploc {
  329. jmp_buf loc;
  330. };
  331. struct globals_misc {
  332. uint8_t exitstatus; /* exit status of last command */
  333. uint8_t back_exitstatus;/* exit status of backquoted command */
  334. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  335. int rootpid; /* pid of main shell */
  336. /* shell level: 0 for the main shell, 1 for its children, and so on */
  337. int shlvl;
  338. #define rootshell (!shlvl)
  339. int errlinno;
  340. char *minusc; /* argument to -c option */
  341. char *curdir; // = nullstr; /* current working directory */
  342. char *physdir; // = nullstr; /* physical working directory */
  343. char *arg0; /* value of $0 */
  344. struct jmploc *exception_handler;
  345. volatile int suppress_int; /* counter */
  346. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  347. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  348. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  349. smallint exception_type; /* kind of exception (0..5) */
  350. /* exceptions */
  351. #define EXINT 0 /* SIGINT received */
  352. #define EXERROR 1 /* a generic error */
  353. #define EXEXIT 4 /* exit the shell */
  354. char nullstr[1]; /* zero length string */
  355. char optlist[NOPTS];
  356. #define eflag optlist[0]
  357. #define fflag optlist[1]
  358. #define Iflag optlist[2]
  359. #define iflag optlist[3]
  360. #define mflag optlist[4]
  361. #define nflag optlist[5]
  362. #define sflag optlist[6]
  363. #define xflag optlist[7]
  364. #define vflag optlist[8]
  365. #define Cflag optlist[9]
  366. #define aflag optlist[10]
  367. #define bflag optlist[11]
  368. #define uflag optlist[12]
  369. #define viflag optlist[13]
  370. #if BASH_PIPEFAIL
  371. # define pipefail optlist[14]
  372. #else
  373. # define pipefail 0
  374. #endif
  375. #if DEBUG
  376. # define nolog optlist[14 + BASH_PIPEFAIL]
  377. # define debug optlist[15 + BASH_PIPEFAIL]
  378. #endif
  379. /* trap handler commands */
  380. /*
  381. * Sigmode records the current value of the signal handlers for the various
  382. * modes. A value of zero means that the current handler is not known.
  383. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  384. */
  385. char sigmode[NSIG - 1];
  386. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  387. #define S_CATCH 2 /* signal is caught */
  388. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  389. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  390. /* indicates specified signal received */
  391. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  392. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  393. char *trap[NSIG];
  394. char **trap_ptr; /* used only by "trap hack" */
  395. /* Rarely referenced stuff */
  396. #if ENABLE_ASH_RANDOM_SUPPORT
  397. random_t random_gen;
  398. #endif
  399. pid_t backgndpid; /* pid of last background process */
  400. };
  401. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  402. #define G_misc (*ash_ptr_to_globals_misc)
  403. #define exitstatus (G_misc.exitstatus )
  404. #define back_exitstatus (G_misc.back_exitstatus )
  405. #define job_warning (G_misc.job_warning)
  406. #define rootpid (G_misc.rootpid )
  407. #define shlvl (G_misc.shlvl )
  408. #define errlinno (G_misc.errlinno )
  409. #define minusc (G_misc.minusc )
  410. #define curdir (G_misc.curdir )
  411. #define physdir (G_misc.physdir )
  412. #define arg0 (G_misc.arg0 )
  413. #define exception_handler (G_misc.exception_handler)
  414. #define exception_type (G_misc.exception_type )
  415. #define suppress_int (G_misc.suppress_int )
  416. #define pending_int (G_misc.pending_int )
  417. #define got_sigchld (G_misc.got_sigchld )
  418. #define pending_sig (G_misc.pending_sig )
  419. #define nullstr (G_misc.nullstr )
  420. #define optlist (G_misc.optlist )
  421. #define sigmode (G_misc.sigmode )
  422. #define gotsig (G_misc.gotsig )
  423. #define may_have_traps (G_misc.may_have_traps )
  424. #define trap (G_misc.trap )
  425. #define trap_ptr (G_misc.trap_ptr )
  426. #define random_gen (G_misc.random_gen )
  427. #define backgndpid (G_misc.backgndpid )
  428. #define INIT_G_misc() do { \
  429. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  430. barrier(); \
  431. curdir = nullstr; \
  432. physdir = nullstr; \
  433. trap_ptr = trap; \
  434. } while (0)
  435. /* ============ DEBUG */
  436. #if DEBUG
  437. static void trace_printf(const char *fmt, ...);
  438. static void trace_vprintf(const char *fmt, va_list va);
  439. # define TRACE(param) trace_printf param
  440. # define TRACEV(param) trace_vprintf param
  441. # define close(fd) do { \
  442. int dfd = (fd); \
  443. if (close(dfd) < 0) \
  444. bb_error_msg("bug on %d: closing %d(0x%x)", \
  445. __LINE__, dfd, dfd); \
  446. } while (0)
  447. #else
  448. # define TRACE(param)
  449. # define TRACEV(param)
  450. #endif
  451. /* ============ Utility functions */
  452. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  453. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  454. static int
  455. isdigit_str9(const char *str)
  456. {
  457. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  458. while (--maxlen && isdigit(*str))
  459. str++;
  460. return (*str == '\0');
  461. }
  462. static const char *
  463. var_end(const char *var)
  464. {
  465. while (*var)
  466. if (*var++ == '=')
  467. break;
  468. return var;
  469. }
  470. /* ============ Interrupts / exceptions */
  471. static void exitshell(void) NORETURN;
  472. /*
  473. * These macros allow the user to suspend the handling of interrupt signals
  474. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  475. * much more efficient and portable. (But hacking the kernel is so much
  476. * more fun than worrying about efficiency and portability. :-))
  477. */
  478. #if DEBUG_INTONOFF
  479. # define INT_OFF do { \
  480. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  481. suppress_int++; \
  482. barrier(); \
  483. } while (0)
  484. #else
  485. # define INT_OFF do { \
  486. suppress_int++; \
  487. barrier(); \
  488. } while (0)
  489. #endif
  490. /*
  491. * Called to raise an exception. Since C doesn't include exceptions, we
  492. * just do a longjmp to the exception handler. The type of exception is
  493. * stored in the global variable "exception_type".
  494. */
  495. static void raise_exception(int) NORETURN;
  496. static void
  497. raise_exception(int e)
  498. {
  499. #if DEBUG
  500. if (exception_handler == NULL)
  501. abort();
  502. #endif
  503. INT_OFF;
  504. exception_type = e;
  505. longjmp(exception_handler->loc, 1);
  506. }
  507. #if DEBUG
  508. #define raise_exception(e) do { \
  509. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  510. raise_exception(e); \
  511. } while (0)
  512. #endif
  513. /*
  514. * Called when a SIGINT is received. (If the user specifies
  515. * that SIGINT is to be trapped or ignored using the trap builtin, then
  516. * this routine is not called.) Suppressint is nonzero when interrupts
  517. * are held using the INT_OFF macro. (The test for iflag is just
  518. * defensive programming.)
  519. */
  520. static void raise_interrupt(void) NORETURN;
  521. static void
  522. raise_interrupt(void)
  523. {
  524. pending_int = 0;
  525. /* Signal is not automatically unmasked after it is raised,
  526. * do it ourself - unmask all signals */
  527. sigprocmask_allsigs(SIG_UNBLOCK);
  528. /* pending_sig = 0; - now done in signal_handler() */
  529. if (!(rootshell && iflag)) {
  530. /* Kill ourself with SIGINT */
  531. signal(SIGINT, SIG_DFL);
  532. raise(SIGINT);
  533. }
  534. /* bash: ^C even on empty command line sets $? */
  535. exitstatus = SIGINT + 128;
  536. raise_exception(EXINT);
  537. /* NOTREACHED */
  538. }
  539. #if DEBUG
  540. #define raise_interrupt() do { \
  541. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  542. raise_interrupt(); \
  543. } while (0)
  544. #endif
  545. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  546. int_on(void)
  547. {
  548. barrier();
  549. if (--suppress_int == 0 && pending_int) {
  550. raise_interrupt();
  551. }
  552. }
  553. #if DEBUG_INTONOFF
  554. # define INT_ON do { \
  555. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  556. int_on(); \
  557. } while (0)
  558. #else
  559. # define INT_ON int_on()
  560. #endif
  561. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  562. force_int_on(void)
  563. {
  564. barrier();
  565. suppress_int = 0;
  566. if (pending_int)
  567. raise_interrupt();
  568. }
  569. #define FORCE_INT_ON force_int_on()
  570. #define SAVE_INT(v) ((v) = suppress_int)
  571. #define RESTORE_INT(v) do { \
  572. barrier(); \
  573. suppress_int = (v); \
  574. if (suppress_int == 0 && pending_int) \
  575. raise_interrupt(); \
  576. } while (0)
  577. /* ============ Stdout/stderr output */
  578. static void
  579. outstr(const char *p, FILE *file)
  580. {
  581. INT_OFF;
  582. fputs(p, file);
  583. INT_ON;
  584. }
  585. static void
  586. flush_stdout_stderr(void)
  587. {
  588. INT_OFF;
  589. fflush_all();
  590. INT_ON;
  591. }
  592. /* Was called outcslow(c,FILE*), but c was always '\n' */
  593. static void
  594. newline_and_flush(FILE *dest)
  595. {
  596. INT_OFF;
  597. putc('\n', dest);
  598. fflush(dest);
  599. INT_ON;
  600. }
  601. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  602. static int
  603. out1fmt(const char *fmt, ...)
  604. {
  605. va_list ap;
  606. int r;
  607. INT_OFF;
  608. va_start(ap, fmt);
  609. r = vprintf(fmt, ap);
  610. va_end(ap);
  611. INT_ON;
  612. return r;
  613. }
  614. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  615. static int
  616. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  617. {
  618. va_list ap;
  619. int ret;
  620. INT_OFF;
  621. va_start(ap, fmt);
  622. ret = vsnprintf(outbuf, length, fmt, ap);
  623. va_end(ap);
  624. INT_ON;
  625. return ret;
  626. }
  627. static void
  628. out1str(const char *p)
  629. {
  630. outstr(p, stdout);
  631. }
  632. static void
  633. out2str(const char *p)
  634. {
  635. outstr(p, stderr);
  636. flush_stdout_stderr();
  637. }
  638. /* ============ Parser structures */
  639. /* control characters in argument strings */
  640. #define CTL_FIRST CTLESC
  641. #define CTLESC ((unsigned char)'\201') /* escape next character */
  642. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  643. #define CTLENDVAR ((unsigned char)'\203')
  644. #define CTLBACKQ ((unsigned char)'\204')
  645. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  646. #define CTLENDARI ((unsigned char)'\207')
  647. #define CTLQUOTEMARK ((unsigned char)'\210')
  648. #define CTL_LAST CTLQUOTEMARK
  649. /* variable substitution byte (follows CTLVAR) */
  650. #define VSTYPE 0x0f /* type of variable substitution */
  651. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  652. /* values of VSTYPE field */
  653. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  654. #define VSMINUS 0x2 /* ${var-text} */
  655. #define VSPLUS 0x3 /* ${var+text} */
  656. #define VSQUESTION 0x4 /* ${var?message} */
  657. #define VSASSIGN 0x5 /* ${var=text} */
  658. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  659. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  660. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  661. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  662. #define VSLENGTH 0xa /* ${#var} */
  663. #if BASH_SUBSTR
  664. #define VSSUBSTR 0xc /* ${var:position:length} */
  665. #endif
  666. #if BASH_PATTERN_SUBST
  667. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  668. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  669. #endif
  670. static const char dolatstr[] ALIGN1 = {
  671. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  672. };
  673. #define DOLATSTRLEN 6
  674. #define NCMD 0
  675. #define NPIPE 1
  676. #define NREDIR 2
  677. #define NBACKGND 3
  678. #define NSUBSHELL 4
  679. #define NAND 5
  680. #define NOR 6
  681. #define NSEMI 7
  682. #define NIF 8
  683. #define NWHILE 9
  684. #define NUNTIL 10
  685. #define NFOR 11
  686. #define NCASE 12
  687. #define NCLIST 13
  688. #define NDEFUN 14
  689. #define NARG 15
  690. #define NTO 16
  691. #if BASH_REDIR_OUTPUT
  692. #define NTO2 17
  693. #endif
  694. #define NCLOBBER 18
  695. #define NFROM 19
  696. #define NFROMTO 20
  697. #define NAPPEND 21
  698. #define NTOFD 22
  699. #define NFROMFD 23
  700. #define NHERE 24
  701. #define NXHERE 25
  702. #define NNOT 26
  703. #define N_NUMBER 27
  704. union node;
  705. struct ncmd {
  706. smallint type; /* Nxxxx */
  707. int linno;
  708. union node *assign;
  709. union node *args;
  710. union node *redirect;
  711. };
  712. struct npipe {
  713. smallint type;
  714. smallint pipe_backgnd;
  715. struct nodelist *cmdlist;
  716. };
  717. struct nredir {
  718. smallint type;
  719. int linno;
  720. union node *n;
  721. union node *redirect;
  722. };
  723. struct nbinary {
  724. smallint type;
  725. union node *ch1;
  726. union node *ch2;
  727. };
  728. struct nif {
  729. smallint type;
  730. union node *test;
  731. union node *ifpart;
  732. union node *elsepart;
  733. };
  734. struct nfor {
  735. smallint type;
  736. int linno;
  737. union node *args;
  738. union node *body;
  739. char *var;
  740. };
  741. struct ncase {
  742. smallint type;
  743. int linno;
  744. union node *expr;
  745. union node *cases;
  746. };
  747. struct nclist {
  748. smallint type;
  749. union node *next;
  750. union node *pattern;
  751. union node *body;
  752. };
  753. struct ndefun {
  754. smallint type;
  755. int linno;
  756. char *text;
  757. union node *body;
  758. };
  759. struct narg {
  760. smallint type;
  761. union node *next;
  762. char *text;
  763. struct nodelist *backquote;
  764. };
  765. /* nfile and ndup layout must match!
  766. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  767. * that it is actually NTO2 (>&file), and change its type.
  768. */
  769. struct nfile {
  770. smallint type;
  771. union node *next;
  772. int fd;
  773. int _unused_dupfd;
  774. union node *fname;
  775. char *expfname;
  776. };
  777. struct ndup {
  778. smallint type;
  779. union node *next;
  780. int fd;
  781. int dupfd;
  782. union node *vname;
  783. char *_unused_expfname;
  784. };
  785. struct nhere {
  786. smallint type;
  787. union node *next;
  788. int fd;
  789. union node *doc;
  790. };
  791. struct nnot {
  792. smallint type;
  793. union node *com;
  794. };
  795. union node {
  796. smallint type;
  797. struct ncmd ncmd;
  798. struct npipe npipe;
  799. struct nredir nredir;
  800. struct nbinary nbinary;
  801. struct nif nif;
  802. struct nfor nfor;
  803. struct ncase ncase;
  804. struct nclist nclist;
  805. struct ndefun ndefun;
  806. struct narg narg;
  807. struct nfile nfile;
  808. struct ndup ndup;
  809. struct nhere nhere;
  810. struct nnot nnot;
  811. };
  812. /*
  813. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  814. * It must be distinct from NULL.
  815. */
  816. #define NODE_EOF ((union node *) -1L)
  817. struct nodelist {
  818. struct nodelist *next;
  819. union node *n;
  820. };
  821. struct funcnode {
  822. int count;
  823. union node n;
  824. };
  825. /*
  826. * Free a parse tree.
  827. */
  828. static void
  829. freefunc(struct funcnode *f)
  830. {
  831. if (f && --f->count < 0)
  832. free(f);
  833. }
  834. /* ============ Debugging output */
  835. #if DEBUG
  836. static FILE *tracefile;
  837. static void
  838. trace_printf(const char *fmt, ...)
  839. {
  840. va_list va;
  841. if (debug != 1)
  842. return;
  843. if (DEBUG_TIME)
  844. fprintf(tracefile, "%u ", (int) time(NULL));
  845. if (DEBUG_PID)
  846. fprintf(tracefile, "[%u] ", (int) getpid());
  847. if (DEBUG_SIG)
  848. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  849. va_start(va, fmt);
  850. vfprintf(tracefile, fmt, va);
  851. va_end(va);
  852. }
  853. static void
  854. trace_vprintf(const char *fmt, va_list va)
  855. {
  856. if (debug != 1)
  857. return;
  858. vfprintf(tracefile, fmt, va);
  859. fprintf(tracefile, "\n");
  860. }
  861. static void
  862. trace_puts(const char *s)
  863. {
  864. if (debug != 1)
  865. return;
  866. fputs(s, tracefile);
  867. }
  868. static void
  869. trace_puts_quoted(char *s)
  870. {
  871. char *p;
  872. char c;
  873. if (debug != 1)
  874. return;
  875. putc('"', tracefile);
  876. for (p = s; *p; p++) {
  877. switch ((unsigned char)*p) {
  878. case '\n': c = 'n'; goto backslash;
  879. case '\t': c = 't'; goto backslash;
  880. case '\r': c = 'r'; goto backslash;
  881. case '\"': c = '\"'; goto backslash;
  882. case '\\': c = '\\'; goto backslash;
  883. case CTLESC: c = 'e'; goto backslash;
  884. case CTLVAR: c = 'v'; goto backslash;
  885. case CTLBACKQ: c = 'q'; goto backslash;
  886. backslash:
  887. putc('\\', tracefile);
  888. putc(c, tracefile);
  889. break;
  890. default:
  891. if (*p >= ' ' && *p <= '~')
  892. putc(*p, tracefile);
  893. else {
  894. putc('\\', tracefile);
  895. putc((*p >> 6) & 03, tracefile);
  896. putc((*p >> 3) & 07, tracefile);
  897. putc(*p & 07, tracefile);
  898. }
  899. break;
  900. }
  901. }
  902. putc('"', tracefile);
  903. }
  904. static void
  905. trace_puts_args(char **ap)
  906. {
  907. if (debug != 1)
  908. return;
  909. if (!*ap)
  910. return;
  911. while (1) {
  912. trace_puts_quoted(*ap);
  913. if (!*++ap) {
  914. putc('\n', tracefile);
  915. break;
  916. }
  917. putc(' ', tracefile);
  918. }
  919. }
  920. static void
  921. opentrace(void)
  922. {
  923. char s[100];
  924. #ifdef O_APPEND
  925. int flags;
  926. #endif
  927. if (debug != 1) {
  928. if (tracefile)
  929. fflush(tracefile);
  930. /* leave open because libedit might be using it */
  931. return;
  932. }
  933. strcpy(s, "./trace");
  934. if (tracefile) {
  935. if (!freopen(s, "a", tracefile)) {
  936. fprintf(stderr, "Can't re-open %s\n", s);
  937. debug = 0;
  938. return;
  939. }
  940. } else {
  941. tracefile = fopen(s, "a");
  942. if (tracefile == NULL) {
  943. fprintf(stderr, "Can't open %s\n", s);
  944. debug = 0;
  945. return;
  946. }
  947. }
  948. #ifdef O_APPEND
  949. flags = fcntl(fileno(tracefile), F_GETFL);
  950. if (flags >= 0)
  951. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  952. #endif
  953. setlinebuf(tracefile);
  954. fputs("\nTracing started.\n", tracefile);
  955. }
  956. static void
  957. indent(int amount, char *pfx, FILE *fp)
  958. {
  959. int i;
  960. for (i = 0; i < amount; i++) {
  961. if (pfx && i == amount - 1)
  962. fputs(pfx, fp);
  963. putc('\t', fp);
  964. }
  965. }
  966. /* little circular references here... */
  967. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  968. static void
  969. sharg(union node *arg, FILE *fp)
  970. {
  971. char *p;
  972. struct nodelist *bqlist;
  973. unsigned char subtype;
  974. if (arg->type != NARG) {
  975. out1fmt("<node type %d>\n", arg->type);
  976. abort();
  977. }
  978. bqlist = arg->narg.backquote;
  979. for (p = arg->narg.text; *p; p++) {
  980. switch ((unsigned char)*p) {
  981. case CTLESC:
  982. p++;
  983. putc(*p, fp);
  984. break;
  985. case CTLVAR:
  986. putc('$', fp);
  987. putc('{', fp);
  988. subtype = *++p;
  989. if (subtype == VSLENGTH)
  990. putc('#', fp);
  991. while (*p != '=') {
  992. putc(*p, fp);
  993. p++;
  994. }
  995. if (subtype & VSNUL)
  996. putc(':', fp);
  997. switch (subtype & VSTYPE) {
  998. case VSNORMAL:
  999. putc('}', fp);
  1000. break;
  1001. case VSMINUS:
  1002. putc('-', fp);
  1003. break;
  1004. case VSPLUS:
  1005. putc('+', fp);
  1006. break;
  1007. case VSQUESTION:
  1008. putc('?', fp);
  1009. break;
  1010. case VSASSIGN:
  1011. putc('=', fp);
  1012. break;
  1013. case VSTRIMLEFT:
  1014. putc('#', fp);
  1015. break;
  1016. case VSTRIMLEFTMAX:
  1017. putc('#', fp);
  1018. putc('#', fp);
  1019. break;
  1020. case VSTRIMRIGHT:
  1021. putc('%', fp);
  1022. break;
  1023. case VSTRIMRIGHTMAX:
  1024. putc('%', fp);
  1025. putc('%', fp);
  1026. break;
  1027. case VSLENGTH:
  1028. break;
  1029. default:
  1030. out1fmt("<subtype %d>", subtype);
  1031. }
  1032. break;
  1033. case CTLENDVAR:
  1034. putc('}', fp);
  1035. break;
  1036. case CTLBACKQ:
  1037. putc('$', fp);
  1038. putc('(', fp);
  1039. shtree(bqlist->n, -1, NULL, fp);
  1040. putc(')', fp);
  1041. break;
  1042. default:
  1043. putc(*p, fp);
  1044. break;
  1045. }
  1046. }
  1047. }
  1048. static void
  1049. shcmd(union node *cmd, FILE *fp)
  1050. {
  1051. union node *np;
  1052. int first;
  1053. const char *s;
  1054. int dftfd;
  1055. first = 1;
  1056. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1057. if (!first)
  1058. putc(' ', fp);
  1059. sharg(np, fp);
  1060. first = 0;
  1061. }
  1062. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1063. if (!first)
  1064. putc(' ', fp);
  1065. dftfd = 0;
  1066. switch (np->nfile.type) {
  1067. case NTO: s = ">>"+1; dftfd = 1; break;
  1068. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1069. case NAPPEND: s = ">>"; dftfd = 1; break;
  1070. #if BASH_REDIR_OUTPUT
  1071. case NTO2:
  1072. #endif
  1073. case NTOFD: s = ">&"; dftfd = 1; break;
  1074. case NFROM: s = "<"; break;
  1075. case NFROMFD: s = "<&"; break;
  1076. case NFROMTO: s = "<>"; break;
  1077. default: s = "*error*"; break;
  1078. }
  1079. if (np->nfile.fd != dftfd)
  1080. fprintf(fp, "%d", np->nfile.fd);
  1081. fputs(s, fp);
  1082. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1083. fprintf(fp, "%d", np->ndup.dupfd);
  1084. } else {
  1085. sharg(np->nfile.fname, fp);
  1086. }
  1087. first = 0;
  1088. }
  1089. }
  1090. static void
  1091. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1092. {
  1093. struct nodelist *lp;
  1094. const char *s;
  1095. if (n == NULL)
  1096. return;
  1097. indent(ind, pfx, fp);
  1098. if (n == NODE_EOF) {
  1099. fputs("<EOF>", fp);
  1100. return;
  1101. }
  1102. switch (n->type) {
  1103. case NSEMI:
  1104. s = "; ";
  1105. goto binop;
  1106. case NAND:
  1107. s = " && ";
  1108. goto binop;
  1109. case NOR:
  1110. s = " || ";
  1111. binop:
  1112. shtree(n->nbinary.ch1, ind, NULL, fp);
  1113. /* if (ind < 0) */
  1114. fputs(s, fp);
  1115. shtree(n->nbinary.ch2, ind, NULL, fp);
  1116. break;
  1117. case NCMD:
  1118. shcmd(n, fp);
  1119. if (ind >= 0)
  1120. putc('\n', fp);
  1121. break;
  1122. case NPIPE:
  1123. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1124. shtree(lp->n, 0, NULL, fp);
  1125. if (lp->next)
  1126. fputs(" | ", fp);
  1127. }
  1128. if (n->npipe.pipe_backgnd)
  1129. fputs(" &", fp);
  1130. if (ind >= 0)
  1131. putc('\n', fp);
  1132. break;
  1133. default:
  1134. fprintf(fp, "<node type %d>", n->type);
  1135. if (ind >= 0)
  1136. putc('\n', fp);
  1137. break;
  1138. }
  1139. }
  1140. static void
  1141. showtree(union node *n)
  1142. {
  1143. trace_puts("showtree called\n");
  1144. shtree(n, 1, NULL, stderr);
  1145. }
  1146. #endif /* DEBUG */
  1147. /* ============ Parser data */
  1148. /*
  1149. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1150. */
  1151. struct strlist {
  1152. struct strlist *next;
  1153. char *text;
  1154. };
  1155. struct alias;
  1156. struct strpush {
  1157. struct strpush *prev; /* preceding string on stack */
  1158. char *prev_string;
  1159. int prev_left_in_line;
  1160. #if ENABLE_ASH_ALIAS
  1161. struct alias *ap; /* if push was associated with an alias */
  1162. #endif
  1163. char *string; /* remember the string since it may change */
  1164. /* Remember last two characters for pungetc. */
  1165. int lastc[2];
  1166. /* Number of outstanding calls to pungetc. */
  1167. int unget;
  1168. };
  1169. /*
  1170. * The parsefile structure pointed to by the global variable parsefile
  1171. * contains information about the current file being read.
  1172. */
  1173. struct parsefile {
  1174. struct parsefile *prev; /* preceding file on stack */
  1175. int linno; /* current line */
  1176. int pf_fd; /* file descriptor (or -1 if string) */
  1177. int left_in_line; /* number of chars left in this line */
  1178. int left_in_buffer; /* number of chars left in this buffer past the line */
  1179. char *next_to_pgetc; /* next char in buffer */
  1180. char *buf; /* input buffer */
  1181. struct strpush *strpush; /* for pushing strings at this level */
  1182. struct strpush basestrpush; /* so pushing one is fast */
  1183. /* Remember last two characters for pungetc. */
  1184. int lastc[2];
  1185. /* Number of outstanding calls to pungetc. */
  1186. int unget;
  1187. };
  1188. static struct parsefile basepf; /* top level input file */
  1189. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1190. static char *commandname; /* currently executing command */
  1191. /* ============ Message printing */
  1192. static void
  1193. ash_vmsg(const char *msg, va_list ap)
  1194. {
  1195. fprintf(stderr, "%s: ", arg0);
  1196. if (commandname) {
  1197. if (strcmp(arg0, commandname))
  1198. fprintf(stderr, "%s: ", commandname);
  1199. if (!iflag || g_parsefile->pf_fd > 0)
  1200. fprintf(stderr, "line %d: ", errlinno);
  1201. }
  1202. vfprintf(stderr, msg, ap);
  1203. newline_and_flush(stderr);
  1204. }
  1205. /*
  1206. * Exverror is called to raise the error exception. If the second argument
  1207. * is not NULL then error prints an error message using printf style
  1208. * formatting. It then raises the error exception.
  1209. */
  1210. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1211. static void
  1212. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1213. {
  1214. #if DEBUG
  1215. if (msg) {
  1216. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1217. TRACEV((msg, ap));
  1218. } else
  1219. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1220. if (msg)
  1221. #endif
  1222. ash_vmsg(msg, ap);
  1223. flush_stdout_stderr();
  1224. raise_exception(cond);
  1225. /* NOTREACHED */
  1226. }
  1227. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1228. static void
  1229. ash_msg_and_raise_error(const char *msg, ...)
  1230. {
  1231. va_list ap;
  1232. exitstatus = 2;
  1233. va_start(ap, msg);
  1234. ash_vmsg_and_raise(EXERROR, msg, ap);
  1235. /* NOTREACHED */
  1236. va_end(ap);
  1237. }
  1238. /*
  1239. * 'fmt' must be a string literal.
  1240. */
  1241. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1242. static void raise_error_syntax(const char *) NORETURN;
  1243. static void
  1244. raise_error_syntax(const char *msg)
  1245. {
  1246. errlinno = g_parsefile->linno;
  1247. ash_msg_and_raise_error("syntax error: %s", msg);
  1248. /* NOTREACHED */
  1249. }
  1250. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1251. static void
  1252. ash_msg_and_raise(int cond, const char *msg, ...)
  1253. {
  1254. va_list ap;
  1255. va_start(ap, msg);
  1256. ash_vmsg_and_raise(cond, msg, ap);
  1257. /* NOTREACHED */
  1258. va_end(ap);
  1259. }
  1260. /*
  1261. * error/warning routines for external builtins
  1262. */
  1263. static void
  1264. ash_msg(const char *fmt, ...)
  1265. {
  1266. va_list ap;
  1267. va_start(ap, fmt);
  1268. ash_vmsg(fmt, ap);
  1269. va_end(ap);
  1270. }
  1271. /*
  1272. * Return a string describing an error. The returned string may be a
  1273. * pointer to a static buffer that will be overwritten on the next call.
  1274. * Action describes the operation that got the error.
  1275. */
  1276. static const char *
  1277. errmsg(int e, const char *em)
  1278. {
  1279. if (e == ENOENT || e == ENOTDIR) {
  1280. return em;
  1281. }
  1282. return strerror(e);
  1283. }
  1284. /* ============ Memory allocation */
  1285. #if 0
  1286. /* I consider these wrappers nearly useless:
  1287. * ok, they return you to nearest exception handler, but
  1288. * how much memory do you leak in the process, making
  1289. * memory starvation worse?
  1290. */
  1291. static void *
  1292. ckrealloc(void * p, size_t nbytes)
  1293. {
  1294. p = realloc(p, nbytes);
  1295. if (!p)
  1296. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1297. return p;
  1298. }
  1299. static void *
  1300. ckmalloc(size_t nbytes)
  1301. {
  1302. return ckrealloc(NULL, nbytes);
  1303. }
  1304. static void *
  1305. ckzalloc(size_t nbytes)
  1306. {
  1307. return memset(ckmalloc(nbytes), 0, nbytes);
  1308. }
  1309. static char *
  1310. ckstrdup(const char *s)
  1311. {
  1312. char *p = strdup(s);
  1313. if (!p)
  1314. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1315. return p;
  1316. }
  1317. #else
  1318. /* Using bbox equivalents. They exit if out of memory */
  1319. # define ckrealloc xrealloc
  1320. # define ckmalloc xmalloc
  1321. # define ckzalloc xzalloc
  1322. # define ckstrdup xstrdup
  1323. #endif
  1324. /*
  1325. * It appears that grabstackstr() will barf with such alignments
  1326. * because stalloc() will return a string allocated in a new stackblock.
  1327. */
  1328. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1329. enum {
  1330. /* Most machines require the value returned from malloc to be aligned
  1331. * in some way. The following macro will get this right
  1332. * on many machines. */
  1333. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1334. /* Minimum size of a block */
  1335. MINSIZE = SHELL_ALIGN(504),
  1336. };
  1337. struct stack_block {
  1338. struct stack_block *prev;
  1339. char space[MINSIZE];
  1340. };
  1341. struct stackmark {
  1342. struct stack_block *stackp;
  1343. char *stacknxt;
  1344. size_t stacknleft;
  1345. };
  1346. struct globals_memstack {
  1347. struct stack_block *g_stackp; // = &stackbase;
  1348. char *g_stacknxt; // = stackbase.space;
  1349. char *sstrend; // = stackbase.space + MINSIZE;
  1350. size_t g_stacknleft; // = MINSIZE;
  1351. struct stack_block stackbase;
  1352. };
  1353. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1354. #define G_memstack (*ash_ptr_to_globals_memstack)
  1355. #define g_stackp (G_memstack.g_stackp )
  1356. #define g_stacknxt (G_memstack.g_stacknxt )
  1357. #define sstrend (G_memstack.sstrend )
  1358. #define g_stacknleft (G_memstack.g_stacknleft)
  1359. #define stackbase (G_memstack.stackbase )
  1360. #define INIT_G_memstack() do { \
  1361. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1362. barrier(); \
  1363. g_stackp = &stackbase; \
  1364. g_stacknxt = stackbase.space; \
  1365. g_stacknleft = MINSIZE; \
  1366. sstrend = stackbase.space + MINSIZE; \
  1367. } while (0)
  1368. #define stackblock() ((void *)g_stacknxt)
  1369. #define stackblocksize() g_stacknleft
  1370. /*
  1371. * Parse trees for commands are allocated in lifo order, so we use a stack
  1372. * to make this more efficient, and also to avoid all sorts of exception
  1373. * handling code to handle interrupts in the middle of a parse.
  1374. *
  1375. * The size 504 was chosen because the Ultrix malloc handles that size
  1376. * well.
  1377. */
  1378. static void *
  1379. stalloc(size_t nbytes)
  1380. {
  1381. char *p;
  1382. size_t aligned;
  1383. aligned = SHELL_ALIGN(nbytes);
  1384. if (aligned > g_stacknleft) {
  1385. size_t len;
  1386. size_t blocksize;
  1387. struct stack_block *sp;
  1388. blocksize = aligned;
  1389. if (blocksize < MINSIZE)
  1390. blocksize = MINSIZE;
  1391. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1392. if (len < blocksize)
  1393. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1394. INT_OFF;
  1395. sp = ckmalloc(len);
  1396. sp->prev = g_stackp;
  1397. g_stacknxt = sp->space;
  1398. g_stacknleft = blocksize;
  1399. sstrend = g_stacknxt + blocksize;
  1400. g_stackp = sp;
  1401. INT_ON;
  1402. }
  1403. p = g_stacknxt;
  1404. g_stacknxt += aligned;
  1405. g_stacknleft -= aligned;
  1406. return p;
  1407. }
  1408. static void *
  1409. stzalloc(size_t nbytes)
  1410. {
  1411. return memset(stalloc(nbytes), 0, nbytes);
  1412. }
  1413. static void
  1414. stunalloc(void *p)
  1415. {
  1416. #if DEBUG
  1417. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1418. write(STDERR_FILENO, "stunalloc\n", 10);
  1419. abort();
  1420. }
  1421. #endif
  1422. g_stacknleft += g_stacknxt - (char *)p;
  1423. g_stacknxt = p;
  1424. }
  1425. /*
  1426. * Like strdup but works with the ash stack.
  1427. */
  1428. static char *
  1429. sstrdup(const char *p)
  1430. {
  1431. size_t len = strlen(p) + 1;
  1432. return memcpy(stalloc(len), p, len);
  1433. }
  1434. static ALWAYS_INLINE void
  1435. grabstackblock(size_t len)
  1436. {
  1437. stalloc(len);
  1438. }
  1439. static void
  1440. pushstackmark(struct stackmark *mark, size_t len)
  1441. {
  1442. mark->stackp = g_stackp;
  1443. mark->stacknxt = g_stacknxt;
  1444. mark->stacknleft = g_stacknleft;
  1445. grabstackblock(len);
  1446. }
  1447. static void
  1448. setstackmark(struct stackmark *mark)
  1449. {
  1450. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1451. }
  1452. static void
  1453. popstackmark(struct stackmark *mark)
  1454. {
  1455. struct stack_block *sp;
  1456. if (!mark->stackp)
  1457. return;
  1458. INT_OFF;
  1459. while (g_stackp != mark->stackp) {
  1460. sp = g_stackp;
  1461. g_stackp = sp->prev;
  1462. free(sp);
  1463. }
  1464. g_stacknxt = mark->stacknxt;
  1465. g_stacknleft = mark->stacknleft;
  1466. sstrend = mark->stacknxt + mark->stacknleft;
  1467. INT_ON;
  1468. }
  1469. /*
  1470. * When the parser reads in a string, it wants to stick the string on the
  1471. * stack and only adjust the stack pointer when it knows how big the
  1472. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1473. * of space on top of the stack and stackblocklen returns the length of
  1474. * this block. Growstackblock will grow this space by at least one byte,
  1475. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1476. * part of the block that has been used.
  1477. */
  1478. static void
  1479. growstackblock(void)
  1480. {
  1481. size_t newlen;
  1482. newlen = g_stacknleft * 2;
  1483. if (newlen < g_stacknleft)
  1484. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1485. if (newlen < 128)
  1486. newlen += 128;
  1487. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1488. struct stack_block *sp;
  1489. struct stack_block *prevstackp;
  1490. size_t grosslen;
  1491. INT_OFF;
  1492. sp = g_stackp;
  1493. prevstackp = sp->prev;
  1494. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1495. sp = ckrealloc(sp, grosslen);
  1496. sp->prev = prevstackp;
  1497. g_stackp = sp;
  1498. g_stacknxt = sp->space;
  1499. g_stacknleft = newlen;
  1500. sstrend = sp->space + newlen;
  1501. INT_ON;
  1502. } else {
  1503. char *oldspace = g_stacknxt;
  1504. size_t oldlen = g_stacknleft;
  1505. char *p = stalloc(newlen);
  1506. /* free the space we just allocated */
  1507. g_stacknxt = memcpy(p, oldspace, oldlen);
  1508. g_stacknleft += newlen;
  1509. }
  1510. }
  1511. /*
  1512. * The following routines are somewhat easier to use than the above.
  1513. * The user declares a variable of type STACKSTR, which may be declared
  1514. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1515. * the user uses the macro STPUTC to add characters to the string. In
  1516. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1517. * grown as necessary. When the user is done, she can just leave the
  1518. * string there and refer to it using stackblock(). Or she can allocate
  1519. * the space for it using grabstackstr(). If it is necessary to allow
  1520. * someone else to use the stack temporarily and then continue to grow
  1521. * the string, the user should use grabstack to allocate the space, and
  1522. * then call ungrabstr(p) to return to the previous mode of operation.
  1523. *
  1524. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1525. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1526. * is space for at least one character.
  1527. */
  1528. static void *
  1529. growstackstr(void)
  1530. {
  1531. size_t len = stackblocksize();
  1532. growstackblock();
  1533. return (char *)stackblock() + len;
  1534. }
  1535. /*
  1536. * Called from CHECKSTRSPACE.
  1537. */
  1538. static char *
  1539. makestrspace(size_t newlen, char *p)
  1540. {
  1541. size_t len = p - g_stacknxt;
  1542. size_t size;
  1543. for (;;) {
  1544. size_t nleft;
  1545. size = stackblocksize();
  1546. nleft = size - len;
  1547. if (nleft >= newlen)
  1548. break;
  1549. growstackblock();
  1550. }
  1551. return (char *)stackblock() + len;
  1552. }
  1553. static char *
  1554. stack_nputstr(const char *s, size_t n, char *p)
  1555. {
  1556. p = makestrspace(n, p);
  1557. p = (char *)mempcpy(p, s, n);
  1558. return p;
  1559. }
  1560. static char *
  1561. stack_putstr(const char *s, char *p)
  1562. {
  1563. return stack_nputstr(s, strlen(s), p);
  1564. }
  1565. static char *
  1566. _STPUTC(int c, char *p)
  1567. {
  1568. if (p == sstrend)
  1569. p = growstackstr();
  1570. *p++ = c;
  1571. return p;
  1572. }
  1573. #define STARTSTACKSTR(p) ((p) = stackblock())
  1574. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1575. #define CHECKSTRSPACE(n, p) do { \
  1576. char *q = (p); \
  1577. size_t l = (n); \
  1578. size_t m = sstrend - q; \
  1579. if (l > m) \
  1580. (p) = makestrspace(l, q); \
  1581. } while (0)
  1582. #define USTPUTC(c, p) (*(p)++ = (c))
  1583. #define STACKSTRNUL(p) do { \
  1584. if ((p) == sstrend) \
  1585. (p) = growstackstr(); \
  1586. *(p) = '\0'; \
  1587. } while (0)
  1588. #define STUNPUTC(p) (--(p))
  1589. #define STTOPC(p) ((p)[-1])
  1590. #define STADJUST(amount, p) ((p) += (amount))
  1591. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1592. #define ungrabstackstr(s, p) stunalloc(s)
  1593. #define stackstrend() ((void *)sstrend)
  1594. /* ============ String helpers */
  1595. /*
  1596. * prefix -- see if pfx is a prefix of string.
  1597. */
  1598. static char *
  1599. prefix(const char *string, const char *pfx)
  1600. {
  1601. while (*pfx) {
  1602. if (*pfx++ != *string++)
  1603. return NULL;
  1604. }
  1605. return (char *) string;
  1606. }
  1607. /*
  1608. * Check for a valid number. This should be elsewhere.
  1609. */
  1610. static int
  1611. is_number(const char *p)
  1612. {
  1613. do {
  1614. if (!isdigit(*p))
  1615. return 0;
  1616. } while (*++p != '\0');
  1617. return 1;
  1618. }
  1619. /*
  1620. * Convert a string of digits to an integer, printing an error message on
  1621. * failure.
  1622. */
  1623. static int
  1624. number(const char *s)
  1625. {
  1626. if (!is_number(s))
  1627. ash_msg_and_raise_error(msg_illnum, s);
  1628. return atoi(s);
  1629. }
  1630. /*
  1631. * Produce a single quoted string suitable as input to the shell.
  1632. * The return string is allocated on the stack.
  1633. */
  1634. static char *
  1635. single_quote(const char *s)
  1636. {
  1637. char *p;
  1638. STARTSTACKSTR(p);
  1639. do {
  1640. char *q;
  1641. size_t len;
  1642. len = strchrnul(s, '\'') - s;
  1643. q = p = makestrspace(len + 3, p);
  1644. *q++ = '\'';
  1645. q = (char *)mempcpy(q, s, len);
  1646. *q++ = '\'';
  1647. s += len;
  1648. STADJUST(q - p, p);
  1649. if (*s != '\'')
  1650. break;
  1651. len = 0;
  1652. do len++; while (*++s == '\'');
  1653. q = p = makestrspace(len + 3, p);
  1654. *q++ = '"';
  1655. q = (char *)mempcpy(q, s - len, len);
  1656. *q++ = '"';
  1657. STADJUST(q - p, p);
  1658. } while (*s);
  1659. USTPUTC('\0', p);
  1660. return stackblock();
  1661. }
  1662. /*
  1663. * Produce a possibly single quoted string suitable as input to the shell.
  1664. * If quoting was done, the return string is allocated on the stack,
  1665. * otherwise a pointer to the original string is returned.
  1666. */
  1667. static const char *
  1668. maybe_single_quote(const char *s)
  1669. {
  1670. const char *p = s;
  1671. while (*p) {
  1672. /* Assuming ACSII */
  1673. /* quote ctrl_chars space !"#$%&'()* */
  1674. if (*p < '+')
  1675. goto need_quoting;
  1676. /* quote ;<=>? */
  1677. if (*p >= ';' && *p <= '?')
  1678. goto need_quoting;
  1679. /* quote `[\ */
  1680. if (*p == '`')
  1681. goto need_quoting;
  1682. if (*p == '[')
  1683. goto need_quoting;
  1684. if (*p == '\\')
  1685. goto need_quoting;
  1686. /* quote {|}~ DEL and high bytes */
  1687. if (*p > 'z')
  1688. goto need_quoting;
  1689. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1690. /* TODO: maybe avoid quoting % */
  1691. p++;
  1692. }
  1693. return s;
  1694. need_quoting:
  1695. return single_quote(s);
  1696. }
  1697. /* ============ nextopt */
  1698. static char **argptr; /* argument list for builtin commands */
  1699. static char *optionarg; /* set by nextopt (like getopt) */
  1700. static char *optptr; /* used by nextopt */
  1701. /*
  1702. * XXX - should get rid of. Have all builtins use getopt(3).
  1703. * The library getopt must have the BSD extension static variable
  1704. * "optreset", otherwise it can't be used within the shell safely.
  1705. *
  1706. * Standard option processing (a la getopt) for builtin routines.
  1707. * The only argument that is passed to nextopt is the option string;
  1708. * the other arguments are unnecessary. It returns the character,
  1709. * or '\0' on end of input.
  1710. */
  1711. static int
  1712. nextopt(const char *optstring)
  1713. {
  1714. char *p;
  1715. const char *q;
  1716. char c;
  1717. p = optptr;
  1718. if (p == NULL || *p == '\0') {
  1719. /* We ate entire "-param", take next one */
  1720. p = *argptr;
  1721. if (p == NULL)
  1722. return '\0';
  1723. if (*p != '-')
  1724. return '\0';
  1725. if (*++p == '\0') /* just "-" ? */
  1726. return '\0';
  1727. argptr++;
  1728. if (LONE_DASH(p)) /* "--" ? */
  1729. return '\0';
  1730. /* p => next "-param" */
  1731. }
  1732. /* p => some option char in the middle of a "-param" */
  1733. c = *p++;
  1734. for (q = optstring; *q != c;) {
  1735. if (*q == '\0')
  1736. ash_msg_and_raise_error("illegal option -%c", c);
  1737. if (*++q == ':')
  1738. q++;
  1739. }
  1740. if (*++q == ':') {
  1741. if (*p == '\0') {
  1742. p = *argptr++;
  1743. if (p == NULL)
  1744. ash_msg_and_raise_error("no arg for -%c option", c);
  1745. }
  1746. optionarg = p;
  1747. p = NULL;
  1748. }
  1749. optptr = p;
  1750. return c;
  1751. }
  1752. /* ============ Shell variables */
  1753. struct shparam {
  1754. int nparam; /* # of positional parameters (without $0) */
  1755. #if ENABLE_ASH_GETOPTS
  1756. int optind; /* next parameter to be processed by getopts */
  1757. int optoff; /* used by getopts */
  1758. #endif
  1759. unsigned char malloced; /* if parameter list dynamically allocated */
  1760. char **p; /* parameter list */
  1761. };
  1762. /*
  1763. * Free the list of positional parameters.
  1764. */
  1765. static void
  1766. freeparam(volatile struct shparam *param)
  1767. {
  1768. if (param->malloced) {
  1769. char **ap, **ap1;
  1770. ap = ap1 = param->p;
  1771. while (*ap)
  1772. free(*ap++);
  1773. free(ap1);
  1774. }
  1775. }
  1776. #if ENABLE_ASH_GETOPTS
  1777. static void FAST_FUNC getoptsreset(const char *value);
  1778. #endif
  1779. struct var {
  1780. struct var *next; /* next entry in hash list */
  1781. int flags; /* flags are defined above */
  1782. const char *var_text; /* name=value */
  1783. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1784. /* the variable gets set/unset */
  1785. };
  1786. struct localvar {
  1787. struct localvar *next; /* next local variable in list */
  1788. struct var *vp; /* the variable that was made local */
  1789. int flags; /* saved flags */
  1790. const char *text; /* saved text */
  1791. };
  1792. /* flags */
  1793. #define VEXPORT 0x01 /* variable is exported */
  1794. #define VREADONLY 0x02 /* variable cannot be modified */
  1795. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1796. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1797. #define VSTACK 0x10 /* text is allocated on the stack */
  1798. #define VUNSET 0x20 /* the variable is not set */
  1799. #define VNOFUNC 0x40 /* don't call the callback function */
  1800. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1801. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1802. #if ENABLE_ASH_RANDOM_SUPPORT
  1803. # define VDYNAMIC 0x200 /* dynamic variable */
  1804. #else
  1805. # define VDYNAMIC 0
  1806. #endif
  1807. /* Need to be before varinit_data[] */
  1808. #if ENABLE_LOCALE_SUPPORT
  1809. static void FAST_FUNC
  1810. change_lc_all(const char *value)
  1811. {
  1812. if (value && *value != '\0')
  1813. setlocale(LC_ALL, value);
  1814. }
  1815. static void FAST_FUNC
  1816. change_lc_ctype(const char *value)
  1817. {
  1818. if (value && *value != '\0')
  1819. setlocale(LC_CTYPE, value);
  1820. }
  1821. #endif
  1822. #if ENABLE_ASH_MAIL
  1823. static void chkmail(void);
  1824. static void changemail(const char *var_value) FAST_FUNC;
  1825. #else
  1826. # define chkmail() ((void)0)
  1827. #endif
  1828. static void changepath(const char *) FAST_FUNC;
  1829. #if ENABLE_ASH_RANDOM_SUPPORT
  1830. static void change_random(const char *) FAST_FUNC;
  1831. #endif
  1832. static const struct {
  1833. int flags;
  1834. const char *var_text;
  1835. void (*var_func)(const char *) FAST_FUNC;
  1836. } varinit_data[] = {
  1837. /*
  1838. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1839. * some environment strings may be constant.
  1840. */
  1841. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1842. #if ENABLE_ASH_MAIL
  1843. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1844. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1845. #endif
  1846. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1847. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1848. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1849. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1850. #if ENABLE_ASH_GETOPTS
  1851. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1852. #endif
  1853. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1854. #if ENABLE_ASH_RANDOM_SUPPORT
  1855. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1856. #endif
  1857. #if ENABLE_LOCALE_SUPPORT
  1858. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1859. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1860. #endif
  1861. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1862. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1863. #endif
  1864. };
  1865. struct redirtab;
  1866. struct globals_var {
  1867. struct shparam shellparam; /* $@ current positional parameters */
  1868. struct redirtab *redirlist;
  1869. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1870. struct var *vartab[VTABSIZE];
  1871. struct var varinit[ARRAY_SIZE(varinit_data)];
  1872. int lineno;
  1873. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1874. };
  1875. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1876. #define G_var (*ash_ptr_to_globals_var)
  1877. #define shellparam (G_var.shellparam )
  1878. //#define redirlist (G_var.redirlist )
  1879. #define preverrout_fd (G_var.preverrout_fd)
  1880. #define vartab (G_var.vartab )
  1881. #define varinit (G_var.varinit )
  1882. #define lineno (G_var.lineno )
  1883. #define linenovar (G_var.linenovar )
  1884. #define vifs varinit[0]
  1885. #if ENABLE_ASH_MAIL
  1886. # define vmail (&vifs)[1]
  1887. # define vmpath (&vmail)[1]
  1888. # define vpath (&vmpath)[1]
  1889. #else
  1890. # define vpath (&vifs)[1]
  1891. #endif
  1892. #define vps1 (&vpath)[1]
  1893. #define vps2 (&vps1)[1]
  1894. #define vps4 (&vps2)[1]
  1895. #if ENABLE_ASH_GETOPTS
  1896. # define voptind (&vps4)[1]
  1897. # define vlineno (&voptind)[1]
  1898. # if ENABLE_ASH_RANDOM_SUPPORT
  1899. # define vrandom (&vlineno)[1]
  1900. # endif
  1901. #else
  1902. # define vlineno (&vps4)[1]
  1903. # if ENABLE_ASH_RANDOM_SUPPORT
  1904. # define vrandom (&vlineno)[1]
  1905. # endif
  1906. #endif
  1907. #define INIT_G_var() do { \
  1908. unsigned i; \
  1909. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1910. barrier(); \
  1911. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1912. varinit[i].flags = varinit_data[i].flags; \
  1913. varinit[i].var_text = varinit_data[i].var_text; \
  1914. varinit[i].var_func = varinit_data[i].var_func; \
  1915. } \
  1916. strcpy(linenovar, "LINENO="); \
  1917. vlineno.var_text = linenovar; \
  1918. } while (0)
  1919. /*
  1920. * The following macros access the values of the above variables.
  1921. * They have to skip over the name. They return the null string
  1922. * for unset variables.
  1923. */
  1924. #define ifsval() (vifs.var_text + 4)
  1925. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1926. #if ENABLE_ASH_MAIL
  1927. # define mailval() (vmail.var_text + 5)
  1928. # define mpathval() (vmpath.var_text + 9)
  1929. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1930. #endif
  1931. #define pathval() (vpath.var_text + 5)
  1932. #define ps1val() (vps1.var_text + 4)
  1933. #define ps2val() (vps2.var_text + 4)
  1934. #define ps4val() (vps4.var_text + 4)
  1935. #if ENABLE_ASH_GETOPTS
  1936. # define optindval() (voptind.var_text + 7)
  1937. #endif
  1938. #if ENABLE_ASH_GETOPTS
  1939. static void FAST_FUNC
  1940. getoptsreset(const char *value)
  1941. {
  1942. shellparam.optind = 1;
  1943. if (is_number(value))
  1944. shellparam.optind = number(value) ?: 1;
  1945. shellparam.optoff = -1;
  1946. }
  1947. #endif
  1948. /*
  1949. * Compares two strings up to the first = or '\0'. The first
  1950. * string must be terminated by '='; the second may be terminated by
  1951. * either '=' or '\0'.
  1952. */
  1953. static int
  1954. varcmp(const char *p, const char *q)
  1955. {
  1956. int c, d;
  1957. while ((c = *p) == (d = *q)) {
  1958. if (c == '\0' || c == '=')
  1959. goto out;
  1960. p++;
  1961. q++;
  1962. }
  1963. if (c == '=')
  1964. c = '\0';
  1965. if (d == '=')
  1966. d = '\0';
  1967. out:
  1968. return c - d;
  1969. }
  1970. /*
  1971. * Find the appropriate entry in the hash table from the name.
  1972. */
  1973. static struct var **
  1974. hashvar(const char *p)
  1975. {
  1976. unsigned hashval;
  1977. hashval = ((unsigned char) *p) << 4;
  1978. while (*p && *p != '=')
  1979. hashval += (unsigned char) *p++;
  1980. return &vartab[hashval % VTABSIZE];
  1981. }
  1982. static int
  1983. vpcmp(const void *a, const void *b)
  1984. {
  1985. return varcmp(*(const char **)a, *(const char **)b);
  1986. }
  1987. /*
  1988. * This routine initializes the builtin variables.
  1989. */
  1990. static void
  1991. initvar(void)
  1992. {
  1993. struct var *vp;
  1994. struct var *end;
  1995. struct var **vpp;
  1996. /*
  1997. * PS1 depends on uid
  1998. */
  1999. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2000. vps1.var_text = "PS1=\\w \\$ ";
  2001. #else
  2002. if (!geteuid())
  2003. vps1.var_text = "PS1=# ";
  2004. #endif
  2005. vp = varinit;
  2006. end = vp + ARRAY_SIZE(varinit);
  2007. do {
  2008. vpp = hashvar(vp->var_text);
  2009. vp->next = *vpp;
  2010. *vpp = vp;
  2011. } while (++vp < end);
  2012. }
  2013. static struct var **
  2014. findvar(struct var **vpp, const char *name)
  2015. {
  2016. for (; *vpp; vpp = &(*vpp)->next) {
  2017. if (varcmp((*vpp)->var_text, name) == 0) {
  2018. break;
  2019. }
  2020. }
  2021. return vpp;
  2022. }
  2023. /*
  2024. * Find the value of a variable. Returns NULL if not set.
  2025. */
  2026. static const char* FAST_FUNC
  2027. lookupvar(const char *name)
  2028. {
  2029. struct var *v;
  2030. v = *findvar(hashvar(name), name);
  2031. if (v) {
  2032. #if ENABLE_ASH_RANDOM_SUPPORT
  2033. /*
  2034. * Dynamic variables are implemented roughly the same way they are
  2035. * in bash. Namely, they're "special" so long as they aren't unset.
  2036. * As soon as they're unset, they're no longer dynamic, and dynamic
  2037. * lookup will no longer happen at that point. -- PFM.
  2038. */
  2039. if (v->flags & VDYNAMIC)
  2040. v->var_func(NULL);
  2041. #endif
  2042. if (!(v->flags & VUNSET)) {
  2043. if (v == &vlineno && v->var_text == linenovar) {
  2044. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2045. }
  2046. return var_end(v->var_text);
  2047. }
  2048. }
  2049. return NULL;
  2050. }
  2051. #if ENABLE_UNICODE_SUPPORT
  2052. static void
  2053. reinit_unicode_for_ash(void)
  2054. {
  2055. /* Unicode support should be activated even if LANG is set
  2056. * _during_ shell execution, not only if it was set when
  2057. * shell was started. Therefore, re-check LANG every time:
  2058. */
  2059. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2060. || ENABLE_UNICODE_USING_LOCALE
  2061. ) {
  2062. const char *s = lookupvar("LC_ALL");
  2063. if (!s) s = lookupvar("LC_CTYPE");
  2064. if (!s) s = lookupvar("LANG");
  2065. reinit_unicode(s);
  2066. }
  2067. }
  2068. #else
  2069. # define reinit_unicode_for_ash() ((void)0)
  2070. #endif
  2071. /*
  2072. * Search the environment of a builtin command.
  2073. */
  2074. static ALWAYS_INLINE const char *
  2075. bltinlookup(const char *name)
  2076. {
  2077. return lookupvar(name);
  2078. }
  2079. /*
  2080. * Same as setvar except that the variable and value are passed in
  2081. * the first argument as name=value. Since the first argument will
  2082. * be actually stored in the table, it should not be a string that
  2083. * will go away.
  2084. * Called with interrupts off.
  2085. */
  2086. static struct var *
  2087. setvareq(char *s, int flags)
  2088. {
  2089. struct var *vp, **vpp;
  2090. vpp = hashvar(s);
  2091. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2092. vpp = findvar(vpp, s);
  2093. vp = *vpp;
  2094. if (vp) {
  2095. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2096. const char *n;
  2097. if (flags & VNOSAVE)
  2098. free(s);
  2099. n = vp->var_text;
  2100. exitstatus = 1;
  2101. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2102. }
  2103. if (flags & VNOSET)
  2104. goto out;
  2105. if (vp->var_func && !(flags & VNOFUNC))
  2106. vp->var_func(var_end(s));
  2107. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2108. free((char*)vp->var_text);
  2109. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2110. *vpp = vp->next;
  2111. free(vp);
  2112. out_free:
  2113. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2114. free(s);
  2115. goto out;
  2116. }
  2117. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2118. } else {
  2119. /* variable s is not found */
  2120. if (flags & VNOSET)
  2121. goto out;
  2122. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2123. goto out_free;
  2124. vp = ckzalloc(sizeof(*vp));
  2125. vp->next = *vpp;
  2126. /*vp->func = NULL; - ckzalloc did it */
  2127. *vpp = vp;
  2128. }
  2129. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2130. s = ckstrdup(s);
  2131. vp->var_text = s;
  2132. vp->flags = flags;
  2133. out:
  2134. return vp;
  2135. }
  2136. /*
  2137. * Set the value of a variable. The flags argument is ored with the
  2138. * flags of the variable. If val is NULL, the variable is unset.
  2139. */
  2140. static struct var *
  2141. setvar(const char *name, const char *val, int flags)
  2142. {
  2143. const char *q;
  2144. char *p;
  2145. char *nameeq;
  2146. size_t namelen;
  2147. size_t vallen;
  2148. struct var *vp;
  2149. q = endofname(name);
  2150. p = strchrnul(q, '=');
  2151. namelen = p - name;
  2152. if (!namelen || p != q)
  2153. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2154. vallen = 0;
  2155. if (val == NULL) {
  2156. flags |= VUNSET;
  2157. } else {
  2158. vallen = strlen(val);
  2159. }
  2160. INT_OFF;
  2161. nameeq = ckzalloc(namelen + vallen + 2);
  2162. p = mempcpy(nameeq, name, namelen);
  2163. if (val) {
  2164. *p++ = '=';
  2165. memcpy(p, val, vallen);
  2166. }
  2167. vp = setvareq(nameeq, flags | VNOSAVE);
  2168. INT_ON;
  2169. return vp;
  2170. }
  2171. static void FAST_FUNC
  2172. setvar0(const char *name, const char *val)
  2173. {
  2174. setvar(name, val, 0);
  2175. }
  2176. /*
  2177. * Unset the specified variable.
  2178. */
  2179. static void
  2180. unsetvar(const char *s)
  2181. {
  2182. setvar(s, NULL, 0);
  2183. }
  2184. /*
  2185. * Process a linked list of variable assignments.
  2186. */
  2187. static void
  2188. listsetvar(struct strlist *list_set_var, int flags)
  2189. {
  2190. struct strlist *lp = list_set_var;
  2191. if (!lp)
  2192. return;
  2193. INT_OFF;
  2194. do {
  2195. setvareq(lp->text, flags);
  2196. lp = lp->next;
  2197. } while (lp);
  2198. INT_ON;
  2199. }
  2200. /*
  2201. * Generate a list of variables satisfying the given conditions.
  2202. */
  2203. #if !ENABLE_FEATURE_SH_NOFORK
  2204. # define listvars(on, off, lp, end) listvars(on, off, end)
  2205. #endif
  2206. static char **
  2207. listvars(int on, int off, struct strlist *lp, char ***end)
  2208. {
  2209. struct var **vpp;
  2210. struct var *vp;
  2211. char **ep;
  2212. int mask;
  2213. STARTSTACKSTR(ep);
  2214. vpp = vartab;
  2215. mask = on | off;
  2216. do {
  2217. for (vp = *vpp; vp; vp = vp->next) {
  2218. if ((vp->flags & mask) == on) {
  2219. #if ENABLE_FEATURE_SH_NOFORK
  2220. /* If variable with the same name is both
  2221. * exported and temporarily set for a command:
  2222. * export ZVAR=5
  2223. * ZVAR=6 printenv
  2224. * then "ZVAR=6" will be both in vartab and
  2225. * lp lists. Do not pass it twice to printenv.
  2226. */
  2227. struct strlist *lp1 = lp;
  2228. while (lp1) {
  2229. if (strcmp(lp1->text, vp->var_text) == 0)
  2230. goto skip;
  2231. lp1 = lp1->next;
  2232. }
  2233. #endif
  2234. if (ep == stackstrend())
  2235. ep = growstackstr();
  2236. *ep++ = (char*)vp->var_text;
  2237. #if ENABLE_FEATURE_SH_NOFORK
  2238. skip: ;
  2239. #endif
  2240. }
  2241. }
  2242. } while (++vpp < vartab + VTABSIZE);
  2243. #if ENABLE_FEATURE_SH_NOFORK
  2244. while (lp) {
  2245. if (ep == stackstrend())
  2246. ep = growstackstr();
  2247. *ep++ = lp->text;
  2248. lp = lp->next;
  2249. }
  2250. #endif
  2251. if (ep == stackstrend())
  2252. ep = growstackstr();
  2253. if (end)
  2254. *end = ep;
  2255. *ep++ = NULL;
  2256. return grabstackstr(ep);
  2257. }
  2258. /* ============ Path search helper
  2259. *
  2260. * The variable path (passed by reference) should be set to the start
  2261. * of the path before the first call; path_advance will update
  2262. * this value as it proceeds. Successive calls to path_advance will return
  2263. * the possible path expansions in sequence. If an option (indicated by
  2264. * a percent sign) appears in the path entry then the global variable
  2265. * pathopt will be set to point to it; otherwise pathopt will be set to
  2266. * NULL.
  2267. */
  2268. static const char *pathopt; /* set by path_advance */
  2269. static char *
  2270. path_advance(const char **path, const char *name)
  2271. {
  2272. const char *p;
  2273. char *q;
  2274. const char *start;
  2275. size_t len;
  2276. if (*path == NULL)
  2277. return NULL;
  2278. start = *path;
  2279. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2280. continue;
  2281. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2282. while (stackblocksize() < len)
  2283. growstackblock();
  2284. q = stackblock();
  2285. if (p != start) {
  2286. q = mempcpy(q, start, p - start);
  2287. *q++ = '/';
  2288. }
  2289. strcpy(q, name);
  2290. pathopt = NULL;
  2291. if (*p == '%') {
  2292. pathopt = ++p;
  2293. while (*p && *p != ':')
  2294. p++;
  2295. }
  2296. if (*p == ':')
  2297. *path = p + 1;
  2298. else
  2299. *path = NULL;
  2300. return stalloc(len);
  2301. }
  2302. /* ============ Prompt */
  2303. static smallint doprompt; /* if set, prompt the user */
  2304. static smallint needprompt; /* true if interactive and at start of line */
  2305. #if ENABLE_FEATURE_EDITING
  2306. static line_input_t *line_input_state;
  2307. static const char *cmdedit_prompt;
  2308. static void
  2309. putprompt(const char *s)
  2310. {
  2311. if (ENABLE_ASH_EXPAND_PRMT) {
  2312. free((char*)cmdedit_prompt);
  2313. cmdedit_prompt = ckstrdup(s);
  2314. return;
  2315. }
  2316. cmdedit_prompt = s;
  2317. }
  2318. #else
  2319. static void
  2320. putprompt(const char *s)
  2321. {
  2322. out2str(s);
  2323. }
  2324. #endif
  2325. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2326. static const char *expandstr(const char *ps, int syntax_type);
  2327. /* Values for syntax param */
  2328. #define BASESYNTAX 0 /* not in quotes */
  2329. #define DQSYNTAX 1 /* in double quotes */
  2330. #define SQSYNTAX 2 /* in single quotes */
  2331. #define ARISYNTAX 3 /* in arithmetic */
  2332. #if ENABLE_ASH_EXPAND_PRMT
  2333. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2334. #endif
  2335. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2336. /*
  2337. * called by editline -- any expansions to the prompt should be added here.
  2338. */
  2339. static void
  2340. setprompt_if(smallint do_set, int whichprompt)
  2341. {
  2342. const char *prompt;
  2343. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2344. if (!do_set)
  2345. return;
  2346. needprompt = 0;
  2347. switch (whichprompt) {
  2348. case 1:
  2349. prompt = ps1val();
  2350. break;
  2351. case 2:
  2352. prompt = ps2val();
  2353. break;
  2354. default: /* 0 */
  2355. prompt = nullstr;
  2356. }
  2357. #if ENABLE_ASH_EXPAND_PRMT
  2358. pushstackmark(&smark, stackblocksize());
  2359. putprompt(expandstr(prompt, PSSYNTAX));
  2360. popstackmark(&smark);
  2361. #else
  2362. putprompt(prompt);
  2363. #endif
  2364. }
  2365. /* ============ The cd and pwd commands */
  2366. #define CD_PHYSICAL 1
  2367. #define CD_PRINT 2
  2368. static int
  2369. cdopt(void)
  2370. {
  2371. int flags = 0;
  2372. int i, j;
  2373. j = 'L';
  2374. while ((i = nextopt("LP")) != '\0') {
  2375. if (i != j) {
  2376. flags ^= CD_PHYSICAL;
  2377. j = i;
  2378. }
  2379. }
  2380. return flags;
  2381. }
  2382. /*
  2383. * Update curdir (the name of the current directory) in response to a
  2384. * cd command.
  2385. */
  2386. static const char *
  2387. updatepwd(const char *dir)
  2388. {
  2389. char *new;
  2390. char *p;
  2391. char *cdcomppath;
  2392. const char *lim;
  2393. cdcomppath = sstrdup(dir);
  2394. STARTSTACKSTR(new);
  2395. if (*dir != '/') {
  2396. if (curdir == nullstr)
  2397. return 0;
  2398. new = stack_putstr(curdir, new);
  2399. }
  2400. new = makestrspace(strlen(dir) + 2, new);
  2401. lim = (char *)stackblock() + 1;
  2402. if (*dir != '/') {
  2403. if (new[-1] != '/')
  2404. USTPUTC('/', new);
  2405. if (new > lim && *lim == '/')
  2406. lim++;
  2407. } else {
  2408. USTPUTC('/', new);
  2409. cdcomppath++;
  2410. if (dir[1] == '/' && dir[2] != '/') {
  2411. USTPUTC('/', new);
  2412. cdcomppath++;
  2413. lim++;
  2414. }
  2415. }
  2416. p = strtok(cdcomppath, "/");
  2417. while (p) {
  2418. switch (*p) {
  2419. case '.':
  2420. if (p[1] == '.' && p[2] == '\0') {
  2421. while (new > lim) {
  2422. STUNPUTC(new);
  2423. if (new[-1] == '/')
  2424. break;
  2425. }
  2426. break;
  2427. }
  2428. if (p[1] == '\0')
  2429. break;
  2430. /* fall through */
  2431. default:
  2432. new = stack_putstr(p, new);
  2433. USTPUTC('/', new);
  2434. }
  2435. p = strtok(NULL, "/");
  2436. }
  2437. if (new > lim)
  2438. STUNPUTC(new);
  2439. *new = 0;
  2440. return stackblock();
  2441. }
  2442. /*
  2443. * Find out what the current directory is. If we already know the current
  2444. * directory, this routine returns immediately.
  2445. */
  2446. static char *
  2447. getpwd(void)
  2448. {
  2449. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2450. return dir ? dir : nullstr;
  2451. }
  2452. static void
  2453. setpwd(const char *val, int setold)
  2454. {
  2455. char *oldcur, *dir;
  2456. oldcur = dir = curdir;
  2457. if (setold) {
  2458. setvar("OLDPWD", oldcur, VEXPORT);
  2459. }
  2460. INT_OFF;
  2461. if (physdir != nullstr) {
  2462. if (physdir != oldcur)
  2463. free(physdir);
  2464. physdir = nullstr;
  2465. }
  2466. if (oldcur == val || !val) {
  2467. char *s = getpwd();
  2468. physdir = s;
  2469. if (!val)
  2470. dir = s;
  2471. } else
  2472. dir = ckstrdup(val);
  2473. if (oldcur != dir && oldcur != nullstr) {
  2474. free(oldcur);
  2475. }
  2476. curdir = dir;
  2477. INT_ON;
  2478. setvar("PWD", dir, VEXPORT);
  2479. }
  2480. static void hashcd(void);
  2481. /*
  2482. * Actually do the chdir. We also call hashcd to let other routines
  2483. * know that the current directory has changed.
  2484. */
  2485. static int
  2486. docd(const char *dest, int flags)
  2487. {
  2488. const char *dir = NULL;
  2489. int err;
  2490. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2491. INT_OFF;
  2492. if (!(flags & CD_PHYSICAL)) {
  2493. dir = updatepwd(dest);
  2494. if (dir)
  2495. dest = dir;
  2496. }
  2497. err = chdir(dest);
  2498. if (err)
  2499. goto out;
  2500. setpwd(dir, 1);
  2501. hashcd();
  2502. out:
  2503. INT_ON;
  2504. return err;
  2505. }
  2506. static int FAST_FUNC
  2507. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2508. {
  2509. const char *dest;
  2510. const char *path;
  2511. const char *p;
  2512. char c;
  2513. struct stat statb;
  2514. int flags;
  2515. flags = cdopt();
  2516. dest = *argptr;
  2517. if (!dest)
  2518. dest = bltinlookup("HOME");
  2519. else if (LONE_DASH(dest)) {
  2520. dest = bltinlookup("OLDPWD");
  2521. flags |= CD_PRINT;
  2522. }
  2523. if (!dest)
  2524. dest = nullstr;
  2525. if (*dest == '/')
  2526. goto step6;
  2527. if (*dest == '.') {
  2528. c = dest[1];
  2529. dotdot:
  2530. switch (c) {
  2531. case '\0':
  2532. case '/':
  2533. goto step6;
  2534. case '.':
  2535. c = dest[2];
  2536. if (c != '.')
  2537. goto dotdot;
  2538. }
  2539. }
  2540. if (!*dest)
  2541. dest = ".";
  2542. path = bltinlookup("CDPATH");
  2543. while (path) {
  2544. c = *path;
  2545. p = path_advance(&path, dest);
  2546. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2547. if (c && c != ':')
  2548. flags |= CD_PRINT;
  2549. docd:
  2550. if (!docd(p, flags))
  2551. goto out;
  2552. goto err;
  2553. }
  2554. }
  2555. step6:
  2556. p = dest;
  2557. goto docd;
  2558. err:
  2559. ash_msg_and_raise_perror("can't cd to %s", dest);
  2560. /* NOTREACHED */
  2561. out:
  2562. if (flags & CD_PRINT)
  2563. out1fmt("%s\n", curdir);
  2564. return 0;
  2565. }
  2566. static int FAST_FUNC
  2567. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2568. {
  2569. int flags;
  2570. const char *dir = curdir;
  2571. flags = cdopt();
  2572. if (flags) {
  2573. if (physdir == nullstr)
  2574. setpwd(dir, 0);
  2575. dir = physdir;
  2576. }
  2577. out1fmt("%s\n", dir);
  2578. return 0;
  2579. }
  2580. /* ============ ... */
  2581. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2582. /* Syntax classes */
  2583. #define CWORD 0 /* character is nothing special */
  2584. #define CNL 1 /* newline character */
  2585. #define CBACK 2 /* a backslash character */
  2586. #define CSQUOTE 3 /* single quote */
  2587. #define CDQUOTE 4 /* double quote */
  2588. #define CENDQUOTE 5 /* a terminating quote */
  2589. #define CBQUOTE 6 /* backwards single quote */
  2590. #define CVAR 7 /* a dollar sign */
  2591. #define CENDVAR 8 /* a '}' character */
  2592. #define CLP 9 /* a left paren in arithmetic */
  2593. #define CRP 10 /* a right paren in arithmetic */
  2594. #define CENDFILE 11 /* end of file */
  2595. #define CCTL 12 /* like CWORD, except it must be escaped */
  2596. #define CSPCL 13 /* these terminate a word */
  2597. #define CIGN 14 /* character should be ignored */
  2598. #define PEOF 256
  2599. #if ENABLE_ASH_ALIAS
  2600. # define PEOA 257
  2601. #endif
  2602. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2603. #if ENABLE_FEATURE_SH_MATH
  2604. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2605. #else
  2606. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2607. #endif
  2608. static const uint16_t S_I_T[] ALIGN2 = {
  2609. #if ENABLE_ASH_ALIAS
  2610. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2611. #endif
  2612. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2613. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2614. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2615. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2616. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2617. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2618. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2619. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2620. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2621. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2622. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2623. #if !USE_SIT_FUNCTION
  2624. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2625. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2626. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2627. #endif
  2628. #undef SIT_ITEM
  2629. };
  2630. /* Constants below must match table above */
  2631. enum {
  2632. #if ENABLE_ASH_ALIAS
  2633. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2634. #endif
  2635. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2636. CNL_CNL_CNL_CNL , /* 2 */
  2637. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2638. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2639. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2640. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2641. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2642. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2643. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2644. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2645. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2646. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2647. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2648. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2649. };
  2650. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2651. * caller must ensure proper cast on it if c is *char_ptr!
  2652. */
  2653. #if USE_SIT_FUNCTION
  2654. static int
  2655. SIT(int c, int syntax)
  2656. {
  2657. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2658. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2659. /*
  2660. * This causes '/' to be prepended with CTLESC in dquoted string,
  2661. * making "./file"* treated incorrectly because we feed
  2662. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2663. * The "homegrown" glob implementation is okay with that,
  2664. * but glibc one isn't. With '/' always treated as CWORD,
  2665. * both work fine.
  2666. */
  2667. # if ENABLE_ASH_ALIAS
  2668. static const uint8_t syntax_index_table[] ALIGN1 = {
  2669. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2670. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2671. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2672. 11, 3 /* "}~" */
  2673. };
  2674. # else
  2675. static const uint8_t syntax_index_table[] ALIGN1 = {
  2676. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2677. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2678. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2679. 10, 2 /* "}~" */
  2680. };
  2681. # endif
  2682. const char *s;
  2683. int indx;
  2684. if (c == PEOF)
  2685. return CENDFILE;
  2686. # if ENABLE_ASH_ALIAS
  2687. if (c == PEOA)
  2688. indx = 0;
  2689. else
  2690. # endif
  2691. {
  2692. /* Cast is purely for paranoia here,
  2693. * just in case someone passed signed char to us */
  2694. if ((unsigned char)c >= CTL_FIRST
  2695. && (unsigned char)c <= CTL_LAST
  2696. ) {
  2697. return CCTL;
  2698. }
  2699. s = strchrnul(spec_symbls, c);
  2700. if (*s == '\0')
  2701. return CWORD;
  2702. indx = syntax_index_table[s - spec_symbls];
  2703. }
  2704. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2705. }
  2706. #else /* !USE_SIT_FUNCTION */
  2707. static const uint8_t syntax_index_table[] ALIGN1 = {
  2708. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2709. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2710. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2711. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2712. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2713. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2714. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2715. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2716. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2717. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2718. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2719. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2720. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2721. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2722. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2723. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2724. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2725. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2726. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2727. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2728. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2729. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2730. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2731. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2732. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2733. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2734. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2735. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2736. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2737. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2738. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2739. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2740. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2741. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2742. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2743. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2744. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2745. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2746. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2747. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2748. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2749. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2750. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2751. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2752. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2753. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2755. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2756. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2757. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2758. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2759. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2760. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2761. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2762. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2763. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2764. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2765. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2766. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2767. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2768. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2769. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2770. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2771. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2772. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2773. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2774. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2781. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2802. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2803. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2804. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2807. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2831. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2832. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2833. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2835. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2836. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2837. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2838. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2839. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2840. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2841. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2842. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2843. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2844. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2845. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2846. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2847. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2897. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2899. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2902. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2903. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2904. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2905. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2906. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2922. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2923. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2924. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2925. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2926. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2927. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2928. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2929. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2930. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2931. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2932. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2933. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2934. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2935. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2936. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2937. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2967. # if ENABLE_ASH_ALIAS
  2968. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2969. # endif
  2970. };
  2971. #if 1
  2972. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2973. #else /* debug version, caught one signed char bug */
  2974. # define SIT(c, syntax) \
  2975. ({ \
  2976. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  2977. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2978. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  2979. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2980. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  2981. })
  2982. #endif
  2983. #endif /* !USE_SIT_FUNCTION */
  2984. /* ============ Alias handling */
  2985. #if ENABLE_ASH_ALIAS
  2986. #define ALIASINUSE 1
  2987. #define ALIASDEAD 2
  2988. struct alias {
  2989. struct alias *next;
  2990. char *name;
  2991. char *val;
  2992. int flag;
  2993. };
  2994. static struct alias **atab; // [ATABSIZE];
  2995. #define INIT_G_alias() do { \
  2996. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2997. } while (0)
  2998. static struct alias **
  2999. __lookupalias(const char *name)
  3000. {
  3001. unsigned int hashval;
  3002. struct alias **app;
  3003. const char *p;
  3004. unsigned int ch;
  3005. p = name;
  3006. ch = (unsigned char)*p;
  3007. hashval = ch << 4;
  3008. while (ch) {
  3009. hashval += ch;
  3010. ch = (unsigned char)*++p;
  3011. }
  3012. app = &atab[hashval % ATABSIZE];
  3013. for (; *app; app = &(*app)->next) {
  3014. if (strcmp(name, (*app)->name) == 0) {
  3015. break;
  3016. }
  3017. }
  3018. return app;
  3019. }
  3020. static struct alias *
  3021. lookupalias(const char *name, int check)
  3022. {
  3023. struct alias *ap = *__lookupalias(name);
  3024. if (check && ap && (ap->flag & ALIASINUSE))
  3025. return NULL;
  3026. return ap;
  3027. }
  3028. static struct alias *
  3029. freealias(struct alias *ap)
  3030. {
  3031. struct alias *next;
  3032. if (ap->flag & ALIASINUSE) {
  3033. ap->flag |= ALIASDEAD;
  3034. return ap;
  3035. }
  3036. next = ap->next;
  3037. free(ap->name);
  3038. free(ap->val);
  3039. free(ap);
  3040. return next;
  3041. }
  3042. static void
  3043. setalias(const char *name, const char *val)
  3044. {
  3045. struct alias *ap, **app;
  3046. app = __lookupalias(name);
  3047. ap = *app;
  3048. INT_OFF;
  3049. if (ap) {
  3050. if (!(ap->flag & ALIASINUSE)) {
  3051. free(ap->val);
  3052. }
  3053. ap->val = ckstrdup(val);
  3054. ap->flag &= ~ALIASDEAD;
  3055. } else {
  3056. /* not found */
  3057. ap = ckzalloc(sizeof(struct alias));
  3058. ap->name = ckstrdup(name);
  3059. ap->val = ckstrdup(val);
  3060. /*ap->flag = 0; - ckzalloc did it */
  3061. /*ap->next = NULL;*/
  3062. *app = ap;
  3063. }
  3064. INT_ON;
  3065. }
  3066. static int
  3067. unalias(const char *name)
  3068. {
  3069. struct alias **app;
  3070. app = __lookupalias(name);
  3071. if (*app) {
  3072. INT_OFF;
  3073. *app = freealias(*app);
  3074. INT_ON;
  3075. return 0;
  3076. }
  3077. return 1;
  3078. }
  3079. static void
  3080. rmaliases(void)
  3081. {
  3082. struct alias *ap, **app;
  3083. int i;
  3084. INT_OFF;
  3085. for (i = 0; i < ATABSIZE; i++) {
  3086. app = &atab[i];
  3087. for (ap = *app; ap; ap = *app) {
  3088. *app = freealias(*app);
  3089. if (ap == *app) {
  3090. app = &ap->next;
  3091. }
  3092. }
  3093. }
  3094. INT_ON;
  3095. }
  3096. static void
  3097. printalias(const struct alias *ap)
  3098. {
  3099. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3100. }
  3101. /*
  3102. * TODO - sort output
  3103. */
  3104. static int FAST_FUNC
  3105. aliascmd(int argc UNUSED_PARAM, char **argv)
  3106. {
  3107. char *n, *v;
  3108. int ret = 0;
  3109. struct alias *ap;
  3110. if (!argv[1]) {
  3111. int i;
  3112. for (i = 0; i < ATABSIZE; i++) {
  3113. for (ap = atab[i]; ap; ap = ap->next) {
  3114. printalias(ap);
  3115. }
  3116. }
  3117. return 0;
  3118. }
  3119. while ((n = *++argv) != NULL) {
  3120. v = strchr(n+1, '=');
  3121. if (v == NULL) { /* n+1: funny ksh stuff */
  3122. ap = *__lookupalias(n);
  3123. if (ap == NULL) {
  3124. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3125. ret = 1;
  3126. } else
  3127. printalias(ap);
  3128. } else {
  3129. *v++ = '\0';
  3130. setalias(n, v);
  3131. }
  3132. }
  3133. return ret;
  3134. }
  3135. static int FAST_FUNC
  3136. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3137. {
  3138. int i;
  3139. while (nextopt("a") != '\0') {
  3140. rmaliases();
  3141. return 0;
  3142. }
  3143. for (i = 0; *argptr; argptr++) {
  3144. if (unalias(*argptr)) {
  3145. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3146. i = 1;
  3147. }
  3148. }
  3149. return i;
  3150. }
  3151. #endif /* ASH_ALIAS */
  3152. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3153. #define FORK_FG 0
  3154. #define FORK_BG 1
  3155. #define FORK_NOJOB 2
  3156. /* mode flags for showjob(s) */
  3157. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3158. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3159. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3160. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3161. /*
  3162. * A job structure contains information about a job. A job is either a
  3163. * single process or a set of processes contained in a pipeline. In the
  3164. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3165. * array of pids.
  3166. */
  3167. struct procstat {
  3168. pid_t ps_pid; /* process id */
  3169. int ps_status; /* last process status from wait() */
  3170. char *ps_cmd; /* text of command being run */
  3171. };
  3172. struct job {
  3173. struct procstat ps0; /* status of process */
  3174. struct procstat *ps; /* status or processes when more than one */
  3175. #if JOBS
  3176. int stopstatus; /* status of a stopped job */
  3177. #endif
  3178. unsigned nprocs; /* number of processes */
  3179. #define JOBRUNNING 0 /* at least one proc running */
  3180. #define JOBSTOPPED 1 /* all procs are stopped */
  3181. #define JOBDONE 2 /* all procs are completed */
  3182. unsigned
  3183. state: 8,
  3184. #if JOBS
  3185. sigint: 1, /* job was killed by SIGINT */
  3186. jobctl: 1, /* job running under job control */
  3187. #endif
  3188. waited: 1, /* true if this entry has been waited for */
  3189. used: 1, /* true if this entry is in used */
  3190. changed: 1; /* true if status has changed */
  3191. struct job *prev_job; /* previous job */
  3192. };
  3193. static struct job *makejob(/*union node *,*/ int);
  3194. static int forkshell(struct job *, union node *, int);
  3195. static int waitforjob(struct job *);
  3196. #if !JOBS
  3197. enum { doing_jobctl = 0 };
  3198. #define setjobctl(on) do {} while (0)
  3199. #else
  3200. static smallint doing_jobctl; //references:8
  3201. static void setjobctl(int);
  3202. #endif
  3203. /*
  3204. * Ignore a signal.
  3205. */
  3206. static void
  3207. ignoresig(int signo)
  3208. {
  3209. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3210. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3211. /* No, need to do it */
  3212. signal(signo, SIG_IGN);
  3213. }
  3214. sigmode[signo - 1] = S_HARD_IGN;
  3215. }
  3216. /*
  3217. * Only one usage site - in setsignal()
  3218. */
  3219. static void
  3220. signal_handler(int signo)
  3221. {
  3222. if (signo == SIGCHLD) {
  3223. got_sigchld = 1;
  3224. if (!trap[SIGCHLD])
  3225. return;
  3226. }
  3227. gotsig[signo - 1] = 1;
  3228. pending_sig = signo;
  3229. if (signo == SIGINT && !trap[SIGINT]) {
  3230. if (!suppress_int) {
  3231. pending_sig = 0;
  3232. raise_interrupt(); /* does not return */
  3233. }
  3234. pending_int = 1;
  3235. }
  3236. }
  3237. /*
  3238. * Set the signal handler for the specified signal. The routine figures
  3239. * out what it should be set to.
  3240. */
  3241. static void
  3242. setsignal(int signo)
  3243. {
  3244. char *t;
  3245. char cur_act, new_act;
  3246. struct sigaction act;
  3247. t = trap[signo];
  3248. new_act = S_DFL;
  3249. if (t != NULL) { /* trap for this sig is set */
  3250. new_act = S_CATCH;
  3251. if (t[0] == '\0') /* trap is "": ignore this sig */
  3252. new_act = S_IGN;
  3253. }
  3254. if (rootshell && new_act == S_DFL) {
  3255. switch (signo) {
  3256. case SIGINT:
  3257. if (iflag || minusc || sflag == 0)
  3258. new_act = S_CATCH;
  3259. break;
  3260. case SIGQUIT:
  3261. #if DEBUG
  3262. if (debug)
  3263. break;
  3264. #endif
  3265. /* man bash:
  3266. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3267. * commands run by bash have signal handlers
  3268. * set to the values inherited by the shell
  3269. * from its parent". */
  3270. new_act = S_IGN;
  3271. break;
  3272. case SIGTERM:
  3273. if (iflag)
  3274. new_act = S_IGN;
  3275. break;
  3276. #if JOBS
  3277. case SIGTSTP:
  3278. case SIGTTOU:
  3279. if (mflag)
  3280. new_act = S_IGN;
  3281. break;
  3282. #endif
  3283. }
  3284. }
  3285. /* if !rootshell, we reset SIGQUIT to DFL,
  3286. * whereas we have to restore it to what shell got on entry.
  3287. * This is handled by the fact that if signal was IGNored on entry,
  3288. * then cur_act is S_HARD_IGN and we never change its sigaction
  3289. * (see code below).
  3290. */
  3291. if (signo == SIGCHLD)
  3292. new_act = S_CATCH;
  3293. t = &sigmode[signo - 1];
  3294. cur_act = *t;
  3295. if (cur_act == 0) {
  3296. /* current setting is not yet known */
  3297. if (sigaction(signo, NULL, &act)) {
  3298. /* pretend it worked; maybe we should give a warning,
  3299. * but other shells don't. We don't alter sigmode,
  3300. * so we retry every time.
  3301. * btw, in Linux it never fails. --vda */
  3302. return;
  3303. }
  3304. if (act.sa_handler == SIG_IGN) {
  3305. cur_act = S_HARD_IGN;
  3306. if (mflag
  3307. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3308. ) {
  3309. cur_act = S_IGN; /* don't hard ignore these */
  3310. }
  3311. }
  3312. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3313. /* installing SIG_DFL over SIG_DFL is a no-op */
  3314. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3315. *t = S_DFL;
  3316. return;
  3317. }
  3318. }
  3319. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3320. return;
  3321. *t = new_act;
  3322. act.sa_handler = SIG_DFL;
  3323. switch (new_act) {
  3324. case S_CATCH:
  3325. act.sa_handler = signal_handler;
  3326. break;
  3327. case S_IGN:
  3328. act.sa_handler = SIG_IGN;
  3329. break;
  3330. }
  3331. /* flags and mask matter only if !DFL and !IGN, but we do it
  3332. * for all cases for more deterministic behavior:
  3333. */
  3334. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3335. sigfillset(&act.sa_mask);
  3336. sigaction_set(signo, &act);
  3337. }
  3338. /* mode flags for set_curjob */
  3339. #define CUR_DELETE 2
  3340. #define CUR_RUNNING 1
  3341. #define CUR_STOPPED 0
  3342. #if JOBS
  3343. /* pgrp of shell on invocation */
  3344. static int initialpgrp; //references:2
  3345. static int ttyfd = -1; //5
  3346. #endif
  3347. /* array of jobs */
  3348. static struct job *jobtab; //5
  3349. /* size of array */
  3350. static unsigned njobs; //4
  3351. /* current job */
  3352. static struct job *curjob; //lots
  3353. /* number of presumed living untracked jobs */
  3354. static int jobless; //4
  3355. #if 0
  3356. /* Bash has a feature: it restores termios after a successful wait for
  3357. * a foreground job which had at least one stopped or sigkilled member.
  3358. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3359. * properly restoring tty state. Should we do this too?
  3360. * A reproducer: ^Z an interactive python:
  3361. *
  3362. * # python
  3363. * Python 2.7.12 (...)
  3364. * >>> ^Z
  3365. * { python leaves tty in -icanon -echo state. We do survive that... }
  3366. * [1]+ Stopped python
  3367. * { ...however, next program (python #2) does not survive it well: }
  3368. * # python
  3369. * Python 2.7.12 (...)
  3370. * >>> Traceback (most recent call last):
  3371. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3372. * File "<stdin>", line 1, in <module>
  3373. * NameError: name 'qwerty' is not defined
  3374. *
  3375. * The implementation below is modeled on bash code and seems to work.
  3376. * However, I'm not sure we should do this. For one: what if I'd fg
  3377. * the stopped python instead? It'll be confused by "restored" tty state.
  3378. */
  3379. static struct termios shell_tty_info;
  3380. static void
  3381. get_tty_state(void)
  3382. {
  3383. if (rootshell && ttyfd >= 0)
  3384. tcgetattr(ttyfd, &shell_tty_info);
  3385. }
  3386. static void
  3387. set_tty_state(void)
  3388. {
  3389. /* if (rootshell) - caller ensures this */
  3390. if (ttyfd >= 0)
  3391. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3392. }
  3393. static int
  3394. job_signal_status(struct job *jp)
  3395. {
  3396. int status;
  3397. unsigned i;
  3398. struct procstat *ps = jp->ps;
  3399. for (i = 0; i < jp->nprocs; i++) {
  3400. status = ps[i].ps_status;
  3401. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3402. return status;
  3403. }
  3404. return 0;
  3405. }
  3406. static void
  3407. restore_tty_if_stopped_or_signaled(struct job *jp)
  3408. {
  3409. //TODO: check what happens if we come from waitforjob() in expbackq()
  3410. if (rootshell) {
  3411. int s = job_signal_status(jp);
  3412. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3413. set_tty_state();
  3414. }
  3415. }
  3416. #else
  3417. # define get_tty_state() ((void)0)
  3418. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3419. #endif
  3420. static void
  3421. set_curjob(struct job *jp, unsigned mode)
  3422. {
  3423. struct job *jp1;
  3424. struct job **jpp, **curp;
  3425. /* first remove from list */
  3426. jpp = curp = &curjob;
  3427. while (1) {
  3428. jp1 = *jpp;
  3429. if (jp1 == jp)
  3430. break;
  3431. jpp = &jp1->prev_job;
  3432. }
  3433. *jpp = jp1->prev_job;
  3434. /* Then re-insert in correct position */
  3435. jpp = curp;
  3436. switch (mode) {
  3437. default:
  3438. #if DEBUG
  3439. abort();
  3440. #endif
  3441. case CUR_DELETE:
  3442. /* job being deleted */
  3443. break;
  3444. case CUR_RUNNING:
  3445. /* newly created job or backgrounded job,
  3446. * put after all stopped jobs.
  3447. */
  3448. while (1) {
  3449. jp1 = *jpp;
  3450. #if JOBS
  3451. if (!jp1 || jp1->state != JOBSTOPPED)
  3452. #endif
  3453. break;
  3454. jpp = &jp1->prev_job;
  3455. }
  3456. /* FALLTHROUGH */
  3457. #if JOBS
  3458. case CUR_STOPPED:
  3459. #endif
  3460. /* newly stopped job - becomes curjob */
  3461. jp->prev_job = *jpp;
  3462. *jpp = jp;
  3463. break;
  3464. }
  3465. }
  3466. #if JOBS || DEBUG
  3467. static int
  3468. jobno(const struct job *jp)
  3469. {
  3470. return jp - jobtab + 1;
  3471. }
  3472. #endif
  3473. /*
  3474. * Convert a job name to a job structure.
  3475. */
  3476. #if !JOBS
  3477. #define getjob(name, getctl) getjob(name)
  3478. #endif
  3479. static struct job *
  3480. getjob(const char *name, int getctl)
  3481. {
  3482. struct job *jp;
  3483. struct job *found;
  3484. const char *err_msg = "%s: no such job";
  3485. unsigned num;
  3486. int c;
  3487. const char *p;
  3488. char *(*match)(const char *, const char *);
  3489. jp = curjob;
  3490. p = name;
  3491. if (!p)
  3492. goto currentjob;
  3493. if (*p != '%')
  3494. goto err;
  3495. c = *++p;
  3496. if (!c)
  3497. goto currentjob;
  3498. if (!p[1]) {
  3499. if (c == '+' || c == '%') {
  3500. currentjob:
  3501. err_msg = "No current job";
  3502. goto check;
  3503. }
  3504. if (c == '-') {
  3505. if (jp)
  3506. jp = jp->prev_job;
  3507. err_msg = "No previous job";
  3508. check:
  3509. if (!jp)
  3510. goto err;
  3511. goto gotit;
  3512. }
  3513. }
  3514. if (is_number(p)) {
  3515. num = atoi(p);
  3516. if (num > 0 && num <= njobs) {
  3517. jp = jobtab + num - 1;
  3518. if (jp->used)
  3519. goto gotit;
  3520. goto err;
  3521. }
  3522. }
  3523. match = prefix;
  3524. if (*p == '?') {
  3525. match = strstr;
  3526. p++;
  3527. }
  3528. found = NULL;
  3529. while (jp) {
  3530. if (match(jp->ps[0].ps_cmd, p)) {
  3531. if (found)
  3532. goto err;
  3533. found = jp;
  3534. err_msg = "%s: ambiguous";
  3535. }
  3536. jp = jp->prev_job;
  3537. }
  3538. if (!found)
  3539. goto err;
  3540. jp = found;
  3541. gotit:
  3542. #if JOBS
  3543. err_msg = "job %s not created under job control";
  3544. if (getctl && jp->jobctl == 0)
  3545. goto err;
  3546. #endif
  3547. return jp;
  3548. err:
  3549. ash_msg_and_raise_error(err_msg, name);
  3550. }
  3551. /*
  3552. * Mark a job structure as unused.
  3553. */
  3554. static void
  3555. freejob(struct job *jp)
  3556. {
  3557. struct procstat *ps;
  3558. int i;
  3559. INT_OFF;
  3560. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3561. if (ps->ps_cmd != nullstr)
  3562. free(ps->ps_cmd);
  3563. }
  3564. if (jp->ps != &jp->ps0)
  3565. free(jp->ps);
  3566. jp->used = 0;
  3567. set_curjob(jp, CUR_DELETE);
  3568. INT_ON;
  3569. }
  3570. #if JOBS
  3571. static void
  3572. xtcsetpgrp(int fd, pid_t pgrp)
  3573. {
  3574. if (tcsetpgrp(fd, pgrp))
  3575. ash_msg_and_raise_perror("can't set tty process group");
  3576. }
  3577. /*
  3578. * Turn job control on and off.
  3579. *
  3580. * Note: This code assumes that the third arg to ioctl is a character
  3581. * pointer, which is true on Berkeley systems but not System V. Since
  3582. * System V doesn't have job control yet, this isn't a problem now.
  3583. *
  3584. * Called with interrupts off.
  3585. */
  3586. static void
  3587. setjobctl(int on)
  3588. {
  3589. int fd;
  3590. int pgrp;
  3591. if (on == doing_jobctl || rootshell == 0)
  3592. return;
  3593. if (on) {
  3594. int ofd;
  3595. ofd = fd = open(_PATH_TTY, O_RDWR);
  3596. if (fd < 0) {
  3597. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3598. * That sometimes helps to acquire controlling tty.
  3599. * Obviously, a workaround for bugs when someone
  3600. * failed to provide a controlling tty to bash! :) */
  3601. fd = 2;
  3602. while (!isatty(fd))
  3603. if (--fd < 0)
  3604. goto out;
  3605. }
  3606. /* fd is a tty at this point */
  3607. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3608. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3609. close(ofd);
  3610. if (fd < 0)
  3611. goto out; /* F_DUPFD failed */
  3612. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3613. close_on_exec_on(fd);
  3614. while (1) { /* while we are in the background */
  3615. pgrp = tcgetpgrp(fd);
  3616. if (pgrp < 0) {
  3617. out:
  3618. ash_msg("can't access tty; job control turned off");
  3619. mflag = on = 0;
  3620. goto close;
  3621. }
  3622. if (pgrp == getpgrp())
  3623. break;
  3624. killpg(0, SIGTTIN);
  3625. }
  3626. initialpgrp = pgrp;
  3627. setsignal(SIGTSTP);
  3628. setsignal(SIGTTOU);
  3629. setsignal(SIGTTIN);
  3630. pgrp = rootpid;
  3631. setpgid(0, pgrp);
  3632. xtcsetpgrp(fd, pgrp);
  3633. } else {
  3634. /* turning job control off */
  3635. fd = ttyfd;
  3636. pgrp = initialpgrp;
  3637. /* was xtcsetpgrp, but this can make exiting ash
  3638. * loop forever if pty is already deleted */
  3639. tcsetpgrp(fd, pgrp);
  3640. setpgid(0, pgrp);
  3641. setsignal(SIGTSTP);
  3642. setsignal(SIGTTOU);
  3643. setsignal(SIGTTIN);
  3644. close:
  3645. if (fd >= 0)
  3646. close(fd);
  3647. fd = -1;
  3648. }
  3649. ttyfd = fd;
  3650. doing_jobctl = on;
  3651. }
  3652. static int FAST_FUNC
  3653. killcmd(int argc, char **argv)
  3654. {
  3655. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3656. int i = 1;
  3657. do {
  3658. if (argv[i][0] == '%') {
  3659. /*
  3660. * "kill %N" - job kill
  3661. * Converting to pgrp / pid kill
  3662. */
  3663. struct job *jp;
  3664. char *dst;
  3665. int j, n;
  3666. jp = getjob(argv[i], 0);
  3667. /*
  3668. * In jobs started under job control, we signal
  3669. * entire process group by kill -PGRP_ID.
  3670. * This happens, f.e., in interactive shell.
  3671. *
  3672. * Otherwise, we signal each child via
  3673. * kill PID1 PID2 PID3.
  3674. * Testcases:
  3675. * sh -c 'sleep 1|sleep 1 & kill %1'
  3676. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3677. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3678. */
  3679. n = jp->nprocs; /* can't be 0 (I hope) */
  3680. if (jp->jobctl)
  3681. n = 1;
  3682. dst = alloca(n * sizeof(int)*4);
  3683. argv[i] = dst;
  3684. for (j = 0; j < n; j++) {
  3685. struct procstat *ps = &jp->ps[j];
  3686. /* Skip non-running and not-stopped members
  3687. * (i.e. dead members) of the job
  3688. */
  3689. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3690. continue;
  3691. /*
  3692. * kill_main has matching code to expect
  3693. * leading space. Needed to not confuse
  3694. * negative pids with "kill -SIGNAL_NO" syntax
  3695. */
  3696. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3697. }
  3698. *dst = '\0';
  3699. }
  3700. } while (argv[++i]);
  3701. }
  3702. return kill_main(argc, argv);
  3703. }
  3704. static void
  3705. showpipe(struct job *jp /*, FILE *out*/)
  3706. {
  3707. struct procstat *ps;
  3708. struct procstat *psend;
  3709. psend = jp->ps + jp->nprocs;
  3710. for (ps = jp->ps + 1; ps < psend; ps++)
  3711. printf(" | %s", ps->ps_cmd);
  3712. newline_and_flush(stdout);
  3713. flush_stdout_stderr();
  3714. }
  3715. static int
  3716. restartjob(struct job *jp, int mode)
  3717. {
  3718. struct procstat *ps;
  3719. int i;
  3720. int status;
  3721. pid_t pgid;
  3722. INT_OFF;
  3723. if (jp->state == JOBDONE)
  3724. goto out;
  3725. jp->state = JOBRUNNING;
  3726. pgid = jp->ps[0].ps_pid;
  3727. if (mode == FORK_FG) {
  3728. get_tty_state();
  3729. xtcsetpgrp(ttyfd, pgid);
  3730. }
  3731. killpg(pgid, SIGCONT);
  3732. ps = jp->ps;
  3733. i = jp->nprocs;
  3734. do {
  3735. if (WIFSTOPPED(ps->ps_status)) {
  3736. ps->ps_status = -1;
  3737. }
  3738. ps++;
  3739. } while (--i);
  3740. out:
  3741. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3742. INT_ON;
  3743. return status;
  3744. }
  3745. static int FAST_FUNC
  3746. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3747. {
  3748. struct job *jp;
  3749. int mode;
  3750. int retval;
  3751. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3752. nextopt(nullstr);
  3753. argv = argptr;
  3754. do {
  3755. jp = getjob(*argv, 1);
  3756. if (mode == FORK_BG) {
  3757. set_curjob(jp, CUR_RUNNING);
  3758. printf("[%d] ", jobno(jp));
  3759. }
  3760. out1str(jp->ps[0].ps_cmd);
  3761. showpipe(jp /*, stdout*/);
  3762. retval = restartjob(jp, mode);
  3763. } while (*argv && *++argv);
  3764. return retval;
  3765. }
  3766. #endif
  3767. static int
  3768. sprint_status48(char *s, int status, int sigonly)
  3769. {
  3770. int col;
  3771. int st;
  3772. col = 0;
  3773. if (!WIFEXITED(status)) {
  3774. #if JOBS
  3775. if (WIFSTOPPED(status))
  3776. st = WSTOPSIG(status);
  3777. else
  3778. #endif
  3779. st = WTERMSIG(status);
  3780. if (sigonly) {
  3781. if (st == SIGINT || st == SIGPIPE)
  3782. goto out;
  3783. #if JOBS
  3784. if (WIFSTOPPED(status))
  3785. goto out;
  3786. #endif
  3787. }
  3788. st &= 0x7f;
  3789. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3790. col = fmtstr(s, 32, strsignal(st));
  3791. if (WCOREDUMP(status)) {
  3792. strcpy(s + col, " (core dumped)");
  3793. col += sizeof(" (core dumped)")-1;
  3794. }
  3795. } else if (!sigonly) {
  3796. st = WEXITSTATUS(status);
  3797. col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3798. }
  3799. out:
  3800. return col;
  3801. }
  3802. static int
  3803. wait_block_or_sig(int *status)
  3804. {
  3805. int pid;
  3806. do {
  3807. sigset_t mask;
  3808. /* Poll all children for changes in their state */
  3809. got_sigchld = 0;
  3810. /* if job control is active, accept stopped processes too */
  3811. pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
  3812. if (pid != 0)
  3813. break; /* Error (e.g. EINTR, ECHILD) or pid */
  3814. /* Children exist, but none are ready. Sleep until interesting signal */
  3815. #if 1
  3816. sigfillset(&mask);
  3817. sigprocmask2(SIG_SETMASK, &mask); /* mask is updated */
  3818. while (!got_sigchld && !pending_sig)
  3819. sigsuspend(&mask);
  3820. sigprocmask(SIG_SETMASK, &mask, NULL);
  3821. #else /* unsafe: a signal can set pending_sig after check, but before pause() */
  3822. while (!got_sigchld && !pending_sig)
  3823. pause();
  3824. #endif
  3825. /* If it was SIGCHLD, poll children again */
  3826. } while (got_sigchld);
  3827. return pid;
  3828. }
  3829. #define DOWAIT_NONBLOCK 0
  3830. #define DOWAIT_BLOCK 1
  3831. #define DOWAIT_BLOCK_OR_SIG 2
  3832. static int
  3833. dowait(int block, struct job *job)
  3834. {
  3835. int pid;
  3836. int status;
  3837. struct job *jp;
  3838. struct job *thisjob = NULL;
  3839. TRACE(("dowait(0x%x) called\n", block));
  3840. /* It's wrong to call waitpid() outside of INT_OFF region:
  3841. * signal can arrive just after syscall return and handler can
  3842. * longjmp away, losing stop/exit notification processing.
  3843. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3844. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3845. *
  3846. * However, for "wait" builtin it is wrong to simply call waitpid()
  3847. * in INT_OFF region: "wait" needs to wait for any running job
  3848. * to change state, but should exit on any trap too.
  3849. * In INT_OFF region, a signal just before syscall entry can set
  3850. * pending_sig variables, but we can't check them, and we would
  3851. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3852. *
  3853. * Because of this, we run inside INT_OFF, but use a special routine
  3854. * which combines waitpid() and sigsuspend().
  3855. * This is the reason why we need to have a handler for SIGCHLD:
  3856. * SIG_DFL handler does not wake sigsuspend().
  3857. */
  3858. INT_OFF;
  3859. if (block == DOWAIT_BLOCK_OR_SIG) {
  3860. pid = wait_block_or_sig(&status);
  3861. } else {
  3862. int wait_flags = 0;
  3863. if (block == DOWAIT_NONBLOCK)
  3864. wait_flags = WNOHANG;
  3865. /* if job control is active, accept stopped processes too */
  3866. if (doing_jobctl)
  3867. wait_flags |= WUNTRACED;
  3868. /* NB: _not_ safe_waitpid, we need to detect EINTR */
  3869. pid = waitpid(-1, &status, wait_flags);
  3870. }
  3871. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3872. pid, status, errno, strerror(errno)));
  3873. if (pid <= 0)
  3874. goto out;
  3875. thisjob = NULL;
  3876. for (jp = curjob; jp; jp = jp->prev_job) {
  3877. int jobstate;
  3878. struct procstat *ps;
  3879. struct procstat *psend;
  3880. if (jp->state == JOBDONE)
  3881. continue;
  3882. jobstate = JOBDONE;
  3883. ps = jp->ps;
  3884. psend = ps + jp->nprocs;
  3885. do {
  3886. if (ps->ps_pid == pid) {
  3887. TRACE(("Job %d: changing status of proc %d "
  3888. "from 0x%x to 0x%x\n",
  3889. jobno(jp), pid, ps->ps_status, status));
  3890. ps->ps_status = status;
  3891. thisjob = jp;
  3892. }
  3893. if (ps->ps_status == -1)
  3894. jobstate = JOBRUNNING;
  3895. #if JOBS
  3896. if (jobstate == JOBRUNNING)
  3897. continue;
  3898. if (WIFSTOPPED(ps->ps_status)) {
  3899. jp->stopstatus = ps->ps_status;
  3900. jobstate = JOBSTOPPED;
  3901. }
  3902. #endif
  3903. } while (++ps < psend);
  3904. if (!thisjob)
  3905. continue;
  3906. /* Found the job where one of its processes changed its state.
  3907. * Is there at least one live and running process in this job? */
  3908. if (jobstate != JOBRUNNING) {
  3909. /* No. All live processes in the job are stopped
  3910. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3911. */
  3912. thisjob->changed = 1;
  3913. if (thisjob->state != jobstate) {
  3914. TRACE(("Job %d: changing state from %d to %d\n",
  3915. jobno(thisjob), thisjob->state, jobstate));
  3916. thisjob->state = jobstate;
  3917. #if JOBS
  3918. if (jobstate == JOBSTOPPED)
  3919. set_curjob(thisjob, CUR_STOPPED);
  3920. #endif
  3921. }
  3922. }
  3923. goto out;
  3924. }
  3925. /* The process wasn't found in job list */
  3926. #if JOBS
  3927. if (!WIFSTOPPED(status))
  3928. jobless--;
  3929. #endif
  3930. out:
  3931. INT_ON;
  3932. if (thisjob && thisjob == job) {
  3933. char s[48 + 1];
  3934. int len;
  3935. len = sprint_status48(s, status, 1);
  3936. if (len) {
  3937. s[len] = '\n';
  3938. s[len + 1] = '\0';
  3939. out2str(s);
  3940. }
  3941. }
  3942. return pid;
  3943. }
  3944. #if JOBS
  3945. static void
  3946. showjob(struct job *jp, int mode)
  3947. {
  3948. struct procstat *ps;
  3949. struct procstat *psend;
  3950. int col;
  3951. int indent_col;
  3952. char s[16 + 16 + 48];
  3953. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  3954. ps = jp->ps;
  3955. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3956. /* just output process (group) id of pipeline */
  3957. fprintf(out, "%d\n", ps->ps_pid);
  3958. return;
  3959. }
  3960. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3961. indent_col = col;
  3962. if (jp == curjob)
  3963. s[col - 3] = '+';
  3964. else if (curjob && jp == curjob->prev_job)
  3965. s[col - 3] = '-';
  3966. if (mode & SHOW_PIDS)
  3967. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3968. psend = ps + jp->nprocs;
  3969. if (jp->state == JOBRUNNING) {
  3970. strcpy(s + col, "Running");
  3971. col += sizeof("Running") - 1;
  3972. } else {
  3973. int status = psend[-1].ps_status;
  3974. if (jp->state == JOBSTOPPED)
  3975. status = jp->stopstatus;
  3976. col += sprint_status48(s + col, status, 0);
  3977. }
  3978. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3979. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3980. * or prints several "PID | <cmdN>" lines,
  3981. * depending on SHOW_PIDS bit.
  3982. * We do not print status of individual processes
  3983. * between PID and <cmdN>. bash does it, but not very well:
  3984. * first line shows overall job status, not process status,
  3985. * making it impossible to know 1st process status.
  3986. */
  3987. goto start;
  3988. do {
  3989. /* for each process */
  3990. s[0] = '\0';
  3991. col = 33;
  3992. if (mode & SHOW_PIDS)
  3993. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3994. start:
  3995. fprintf(out, "%s%*c%s%s",
  3996. s,
  3997. 33 - col >= 0 ? 33 - col : 0, ' ',
  3998. ps == jp->ps ? "" : "| ",
  3999. ps->ps_cmd
  4000. );
  4001. } while (++ps != psend);
  4002. newline_and_flush(out);
  4003. jp->changed = 0;
  4004. if (jp->state == JOBDONE) {
  4005. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4006. freejob(jp);
  4007. }
  4008. }
  4009. /*
  4010. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4011. * statuses have changed since the last call to showjobs.
  4012. */
  4013. static void
  4014. showjobs(int mode)
  4015. {
  4016. struct job *jp;
  4017. TRACE(("showjobs(0x%x) called\n", mode));
  4018. /* Handle all finished jobs */
  4019. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4020. continue;
  4021. for (jp = curjob; jp; jp = jp->prev_job) {
  4022. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4023. showjob(jp, mode);
  4024. }
  4025. }
  4026. }
  4027. static int FAST_FUNC
  4028. jobscmd(int argc UNUSED_PARAM, char **argv)
  4029. {
  4030. int mode, m;
  4031. mode = 0;
  4032. while ((m = nextopt("lp")) != '\0') {
  4033. if (m == 'l')
  4034. mode |= SHOW_PIDS;
  4035. else
  4036. mode |= SHOW_ONLY_PGID;
  4037. }
  4038. argv = argptr;
  4039. if (*argv) {
  4040. do
  4041. showjob(getjob(*argv, 0), mode);
  4042. while (*++argv);
  4043. } else {
  4044. showjobs(mode);
  4045. }
  4046. return 0;
  4047. }
  4048. #endif /* JOBS */
  4049. /* Called only on finished or stopped jobs (no members are running) */
  4050. static int
  4051. getstatus(struct job *job)
  4052. {
  4053. int status;
  4054. int retval;
  4055. struct procstat *ps;
  4056. /* Fetch last member's status */
  4057. ps = job->ps + job->nprocs - 1;
  4058. status = ps->ps_status;
  4059. if (pipefail) {
  4060. /* "set -o pipefail" mode: use last _nonzero_ status */
  4061. while (status == 0 && --ps >= job->ps)
  4062. status = ps->ps_status;
  4063. }
  4064. retval = WEXITSTATUS(status);
  4065. if (!WIFEXITED(status)) {
  4066. #if JOBS
  4067. retval = WSTOPSIG(status);
  4068. if (!WIFSTOPPED(status))
  4069. #endif
  4070. {
  4071. /* XXX: limits number of signals */
  4072. retval = WTERMSIG(status);
  4073. #if JOBS
  4074. if (retval == SIGINT)
  4075. job->sigint = 1;
  4076. #endif
  4077. }
  4078. retval += 128;
  4079. }
  4080. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4081. jobno(job), job->nprocs, status, retval));
  4082. return retval;
  4083. }
  4084. static int FAST_FUNC
  4085. waitcmd(int argc UNUSED_PARAM, char **argv)
  4086. {
  4087. struct job *job;
  4088. int retval;
  4089. struct job *jp;
  4090. nextopt(nullstr);
  4091. retval = 0;
  4092. argv = argptr;
  4093. if (!*argv) {
  4094. /* wait for all jobs */
  4095. for (;;) {
  4096. jp = curjob;
  4097. while (1) {
  4098. if (!jp) /* no running procs */
  4099. goto ret;
  4100. if (jp->state == JOBRUNNING)
  4101. break;
  4102. jp->waited = 1;
  4103. jp = jp->prev_job;
  4104. }
  4105. /* man bash:
  4106. * "When bash is waiting for an asynchronous command via
  4107. * the wait builtin, the reception of a signal for which a trap
  4108. * has been set will cause the wait builtin to return immediately
  4109. * with an exit status greater than 128, immediately after which
  4110. * the trap is executed."
  4111. */
  4112. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4113. /* if child sends us a signal *and immediately exits*,
  4114. * dowait() returns pid > 0. Check this case,
  4115. * not "if (dowait() < 0)"!
  4116. */
  4117. if (pending_sig)
  4118. goto sigout;
  4119. }
  4120. }
  4121. retval = 127;
  4122. do {
  4123. if (**argv != '%') {
  4124. pid_t pid = number(*argv);
  4125. job = curjob;
  4126. while (1) {
  4127. if (!job)
  4128. goto repeat;
  4129. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4130. break;
  4131. job = job->prev_job;
  4132. }
  4133. } else {
  4134. job = getjob(*argv, 0);
  4135. }
  4136. /* loop until process terminated or stopped */
  4137. while (job->state == JOBRUNNING) {
  4138. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4139. if (pending_sig)
  4140. goto sigout;
  4141. }
  4142. job->waited = 1;
  4143. retval = getstatus(job);
  4144. repeat: ;
  4145. } while (*++argv);
  4146. ret:
  4147. return retval;
  4148. sigout:
  4149. retval = 128 + pending_sig;
  4150. return retval;
  4151. }
  4152. static struct job *
  4153. growjobtab(void)
  4154. {
  4155. size_t len;
  4156. ptrdiff_t offset;
  4157. struct job *jp, *jq;
  4158. len = njobs * sizeof(*jp);
  4159. jq = jobtab;
  4160. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4161. offset = (char *)jp - (char *)jq;
  4162. if (offset) {
  4163. /* Relocate pointers */
  4164. size_t l = len;
  4165. jq = (struct job *)((char *)jq + l);
  4166. while (l) {
  4167. l -= sizeof(*jp);
  4168. jq--;
  4169. #define joff(p) ((struct job *)((char *)(p) + l))
  4170. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4171. if (joff(jp)->ps == &jq->ps0)
  4172. jmove(joff(jp)->ps);
  4173. if (joff(jp)->prev_job)
  4174. jmove(joff(jp)->prev_job);
  4175. }
  4176. if (curjob)
  4177. jmove(curjob);
  4178. #undef joff
  4179. #undef jmove
  4180. }
  4181. njobs += 4;
  4182. jobtab = jp;
  4183. jp = (struct job *)((char *)jp + len);
  4184. jq = jp + 3;
  4185. do {
  4186. jq->used = 0;
  4187. } while (--jq >= jp);
  4188. return jp;
  4189. }
  4190. /*
  4191. * Return a new job structure.
  4192. * Called with interrupts off.
  4193. */
  4194. static struct job *
  4195. makejob(/*union node *node,*/ int nprocs)
  4196. {
  4197. int i;
  4198. struct job *jp;
  4199. for (i = njobs, jp = jobtab; ; jp++) {
  4200. if (--i < 0) {
  4201. jp = growjobtab();
  4202. break;
  4203. }
  4204. if (jp->used == 0)
  4205. break;
  4206. if (jp->state != JOBDONE || !jp->waited)
  4207. continue;
  4208. #if JOBS
  4209. if (doing_jobctl)
  4210. continue;
  4211. #endif
  4212. freejob(jp);
  4213. break;
  4214. }
  4215. memset(jp, 0, sizeof(*jp));
  4216. #if JOBS
  4217. /* jp->jobctl is a bitfield.
  4218. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4219. if (doing_jobctl)
  4220. jp->jobctl = 1;
  4221. #endif
  4222. jp->prev_job = curjob;
  4223. curjob = jp;
  4224. jp->used = 1;
  4225. jp->ps = &jp->ps0;
  4226. if (nprocs > 1) {
  4227. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4228. }
  4229. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4230. jobno(jp)));
  4231. return jp;
  4232. }
  4233. #if JOBS
  4234. /*
  4235. * Return a string identifying a command (to be printed by the
  4236. * jobs command).
  4237. */
  4238. static char *cmdnextc;
  4239. static void
  4240. cmdputs(const char *s)
  4241. {
  4242. static const char vstype[VSTYPE + 1][3] = {
  4243. "", "}", "-", "+", "?", "=",
  4244. "%", "%%", "#", "##"
  4245. IF_BASH_SUBSTR(, ":")
  4246. IF_BASH_PATTERN_SUBST(, "/", "//")
  4247. };
  4248. const char *p, *str;
  4249. char cc[2];
  4250. char *nextc;
  4251. unsigned char c;
  4252. unsigned char subtype = 0;
  4253. int quoted = 0;
  4254. cc[1] = '\0';
  4255. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4256. p = s;
  4257. while ((c = *p++) != '\0') {
  4258. str = NULL;
  4259. switch (c) {
  4260. case CTLESC:
  4261. c = *p++;
  4262. break;
  4263. case CTLVAR:
  4264. subtype = *p++;
  4265. if ((subtype & VSTYPE) == VSLENGTH)
  4266. str = "${#";
  4267. else
  4268. str = "${";
  4269. goto dostr;
  4270. case CTLENDVAR:
  4271. str = "\"}" + !(quoted & 1);
  4272. quoted >>= 1;
  4273. subtype = 0;
  4274. goto dostr;
  4275. case CTLBACKQ:
  4276. str = "$(...)";
  4277. goto dostr;
  4278. #if ENABLE_FEATURE_SH_MATH
  4279. case CTLARI:
  4280. str = "$((";
  4281. goto dostr;
  4282. case CTLENDARI:
  4283. str = "))";
  4284. goto dostr;
  4285. #endif
  4286. case CTLQUOTEMARK:
  4287. quoted ^= 1;
  4288. c = '"';
  4289. break;
  4290. case '=':
  4291. if (subtype == 0)
  4292. break;
  4293. if ((subtype & VSTYPE) != VSNORMAL)
  4294. quoted <<= 1;
  4295. str = vstype[subtype & VSTYPE];
  4296. if (subtype & VSNUL)
  4297. c = ':';
  4298. else
  4299. goto checkstr;
  4300. break;
  4301. case '\'':
  4302. case '\\':
  4303. case '"':
  4304. case '$':
  4305. /* These can only happen inside quotes */
  4306. cc[0] = c;
  4307. str = cc;
  4308. //FIXME:
  4309. // $ true $$ &
  4310. // $ <cr>
  4311. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4312. c = '\\';
  4313. break;
  4314. default:
  4315. break;
  4316. }
  4317. USTPUTC(c, nextc);
  4318. checkstr:
  4319. if (!str)
  4320. continue;
  4321. dostr:
  4322. while ((c = *str++) != '\0') {
  4323. USTPUTC(c, nextc);
  4324. }
  4325. } /* while *p++ not NUL */
  4326. if (quoted & 1) {
  4327. USTPUTC('"', nextc);
  4328. }
  4329. *nextc = 0;
  4330. cmdnextc = nextc;
  4331. }
  4332. /* cmdtxt() and cmdlist() call each other */
  4333. static void cmdtxt(union node *n);
  4334. static void
  4335. cmdlist(union node *np, int sep)
  4336. {
  4337. for (; np; np = np->narg.next) {
  4338. if (!sep)
  4339. cmdputs(" ");
  4340. cmdtxt(np);
  4341. if (sep && np->narg.next)
  4342. cmdputs(" ");
  4343. }
  4344. }
  4345. static void
  4346. cmdtxt(union node *n)
  4347. {
  4348. union node *np;
  4349. struct nodelist *lp;
  4350. const char *p;
  4351. if (!n)
  4352. return;
  4353. switch (n->type) {
  4354. default:
  4355. #if DEBUG
  4356. abort();
  4357. #endif
  4358. case NPIPE:
  4359. lp = n->npipe.cmdlist;
  4360. for (;;) {
  4361. cmdtxt(lp->n);
  4362. lp = lp->next;
  4363. if (!lp)
  4364. break;
  4365. cmdputs(" | ");
  4366. }
  4367. break;
  4368. case NSEMI:
  4369. p = "; ";
  4370. goto binop;
  4371. case NAND:
  4372. p = " && ";
  4373. goto binop;
  4374. case NOR:
  4375. p = " || ";
  4376. binop:
  4377. cmdtxt(n->nbinary.ch1);
  4378. cmdputs(p);
  4379. n = n->nbinary.ch2;
  4380. goto donode;
  4381. case NREDIR:
  4382. case NBACKGND:
  4383. n = n->nredir.n;
  4384. goto donode;
  4385. case NNOT:
  4386. cmdputs("!");
  4387. n = n->nnot.com;
  4388. donode:
  4389. cmdtxt(n);
  4390. break;
  4391. case NIF:
  4392. cmdputs("if ");
  4393. cmdtxt(n->nif.test);
  4394. cmdputs("; then ");
  4395. if (n->nif.elsepart) {
  4396. cmdtxt(n->nif.ifpart);
  4397. cmdputs("; else ");
  4398. n = n->nif.elsepart;
  4399. } else {
  4400. n = n->nif.ifpart;
  4401. }
  4402. p = "; fi";
  4403. goto dotail;
  4404. case NSUBSHELL:
  4405. cmdputs("(");
  4406. n = n->nredir.n;
  4407. p = ")";
  4408. goto dotail;
  4409. case NWHILE:
  4410. p = "while ";
  4411. goto until;
  4412. case NUNTIL:
  4413. p = "until ";
  4414. until:
  4415. cmdputs(p);
  4416. cmdtxt(n->nbinary.ch1);
  4417. n = n->nbinary.ch2;
  4418. p = "; done";
  4419. dodo:
  4420. cmdputs("; do ");
  4421. dotail:
  4422. cmdtxt(n);
  4423. goto dotail2;
  4424. case NFOR:
  4425. cmdputs("for ");
  4426. cmdputs(n->nfor.var);
  4427. cmdputs(" in ");
  4428. cmdlist(n->nfor.args, 1);
  4429. n = n->nfor.body;
  4430. p = "; done";
  4431. goto dodo;
  4432. case NDEFUN:
  4433. cmdputs(n->ndefun.text);
  4434. p = "() { ... }";
  4435. goto dotail2;
  4436. case NCMD:
  4437. cmdlist(n->ncmd.args, 1);
  4438. cmdlist(n->ncmd.redirect, 0);
  4439. break;
  4440. case NARG:
  4441. p = n->narg.text;
  4442. dotail2:
  4443. cmdputs(p);
  4444. break;
  4445. case NHERE:
  4446. case NXHERE:
  4447. p = "<<...";
  4448. goto dotail2;
  4449. case NCASE:
  4450. cmdputs("case ");
  4451. cmdputs(n->ncase.expr->narg.text);
  4452. cmdputs(" in ");
  4453. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4454. cmdtxt(np->nclist.pattern);
  4455. cmdputs(") ");
  4456. cmdtxt(np->nclist.body);
  4457. cmdputs(";; ");
  4458. }
  4459. p = "esac";
  4460. goto dotail2;
  4461. case NTO:
  4462. p = ">";
  4463. goto redir;
  4464. case NCLOBBER:
  4465. p = ">|";
  4466. goto redir;
  4467. case NAPPEND:
  4468. p = ">>";
  4469. goto redir;
  4470. #if BASH_REDIR_OUTPUT
  4471. case NTO2:
  4472. #endif
  4473. case NTOFD:
  4474. p = ">&";
  4475. goto redir;
  4476. case NFROM:
  4477. p = "<";
  4478. goto redir;
  4479. case NFROMFD:
  4480. p = "<&";
  4481. goto redir;
  4482. case NFROMTO:
  4483. p = "<>";
  4484. redir:
  4485. cmdputs(utoa(n->nfile.fd));
  4486. cmdputs(p);
  4487. if (n->type == NTOFD || n->type == NFROMFD) {
  4488. if (n->ndup.dupfd >= 0)
  4489. cmdputs(utoa(n->ndup.dupfd));
  4490. else
  4491. cmdputs("-");
  4492. break;
  4493. }
  4494. n = n->nfile.fname;
  4495. goto donode;
  4496. }
  4497. }
  4498. static char *
  4499. commandtext(union node *n)
  4500. {
  4501. char *name;
  4502. STARTSTACKSTR(cmdnextc);
  4503. cmdtxt(n);
  4504. name = stackblock();
  4505. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4506. return ckstrdup(name);
  4507. }
  4508. #endif /* JOBS */
  4509. /*
  4510. * Fork off a subshell. If we are doing job control, give the subshell its
  4511. * own process group. Jp is a job structure that the job is to be added to.
  4512. * N is the command that will be evaluated by the child. Both jp and n may
  4513. * be NULL. The mode parameter can be one of the following:
  4514. * FORK_FG - Fork off a foreground process.
  4515. * FORK_BG - Fork off a background process.
  4516. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4517. * process group even if job control is on.
  4518. *
  4519. * When job control is turned off, background processes have their standard
  4520. * input redirected to /dev/null (except for the second and later processes
  4521. * in a pipeline).
  4522. *
  4523. * Called with interrupts off.
  4524. */
  4525. /*
  4526. * Clear traps on a fork.
  4527. */
  4528. static void
  4529. clear_traps(void)
  4530. {
  4531. char **tp;
  4532. INT_OFF;
  4533. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4534. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4535. if (trap_ptr == trap)
  4536. free(*tp);
  4537. /* else: it "belongs" to trap_ptr vector, don't free */
  4538. *tp = NULL;
  4539. if ((tp - trap) != 0)
  4540. setsignal(tp - trap);
  4541. }
  4542. }
  4543. may_have_traps = 0;
  4544. INT_ON;
  4545. }
  4546. /* Lives far away from here, needed for forkchild */
  4547. static void closescript(void);
  4548. /* Called after fork(), in child */
  4549. /* jp and n are NULL when called by openhere() for heredoc support */
  4550. static NOINLINE void
  4551. forkchild(struct job *jp, union node *n, int mode)
  4552. {
  4553. int oldlvl;
  4554. TRACE(("Child shell %d\n", getpid()));
  4555. oldlvl = shlvl;
  4556. shlvl++;
  4557. /* man bash: "Non-builtin commands run by bash have signal handlers
  4558. * set to the values inherited by the shell from its parent".
  4559. * Do we do it correctly? */
  4560. closescript();
  4561. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4562. && n && n->type == NCMD /* is it single cmd? */
  4563. /* && n->ncmd.args->type == NARG - always true? */
  4564. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4565. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4566. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4567. ) {
  4568. TRACE(("Trap hack\n"));
  4569. /* Awful hack for `trap` or $(trap).
  4570. *
  4571. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4572. * contains an example where "trap" is executed in a subshell:
  4573. *
  4574. * save_traps=$(trap)
  4575. * ...
  4576. * eval "$save_traps"
  4577. *
  4578. * Standard does not say that "trap" in subshell shall print
  4579. * parent shell's traps. It only says that its output
  4580. * must have suitable form, but then, in the above example
  4581. * (which is not supposed to be normative), it implies that.
  4582. *
  4583. * bash (and probably other shell) does implement it
  4584. * (traps are reset to defaults, but "trap" still shows them),
  4585. * but as a result, "trap" logic is hopelessly messed up:
  4586. *
  4587. * # trap
  4588. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4589. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4590. * # true | trap <--- trap is in subshell - no output (ditto)
  4591. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4592. * trap -- 'echo Ho' SIGWINCH
  4593. * # echo `(trap)` <--- in subshell in subshell - output
  4594. * trap -- 'echo Ho' SIGWINCH
  4595. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4596. * trap -- 'echo Ho' SIGWINCH
  4597. *
  4598. * The rules when to forget and when to not forget traps
  4599. * get really complex and nonsensical.
  4600. *
  4601. * Our solution: ONLY bare $(trap) or `trap` is special.
  4602. */
  4603. /* Save trap handler strings for trap builtin to print */
  4604. trap_ptr = xmemdup(trap, sizeof(trap));
  4605. /* Fall through into clearing traps */
  4606. }
  4607. clear_traps();
  4608. #if JOBS
  4609. /* do job control only in root shell */
  4610. doing_jobctl = 0;
  4611. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4612. pid_t pgrp;
  4613. if (jp->nprocs == 0)
  4614. pgrp = getpid();
  4615. else
  4616. pgrp = jp->ps[0].ps_pid;
  4617. /* this can fail because we are doing it in the parent also */
  4618. setpgid(0, pgrp);
  4619. if (mode == FORK_FG)
  4620. xtcsetpgrp(ttyfd, pgrp);
  4621. setsignal(SIGTSTP);
  4622. setsignal(SIGTTOU);
  4623. } else
  4624. #endif
  4625. if (mode == FORK_BG) {
  4626. /* man bash: "When job control is not in effect,
  4627. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4628. ignoresig(SIGINT);
  4629. ignoresig(SIGQUIT);
  4630. if (jp->nprocs == 0) {
  4631. close(0);
  4632. if (open(bb_dev_null, O_RDONLY) != 0)
  4633. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4634. }
  4635. }
  4636. if (oldlvl == 0) {
  4637. if (iflag) { /* why if iflag only? */
  4638. setsignal(SIGINT);
  4639. setsignal(SIGTERM);
  4640. }
  4641. /* man bash:
  4642. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4643. * commands run by bash have signal handlers
  4644. * set to the values inherited by the shell
  4645. * from its parent".
  4646. * Take care of the second rule: */
  4647. setsignal(SIGQUIT);
  4648. }
  4649. #if JOBS
  4650. if (n && n->type == NCMD
  4651. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4652. ) {
  4653. TRACE(("Job hack\n"));
  4654. /* "jobs": we do not want to clear job list for it,
  4655. * instead we remove only _its_ own_ job from job list.
  4656. * This makes "jobs .... | cat" more useful.
  4657. */
  4658. freejob(curjob);
  4659. return;
  4660. }
  4661. #endif
  4662. for (jp = curjob; jp; jp = jp->prev_job)
  4663. freejob(jp);
  4664. jobless = 0;
  4665. }
  4666. /* Called after fork(), in parent */
  4667. #if !JOBS
  4668. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4669. #endif
  4670. static void
  4671. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4672. {
  4673. TRACE(("In parent shell: child = %d\n", pid));
  4674. if (!jp) {
  4675. /* jp is NULL when called by openhere() for heredoc support */
  4676. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4677. continue;
  4678. jobless++;
  4679. return;
  4680. }
  4681. #if JOBS
  4682. if (mode != FORK_NOJOB && jp->jobctl) {
  4683. int pgrp;
  4684. if (jp->nprocs == 0)
  4685. pgrp = pid;
  4686. else
  4687. pgrp = jp->ps[0].ps_pid;
  4688. /* This can fail because we are doing it in the child also */
  4689. setpgid(pid, pgrp);
  4690. }
  4691. #endif
  4692. if (mode == FORK_BG) {
  4693. backgndpid = pid; /* set $! */
  4694. set_curjob(jp, CUR_RUNNING);
  4695. }
  4696. if (jp) {
  4697. struct procstat *ps = &jp->ps[jp->nprocs++];
  4698. ps->ps_pid = pid;
  4699. ps->ps_status = -1;
  4700. ps->ps_cmd = nullstr;
  4701. #if JOBS
  4702. if (doing_jobctl && n)
  4703. ps->ps_cmd = commandtext(n);
  4704. #endif
  4705. }
  4706. }
  4707. /* jp and n are NULL when called by openhere() for heredoc support */
  4708. static int
  4709. forkshell(struct job *jp, union node *n, int mode)
  4710. {
  4711. int pid;
  4712. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4713. pid = fork();
  4714. if (pid < 0) {
  4715. TRACE(("Fork failed, errno=%d", errno));
  4716. if (jp)
  4717. freejob(jp);
  4718. ash_msg_and_raise_perror("can't fork");
  4719. }
  4720. if (pid == 0) {
  4721. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4722. forkchild(jp, n, mode);
  4723. } else {
  4724. forkparent(jp, n, mode, pid);
  4725. }
  4726. return pid;
  4727. }
  4728. /*
  4729. * Wait for job to finish.
  4730. *
  4731. * Under job control we have the problem that while a child process
  4732. * is running interrupts generated by the user are sent to the child
  4733. * but not to the shell. This means that an infinite loop started by
  4734. * an interactive user may be hard to kill. With job control turned off,
  4735. * an interactive user may place an interactive program inside a loop.
  4736. * If the interactive program catches interrupts, the user doesn't want
  4737. * these interrupts to also abort the loop. The approach we take here
  4738. * is to have the shell ignore interrupt signals while waiting for a
  4739. * foreground process to terminate, and then send itself an interrupt
  4740. * signal if the child process was terminated by an interrupt signal.
  4741. * Unfortunately, some programs want to do a bit of cleanup and then
  4742. * exit on interrupt; unless these processes terminate themselves by
  4743. * sending a signal to themselves (instead of calling exit) they will
  4744. * confuse this approach.
  4745. *
  4746. * Called with interrupts off.
  4747. */
  4748. static int
  4749. waitforjob(struct job *jp)
  4750. {
  4751. int st;
  4752. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4753. INT_OFF;
  4754. while (jp->state == JOBRUNNING) {
  4755. /* In non-interactive shells, we _can_ get
  4756. * a keyboard signal here and be EINTRed,
  4757. * but we just loop back, waiting for command to complete.
  4758. *
  4759. * man bash:
  4760. * "If bash is waiting for a command to complete and receives
  4761. * a signal for which a trap has been set, the trap
  4762. * will not be executed until the command completes."
  4763. *
  4764. * Reality is that even if trap is not set, bash
  4765. * will not act on the signal until command completes.
  4766. * Try this. sleep5intoff.c:
  4767. * #include <signal.h>
  4768. * #include <unistd.h>
  4769. * int main() {
  4770. * sigset_t set;
  4771. * sigemptyset(&set);
  4772. * sigaddset(&set, SIGINT);
  4773. * sigaddset(&set, SIGQUIT);
  4774. * sigprocmask(SIG_BLOCK, &set, NULL);
  4775. * sleep(5);
  4776. * return 0;
  4777. * }
  4778. * $ bash -c './sleep5intoff; echo hi'
  4779. * ^C^C^C^C <--- pressing ^C once a second
  4780. * $ _
  4781. * $ bash -c './sleep5intoff; echo hi'
  4782. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4783. * $ _
  4784. */
  4785. dowait(DOWAIT_BLOCK, jp);
  4786. }
  4787. INT_ON;
  4788. st = getstatus(jp);
  4789. #if JOBS
  4790. if (jp->jobctl) {
  4791. xtcsetpgrp(ttyfd, rootpid);
  4792. restore_tty_if_stopped_or_signaled(jp);
  4793. /*
  4794. * This is truly gross.
  4795. * If we're doing job control, then we did a TIOCSPGRP which
  4796. * caused us (the shell) to no longer be in the controlling
  4797. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4798. * intuit from the subprocess exit status whether a SIGINT
  4799. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4800. */
  4801. if (jp->sigint) /* TODO: do the same with all signals */
  4802. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4803. }
  4804. if (jp->state == JOBDONE)
  4805. #endif
  4806. freejob(jp);
  4807. return st;
  4808. }
  4809. /*
  4810. * return 1 if there are stopped jobs, otherwise 0
  4811. */
  4812. static int
  4813. stoppedjobs(void)
  4814. {
  4815. struct job *jp;
  4816. int retval;
  4817. retval = 0;
  4818. if (job_warning)
  4819. goto out;
  4820. jp = curjob;
  4821. if (jp && jp->state == JOBSTOPPED) {
  4822. out2str("You have stopped jobs.\n");
  4823. job_warning = 2;
  4824. retval++;
  4825. }
  4826. out:
  4827. return retval;
  4828. }
  4829. /*
  4830. * Code for dealing with input/output redirection.
  4831. */
  4832. #undef EMPTY
  4833. #undef CLOSED
  4834. #define EMPTY -2 /* marks an unused slot in redirtab */
  4835. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4836. /*
  4837. * Handle here documents. Normally we fork off a process to write the
  4838. * data to a pipe. If the document is short, we can stuff the data in
  4839. * the pipe without forking.
  4840. */
  4841. /* openhere needs this forward reference */
  4842. static void expandhere(union node *arg, int fd);
  4843. static int
  4844. openhere(union node *redir)
  4845. {
  4846. int pip[2];
  4847. size_t len = 0;
  4848. if (pipe(pip) < 0)
  4849. ash_msg_and_raise_perror("can't create pipe");
  4850. if (redir->type == NHERE) {
  4851. len = strlen(redir->nhere.doc->narg.text);
  4852. if (len <= PIPE_BUF) {
  4853. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4854. goto out;
  4855. }
  4856. }
  4857. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4858. /* child */
  4859. close(pip[0]);
  4860. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4861. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4862. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4863. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4864. signal(SIGPIPE, SIG_DFL);
  4865. if (redir->type == NHERE)
  4866. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4867. else /* NXHERE */
  4868. expandhere(redir->nhere.doc, pip[1]);
  4869. _exit(EXIT_SUCCESS);
  4870. }
  4871. out:
  4872. close(pip[1]);
  4873. return pip[0];
  4874. }
  4875. static int
  4876. openredirect(union node *redir)
  4877. {
  4878. struct stat sb;
  4879. char *fname;
  4880. int f;
  4881. switch (redir->nfile.type) {
  4882. /* Can't happen, our single caller does this itself */
  4883. // case NTOFD:
  4884. // case NFROMFD:
  4885. // return -1;
  4886. case NHERE:
  4887. case NXHERE:
  4888. return openhere(redir);
  4889. }
  4890. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4891. * allocated space. Do it only when we know it is safe.
  4892. */
  4893. fname = redir->nfile.expfname;
  4894. switch (redir->nfile.type) {
  4895. default:
  4896. #if DEBUG
  4897. abort();
  4898. #endif
  4899. case NFROM:
  4900. f = open(fname, O_RDONLY);
  4901. if (f < 0)
  4902. goto eopen;
  4903. break;
  4904. case NFROMTO:
  4905. f = open(fname, O_RDWR|O_CREAT, 0666);
  4906. if (f < 0)
  4907. goto ecreate;
  4908. break;
  4909. case NTO:
  4910. #if BASH_REDIR_OUTPUT
  4911. case NTO2:
  4912. #endif
  4913. /* Take care of noclobber mode. */
  4914. if (Cflag) {
  4915. if (stat(fname, &sb) < 0) {
  4916. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4917. if (f < 0)
  4918. goto ecreate;
  4919. } else if (!S_ISREG(sb.st_mode)) {
  4920. f = open(fname, O_WRONLY, 0666);
  4921. if (f < 0)
  4922. goto ecreate;
  4923. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  4924. close(f);
  4925. errno = EEXIST;
  4926. goto ecreate;
  4927. }
  4928. } else {
  4929. errno = EEXIST;
  4930. goto ecreate;
  4931. }
  4932. break;
  4933. }
  4934. /* FALLTHROUGH */
  4935. case NCLOBBER:
  4936. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4937. if (f < 0)
  4938. goto ecreate;
  4939. break;
  4940. case NAPPEND:
  4941. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4942. if (f < 0)
  4943. goto ecreate;
  4944. break;
  4945. }
  4946. return f;
  4947. ecreate:
  4948. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4949. eopen:
  4950. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4951. }
  4952. /*
  4953. * Copy a file descriptor to be >= 10. Throws exception on error.
  4954. */
  4955. static int
  4956. savefd(int from)
  4957. {
  4958. int newfd;
  4959. int err;
  4960. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  4961. err = newfd < 0 ? errno : 0;
  4962. if (err != EBADF) {
  4963. if (err)
  4964. ash_msg_and_raise_perror("%d", from);
  4965. close(from);
  4966. if (F_DUPFD_CLOEXEC == F_DUPFD)
  4967. close_on_exec_on(newfd);
  4968. }
  4969. return newfd;
  4970. }
  4971. static int
  4972. dup2_or_raise(int from, int to)
  4973. {
  4974. int newfd;
  4975. newfd = (from != to) ? dup2(from, to) : to;
  4976. if (newfd < 0) {
  4977. /* Happens when source fd is not open: try "echo >&99" */
  4978. ash_msg_and_raise_perror("%d", from);
  4979. }
  4980. return newfd;
  4981. }
  4982. static int
  4983. dup_CLOEXEC(int fd, int avoid_fd)
  4984. {
  4985. int newfd;
  4986. repeat:
  4987. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  4988. if (newfd >= 0) {
  4989. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  4990. close_on_exec_on(newfd);
  4991. } else { /* newfd < 0 */
  4992. if (errno == EBUSY)
  4993. goto repeat;
  4994. if (errno == EINTR)
  4995. goto repeat;
  4996. }
  4997. return newfd;
  4998. }
  4999. static int
  5000. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5001. {
  5002. int newfd;
  5003. repeat:
  5004. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5005. if (newfd < 0) {
  5006. if (errno == EBUSY)
  5007. goto repeat;
  5008. if (errno == EINTR)
  5009. goto repeat;
  5010. /* fd was not open? */
  5011. if (errno == EBADF)
  5012. return fd;
  5013. ash_msg_and_raise_perror("%d", newfd);
  5014. }
  5015. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5016. close_on_exec_on(newfd);
  5017. close(fd);
  5018. return newfd;
  5019. }
  5020. /* Struct def and variable are moved down to the first usage site */
  5021. struct squirrel {
  5022. int orig_fd;
  5023. int moved_to;
  5024. };
  5025. struct redirtab {
  5026. struct redirtab *next;
  5027. int pair_count;
  5028. struct squirrel two_fd[];
  5029. };
  5030. #define redirlist (G_var.redirlist)
  5031. static void
  5032. add_squirrel_closed(struct redirtab *sq, int fd)
  5033. {
  5034. int i;
  5035. if (!sq)
  5036. return;
  5037. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5038. /* If we collide with an already moved fd... */
  5039. if (fd == sq->two_fd[i].orig_fd) {
  5040. /* Examples:
  5041. * "echo 3>FILE 3>&- 3>FILE"
  5042. * "echo 3>&- 3>FILE"
  5043. * No need for last redirect to insert
  5044. * another "need to close 3" indicator.
  5045. */
  5046. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5047. return;
  5048. }
  5049. }
  5050. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5051. sq->two_fd[i].orig_fd = fd;
  5052. sq->two_fd[i].moved_to = CLOSED;
  5053. }
  5054. static int
  5055. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5056. {
  5057. int i, new_fd;
  5058. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5059. avoid_fd = 9;
  5060. #if JOBS
  5061. if (fd == ttyfd) {
  5062. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5063. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5064. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5065. return 1; /* "we closed fd" */
  5066. }
  5067. #endif
  5068. /* Are we called from redirect(0)? E.g. redirect
  5069. * in a forked child. No need to save fds,
  5070. * we aren't going to use them anymore, ok to trash.
  5071. */
  5072. if (!sq)
  5073. return 0;
  5074. /* If this one of script's fds? */
  5075. if (fd != 0) {
  5076. struct parsefile *pf = g_parsefile;
  5077. while (pf) {
  5078. /* We skip fd == 0 case because of the following:
  5079. * $ ash # running ash interactively
  5080. * $ . ./script.sh
  5081. * and in script.sh: "exec 9>&0".
  5082. * Even though top-level pf_fd _is_ 0,
  5083. * it's still ok to use it: "read" builtin uses it,
  5084. * why should we cripple "exec" builtin?
  5085. */
  5086. if (fd == pf->pf_fd) {
  5087. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5088. return 1; /* "we closed fd" */
  5089. }
  5090. pf = pf->prev;
  5091. }
  5092. }
  5093. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5094. /* First: do we collide with some already moved fds? */
  5095. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5096. /* If we collide with an already moved fd... */
  5097. if (fd == sq->two_fd[i].moved_to) {
  5098. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5099. sq->two_fd[i].moved_to = new_fd;
  5100. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5101. if (new_fd < 0) /* what? */
  5102. xfunc_die();
  5103. return 0; /* "we did not close fd" */
  5104. }
  5105. if (fd == sq->two_fd[i].orig_fd) {
  5106. /* Example: echo Hello >/dev/null 1>&2 */
  5107. TRACE(("redirect_fd %d: already moved\n", fd));
  5108. return 0; /* "we did not close fd" */
  5109. }
  5110. }
  5111. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5112. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5113. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5114. if (new_fd < 0) {
  5115. if (errno != EBADF)
  5116. xfunc_die();
  5117. /* new_fd = CLOSED; - already is -1 */
  5118. }
  5119. sq->two_fd[i].moved_to = new_fd;
  5120. sq->two_fd[i].orig_fd = fd;
  5121. /* if we move stderr, let "set -x" code know */
  5122. if (fd == preverrout_fd)
  5123. preverrout_fd = new_fd;
  5124. return 0; /* "we did not close fd" */
  5125. }
  5126. static int
  5127. internally_opened_fd(int fd, struct redirtab *sq)
  5128. {
  5129. int i;
  5130. #if JOBS
  5131. if (fd == ttyfd)
  5132. return 1;
  5133. #endif
  5134. /* If this one of script's fds? */
  5135. if (fd != 0) {
  5136. struct parsefile *pf = g_parsefile;
  5137. while (pf) {
  5138. if (fd == pf->pf_fd)
  5139. return 1;
  5140. pf = pf->prev;
  5141. }
  5142. }
  5143. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5144. if (fd == sq->two_fd[i].moved_to)
  5145. return 1;
  5146. }
  5147. return 0;
  5148. }
  5149. /*
  5150. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5151. * old file descriptors are stashed away so that the redirection can be
  5152. * undone by calling popredir.
  5153. */
  5154. /* flags passed to redirect */
  5155. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5156. static void
  5157. redirect(union node *redir, int flags)
  5158. {
  5159. struct redirtab *sv;
  5160. if (!redir)
  5161. return;
  5162. sv = NULL;
  5163. INT_OFF;
  5164. if (flags & REDIR_PUSH)
  5165. sv = redirlist;
  5166. do {
  5167. int fd;
  5168. int newfd;
  5169. int close_fd;
  5170. int closed;
  5171. fd = redir->nfile.fd;
  5172. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5173. //bb_error_msg("doing %d > %d", fd, newfd);
  5174. newfd = redir->ndup.dupfd;
  5175. close_fd = -1;
  5176. } else {
  5177. newfd = openredirect(redir); /* always >= 0 */
  5178. if (fd == newfd) {
  5179. /* open() gave us precisely the fd we wanted.
  5180. * This means that this fd was not busy
  5181. * (not opened to anywhere).
  5182. * Remember to close it on restore:
  5183. */
  5184. add_squirrel_closed(sv, fd);
  5185. continue;
  5186. }
  5187. close_fd = newfd;
  5188. }
  5189. if (fd == newfd)
  5190. continue;
  5191. /* if "N>FILE": move newfd to fd */
  5192. /* if "N>&M": dup newfd to fd */
  5193. /* if "N>&-": close fd (newfd is -1) */
  5194. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5195. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5196. if (newfd == -1) {
  5197. /* "N>&-" means "close me" */
  5198. if (!closed) {
  5199. /* ^^^ optimization: saving may already
  5200. * have closed it. If not... */
  5201. close(fd);
  5202. }
  5203. } else {
  5204. /* if newfd is a script fd or saved fd, simulate EBADF */
  5205. if (internally_opened_fd(newfd, sv)) {
  5206. errno = EBADF;
  5207. ash_msg_and_raise_perror("%d", newfd);
  5208. }
  5209. dup2_or_raise(newfd, fd);
  5210. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5211. close(close_fd);
  5212. #if BASH_REDIR_OUTPUT
  5213. if (redir->nfile.type == NTO2 && fd == 1) {
  5214. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5215. fd = 2;
  5216. newfd = 1;
  5217. close_fd = -1;
  5218. goto redirect_more;
  5219. }
  5220. #endif
  5221. }
  5222. } while ((redir = redir->nfile.next) != NULL);
  5223. INT_ON;
  5224. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5225. #define REDIR_SAVEFD2 0
  5226. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5227. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5228. // not only for calls with flags containing REDIR_SAVEFD2.
  5229. // We do this unconditionally (see save_fd_on_redirect()).
  5230. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5231. // preverrout_fd = copied_fd2;
  5232. }
  5233. static int
  5234. redirectsafe(union node *redir, int flags)
  5235. {
  5236. int err;
  5237. volatile int saveint;
  5238. struct jmploc *volatile savehandler = exception_handler;
  5239. struct jmploc jmploc;
  5240. SAVE_INT(saveint);
  5241. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5242. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5243. if (!err) {
  5244. exception_handler = &jmploc;
  5245. redirect(redir, flags);
  5246. }
  5247. exception_handler = savehandler;
  5248. if (err && exception_type != EXERROR)
  5249. longjmp(exception_handler->loc, 1);
  5250. RESTORE_INT(saveint);
  5251. return err;
  5252. }
  5253. static struct redirtab*
  5254. pushredir(union node *redir)
  5255. {
  5256. struct redirtab *sv;
  5257. int i;
  5258. if (!redir)
  5259. return redirlist;
  5260. i = 0;
  5261. do {
  5262. i++;
  5263. #if BASH_REDIR_OUTPUT
  5264. if (redir->nfile.type == NTO2)
  5265. i++;
  5266. #endif
  5267. redir = redir->nfile.next;
  5268. } while (redir);
  5269. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5270. sv->pair_count = i;
  5271. while (--i >= 0)
  5272. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5273. sv->next = redirlist;
  5274. redirlist = sv;
  5275. return sv->next;
  5276. }
  5277. /*
  5278. * Undo the effects of the last redirection.
  5279. */
  5280. static void
  5281. popredir(int drop)
  5282. {
  5283. struct redirtab *rp;
  5284. int i;
  5285. if (redirlist == NULL)
  5286. return;
  5287. INT_OFF;
  5288. rp = redirlist;
  5289. for (i = 0; i < rp->pair_count; i++) {
  5290. int fd = rp->two_fd[i].orig_fd;
  5291. int copy = rp->two_fd[i].moved_to;
  5292. if (copy == CLOSED) {
  5293. if (!drop)
  5294. close(fd);
  5295. continue;
  5296. }
  5297. if (copy != EMPTY) {
  5298. if (!drop) {
  5299. /*close(fd);*/
  5300. dup2_or_raise(copy, fd);
  5301. }
  5302. close(copy);
  5303. }
  5304. }
  5305. redirlist = rp->next;
  5306. free(rp);
  5307. INT_ON;
  5308. }
  5309. static void
  5310. unwindredir(struct redirtab *stop)
  5311. {
  5312. while (redirlist != stop)
  5313. popredir(/*drop:*/ 0);
  5314. }
  5315. /* ============ Routines to expand arguments to commands
  5316. *
  5317. * We have to deal with backquotes, shell variables, and file metacharacters.
  5318. */
  5319. #if ENABLE_FEATURE_SH_MATH
  5320. static arith_t
  5321. ash_arith(const char *s)
  5322. {
  5323. arith_state_t math_state;
  5324. arith_t result;
  5325. math_state.lookupvar = lookupvar;
  5326. math_state.setvar = setvar0;
  5327. //math_state.endofname = endofname;
  5328. INT_OFF;
  5329. result = arith(&math_state, s);
  5330. if (math_state.errmsg)
  5331. ash_msg_and_raise_error(math_state.errmsg);
  5332. INT_ON;
  5333. return result;
  5334. }
  5335. #endif
  5336. #if BASH_SUBSTR
  5337. # if ENABLE_FEATURE_SH_MATH
  5338. static int substr_atoi(const char *s)
  5339. {
  5340. arith_t t = ash_arith(s);
  5341. if (sizeof(t) > sizeof(int)) {
  5342. /* clamp very large or very large negative nums for ${v:N:M}:
  5343. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5344. */
  5345. if (t > INT_MAX)
  5346. t = INT_MAX;
  5347. if (t < INT_MIN)
  5348. t = INT_MIN;
  5349. }
  5350. return t;
  5351. }
  5352. # else
  5353. # define substr_atoi(s) number(s)
  5354. # endif
  5355. #endif
  5356. /*
  5357. * expandarg flags
  5358. */
  5359. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5360. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5361. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5362. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5363. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5364. * POSIX says for this case:
  5365. * Pathname expansion shall not be performed on the word by a
  5366. * non-interactive shell; an interactive shell may perform it, but shall
  5367. * do so only when the expansion would result in one word.
  5368. * Currently, our code complies to the above rule by never globbing
  5369. * redirection filenames.
  5370. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5371. * (this means that on a typical Linux distro, bash almost always
  5372. * performs globbing, and thus diverges from what we do).
  5373. */
  5374. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5375. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5376. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5377. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5378. /*
  5379. * rmescape() flags
  5380. */
  5381. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5382. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5383. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5384. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5385. /* Add CTLESC when necessary. */
  5386. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5387. /* Do not skip NUL characters. */
  5388. #define QUOTES_KEEPNUL EXP_TILDE
  5389. /*
  5390. * Structure specifying which parts of the string should be searched
  5391. * for IFS characters.
  5392. */
  5393. struct ifsregion {
  5394. struct ifsregion *next; /* next region in list */
  5395. int begoff; /* offset of start of region */
  5396. int endoff; /* offset of end of region */
  5397. int nulonly; /* search for nul bytes only */
  5398. };
  5399. struct arglist {
  5400. struct strlist *list;
  5401. struct strlist **lastp;
  5402. };
  5403. /* output of current string */
  5404. static char *expdest;
  5405. /* list of back quote expressions */
  5406. static struct nodelist *argbackq;
  5407. /* first struct in list of ifs regions */
  5408. static struct ifsregion ifsfirst;
  5409. /* last struct in list */
  5410. static struct ifsregion *ifslastp;
  5411. /* holds expanded arg list */
  5412. static struct arglist exparg;
  5413. /*
  5414. * Our own itoa().
  5415. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5416. */
  5417. static int
  5418. cvtnum(arith_t num)
  5419. {
  5420. int len;
  5421. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5422. len = sizeof(arith_t) * 3;
  5423. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5424. if (sizeof(arith_t) < 4) len += 2;
  5425. expdest = makestrspace(len, expdest);
  5426. len = fmtstr(expdest, len, ARITH_FMT, num);
  5427. STADJUST(len, expdest);
  5428. return len;
  5429. }
  5430. /*
  5431. * Break the argument string into pieces based upon IFS and add the
  5432. * strings to the argument list. The regions of the string to be
  5433. * searched for IFS characters have been stored by recordregion.
  5434. */
  5435. static void
  5436. ifsbreakup(char *string, struct arglist *arglist)
  5437. {
  5438. struct ifsregion *ifsp;
  5439. struct strlist *sp;
  5440. char *start;
  5441. char *p;
  5442. char *q;
  5443. const char *ifs, *realifs;
  5444. int ifsspc;
  5445. int nulonly;
  5446. start = string;
  5447. if (ifslastp != NULL) {
  5448. ifsspc = 0;
  5449. nulonly = 0;
  5450. realifs = ifsset() ? ifsval() : defifs;
  5451. ifsp = &ifsfirst;
  5452. do {
  5453. int afternul;
  5454. p = string + ifsp->begoff;
  5455. afternul = nulonly;
  5456. nulonly = ifsp->nulonly;
  5457. ifs = nulonly ? nullstr : realifs;
  5458. ifsspc = 0;
  5459. while (p < string + ifsp->endoff) {
  5460. q = p;
  5461. if ((unsigned char)*p == CTLESC)
  5462. p++;
  5463. if (!strchr(ifs, *p)) {
  5464. p++;
  5465. continue;
  5466. }
  5467. if (!(afternul || nulonly))
  5468. ifsspc = (strchr(defifs, *p) != NULL);
  5469. /* Ignore IFS whitespace at start */
  5470. if (q == start && ifsspc) {
  5471. p++;
  5472. start = p;
  5473. continue;
  5474. }
  5475. *q = '\0';
  5476. sp = stzalloc(sizeof(*sp));
  5477. sp->text = start;
  5478. *arglist->lastp = sp;
  5479. arglist->lastp = &sp->next;
  5480. p++;
  5481. if (!nulonly) {
  5482. for (;;) {
  5483. if (p >= string + ifsp->endoff) {
  5484. break;
  5485. }
  5486. q = p;
  5487. if ((unsigned char)*p == CTLESC)
  5488. p++;
  5489. if (strchr(ifs, *p) == NULL) {
  5490. p = q;
  5491. break;
  5492. }
  5493. if (strchr(defifs, *p) == NULL) {
  5494. if (ifsspc) {
  5495. p++;
  5496. ifsspc = 0;
  5497. } else {
  5498. p = q;
  5499. break;
  5500. }
  5501. } else
  5502. p++;
  5503. }
  5504. }
  5505. start = p;
  5506. } /* while */
  5507. ifsp = ifsp->next;
  5508. } while (ifsp != NULL);
  5509. if (nulonly)
  5510. goto add;
  5511. }
  5512. if (!*start)
  5513. return;
  5514. add:
  5515. sp = stzalloc(sizeof(*sp));
  5516. sp->text = start;
  5517. *arglist->lastp = sp;
  5518. arglist->lastp = &sp->next;
  5519. }
  5520. static void
  5521. ifsfree(void)
  5522. {
  5523. struct ifsregion *p = ifsfirst.next;
  5524. if (!p)
  5525. goto out;
  5526. INT_OFF;
  5527. do {
  5528. struct ifsregion *ifsp;
  5529. ifsp = p->next;
  5530. free(p);
  5531. p = ifsp;
  5532. } while (p);
  5533. ifsfirst.next = NULL;
  5534. INT_ON;
  5535. out:
  5536. ifslastp = NULL;
  5537. }
  5538. static size_t
  5539. esclen(const char *start, const char *p)
  5540. {
  5541. size_t esc = 0;
  5542. while (p > start && (unsigned char)*--p == CTLESC) {
  5543. esc++;
  5544. }
  5545. return esc;
  5546. }
  5547. /*
  5548. * Remove any CTLESC characters from a string.
  5549. */
  5550. #if !BASH_PATTERN_SUBST
  5551. #define rmescapes(str, flag, slash_position) \
  5552. rmescapes(str, flag)
  5553. #endif
  5554. static char *
  5555. rmescapes(char *str, int flag, int *slash_position)
  5556. {
  5557. static const char qchars[] ALIGN1 = {
  5558. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5559. char *p, *q, *r;
  5560. unsigned protect_against_glob;
  5561. unsigned globbing;
  5562. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5563. if (!p)
  5564. return str;
  5565. q = p;
  5566. r = str;
  5567. if (flag & RMESCAPE_ALLOC) {
  5568. size_t len = p - str;
  5569. size_t fulllen = len + strlen(p) + 1;
  5570. if (flag & RMESCAPE_GROW) {
  5571. int strloc = str - (char *)stackblock();
  5572. r = makestrspace(fulllen, expdest);
  5573. /* p and str may be invalidated by makestrspace */
  5574. str = (char *)stackblock() + strloc;
  5575. p = str + len;
  5576. } else if (flag & RMESCAPE_HEAP) {
  5577. r = ckmalloc(fulllen);
  5578. } else {
  5579. r = stalloc(fulllen);
  5580. }
  5581. q = r;
  5582. if (len > 0) {
  5583. q = (char *)mempcpy(q, str, len);
  5584. }
  5585. }
  5586. globbing = flag & RMESCAPE_GLOB;
  5587. protect_against_glob = globbing;
  5588. while (*p) {
  5589. if ((unsigned char)*p == CTLQUOTEMARK) {
  5590. // Note: protect_against_glob only affect whether
  5591. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5592. p++;
  5593. protect_against_glob = globbing;
  5594. continue;
  5595. }
  5596. if (*p == '\\') {
  5597. /* naked back slash */
  5598. protect_against_glob = 0;
  5599. goto copy;
  5600. }
  5601. if ((unsigned char)*p == CTLESC) {
  5602. p++;
  5603. #if DEBUG
  5604. if (*p == '\0')
  5605. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5606. #endif
  5607. if (protect_against_glob) {
  5608. /*
  5609. * We used to trust glob() and fnmatch() to eat
  5610. * superfluous escapes (\z where z has no
  5611. * special meaning anyway). But this causes
  5612. * bugs such as string of one greek letter rho
  5613. * (unicode-encoded as two bytes "cf,81")
  5614. * getting encoded as "cf,CTLESC,81"
  5615. * and here, converted to "cf,\,81" -
  5616. * which does not go well with some flavors
  5617. * of fnmatch() in unicode locales
  5618. * (for example, glibc <= 2.22).
  5619. *
  5620. * Lets add "\" only on the chars which need it.
  5621. * Testcases for less obvious chars are shown.
  5622. */
  5623. if (*p == '*'
  5624. || *p == '?'
  5625. || *p == '['
  5626. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5627. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5628. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5629. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5630. /* Some libc support [^negate], that's why "^" also needs love */
  5631. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5632. ) {
  5633. *q++ = '\\';
  5634. }
  5635. }
  5636. }
  5637. #if BASH_PATTERN_SUBST
  5638. else if (slash_position && p == str + *slash_position) {
  5639. /* stop handling globbing */
  5640. globbing = 0;
  5641. *slash_position = q - r;
  5642. slash_position = NULL;
  5643. }
  5644. #endif
  5645. protect_against_glob = globbing;
  5646. copy:
  5647. *q++ = *p++;
  5648. }
  5649. *q = '\0';
  5650. if (flag & RMESCAPE_GROW) {
  5651. expdest = r;
  5652. STADJUST(q - r + 1, expdest);
  5653. }
  5654. return r;
  5655. }
  5656. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5657. /*
  5658. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5659. *
  5660. * Returns an stalloced string.
  5661. */
  5662. static char *
  5663. preglob(const char *pattern, int flag)
  5664. {
  5665. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5666. }
  5667. /*
  5668. * Put a string on the stack.
  5669. */
  5670. static void
  5671. memtodest(const char *p, size_t len, int syntax, int quotes)
  5672. {
  5673. char *q;
  5674. if (!len)
  5675. return;
  5676. q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
  5677. do {
  5678. unsigned char c = *p++;
  5679. if (c) {
  5680. if (quotes & QUOTES_ESC) {
  5681. int n = SIT(c, syntax);
  5682. if (n == CCTL
  5683. || (syntax != BASESYNTAX && n == CBACK)
  5684. ) {
  5685. USTPUTC(CTLESC, q);
  5686. }
  5687. }
  5688. } else if (!(quotes & QUOTES_KEEPNUL))
  5689. continue;
  5690. USTPUTC(c, q);
  5691. } while (--len);
  5692. expdest = q;
  5693. }
  5694. static size_t
  5695. strtodest(const char *p, int syntax, int quotes)
  5696. {
  5697. size_t len = strlen(p);
  5698. memtodest(p, len, syntax, quotes);
  5699. return len;
  5700. }
  5701. /*
  5702. * Record the fact that we have to scan this region of the
  5703. * string for IFS characters.
  5704. */
  5705. static void
  5706. recordregion(int start, int end, int nulonly)
  5707. {
  5708. struct ifsregion *ifsp;
  5709. if (ifslastp == NULL) {
  5710. ifsp = &ifsfirst;
  5711. } else {
  5712. INT_OFF;
  5713. ifsp = ckzalloc(sizeof(*ifsp));
  5714. /*ifsp->next = NULL; - ckzalloc did it */
  5715. ifslastp->next = ifsp;
  5716. INT_ON;
  5717. }
  5718. ifslastp = ifsp;
  5719. ifslastp->begoff = start;
  5720. ifslastp->endoff = end;
  5721. ifslastp->nulonly = nulonly;
  5722. }
  5723. static void
  5724. removerecordregions(int endoff)
  5725. {
  5726. if (ifslastp == NULL)
  5727. return;
  5728. if (ifsfirst.endoff > endoff) {
  5729. while (ifsfirst.next) {
  5730. struct ifsregion *ifsp;
  5731. INT_OFF;
  5732. ifsp = ifsfirst.next->next;
  5733. free(ifsfirst.next);
  5734. ifsfirst.next = ifsp;
  5735. INT_ON;
  5736. }
  5737. if (ifsfirst.begoff > endoff) {
  5738. ifslastp = NULL;
  5739. } else {
  5740. ifslastp = &ifsfirst;
  5741. ifsfirst.endoff = endoff;
  5742. }
  5743. return;
  5744. }
  5745. ifslastp = &ifsfirst;
  5746. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5747. ifslastp = ifslastp->next;
  5748. while (ifslastp->next) {
  5749. struct ifsregion *ifsp;
  5750. INT_OFF;
  5751. ifsp = ifslastp->next->next;
  5752. free(ifslastp->next);
  5753. ifslastp->next = ifsp;
  5754. INT_ON;
  5755. }
  5756. if (ifslastp->endoff > endoff)
  5757. ifslastp->endoff = endoff;
  5758. }
  5759. static char *
  5760. exptilde(char *startp, char *p, int flags)
  5761. {
  5762. unsigned char c;
  5763. char *name;
  5764. struct passwd *pw;
  5765. const char *home;
  5766. int quotes = flags & QUOTES_ESC;
  5767. name = p + 1;
  5768. while ((c = *++p) != '\0') {
  5769. switch (c) {
  5770. case CTLESC:
  5771. return startp;
  5772. case CTLQUOTEMARK:
  5773. return startp;
  5774. case ':':
  5775. if (flags & EXP_VARTILDE)
  5776. goto done;
  5777. break;
  5778. case '/':
  5779. case CTLENDVAR:
  5780. goto done;
  5781. }
  5782. }
  5783. done:
  5784. *p = '\0';
  5785. if (*name == '\0') {
  5786. home = lookupvar("HOME");
  5787. } else {
  5788. pw = getpwnam(name);
  5789. if (pw == NULL)
  5790. goto lose;
  5791. home = pw->pw_dir;
  5792. }
  5793. if (!home || !*home)
  5794. goto lose;
  5795. *p = c;
  5796. strtodest(home, SQSYNTAX, quotes);
  5797. return p;
  5798. lose:
  5799. *p = c;
  5800. return startp;
  5801. }
  5802. /*
  5803. * Execute a command inside back quotes. If it's a builtin command, we
  5804. * want to save its output in a block obtained from malloc. Otherwise
  5805. * we fork off a subprocess and get the output of the command via a pipe.
  5806. * Should be called with interrupts off.
  5807. */
  5808. struct backcmd { /* result of evalbackcmd */
  5809. int fd; /* file descriptor to read from */
  5810. int nleft; /* number of chars in buffer */
  5811. char *buf; /* buffer */
  5812. struct job *jp; /* job structure for command */
  5813. };
  5814. /* These forward decls are needed to use "eval" code for backticks handling: */
  5815. /* flags in argument to evaltree */
  5816. #define EV_EXIT 01 /* exit after evaluating tree */
  5817. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5818. static int evaltree(union node *, int);
  5819. /* An evaltree() which is known to never return.
  5820. * Used to use an alias:
  5821. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5822. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5823. */
  5824. static ALWAYS_INLINE NORETURN void
  5825. evaltreenr(union node *n, int flags)
  5826. {
  5827. evaltree(n, flags);
  5828. bb_unreachable(abort());
  5829. /* NOTREACHED */
  5830. }
  5831. static void FAST_FUNC
  5832. evalbackcmd(union node *n, struct backcmd *result)
  5833. {
  5834. int pip[2];
  5835. struct job *jp;
  5836. result->fd = -1;
  5837. result->buf = NULL;
  5838. result->nleft = 0;
  5839. result->jp = NULL;
  5840. if (n == NULL) {
  5841. goto out;
  5842. }
  5843. if (pipe(pip) < 0)
  5844. ash_msg_and_raise_perror("can't create pipe");
  5845. jp = makejob(/*n,*/ 1);
  5846. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5847. /* child */
  5848. FORCE_INT_ON;
  5849. close(pip[0]);
  5850. if (pip[1] != 1) {
  5851. /*close(1);*/
  5852. dup2_or_raise(pip[1], 1);
  5853. close(pip[1]);
  5854. }
  5855. /* TODO: eflag clearing makes the following not abort:
  5856. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5857. * which is what bash does (unless it is in POSIX mode).
  5858. * dash deleted "eflag = 0" line in the commit
  5859. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5860. * [EVAL] Don't clear eflag in evalbackcmd
  5861. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5862. */
  5863. eflag = 0;
  5864. ifsfree();
  5865. evaltreenr(n, EV_EXIT);
  5866. /* NOTREACHED */
  5867. }
  5868. /* parent */
  5869. close(pip[1]);
  5870. result->fd = pip[0];
  5871. result->jp = jp;
  5872. out:
  5873. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5874. result->fd, result->buf, result->nleft, result->jp));
  5875. }
  5876. /*
  5877. * Expand stuff in backwards quotes.
  5878. */
  5879. static void
  5880. expbackq(union node *cmd, int flag)
  5881. {
  5882. struct backcmd in;
  5883. int i;
  5884. char buf[128];
  5885. char *p;
  5886. char *dest;
  5887. int startloc;
  5888. int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5889. struct stackmark smark;
  5890. INT_OFF;
  5891. startloc = expdest - (char *)stackblock();
  5892. pushstackmark(&smark, startloc);
  5893. evalbackcmd(cmd, &in);
  5894. popstackmark(&smark);
  5895. p = in.buf;
  5896. i = in.nleft;
  5897. if (i == 0)
  5898. goto read;
  5899. for (;;) {
  5900. memtodest(p, i, syntax, flag & QUOTES_ESC);
  5901. read:
  5902. if (in.fd < 0)
  5903. break;
  5904. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  5905. TRACE(("expbackq: read returns %d\n", i));
  5906. if (i <= 0)
  5907. break;
  5908. p = buf;
  5909. }
  5910. free(in.buf);
  5911. if (in.fd >= 0) {
  5912. close(in.fd);
  5913. back_exitstatus = waitforjob(in.jp);
  5914. }
  5915. INT_ON;
  5916. /* Eat all trailing newlines */
  5917. dest = expdest;
  5918. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5919. STUNPUTC(dest);
  5920. expdest = dest;
  5921. if (!(flag & EXP_QUOTED))
  5922. recordregion(startloc, dest - (char *)stackblock(), 0);
  5923. TRACE(("evalbackq: size:%d:'%.*s'\n",
  5924. (int)((dest - (char *)stackblock()) - startloc),
  5925. (int)((dest - (char *)stackblock()) - startloc),
  5926. stackblock() + startloc));
  5927. }
  5928. #if ENABLE_FEATURE_SH_MATH
  5929. /*
  5930. * Expand arithmetic expression. Backup to start of expression,
  5931. * evaluate, place result in (backed up) result, adjust string position.
  5932. */
  5933. static void
  5934. expari(int flag)
  5935. {
  5936. char *p, *start;
  5937. int begoff;
  5938. int len;
  5939. /* ifsfree(); */
  5940. /*
  5941. * This routine is slightly over-complicated for
  5942. * efficiency. Next we scan backwards looking for the
  5943. * start of arithmetic.
  5944. */
  5945. start = stackblock();
  5946. p = expdest - 1;
  5947. *p = '\0';
  5948. p--;
  5949. while (1) {
  5950. int esc;
  5951. while ((unsigned char)*p != CTLARI) {
  5952. p--;
  5953. #if DEBUG
  5954. if (p < start) {
  5955. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5956. }
  5957. #endif
  5958. }
  5959. esc = esclen(start, p);
  5960. if (!(esc % 2)) {
  5961. break;
  5962. }
  5963. p -= esc + 1;
  5964. }
  5965. begoff = p - start;
  5966. removerecordregions(begoff);
  5967. expdest = p;
  5968. if (flag & QUOTES_ESC)
  5969. rmescapes(p + 1, 0, NULL);
  5970. len = cvtnum(ash_arith(p + 1));
  5971. if (!(flag & EXP_QUOTED))
  5972. recordregion(begoff, begoff + len, 0);
  5973. }
  5974. #endif
  5975. /* argstr needs it */
  5976. static char *evalvar(char *p, int flags);
  5977. /*
  5978. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5979. * characters to allow for further processing. Otherwise treat
  5980. * $@ like $* since no splitting will be performed.
  5981. */
  5982. static void
  5983. argstr(char *p, int flags)
  5984. {
  5985. static const char spclchars[] ALIGN1 = {
  5986. '=',
  5987. ':',
  5988. CTLQUOTEMARK,
  5989. CTLENDVAR,
  5990. CTLESC,
  5991. CTLVAR,
  5992. CTLBACKQ,
  5993. #if ENABLE_FEATURE_SH_MATH
  5994. CTLENDARI,
  5995. #endif
  5996. '\0'
  5997. };
  5998. const char *reject = spclchars;
  5999. int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6000. int inquotes;
  6001. size_t length;
  6002. int startloc;
  6003. if (!(flags & EXP_VARTILDE)) {
  6004. reject += 2;
  6005. } else if (flags & EXP_VARTILDE2) {
  6006. reject++;
  6007. }
  6008. inquotes = 0;
  6009. length = 0;
  6010. if (flags & EXP_TILDE) {
  6011. char *q;
  6012. flags &= ~EXP_TILDE;
  6013. tilde:
  6014. q = p;
  6015. if (*q == '~')
  6016. p = exptilde(p, q, flags);
  6017. }
  6018. start:
  6019. startloc = expdest - (char *)stackblock();
  6020. for (;;) {
  6021. unsigned char c;
  6022. length += strcspn(p + length, reject);
  6023. c = p[length];
  6024. if (c) {
  6025. if (!(c & 0x80)
  6026. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6027. ) {
  6028. /* c == '=' || c == ':' || c == CTLENDARI */
  6029. length++;
  6030. }
  6031. }
  6032. if (length > 0) {
  6033. int newloc;
  6034. expdest = stack_nputstr(p, length, expdest);
  6035. newloc = expdest - (char *)stackblock();
  6036. if (breakall && !inquotes && newloc > startloc) {
  6037. recordregion(startloc, newloc, 0);
  6038. }
  6039. startloc = newloc;
  6040. }
  6041. p += length + 1;
  6042. length = 0;
  6043. switch (c) {
  6044. case '\0':
  6045. goto breakloop;
  6046. case '=':
  6047. if (flags & EXP_VARTILDE2) {
  6048. p--;
  6049. continue;
  6050. }
  6051. flags |= EXP_VARTILDE2;
  6052. reject++;
  6053. /* fall through */
  6054. case ':':
  6055. /*
  6056. * sort of a hack - expand tildes in variable
  6057. * assignments (after the first '=' and after ':'s).
  6058. */
  6059. if (*--p == '~') {
  6060. goto tilde;
  6061. }
  6062. continue;
  6063. }
  6064. switch (c) {
  6065. case CTLENDVAR: /* ??? */
  6066. goto breakloop;
  6067. case CTLQUOTEMARK:
  6068. /* "$@" syntax adherence hack */
  6069. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6070. p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
  6071. goto start;
  6072. }
  6073. inquotes ^= EXP_QUOTED;
  6074. addquote:
  6075. if (flags & QUOTES_ESC) {
  6076. p--;
  6077. length++;
  6078. startloc++;
  6079. }
  6080. break;
  6081. case CTLESC:
  6082. startloc++;
  6083. length++;
  6084. goto addquote;
  6085. case CTLVAR:
  6086. TRACE(("argstr: evalvar('%s')\n", p));
  6087. p = evalvar(p, flags | inquotes);
  6088. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6089. goto start;
  6090. case CTLBACKQ:
  6091. expbackq(argbackq->n, flags | inquotes);
  6092. argbackq = argbackq->next;
  6093. goto start;
  6094. #if ENABLE_FEATURE_SH_MATH
  6095. case CTLENDARI:
  6096. p--;
  6097. expari(flags | inquotes);
  6098. goto start;
  6099. #endif
  6100. }
  6101. }
  6102. breakloop: ;
  6103. }
  6104. static char *
  6105. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6106. char *pattern, int quotes, int zero)
  6107. {
  6108. char *loc, *loc2;
  6109. char c;
  6110. loc = startp;
  6111. loc2 = rmesc;
  6112. do {
  6113. int match;
  6114. const char *s = loc2;
  6115. c = *loc2;
  6116. if (zero) {
  6117. *loc2 = '\0';
  6118. s = rmesc;
  6119. }
  6120. match = pmatch(pattern, s);
  6121. *loc2 = c;
  6122. if (match)
  6123. return loc;
  6124. if (quotes && (unsigned char)*loc == CTLESC)
  6125. loc++;
  6126. loc++;
  6127. loc2++;
  6128. } while (c);
  6129. return NULL;
  6130. }
  6131. static char *
  6132. scanright(char *startp, char *rmesc, char *rmescend,
  6133. char *pattern, int quotes, int match_at_start)
  6134. {
  6135. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6136. int try2optimize = match_at_start;
  6137. #endif
  6138. int esc = 0;
  6139. char *loc;
  6140. char *loc2;
  6141. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6142. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6143. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6144. * Logic:
  6145. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6146. * and on each iteration they go back two/one char until they reach the beginning.
  6147. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6148. */
  6149. /* TODO: document in what other circumstances we are called. */
  6150. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6151. int match;
  6152. char c = *loc2;
  6153. const char *s = loc2;
  6154. if (match_at_start) {
  6155. *loc2 = '\0';
  6156. s = rmesc;
  6157. }
  6158. match = pmatch(pattern, s);
  6159. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6160. *loc2 = c;
  6161. if (match)
  6162. return loc;
  6163. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6164. if (try2optimize) {
  6165. /* Maybe we can optimize this:
  6166. * if pattern ends with unescaped *, we can avoid checking
  6167. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6168. * it won't match truncated "raw_value_of_" strings too.
  6169. */
  6170. unsigned plen = strlen(pattern);
  6171. /* Does it end with "*"? */
  6172. if (plen != 0 && pattern[--plen] == '*') {
  6173. /* "xxxx*" is not escaped */
  6174. /* "xxx\*" is escaped */
  6175. /* "xx\\*" is not escaped */
  6176. /* "x\\\*" is escaped */
  6177. int slashes = 0;
  6178. while (plen != 0 && pattern[--plen] == '\\')
  6179. slashes++;
  6180. if (!(slashes & 1))
  6181. break; /* ends with unescaped "*" */
  6182. }
  6183. try2optimize = 0;
  6184. }
  6185. #endif
  6186. loc--;
  6187. if (quotes) {
  6188. if (--esc < 0) {
  6189. esc = esclen(startp, loc);
  6190. }
  6191. if (esc % 2) {
  6192. esc--;
  6193. loc--;
  6194. }
  6195. }
  6196. }
  6197. return NULL;
  6198. }
  6199. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6200. static void
  6201. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6202. {
  6203. const char *msg;
  6204. const char *tail;
  6205. tail = nullstr;
  6206. msg = "parameter not set";
  6207. if (umsg) {
  6208. if ((unsigned char)*end == CTLENDVAR) {
  6209. if (varflags & VSNUL)
  6210. tail = " or null";
  6211. } else {
  6212. msg = umsg;
  6213. }
  6214. }
  6215. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6216. }
  6217. static const char *
  6218. subevalvar(char *p, char *varname, int strloc, int subtype,
  6219. int startloc, int varflags, int flag)
  6220. {
  6221. struct nodelist *saveargbackq = argbackq;
  6222. int quotes = flag & QUOTES_ESC;
  6223. char *startp;
  6224. char *loc;
  6225. char *rmesc, *rmescend;
  6226. char *str;
  6227. int amount, resetloc;
  6228. int argstr_flags;
  6229. IF_BASH_PATTERN_SUBST(int workloc;)
  6230. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6231. IF_BASH_PATTERN_SUBST(char *repl;)
  6232. int zero;
  6233. char *(*scan)(char*, char*, char*, char*, int, int);
  6234. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  6235. // p, varname, strloc, subtype, startloc, varflags, quotes);
  6236. #if BASH_PATTERN_SUBST
  6237. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6238. * argstr() call expands possible variable references in pattern:
  6239. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6240. */
  6241. repl = NULL;
  6242. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6243. /* Find '/' and replace with NUL */
  6244. repl = p;
  6245. /* The pattern can't be empty.
  6246. * IOW: if the first char after "${v//" is a slash,
  6247. * it does not terminate the pattern - it's the first char of the pattern:
  6248. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6249. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6250. */
  6251. if (*repl == '/')
  6252. repl++;
  6253. for (;;) {
  6254. if (*repl == '\0') {
  6255. repl = NULL;
  6256. break;
  6257. }
  6258. if (*repl == '/') {
  6259. *repl = '\0';
  6260. break;
  6261. }
  6262. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6263. if ((unsigned char)*repl == CTLESC && repl[1])
  6264. repl++;
  6265. repl++;
  6266. }
  6267. }
  6268. #endif
  6269. argstr_flags = EXP_TILDE;
  6270. if (subtype != VSASSIGN
  6271. && subtype != VSQUESTION
  6272. #if BASH_SUBSTR
  6273. && subtype != VSSUBSTR
  6274. #endif
  6275. ) {
  6276. /* EXP_CASE keeps CTLESC's */
  6277. argstr_flags = EXP_TILDE | EXP_CASE;
  6278. }
  6279. argstr(p, argstr_flags);
  6280. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6281. #if BASH_PATTERN_SUBST
  6282. slash_pos = -1;
  6283. if (repl) {
  6284. slash_pos = expdest - ((char *)stackblock() + strloc);
  6285. STPUTC('/', expdest);
  6286. //bb_error_msg("repl+1:'%s'", repl + 1);
  6287. argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6288. *repl = '/';
  6289. }
  6290. #endif
  6291. STPUTC('\0', expdest);
  6292. argbackq = saveargbackq;
  6293. startp = (char *)stackblock() + startloc;
  6294. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6295. switch (subtype) {
  6296. case VSASSIGN:
  6297. setvar0(varname, startp);
  6298. amount = startp - expdest;
  6299. STADJUST(amount, expdest);
  6300. return startp;
  6301. case VSQUESTION:
  6302. varunset(p, varname, startp, varflags);
  6303. /* NOTREACHED */
  6304. #if BASH_SUBSTR
  6305. case VSSUBSTR: {
  6306. int pos, len, orig_len;
  6307. char *colon;
  6308. loc = str = stackblock() + strloc;
  6309. /* Read POS in ${var:POS:LEN} */
  6310. colon = strchr(loc, ':');
  6311. if (colon) *colon = '\0';
  6312. pos = substr_atoi(loc);
  6313. if (colon) *colon = ':';
  6314. /* Read LEN in ${var:POS:LEN} */
  6315. len = str - startp - 1;
  6316. /* *loc != '\0', guaranteed by parser */
  6317. if (quotes) {
  6318. char *ptr;
  6319. /* Adjust the length by the number of escapes */
  6320. for (ptr = startp; ptr < (str - 1); ptr++) {
  6321. if ((unsigned char)*ptr == CTLESC) {
  6322. len--;
  6323. ptr++;
  6324. }
  6325. }
  6326. }
  6327. orig_len = len;
  6328. if (*loc++ == ':') {
  6329. /* ${var::LEN} */
  6330. len = substr_atoi(loc);
  6331. } else {
  6332. /* Skip POS in ${var:POS:LEN} */
  6333. len = orig_len;
  6334. while (*loc && *loc != ':')
  6335. loc++;
  6336. if (*loc++ == ':')
  6337. len = substr_atoi(loc);
  6338. }
  6339. if (pos < 0) {
  6340. /* ${VAR:$((-n)):l} starts n chars from the end */
  6341. pos = orig_len + pos;
  6342. }
  6343. if ((unsigned)pos >= orig_len) {
  6344. /* apart from obvious ${VAR:999999:l},
  6345. * covers ${VAR:$((-9999999)):l} - result is ""
  6346. * (bash compat)
  6347. */
  6348. pos = 0;
  6349. len = 0;
  6350. }
  6351. if (len < 0) {
  6352. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6353. len = (orig_len - pos) + len;
  6354. }
  6355. if ((unsigned)len > (orig_len - pos))
  6356. len = orig_len - pos;
  6357. for (str = startp; pos; str++, pos--) {
  6358. if (quotes && (unsigned char)*str == CTLESC)
  6359. str++;
  6360. }
  6361. for (loc = startp; len; len--) {
  6362. if (quotes && (unsigned char)*str == CTLESC)
  6363. *loc++ = *str++;
  6364. *loc++ = *str++;
  6365. }
  6366. *loc = '\0';
  6367. amount = loc - expdest;
  6368. STADJUST(amount, expdest);
  6369. return loc;
  6370. }
  6371. #endif /* BASH_SUBSTR */
  6372. }
  6373. resetloc = expdest - (char *)stackblock();
  6374. #if BASH_PATTERN_SUBST
  6375. repl = NULL;
  6376. /* We'll comeback here if we grow the stack while handling
  6377. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6378. * stack will need rebasing, and we'll need to remove our work
  6379. * areas each time
  6380. */
  6381. restart:
  6382. #endif
  6383. amount = expdest - ((char *)stackblock() + resetloc);
  6384. STADJUST(-amount, expdest);
  6385. startp = (char *)stackblock() + startloc;
  6386. rmesc = startp;
  6387. rmescend = (char *)stackblock() + strloc;
  6388. //bb_error_msg("str7:'%s'", rmescend);
  6389. if (quotes) {
  6390. //TODO: how to handle slash_pos here if string changes (shortens?)
  6391. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6392. if (rmesc != startp) {
  6393. rmescend = expdest;
  6394. startp = (char *)stackblock() + startloc;
  6395. }
  6396. }
  6397. rmescend--;
  6398. str = (char *)stackblock() + strloc;
  6399. /*
  6400. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6401. * The result is a_\_z_c (not a\_\_z_c)!
  6402. *
  6403. * The search pattern and replace string treat backslashes differently!
  6404. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6405. * and string. It's only used on the first call.
  6406. */
  6407. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6408. rmescapes(str, RMESCAPE_GLOB,
  6409. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6410. );
  6411. #if BASH_PATTERN_SUBST
  6412. workloc = expdest - (char *)stackblock();
  6413. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6414. int len;
  6415. char *idx, *end;
  6416. if (!repl) {
  6417. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6418. repl = nullstr;
  6419. if (slash_pos >= 0) {
  6420. repl = str + slash_pos;
  6421. *repl++ = '\0';
  6422. }
  6423. }
  6424. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6425. /* If there's no pattern to match, return the expansion unmolested */
  6426. if (str[0] == '\0')
  6427. return NULL;
  6428. len = 0;
  6429. idx = startp;
  6430. end = str - 1;
  6431. while (idx < end) {
  6432. try_to_match:
  6433. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6434. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6435. if (!loc) {
  6436. /* No match, advance */
  6437. char *restart_detect = stackblock();
  6438. skip_matching:
  6439. STPUTC(*idx, expdest);
  6440. if (quotes && (unsigned char)*idx == CTLESC) {
  6441. idx++;
  6442. len++;
  6443. STPUTC(*idx, expdest);
  6444. }
  6445. if (stackblock() != restart_detect)
  6446. goto restart;
  6447. idx++;
  6448. len++;
  6449. rmesc++;
  6450. /* continue; - prone to quadratic behavior, smarter code: */
  6451. if (idx >= end)
  6452. break;
  6453. if (str[0] == '*') {
  6454. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6455. * it would never match "ong_string" etc, no point in trying.
  6456. */
  6457. goto skip_matching;
  6458. }
  6459. goto try_to_match;
  6460. }
  6461. if (subtype == VSREPLACEALL) {
  6462. while (idx < loc) {
  6463. if (quotes && (unsigned char)*idx == CTLESC)
  6464. idx++;
  6465. idx++;
  6466. rmesc++;
  6467. }
  6468. } else {
  6469. idx = loc;
  6470. }
  6471. //bb_error_msg("repl:'%s'", repl);
  6472. for (loc = (char*)repl; *loc; loc++) {
  6473. char *restart_detect = stackblock();
  6474. if (quotes && *loc == '\\') {
  6475. STPUTC(CTLESC, expdest);
  6476. len++;
  6477. }
  6478. STPUTC(*loc, expdest);
  6479. if (stackblock() != restart_detect)
  6480. goto restart;
  6481. len++;
  6482. }
  6483. if (subtype == VSREPLACE) {
  6484. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6485. while (*idx) {
  6486. char *restart_detect = stackblock();
  6487. STPUTC(*idx, expdest);
  6488. if (stackblock() != restart_detect)
  6489. goto restart;
  6490. len++;
  6491. idx++;
  6492. }
  6493. break;
  6494. }
  6495. }
  6496. /* We've put the replaced text into a buffer at workloc, now
  6497. * move it to the right place and adjust the stack.
  6498. */
  6499. STPUTC('\0', expdest);
  6500. startp = (char *)stackblock() + startloc;
  6501. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6502. //bb_error_msg("startp:'%s'", startp);
  6503. amount = expdest - (startp + len);
  6504. STADJUST(-amount, expdest);
  6505. return startp;
  6506. }
  6507. #endif /* BASH_PATTERN_SUBST */
  6508. subtype -= VSTRIMRIGHT;
  6509. #if DEBUG
  6510. if (subtype < 0 || subtype > 7)
  6511. abort();
  6512. #endif
  6513. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6514. zero = subtype >> 1;
  6515. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6516. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6517. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6518. if (loc) {
  6519. if (zero) {
  6520. memmove(startp, loc, str - loc);
  6521. loc = startp + (str - loc) - 1;
  6522. }
  6523. *loc = '\0';
  6524. amount = loc - expdest;
  6525. STADJUST(amount, expdest);
  6526. }
  6527. return loc;
  6528. }
  6529. /*
  6530. * Add the value of a specialized variable to the stack string.
  6531. * name parameter (examples):
  6532. * ash -c 'echo $1' name:'1='
  6533. * ash -c 'echo $qwe' name:'qwe='
  6534. * ash -c 'echo $$' name:'$='
  6535. * ash -c 'echo ${$}' name:'$='
  6536. * ash -c 'echo ${$##q}' name:'$=q'
  6537. * ash -c 'echo ${#$}' name:'$='
  6538. * note: examples with bad shell syntax:
  6539. * ash -c 'echo ${#$1}' name:'$=1'
  6540. * ash -c 'echo ${#1#}' name:'1=#'
  6541. */
  6542. static NOINLINE ssize_t
  6543. varvalue(char *name, int varflags, int flags, int quoted)
  6544. {
  6545. const char *p;
  6546. int num;
  6547. int i;
  6548. ssize_t len = 0;
  6549. int sep;
  6550. int subtype = varflags & VSTYPE;
  6551. int discard = subtype == VSPLUS || subtype == VSLENGTH;
  6552. int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
  6553. int syntax;
  6554. sep = (flags & EXP_FULL) << CHAR_BIT;
  6555. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  6556. switch (*name) {
  6557. case '$':
  6558. num = rootpid;
  6559. goto numvar;
  6560. case '?':
  6561. num = exitstatus;
  6562. goto numvar;
  6563. case '#':
  6564. num = shellparam.nparam;
  6565. goto numvar;
  6566. case '!':
  6567. num = backgndpid;
  6568. if (num == 0)
  6569. return -1;
  6570. numvar:
  6571. len = cvtnum(num);
  6572. goto check_1char_name;
  6573. case '-':
  6574. expdest = makestrspace(NOPTS, expdest);
  6575. for (i = NOPTS - 1; i >= 0; i--) {
  6576. if (optlist[i] && optletters(i)) {
  6577. USTPUTC(optletters(i), expdest);
  6578. len++;
  6579. }
  6580. }
  6581. check_1char_name:
  6582. #if 0
  6583. /* handles cases similar to ${#$1} */
  6584. if (name[2] != '\0')
  6585. raise_error_syntax("bad substitution");
  6586. #endif
  6587. break;
  6588. case '@':
  6589. if (quoted && sep)
  6590. goto param;
  6591. /* fall through */
  6592. case '*': {
  6593. char **ap;
  6594. char sepc;
  6595. char c;
  6596. /* We will set c to 0 or ~0 depending on whether
  6597. * we're doing field splitting. We won't do field
  6598. * splitting if either we're quoted or sep is zero.
  6599. *
  6600. * Instead of testing (quoted || !sep) the following
  6601. * trick optimises away any branches by using the
  6602. * fact that EXP_QUOTED (which is the only bit that
  6603. * can be set in quoted) is the same as EXP_FULL <<
  6604. * CHAR_BIT (which is the only bit that can be set
  6605. * in sep).
  6606. */
  6607. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6608. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6609. #endif
  6610. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6611. sep &= ~quoted;
  6612. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6613. param:
  6614. sepc = sep;
  6615. ap = shellparam.p;
  6616. if (!ap)
  6617. return -1;
  6618. while ((p = *ap++) != NULL) {
  6619. len += strtodest(p, syntax, quotes);
  6620. if (*ap && sep) {
  6621. len++;
  6622. memtodest(&sepc, 1, syntax, quotes);
  6623. }
  6624. }
  6625. break;
  6626. } /* case '*' */
  6627. case '0':
  6628. case '1':
  6629. case '2':
  6630. case '3':
  6631. case '4':
  6632. case '5':
  6633. case '6':
  6634. case '7':
  6635. case '8':
  6636. case '9':
  6637. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6638. if (num < 0 || num > shellparam.nparam)
  6639. return -1;
  6640. p = num ? shellparam.p[num - 1] : arg0;
  6641. goto value;
  6642. default:
  6643. /* NB: name has form "VAR=..." */
  6644. p = lookupvar(name);
  6645. value:
  6646. if (!p)
  6647. return -1;
  6648. len = strtodest(p, syntax, quotes);
  6649. #if ENABLE_UNICODE_SUPPORT
  6650. if (subtype == VSLENGTH && len > 0) {
  6651. reinit_unicode_for_ash();
  6652. if (unicode_status == UNICODE_ON) {
  6653. STADJUST(-len, expdest);
  6654. discard = 0;
  6655. len = unicode_strlen(p);
  6656. }
  6657. }
  6658. #endif
  6659. break;
  6660. }
  6661. if (discard)
  6662. STADJUST(-len, expdest);
  6663. return len;
  6664. }
  6665. /*
  6666. * Expand a variable, and return a pointer to the next character in the
  6667. * input string.
  6668. */
  6669. static char *
  6670. evalvar(char *p, int flag)
  6671. {
  6672. char varflags;
  6673. char subtype;
  6674. int quoted;
  6675. char *var;
  6676. int patloc;
  6677. int startloc;
  6678. ssize_t varlen;
  6679. varflags = (unsigned char) *p++;
  6680. subtype = varflags & VSTYPE;
  6681. if (!subtype)
  6682. raise_error_syntax("bad substitution");
  6683. quoted = flag & EXP_QUOTED;
  6684. var = p;
  6685. startloc = expdest - (char *)stackblock();
  6686. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6687. again:
  6688. varlen = varvalue(var, varflags, flag, quoted);
  6689. if (varflags & VSNUL)
  6690. varlen--;
  6691. if (subtype == VSPLUS) {
  6692. varlen = -1 - varlen;
  6693. goto vsplus;
  6694. }
  6695. if (subtype == VSMINUS) {
  6696. vsplus:
  6697. if (varlen < 0) {
  6698. argstr(
  6699. p,
  6700. flag | EXP_TILDE | EXP_WORD
  6701. );
  6702. goto end;
  6703. }
  6704. goto record;
  6705. }
  6706. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6707. if (varlen >= 0)
  6708. goto record;
  6709. subevalvar(p, var, 0, subtype, startloc, varflags,
  6710. flag & ~QUOTES_ESC);
  6711. varflags &= ~VSNUL;
  6712. /*
  6713. * Remove any recorded regions beyond
  6714. * start of variable
  6715. */
  6716. removerecordregions(startloc);
  6717. goto again;
  6718. }
  6719. if (varlen < 0 && uflag)
  6720. varunset(p, var, 0, 0);
  6721. if (subtype == VSLENGTH) {
  6722. cvtnum(varlen > 0 ? varlen : 0);
  6723. goto record;
  6724. }
  6725. if (subtype == VSNORMAL) {
  6726. record:
  6727. if (quoted) {
  6728. quoted = *var == '@' && shellparam.nparam;
  6729. if (!quoted)
  6730. goto end;
  6731. }
  6732. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6733. goto end;
  6734. }
  6735. #if DEBUG
  6736. switch (subtype) {
  6737. case VSTRIMLEFT:
  6738. case VSTRIMLEFTMAX:
  6739. case VSTRIMRIGHT:
  6740. case VSTRIMRIGHTMAX:
  6741. #if BASH_SUBSTR
  6742. case VSSUBSTR:
  6743. #endif
  6744. #if BASH_PATTERN_SUBST
  6745. case VSREPLACE:
  6746. case VSREPLACEALL:
  6747. #endif
  6748. break;
  6749. default:
  6750. abort();
  6751. }
  6752. #endif
  6753. if (varlen >= 0) {
  6754. /*
  6755. * Terminate the string and start recording the pattern
  6756. * right after it
  6757. */
  6758. STPUTC('\0', expdest);
  6759. patloc = expdest - (char *)stackblock();
  6760. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6761. startloc, varflags, flag)) {
  6762. int amount = expdest - (
  6763. (char *)stackblock() + patloc - 1
  6764. );
  6765. STADJUST(-amount, expdest);
  6766. }
  6767. /* Remove any recorded regions beyond start of variable */
  6768. removerecordregions(startloc);
  6769. goto record;
  6770. }
  6771. end:
  6772. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6773. int nesting = 1;
  6774. for (;;) {
  6775. unsigned char c = *p++;
  6776. if (c == CTLESC)
  6777. p++;
  6778. else if (c == CTLBACKQ) {
  6779. if (varlen >= 0)
  6780. argbackq = argbackq->next;
  6781. } else if (c == CTLVAR) {
  6782. if ((*p++ & VSTYPE) != VSNORMAL)
  6783. nesting++;
  6784. } else if (c == CTLENDVAR) {
  6785. if (--nesting == 0)
  6786. break;
  6787. }
  6788. }
  6789. }
  6790. return p;
  6791. }
  6792. /*
  6793. * Add a file name to the list.
  6794. */
  6795. static void
  6796. addfname(const char *name)
  6797. {
  6798. struct strlist *sp;
  6799. sp = stzalloc(sizeof(*sp));
  6800. sp->text = sstrdup(name);
  6801. *exparg.lastp = sp;
  6802. exparg.lastp = &sp->next;
  6803. }
  6804. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6805. static int
  6806. hasmeta(const char *p)
  6807. {
  6808. static const char chars[] ALIGN1 = {
  6809. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6810. };
  6811. for (;;) {
  6812. p = strpbrk(p, chars);
  6813. if (!p)
  6814. break;
  6815. switch ((unsigned char)*p) {
  6816. case CTLQUOTEMARK:
  6817. for (;;) {
  6818. p++;
  6819. if ((unsigned char)*p == CTLQUOTEMARK)
  6820. break;
  6821. if ((unsigned char)*p == CTLESC)
  6822. p++;
  6823. if (*p == '\0') /* huh? */
  6824. return 0;
  6825. }
  6826. break;
  6827. case '\\':
  6828. case CTLESC:
  6829. p++;
  6830. if (*p == '\0')
  6831. return 0;
  6832. break;
  6833. case '[':
  6834. if (!strchr(p + 1, ']')) {
  6835. /* It's not a properly closed [] pattern,
  6836. * but other metas may follow. Continue checking.
  6837. * my[file* _is_ globbed by bash
  6838. * and matches filenames like "my[file1".
  6839. */
  6840. break;
  6841. }
  6842. /* fallthrough */
  6843. default:
  6844. /* case '*': */
  6845. /* case '?': */
  6846. return 1;
  6847. }
  6848. p++;
  6849. }
  6850. return 0;
  6851. }
  6852. /* If we want to use glob() from libc... */
  6853. #if !ENABLE_ASH_INTERNAL_GLOB
  6854. /* Add the result of glob() to the list */
  6855. static void
  6856. addglob(const glob_t *pglob)
  6857. {
  6858. char **p = pglob->gl_pathv;
  6859. do {
  6860. addfname(*p);
  6861. } while (*++p);
  6862. }
  6863. static void
  6864. expandmeta(struct strlist *str /*, int flag*/)
  6865. {
  6866. /* TODO - EXP_REDIR */
  6867. while (str) {
  6868. char *p;
  6869. glob_t pglob;
  6870. int i;
  6871. if (fflag)
  6872. goto nometa;
  6873. if (!hasmeta(str->text))
  6874. goto nometa;
  6875. INT_OFF;
  6876. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6877. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6878. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6879. //
  6880. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6881. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6882. // Which means you need to unescape the string, right? Not so fast:
  6883. // if there _is_ a file named "file\?" (with backslash), it is returned
  6884. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6885. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6886. //
  6887. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6888. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6889. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6890. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6891. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6892. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6893. i = glob(p, 0, NULL, &pglob);
  6894. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6895. if (p != str->text)
  6896. free(p);
  6897. switch (i) {
  6898. case 0:
  6899. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6900. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6901. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6902. goto nometa2;
  6903. #endif
  6904. addglob(&pglob);
  6905. globfree(&pglob);
  6906. INT_ON;
  6907. break;
  6908. case GLOB_NOMATCH:
  6909. //nometa2:
  6910. globfree(&pglob);
  6911. INT_ON;
  6912. nometa:
  6913. *exparg.lastp = str;
  6914. rmescapes(str->text, 0, NULL);
  6915. exparg.lastp = &str->next;
  6916. break;
  6917. default: /* GLOB_NOSPACE */
  6918. globfree(&pglob);
  6919. INT_ON;
  6920. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  6921. }
  6922. str = str->next;
  6923. }
  6924. }
  6925. #else
  6926. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  6927. /*
  6928. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6929. */
  6930. typedef struct exp_t {
  6931. char *dir;
  6932. unsigned dir_max;
  6933. } exp_t;
  6934. static void
  6935. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  6936. {
  6937. #define expdir exp->dir
  6938. #define expdir_max exp->dir_max
  6939. char *enddir = expdir + expdir_len;
  6940. char *p;
  6941. const char *cp;
  6942. char *start;
  6943. char *endname;
  6944. int metaflag;
  6945. struct stat statb;
  6946. DIR *dirp;
  6947. struct dirent *dp;
  6948. int atend;
  6949. int matchdot;
  6950. int esc;
  6951. metaflag = 0;
  6952. start = name;
  6953. for (p = name; esc = 0, *p; p += esc + 1) {
  6954. if (*p == '*' || *p == '?')
  6955. metaflag = 1;
  6956. else if (*p == '[') {
  6957. char *q = p + 1;
  6958. if (*q == '!')
  6959. q++;
  6960. for (;;) {
  6961. if (*q == '\\')
  6962. q++;
  6963. if (*q == '/' || *q == '\0')
  6964. break;
  6965. if (*++q == ']') {
  6966. metaflag = 1;
  6967. break;
  6968. }
  6969. }
  6970. } else {
  6971. if (*p == '\\' && p[1])
  6972. esc++;
  6973. if (p[esc] == '/') {
  6974. if (metaflag)
  6975. break;
  6976. start = p + esc + 1;
  6977. }
  6978. }
  6979. }
  6980. if (metaflag == 0) { /* we've reached the end of the file name */
  6981. if (!expdir_len)
  6982. return;
  6983. p = name;
  6984. do {
  6985. if (*p == '\\' && p[1])
  6986. p++;
  6987. *enddir++ = *p;
  6988. } while (*p++);
  6989. if (lstat(expdir, &statb) == 0)
  6990. addfname(expdir);
  6991. return;
  6992. }
  6993. endname = p;
  6994. if (name < start) {
  6995. p = name;
  6996. do {
  6997. if (*p == '\\' && p[1])
  6998. p++;
  6999. *enddir++ = *p++;
  7000. } while (p < start);
  7001. }
  7002. *enddir = '\0';
  7003. cp = expdir;
  7004. expdir_len = enddir - cp;
  7005. if (!expdir_len)
  7006. cp = ".";
  7007. dirp = opendir(cp);
  7008. if (dirp == NULL)
  7009. return;
  7010. if (*endname == 0) {
  7011. atend = 1;
  7012. } else {
  7013. atend = 0;
  7014. *endname = '\0';
  7015. endname += esc + 1;
  7016. }
  7017. name_len -= endname - name;
  7018. matchdot = 0;
  7019. p = start;
  7020. if (*p == '\\')
  7021. p++;
  7022. if (*p == '.')
  7023. matchdot++;
  7024. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7025. if (dp->d_name[0] == '.' && !matchdot)
  7026. continue;
  7027. if (pmatch(start, dp->d_name)) {
  7028. if (atend) {
  7029. strcpy(enddir, dp->d_name);
  7030. addfname(expdir);
  7031. } else {
  7032. unsigned offset;
  7033. unsigned len;
  7034. p = stpcpy(enddir, dp->d_name);
  7035. *p = '/';
  7036. offset = p - expdir + 1;
  7037. len = offset + name_len + NAME_MAX;
  7038. if (len > expdir_max) {
  7039. len += PATH_MAX;
  7040. expdir = ckrealloc(expdir, len);
  7041. expdir_max = len;
  7042. }
  7043. expmeta(exp, endname, name_len, offset);
  7044. enddir = expdir + expdir_len;
  7045. }
  7046. }
  7047. }
  7048. closedir(dirp);
  7049. if (!atend)
  7050. endname[-esc - 1] = esc ? '\\' : '/';
  7051. #undef expdir
  7052. #undef expdir_max
  7053. }
  7054. static struct strlist *
  7055. msort(struct strlist *list, int len)
  7056. {
  7057. struct strlist *p, *q = NULL;
  7058. struct strlist **lpp;
  7059. int half;
  7060. int n;
  7061. if (len <= 1)
  7062. return list;
  7063. half = len >> 1;
  7064. p = list;
  7065. for (n = half; --n >= 0;) {
  7066. q = p;
  7067. p = p->next;
  7068. }
  7069. q->next = NULL; /* terminate first half of list */
  7070. q = msort(list, half); /* sort first half of list */
  7071. p = msort(p, len - half); /* sort second half */
  7072. lpp = &list;
  7073. for (;;) {
  7074. #if ENABLE_LOCALE_SUPPORT
  7075. if (strcoll(p->text, q->text) < 0)
  7076. #else
  7077. if (strcmp(p->text, q->text) < 0)
  7078. #endif
  7079. {
  7080. *lpp = p;
  7081. lpp = &p->next;
  7082. p = *lpp;
  7083. if (p == NULL) {
  7084. *lpp = q;
  7085. break;
  7086. }
  7087. } else {
  7088. *lpp = q;
  7089. lpp = &q->next;
  7090. q = *lpp;
  7091. if (q == NULL) {
  7092. *lpp = p;
  7093. break;
  7094. }
  7095. }
  7096. }
  7097. return list;
  7098. }
  7099. /*
  7100. * Sort the results of file name expansion. It calculates the number of
  7101. * strings to sort and then calls msort (short for merge sort) to do the
  7102. * work.
  7103. */
  7104. static struct strlist *
  7105. expsort(struct strlist *str)
  7106. {
  7107. int len;
  7108. struct strlist *sp;
  7109. len = 0;
  7110. for (sp = str; sp; sp = sp->next)
  7111. len++;
  7112. return msort(str, len);
  7113. }
  7114. static void
  7115. expandmeta(struct strlist *str /*, int flag*/)
  7116. {
  7117. /* TODO - EXP_REDIR */
  7118. while (str) {
  7119. exp_t exp;
  7120. struct strlist **savelastp;
  7121. struct strlist *sp;
  7122. char *p;
  7123. unsigned len;
  7124. if (fflag)
  7125. goto nometa;
  7126. if (!hasmeta(str->text))
  7127. goto nometa;
  7128. savelastp = exparg.lastp;
  7129. INT_OFF;
  7130. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7131. len = strlen(p);
  7132. exp.dir_max = len + PATH_MAX;
  7133. exp.dir = ckmalloc(exp.dir_max);
  7134. expmeta(&exp, p, len, 0);
  7135. free(exp.dir);
  7136. if (p != str->text)
  7137. free(p);
  7138. INT_ON;
  7139. if (exparg.lastp == savelastp) {
  7140. /*
  7141. * no matches
  7142. */
  7143. nometa:
  7144. *exparg.lastp = str;
  7145. rmescapes(str->text, 0, NULL);
  7146. exparg.lastp = &str->next;
  7147. } else {
  7148. *exparg.lastp = NULL;
  7149. *savelastp = sp = expsort(*savelastp);
  7150. while (sp->next != NULL)
  7151. sp = sp->next;
  7152. exparg.lastp = &sp->next;
  7153. }
  7154. str = str->next;
  7155. }
  7156. }
  7157. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7158. /*
  7159. * Perform variable substitution and command substitution on an argument,
  7160. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7161. * perform splitting and file name expansion. When arglist is NULL, perform
  7162. * here document expansion.
  7163. */
  7164. static void
  7165. expandarg(union node *arg, struct arglist *arglist, int flag)
  7166. {
  7167. struct strlist *sp;
  7168. char *p;
  7169. argbackq = arg->narg.backquote;
  7170. STARTSTACKSTR(expdest);
  7171. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7172. argstr(arg->narg.text, flag);
  7173. p = _STPUTC('\0', expdest);
  7174. expdest = p - 1;
  7175. if (arglist == NULL) {
  7176. /* here document expanded */
  7177. goto out;
  7178. }
  7179. p = grabstackstr(p);
  7180. TRACE(("expandarg: p:'%s'\n", p));
  7181. exparg.lastp = &exparg.list;
  7182. /*
  7183. * TODO - EXP_REDIR
  7184. */
  7185. if (flag & EXP_FULL) {
  7186. ifsbreakup(p, &exparg);
  7187. *exparg.lastp = NULL;
  7188. exparg.lastp = &exparg.list;
  7189. expandmeta(exparg.list /*, flag*/);
  7190. } else {
  7191. sp = stzalloc(sizeof(*sp));
  7192. sp->text = p;
  7193. *exparg.lastp = sp;
  7194. exparg.lastp = &sp->next;
  7195. }
  7196. *exparg.lastp = NULL;
  7197. if (exparg.list) {
  7198. *arglist->lastp = exparg.list;
  7199. arglist->lastp = exparg.lastp;
  7200. }
  7201. out:
  7202. ifsfree();
  7203. }
  7204. /*
  7205. * Expand shell variables and backquotes inside a here document.
  7206. */
  7207. static void
  7208. expandhere(union node *arg, int fd)
  7209. {
  7210. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7211. full_write(fd, stackblock(), expdest - (char *)stackblock());
  7212. }
  7213. /*
  7214. * Returns true if the pattern matches the string.
  7215. */
  7216. static int
  7217. patmatch(char *pattern, const char *string)
  7218. {
  7219. char *p = preglob(pattern, 0);
  7220. int r = pmatch(p, string);
  7221. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7222. return r;
  7223. }
  7224. /*
  7225. * See if a pattern matches in a case statement.
  7226. */
  7227. static int
  7228. casematch(union node *pattern, char *val)
  7229. {
  7230. struct stackmark smark;
  7231. int result;
  7232. setstackmark(&smark);
  7233. argbackq = pattern->narg.backquote;
  7234. STARTSTACKSTR(expdest);
  7235. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7236. STACKSTRNUL(expdest);
  7237. ifsfree();
  7238. result = patmatch(stackblock(), val);
  7239. popstackmark(&smark);
  7240. return result;
  7241. }
  7242. /* ============ find_command */
  7243. struct builtincmd {
  7244. const char *name;
  7245. int (*builtin)(int, char **) FAST_FUNC;
  7246. /* unsigned flags; */
  7247. };
  7248. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7249. /* "regular" builtins always take precedence over commands,
  7250. * regardless of PATH=....%builtin... position */
  7251. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7252. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7253. struct cmdentry {
  7254. smallint cmdtype; /* CMDxxx */
  7255. union param {
  7256. int index;
  7257. /* index >= 0 for commands without path (slashes) */
  7258. /* (TODO: what exactly does the value mean? PATH position?) */
  7259. /* index == -1 for commands with slashes */
  7260. /* index == (-2 - applet_no) for NOFORK applets */
  7261. const struct builtincmd *cmd;
  7262. struct funcnode *func;
  7263. } u;
  7264. };
  7265. /* values of cmdtype */
  7266. #define CMDUNKNOWN -1 /* no entry in table for command */
  7267. #define CMDNORMAL 0 /* command is an executable program */
  7268. #define CMDFUNCTION 1 /* command is a shell function */
  7269. #define CMDBUILTIN 2 /* command is a shell builtin */
  7270. /* action to find_command() */
  7271. #define DO_ERR 0x01 /* prints errors */
  7272. #define DO_ABS 0x02 /* checks absolute paths */
  7273. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7274. #define DO_ALTPATH 0x08 /* using alternate path */
  7275. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  7276. static void find_command(char *, struct cmdentry *, int, const char *);
  7277. /* ============ Hashing commands */
  7278. /*
  7279. * When commands are first encountered, they are entered in a hash table.
  7280. * This ensures that a full path search will not have to be done for them
  7281. * on each invocation.
  7282. *
  7283. * We should investigate converting to a linear search, even though that
  7284. * would make the command name "hash" a misnomer.
  7285. */
  7286. struct tblentry {
  7287. struct tblentry *next; /* next entry in hash chain */
  7288. union param param; /* definition of builtin function */
  7289. smallint cmdtype; /* CMDxxx */
  7290. char rehash; /* if set, cd done since entry created */
  7291. char cmdname[1]; /* name of command */
  7292. };
  7293. static struct tblentry **cmdtable;
  7294. #define INIT_G_cmdtable() do { \
  7295. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7296. } while (0)
  7297. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7298. static void
  7299. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7300. {
  7301. #if ENABLE_FEATURE_SH_STANDALONE
  7302. if (applet_no >= 0) {
  7303. if (APPLET_IS_NOEXEC(applet_no)) {
  7304. clearenv();
  7305. while (*envp)
  7306. putenv(*envp++);
  7307. popredir(/*drop:*/ 1);
  7308. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7309. }
  7310. /* re-exec ourselves with the new arguments */
  7311. execve(bb_busybox_exec_path, argv, envp);
  7312. /* If they called chroot or otherwise made the binary no longer
  7313. * executable, fall through */
  7314. }
  7315. #endif
  7316. repeat:
  7317. #ifdef SYSV
  7318. do {
  7319. execve(cmd, argv, envp);
  7320. } while (errno == EINTR);
  7321. #else
  7322. execve(cmd, argv, envp);
  7323. #endif
  7324. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7325. /* Run "cmd" as a shell script:
  7326. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7327. * "If the execve() function fails with ENOEXEC, the shell
  7328. * shall execute a command equivalent to having a shell invoked
  7329. * with the command name as its first operand,
  7330. * with any remaining arguments passed to the new shell"
  7331. *
  7332. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7333. * just call ourselves.
  7334. *
  7335. * Note that bash reads ~80 chars of the file, and if it sees
  7336. * a zero byte before it sees newline, it doesn't try to
  7337. * interpret it, but fails with "cannot execute binary file"
  7338. * message and exit code 126. For one, this prevents attempts
  7339. * to interpret foreign ELF binaries as shell scripts.
  7340. */
  7341. argv[0] = (char*) cmd;
  7342. cmd = bb_busybox_exec_path;
  7343. /* NB: this is only possible because all callers of shellexec()
  7344. * ensure that the argv[-1] slot exists!
  7345. */
  7346. argv--;
  7347. argv[0] = (char*) "ash";
  7348. goto repeat;
  7349. }
  7350. }
  7351. /*
  7352. * Exec a program. Never returns. If you change this routine, you may
  7353. * have to change the find_command routine as well.
  7354. * argv[-1] must exist and be writable! See tryexec() for why.
  7355. */
  7356. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7357. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7358. {
  7359. char *cmdname;
  7360. int e;
  7361. char **envp;
  7362. int exerrno;
  7363. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7364. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7365. if (strchr(prog, '/') != NULL
  7366. #if ENABLE_FEATURE_SH_STANDALONE
  7367. || (applet_no = find_applet_by_name(prog)) >= 0
  7368. #endif
  7369. ) {
  7370. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7371. if (applet_no >= 0) {
  7372. /* We tried execing ourself, but it didn't work.
  7373. * Maybe /proc/self/exe doesn't exist?
  7374. * Try $PATH search.
  7375. */
  7376. goto try_PATH;
  7377. }
  7378. e = errno;
  7379. } else {
  7380. try_PATH:
  7381. e = ENOENT;
  7382. while ((cmdname = path_advance(&path, prog)) != NULL) {
  7383. if (--idx < 0 && pathopt == NULL) {
  7384. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7385. if (errno != ENOENT && errno != ENOTDIR)
  7386. e = errno;
  7387. }
  7388. stunalloc(cmdname);
  7389. }
  7390. }
  7391. /* Map to POSIX errors */
  7392. switch (e) {
  7393. default:
  7394. exerrno = 126;
  7395. break;
  7396. case ELOOP:
  7397. case ENAMETOOLONG:
  7398. case ENOENT:
  7399. case ENOTDIR:
  7400. exerrno = 127;
  7401. break;
  7402. }
  7403. exitstatus = exerrno;
  7404. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7405. prog, e, suppress_int));
  7406. ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
  7407. /* NOTREACHED */
  7408. }
  7409. static void
  7410. printentry(struct tblentry *cmdp)
  7411. {
  7412. int idx;
  7413. const char *path;
  7414. char *name;
  7415. idx = cmdp->param.index;
  7416. path = pathval();
  7417. do {
  7418. name = path_advance(&path, cmdp->cmdname);
  7419. stunalloc(name);
  7420. } while (--idx >= 0);
  7421. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7422. }
  7423. /*
  7424. * Clear out command entries. The argument specifies the first entry in
  7425. * PATH which has changed.
  7426. */
  7427. static void
  7428. clearcmdentry(int firstchange)
  7429. {
  7430. struct tblentry **tblp;
  7431. struct tblentry **pp;
  7432. struct tblentry *cmdp;
  7433. INT_OFF;
  7434. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7435. pp = tblp;
  7436. while ((cmdp = *pp) != NULL) {
  7437. if ((cmdp->cmdtype == CMDNORMAL &&
  7438. cmdp->param.index >= firstchange)
  7439. || (cmdp->cmdtype == CMDBUILTIN &&
  7440. builtinloc >= firstchange)
  7441. ) {
  7442. *pp = cmdp->next;
  7443. free(cmdp);
  7444. } else {
  7445. pp = &cmdp->next;
  7446. }
  7447. }
  7448. }
  7449. INT_ON;
  7450. }
  7451. /*
  7452. * Locate a command in the command hash table. If "add" is nonzero,
  7453. * add the command to the table if it is not already present. The
  7454. * variable "lastcmdentry" is set to point to the address of the link
  7455. * pointing to the entry, so that delete_cmd_entry can delete the
  7456. * entry.
  7457. *
  7458. * Interrupts must be off if called with add != 0.
  7459. */
  7460. static struct tblentry **lastcmdentry;
  7461. static struct tblentry *
  7462. cmdlookup(const char *name, int add)
  7463. {
  7464. unsigned int hashval;
  7465. const char *p;
  7466. struct tblentry *cmdp;
  7467. struct tblentry **pp;
  7468. p = name;
  7469. hashval = (unsigned char)*p << 4;
  7470. while (*p)
  7471. hashval += (unsigned char)*p++;
  7472. hashval &= 0x7FFF;
  7473. pp = &cmdtable[hashval % CMDTABLESIZE];
  7474. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7475. if (strcmp(cmdp->cmdname, name) == 0)
  7476. break;
  7477. pp = &cmdp->next;
  7478. }
  7479. if (add && cmdp == NULL) {
  7480. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7481. + strlen(name)
  7482. /* + 1 - already done because
  7483. * tblentry::cmdname is char[1] */);
  7484. /*cmdp->next = NULL; - ckzalloc did it */
  7485. cmdp->cmdtype = CMDUNKNOWN;
  7486. strcpy(cmdp->cmdname, name);
  7487. }
  7488. lastcmdentry = pp;
  7489. return cmdp;
  7490. }
  7491. /*
  7492. * Delete the command entry returned on the last lookup.
  7493. */
  7494. static void
  7495. delete_cmd_entry(void)
  7496. {
  7497. struct tblentry *cmdp;
  7498. INT_OFF;
  7499. cmdp = *lastcmdentry;
  7500. *lastcmdentry = cmdp->next;
  7501. if (cmdp->cmdtype == CMDFUNCTION)
  7502. freefunc(cmdp->param.func);
  7503. free(cmdp);
  7504. INT_ON;
  7505. }
  7506. /*
  7507. * Add a new command entry, replacing any existing command entry for
  7508. * the same name - except special builtins.
  7509. */
  7510. static void
  7511. addcmdentry(char *name, struct cmdentry *entry)
  7512. {
  7513. struct tblentry *cmdp;
  7514. cmdp = cmdlookup(name, 1);
  7515. if (cmdp->cmdtype == CMDFUNCTION) {
  7516. freefunc(cmdp->param.func);
  7517. }
  7518. cmdp->cmdtype = entry->cmdtype;
  7519. cmdp->param = entry->u;
  7520. cmdp->rehash = 0;
  7521. }
  7522. static int FAST_FUNC
  7523. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7524. {
  7525. struct tblentry **pp;
  7526. struct tblentry *cmdp;
  7527. int c;
  7528. struct cmdentry entry;
  7529. char *name;
  7530. if (nextopt("r") != '\0') {
  7531. clearcmdentry(0);
  7532. return 0;
  7533. }
  7534. if (*argptr == NULL) {
  7535. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7536. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7537. if (cmdp->cmdtype == CMDNORMAL)
  7538. printentry(cmdp);
  7539. }
  7540. }
  7541. return 0;
  7542. }
  7543. c = 0;
  7544. while ((name = *argptr) != NULL) {
  7545. cmdp = cmdlookup(name, 0);
  7546. if (cmdp != NULL
  7547. && (cmdp->cmdtype == CMDNORMAL
  7548. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  7549. ) {
  7550. delete_cmd_entry();
  7551. }
  7552. find_command(name, &entry, DO_ERR, pathval());
  7553. if (entry.cmdtype == CMDUNKNOWN)
  7554. c = 1;
  7555. argptr++;
  7556. }
  7557. return c;
  7558. }
  7559. /*
  7560. * Called when a cd is done. Marks all commands so the next time they
  7561. * are executed they will be rehashed.
  7562. */
  7563. static void
  7564. hashcd(void)
  7565. {
  7566. struct tblentry **pp;
  7567. struct tblentry *cmdp;
  7568. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7569. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7570. if (cmdp->cmdtype == CMDNORMAL
  7571. || (cmdp->cmdtype == CMDBUILTIN
  7572. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7573. && builtinloc > 0)
  7574. ) {
  7575. cmdp->rehash = 1;
  7576. }
  7577. }
  7578. }
  7579. }
  7580. /*
  7581. * Fix command hash table when PATH changed.
  7582. * Called before PATH is changed. The argument is the new value of PATH;
  7583. * pathval() still returns the old value at this point.
  7584. * Called with interrupts off.
  7585. */
  7586. static void FAST_FUNC
  7587. changepath(const char *new)
  7588. {
  7589. const char *old;
  7590. int firstchange;
  7591. int idx;
  7592. int idx_bltin;
  7593. old = pathval();
  7594. firstchange = 9999; /* assume no change */
  7595. idx = 0;
  7596. idx_bltin = -1;
  7597. for (;;) {
  7598. if (*old != *new) {
  7599. firstchange = idx;
  7600. if ((*old == '\0' && *new == ':')
  7601. || (*old == ':' && *new == '\0')
  7602. ) {
  7603. firstchange++;
  7604. }
  7605. old = new; /* ignore subsequent differences */
  7606. }
  7607. if (*new == '\0')
  7608. break;
  7609. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7610. idx_bltin = idx;
  7611. if (*new == ':')
  7612. idx++;
  7613. new++;
  7614. old++;
  7615. }
  7616. if (builtinloc < 0 && idx_bltin >= 0)
  7617. builtinloc = idx_bltin; /* zap builtins */
  7618. if (builtinloc >= 0 && idx_bltin < 0)
  7619. firstchange = 0;
  7620. clearcmdentry(firstchange);
  7621. builtinloc = idx_bltin;
  7622. }
  7623. enum {
  7624. TEOF,
  7625. TNL,
  7626. TREDIR,
  7627. TWORD,
  7628. TSEMI,
  7629. TBACKGND,
  7630. TAND,
  7631. TOR,
  7632. TPIPE,
  7633. TLP,
  7634. TRP,
  7635. TENDCASE,
  7636. TENDBQUOTE,
  7637. TNOT,
  7638. TCASE,
  7639. TDO,
  7640. TDONE,
  7641. TELIF,
  7642. TELSE,
  7643. TESAC,
  7644. TFI,
  7645. TFOR,
  7646. #if BASH_FUNCTION
  7647. TFUNCTION,
  7648. #endif
  7649. TIF,
  7650. TIN,
  7651. TTHEN,
  7652. TUNTIL,
  7653. TWHILE,
  7654. TBEGIN,
  7655. TEND
  7656. };
  7657. typedef smallint token_id_t;
  7658. /* Nth bit indicates if token marks the end of a list */
  7659. enum {
  7660. tokendlist = 0
  7661. /* 0 */ | (1u << TEOF)
  7662. /* 1 */ | (0u << TNL)
  7663. /* 2 */ | (0u << TREDIR)
  7664. /* 3 */ | (0u << TWORD)
  7665. /* 4 */ | (0u << TSEMI)
  7666. /* 5 */ | (0u << TBACKGND)
  7667. /* 6 */ | (0u << TAND)
  7668. /* 7 */ | (0u << TOR)
  7669. /* 8 */ | (0u << TPIPE)
  7670. /* 9 */ | (0u << TLP)
  7671. /* 10 */ | (1u << TRP)
  7672. /* 11 */ | (1u << TENDCASE)
  7673. /* 12 */ | (1u << TENDBQUOTE)
  7674. /* 13 */ | (0u << TNOT)
  7675. /* 14 */ | (0u << TCASE)
  7676. /* 15 */ | (1u << TDO)
  7677. /* 16 */ | (1u << TDONE)
  7678. /* 17 */ | (1u << TELIF)
  7679. /* 18 */ | (1u << TELSE)
  7680. /* 19 */ | (1u << TESAC)
  7681. /* 20 */ | (1u << TFI)
  7682. /* 21 */ | (0u << TFOR)
  7683. #if BASH_FUNCTION
  7684. /* 22 */ | (0u << TFUNCTION)
  7685. #endif
  7686. /* 23 */ | (0u << TIF)
  7687. /* 24 */ | (0u << TIN)
  7688. /* 25 */ | (1u << TTHEN)
  7689. /* 26 */ | (0u << TUNTIL)
  7690. /* 27 */ | (0u << TWHILE)
  7691. /* 28 */ | (0u << TBEGIN)
  7692. /* 29 */ | (1u << TEND)
  7693. , /* thus far 29 bits used */
  7694. };
  7695. static const char *const tokname_array[] = {
  7696. "end of file",
  7697. "newline",
  7698. "redirection",
  7699. "word",
  7700. ";",
  7701. "&",
  7702. "&&",
  7703. "||",
  7704. "|",
  7705. "(",
  7706. ")",
  7707. ";;",
  7708. "`",
  7709. #define KWDOFFSET 13
  7710. /* the following are keywords */
  7711. "!",
  7712. "case",
  7713. "do",
  7714. "done",
  7715. "elif",
  7716. "else",
  7717. "esac",
  7718. "fi",
  7719. "for",
  7720. #if BASH_FUNCTION
  7721. "function",
  7722. #endif
  7723. "if",
  7724. "in",
  7725. "then",
  7726. "until",
  7727. "while",
  7728. "{",
  7729. "}",
  7730. };
  7731. /* Wrapper around strcmp for qsort/bsearch/... */
  7732. static int
  7733. pstrcmp(const void *a, const void *b)
  7734. {
  7735. return strcmp((char*)a, *(char**)b);
  7736. }
  7737. static const char *const *
  7738. findkwd(const char *s)
  7739. {
  7740. return bsearch(s, tokname_array + KWDOFFSET,
  7741. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7742. sizeof(tokname_array[0]), pstrcmp);
  7743. }
  7744. /*
  7745. * Locate and print what a word is...
  7746. */
  7747. static int
  7748. describe_command(char *command, const char *path, int describe_command_verbose)
  7749. {
  7750. struct cmdentry entry;
  7751. #if ENABLE_ASH_ALIAS
  7752. const struct alias *ap;
  7753. #endif
  7754. path = path ? path : pathval();
  7755. if (describe_command_verbose) {
  7756. out1str(command);
  7757. }
  7758. /* First look at the keywords */
  7759. if (findkwd(command)) {
  7760. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7761. goto out;
  7762. }
  7763. #if ENABLE_ASH_ALIAS
  7764. /* Then look at the aliases */
  7765. ap = lookupalias(command, 0);
  7766. if (ap != NULL) {
  7767. if (!describe_command_verbose) {
  7768. out1str("alias ");
  7769. printalias(ap);
  7770. return 0;
  7771. }
  7772. out1fmt(" is an alias for %s", ap->val);
  7773. goto out;
  7774. }
  7775. #endif
  7776. /* Brute force */
  7777. find_command(command, &entry, DO_ABS, path);
  7778. switch (entry.cmdtype) {
  7779. case CMDNORMAL: {
  7780. int j = entry.u.index;
  7781. char *p;
  7782. if (j < 0) {
  7783. p = command;
  7784. } else {
  7785. do {
  7786. p = path_advance(&path, command);
  7787. stunalloc(p);
  7788. } while (--j >= 0);
  7789. }
  7790. if (describe_command_verbose) {
  7791. out1fmt(" is %s", p);
  7792. } else {
  7793. out1str(p);
  7794. }
  7795. break;
  7796. }
  7797. case CMDFUNCTION:
  7798. if (describe_command_verbose) {
  7799. /*out1str(" is a shell function");*/
  7800. out1str(" is a function"); /* bash says this */
  7801. } else {
  7802. out1str(command);
  7803. }
  7804. break;
  7805. case CMDBUILTIN:
  7806. if (describe_command_verbose) {
  7807. out1fmt(" is a %sshell builtin",
  7808. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7809. "special " : nullstr
  7810. );
  7811. } else {
  7812. out1str(command);
  7813. }
  7814. break;
  7815. default:
  7816. if (describe_command_verbose) {
  7817. out1str(": not found\n");
  7818. }
  7819. return 127;
  7820. }
  7821. out:
  7822. out1str("\n");
  7823. return 0;
  7824. }
  7825. static int FAST_FUNC
  7826. typecmd(int argc UNUSED_PARAM, char **argv)
  7827. {
  7828. int i = 1;
  7829. int err = 0;
  7830. int verbose = 1;
  7831. /* type -p ... ? (we don't bother checking for 'p') */
  7832. if (argv[1] && argv[1][0] == '-') {
  7833. i++;
  7834. verbose = 0;
  7835. }
  7836. while (argv[i]) {
  7837. err |= describe_command(argv[i++], NULL, verbose);
  7838. }
  7839. return err;
  7840. }
  7841. #if ENABLE_ASH_CMDCMD
  7842. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7843. static char **
  7844. parse_command_args(char **argv, const char **path)
  7845. {
  7846. char *cp, c;
  7847. for (;;) {
  7848. cp = *++argv;
  7849. if (!cp)
  7850. return NULL;
  7851. if (*cp++ != '-')
  7852. break;
  7853. c = *cp++;
  7854. if (!c)
  7855. break;
  7856. if (c == '-' && !*cp) {
  7857. if (!*++argv)
  7858. return NULL;
  7859. break;
  7860. }
  7861. do {
  7862. switch (c) {
  7863. case 'p':
  7864. *path = bb_default_path;
  7865. break;
  7866. default:
  7867. /* run 'typecmd' for other options */
  7868. return NULL;
  7869. }
  7870. c = *cp++;
  7871. } while (c);
  7872. }
  7873. return argv;
  7874. }
  7875. static int FAST_FUNC
  7876. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7877. {
  7878. char *cmd;
  7879. int c;
  7880. enum {
  7881. VERIFY_BRIEF = 1,
  7882. VERIFY_VERBOSE = 2,
  7883. } verify = 0;
  7884. const char *path = NULL;
  7885. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7886. * never reaches this function.
  7887. */
  7888. while ((c = nextopt("pvV")) != '\0')
  7889. if (c == 'V')
  7890. verify |= VERIFY_VERBOSE;
  7891. else if (c == 'v')
  7892. /*verify |= VERIFY_BRIEF*/;
  7893. #if DEBUG
  7894. else if (c != 'p')
  7895. abort();
  7896. #endif
  7897. else
  7898. path = bb_default_path;
  7899. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7900. cmd = *argptr;
  7901. if (/*verify && */ cmd)
  7902. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7903. return 0;
  7904. }
  7905. #endif
  7906. /*static int funcblocksize; // size of structures in function */
  7907. /*static int funcstringsize; // size of strings in node */
  7908. static void *funcblock; /* block to allocate function from */
  7909. static char *funcstring_end; /* end of block to allocate strings from */
  7910. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7911. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7912. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7913. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7914. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7915. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7916. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7917. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7918. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7919. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7920. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7921. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7922. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7923. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7924. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7925. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7926. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7927. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7928. #if BASH_REDIR_OUTPUT
  7929. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7930. #endif
  7931. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7932. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7933. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7934. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7935. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7936. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7937. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7938. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7939. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7940. };
  7941. static int calcsize(int funcblocksize, union node *n);
  7942. static int
  7943. sizenodelist(int funcblocksize, struct nodelist *lp)
  7944. {
  7945. while (lp) {
  7946. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7947. funcblocksize = calcsize(funcblocksize, lp->n);
  7948. lp = lp->next;
  7949. }
  7950. return funcblocksize;
  7951. }
  7952. static int
  7953. calcsize(int funcblocksize, union node *n)
  7954. {
  7955. if (n == NULL)
  7956. return funcblocksize;
  7957. funcblocksize += nodesize[n->type];
  7958. switch (n->type) {
  7959. case NCMD:
  7960. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  7961. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  7962. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  7963. break;
  7964. case NPIPE:
  7965. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  7966. break;
  7967. case NREDIR:
  7968. case NBACKGND:
  7969. case NSUBSHELL:
  7970. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  7971. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  7972. break;
  7973. case NAND:
  7974. case NOR:
  7975. case NSEMI:
  7976. case NWHILE:
  7977. case NUNTIL:
  7978. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  7979. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  7980. break;
  7981. case NIF:
  7982. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  7983. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  7984. funcblocksize = calcsize(funcblocksize, n->nif.test);
  7985. break;
  7986. case NFOR:
  7987. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  7988. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  7989. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  7990. break;
  7991. case NCASE:
  7992. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  7993. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  7994. break;
  7995. case NCLIST:
  7996. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  7997. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  7998. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  7999. break;
  8000. case NDEFUN:
  8001. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8002. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8003. break;
  8004. case NARG:
  8005. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8006. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8007. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8008. break;
  8009. case NTO:
  8010. #if BASH_REDIR_OUTPUT
  8011. case NTO2:
  8012. #endif
  8013. case NCLOBBER:
  8014. case NFROM:
  8015. case NFROMTO:
  8016. case NAPPEND:
  8017. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8018. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8019. break;
  8020. case NTOFD:
  8021. case NFROMFD:
  8022. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8023. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8024. break;
  8025. case NHERE:
  8026. case NXHERE:
  8027. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8028. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8029. break;
  8030. case NNOT:
  8031. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8032. break;
  8033. };
  8034. return funcblocksize;
  8035. }
  8036. static char *
  8037. nodeckstrdup(char *s)
  8038. {
  8039. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8040. return strcpy(funcstring_end, s);
  8041. }
  8042. static union node *copynode(union node *);
  8043. static struct nodelist *
  8044. copynodelist(struct nodelist *lp)
  8045. {
  8046. struct nodelist *start;
  8047. struct nodelist **lpp;
  8048. lpp = &start;
  8049. while (lp) {
  8050. *lpp = funcblock;
  8051. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8052. (*lpp)->n = copynode(lp->n);
  8053. lp = lp->next;
  8054. lpp = &(*lpp)->next;
  8055. }
  8056. *lpp = NULL;
  8057. return start;
  8058. }
  8059. static union node *
  8060. copynode(union node *n)
  8061. {
  8062. union node *new;
  8063. if (n == NULL)
  8064. return NULL;
  8065. new = funcblock;
  8066. funcblock = (char *) funcblock + nodesize[n->type];
  8067. switch (n->type) {
  8068. case NCMD:
  8069. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8070. new->ncmd.args = copynode(n->ncmd.args);
  8071. new->ncmd.assign = copynode(n->ncmd.assign);
  8072. new->ncmd.linno = n->ncmd.linno;
  8073. break;
  8074. case NPIPE:
  8075. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8076. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8077. break;
  8078. case NREDIR:
  8079. case NBACKGND:
  8080. case NSUBSHELL:
  8081. new->nredir.redirect = copynode(n->nredir.redirect);
  8082. new->nredir.n = copynode(n->nredir.n);
  8083. new->nredir.linno = n->nredir.linno;
  8084. break;
  8085. case NAND:
  8086. case NOR:
  8087. case NSEMI:
  8088. case NWHILE:
  8089. case NUNTIL:
  8090. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8091. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8092. break;
  8093. case NIF:
  8094. new->nif.elsepart = copynode(n->nif.elsepart);
  8095. new->nif.ifpart = copynode(n->nif.ifpart);
  8096. new->nif.test = copynode(n->nif.test);
  8097. break;
  8098. case NFOR:
  8099. new->nfor.var = nodeckstrdup(n->nfor.var);
  8100. new->nfor.body = copynode(n->nfor.body);
  8101. new->nfor.args = copynode(n->nfor.args);
  8102. new->nfor.linno = n->nfor.linno;
  8103. break;
  8104. case NCASE:
  8105. new->ncase.cases = copynode(n->ncase.cases);
  8106. new->ncase.expr = copynode(n->ncase.expr);
  8107. new->ncase.linno = n->ncase.linno;
  8108. break;
  8109. case NCLIST:
  8110. new->nclist.body = copynode(n->nclist.body);
  8111. new->nclist.pattern = copynode(n->nclist.pattern);
  8112. new->nclist.next = copynode(n->nclist.next);
  8113. break;
  8114. case NDEFUN:
  8115. new->ndefun.body = copynode(n->ndefun.body);
  8116. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8117. new->ndefun.linno = n->ndefun.linno;
  8118. break;
  8119. case NARG:
  8120. new->narg.backquote = copynodelist(n->narg.backquote);
  8121. new->narg.text = nodeckstrdup(n->narg.text);
  8122. new->narg.next = copynode(n->narg.next);
  8123. break;
  8124. case NTO:
  8125. #if BASH_REDIR_OUTPUT
  8126. case NTO2:
  8127. #endif
  8128. case NCLOBBER:
  8129. case NFROM:
  8130. case NFROMTO:
  8131. case NAPPEND:
  8132. new->nfile.fname = copynode(n->nfile.fname);
  8133. new->nfile.fd = n->nfile.fd;
  8134. new->nfile.next = copynode(n->nfile.next);
  8135. break;
  8136. case NTOFD:
  8137. case NFROMFD:
  8138. new->ndup.vname = copynode(n->ndup.vname);
  8139. new->ndup.dupfd = n->ndup.dupfd;
  8140. new->ndup.fd = n->ndup.fd;
  8141. new->ndup.next = copynode(n->ndup.next);
  8142. break;
  8143. case NHERE:
  8144. case NXHERE:
  8145. new->nhere.doc = copynode(n->nhere.doc);
  8146. new->nhere.fd = n->nhere.fd;
  8147. new->nhere.next = copynode(n->nhere.next);
  8148. break;
  8149. case NNOT:
  8150. new->nnot.com = copynode(n->nnot.com);
  8151. break;
  8152. };
  8153. new->type = n->type;
  8154. return new;
  8155. }
  8156. /*
  8157. * Make a copy of a parse tree.
  8158. */
  8159. static struct funcnode *
  8160. copyfunc(union node *n)
  8161. {
  8162. struct funcnode *f;
  8163. size_t blocksize;
  8164. /*funcstringsize = 0;*/
  8165. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8166. f = ckzalloc(blocksize /* + funcstringsize */);
  8167. funcblock = (char *) f + offsetof(struct funcnode, n);
  8168. funcstring_end = (char *) f + blocksize;
  8169. copynode(n);
  8170. /* f->count = 0; - ckzalloc did it */
  8171. return f;
  8172. }
  8173. /*
  8174. * Define a shell function.
  8175. */
  8176. static void
  8177. defun(union node *func)
  8178. {
  8179. struct cmdentry entry;
  8180. INT_OFF;
  8181. entry.cmdtype = CMDFUNCTION;
  8182. entry.u.func = copyfunc(func);
  8183. addcmdentry(func->ndefun.text, &entry);
  8184. INT_ON;
  8185. }
  8186. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8187. #define SKIPBREAK (1 << 0)
  8188. #define SKIPCONT (1 << 1)
  8189. #define SKIPFUNC (1 << 2)
  8190. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8191. static int skipcount; /* number of levels to skip */
  8192. static int loopnest; /* current loop nesting level */
  8193. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8194. /* Forward decl way out to parsing code - dotrap needs it */
  8195. static int evalstring(char *s, int flags);
  8196. /* Called to execute a trap.
  8197. * Single callsite - at the end of evaltree().
  8198. * If we return non-zero, evaltree raises EXEXIT exception.
  8199. *
  8200. * Perhaps we should avoid entering new trap handlers
  8201. * while we are executing a trap handler. [is it a TODO?]
  8202. */
  8203. static void
  8204. dotrap(void)
  8205. {
  8206. uint8_t *g;
  8207. int sig;
  8208. uint8_t last_status;
  8209. if (!pending_sig)
  8210. return;
  8211. last_status = exitstatus;
  8212. pending_sig = 0;
  8213. barrier();
  8214. TRACE(("dotrap entered\n"));
  8215. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8216. char *p;
  8217. if (!*g)
  8218. continue;
  8219. if (evalskip) {
  8220. pending_sig = sig;
  8221. break;
  8222. }
  8223. p = trap[sig];
  8224. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8225. * don't upset it by resetting gotsig[SIGINT-1] */
  8226. if (sig == SIGINT && !p)
  8227. continue;
  8228. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8229. *g = 0;
  8230. if (!p)
  8231. continue;
  8232. evalstring(p, 0);
  8233. }
  8234. exitstatus = last_status;
  8235. TRACE(("dotrap returns\n"));
  8236. }
  8237. /* forward declarations - evaluation is fairly recursive business... */
  8238. static int evalloop(union node *, int);
  8239. static int evalfor(union node *, int);
  8240. static int evalcase(union node *, int);
  8241. static int evalsubshell(union node *, int);
  8242. static void expredir(union node *);
  8243. static int evalpipe(union node *, int);
  8244. static int evalcommand(union node *, int);
  8245. static int evalbltin(const struct builtincmd *, int, char **, int);
  8246. static void prehash(union node *);
  8247. /*
  8248. * Evaluate a parse tree. The value is left in the global variable
  8249. * exitstatus.
  8250. */
  8251. static int
  8252. evaltree(union node *n, int flags)
  8253. {
  8254. int checkexit = 0;
  8255. int (*evalfn)(union node *, int);
  8256. int status = 0;
  8257. if (n == NULL) {
  8258. TRACE(("evaltree(NULL) called\n"));
  8259. goto out;
  8260. }
  8261. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8262. dotrap();
  8263. switch (n->type) {
  8264. default:
  8265. #if DEBUG
  8266. out1fmt("Node type = %d\n", n->type);
  8267. fflush_all();
  8268. break;
  8269. #endif
  8270. case NNOT:
  8271. status = !evaltree(n->nnot.com, EV_TESTED);
  8272. goto setstatus;
  8273. case NREDIR:
  8274. errlinno = lineno = n->nredir.linno;
  8275. if (funcline)
  8276. lineno -= funcline - 1;
  8277. expredir(n->nredir.redirect);
  8278. pushredir(n->nredir.redirect);
  8279. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8280. if (!status) {
  8281. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8282. }
  8283. if (n->nredir.redirect)
  8284. popredir(/*drop:*/ 0);
  8285. goto setstatus;
  8286. case NCMD:
  8287. evalfn = evalcommand;
  8288. checkexit:
  8289. if (eflag && !(flags & EV_TESTED))
  8290. checkexit = ~0;
  8291. goto calleval;
  8292. case NFOR:
  8293. evalfn = evalfor;
  8294. goto calleval;
  8295. case NWHILE:
  8296. case NUNTIL:
  8297. evalfn = evalloop;
  8298. goto calleval;
  8299. case NSUBSHELL:
  8300. case NBACKGND:
  8301. evalfn = evalsubshell;
  8302. goto checkexit;
  8303. case NPIPE:
  8304. evalfn = evalpipe;
  8305. goto checkexit;
  8306. case NCASE:
  8307. evalfn = evalcase;
  8308. goto calleval;
  8309. case NAND:
  8310. case NOR:
  8311. case NSEMI: {
  8312. #if NAND + 1 != NOR
  8313. #error NAND + 1 != NOR
  8314. #endif
  8315. #if NOR + 1 != NSEMI
  8316. #error NOR + 1 != NSEMI
  8317. #endif
  8318. unsigned is_or = n->type - NAND;
  8319. status = evaltree(
  8320. n->nbinary.ch1,
  8321. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8322. );
  8323. if ((!status) == is_or || evalskip)
  8324. break;
  8325. n = n->nbinary.ch2;
  8326. evaln:
  8327. evalfn = evaltree;
  8328. calleval:
  8329. status = evalfn(n, flags);
  8330. goto setstatus;
  8331. }
  8332. case NIF:
  8333. status = evaltree(n->nif.test, EV_TESTED);
  8334. if (evalskip)
  8335. break;
  8336. if (!status) {
  8337. n = n->nif.ifpart;
  8338. goto evaln;
  8339. }
  8340. if (n->nif.elsepart) {
  8341. n = n->nif.elsepart;
  8342. goto evaln;
  8343. }
  8344. status = 0;
  8345. goto setstatus;
  8346. case NDEFUN:
  8347. defun(n);
  8348. /* Not necessary. To test it:
  8349. * "false; f() { qwerty; }; echo $?" should print 0.
  8350. */
  8351. /* status = 0; */
  8352. setstatus:
  8353. exitstatus = status;
  8354. break;
  8355. }
  8356. out:
  8357. /* Order of checks below is important:
  8358. * signal handlers trigger before exit caused by "set -e".
  8359. */
  8360. dotrap();
  8361. if (checkexit & status)
  8362. raise_exception(EXEXIT);
  8363. if (flags & EV_EXIT)
  8364. raise_exception(EXEXIT);
  8365. TRACE(("leaving evaltree (no interrupts)\n"));
  8366. return exitstatus;
  8367. }
  8368. static int
  8369. skiploop(void)
  8370. {
  8371. int skip = evalskip;
  8372. switch (skip) {
  8373. case 0:
  8374. break;
  8375. case SKIPBREAK:
  8376. case SKIPCONT:
  8377. if (--skipcount <= 0) {
  8378. evalskip = 0;
  8379. break;
  8380. }
  8381. skip = SKIPBREAK;
  8382. break;
  8383. }
  8384. return skip;
  8385. }
  8386. static int
  8387. evalloop(union node *n, int flags)
  8388. {
  8389. int skip;
  8390. int status;
  8391. loopnest++;
  8392. status = 0;
  8393. flags &= EV_TESTED;
  8394. do {
  8395. int i;
  8396. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8397. skip = skiploop();
  8398. if (skip == SKIPFUNC)
  8399. status = i;
  8400. if (skip)
  8401. continue;
  8402. if (n->type != NWHILE)
  8403. i = !i;
  8404. if (i != 0)
  8405. break;
  8406. status = evaltree(n->nbinary.ch2, flags);
  8407. skip = skiploop();
  8408. } while (!(skip & ~SKIPCONT));
  8409. loopnest--;
  8410. return status;
  8411. }
  8412. static int
  8413. evalfor(union node *n, int flags)
  8414. {
  8415. struct arglist arglist;
  8416. union node *argp;
  8417. struct strlist *sp;
  8418. struct stackmark smark;
  8419. int status = 0;
  8420. errlinno = lineno = n->ncase.linno;
  8421. if (funcline)
  8422. lineno -= funcline - 1;
  8423. setstackmark(&smark);
  8424. arglist.list = NULL;
  8425. arglist.lastp = &arglist.list;
  8426. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8427. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8428. }
  8429. *arglist.lastp = NULL;
  8430. loopnest++;
  8431. flags &= EV_TESTED;
  8432. for (sp = arglist.list; sp; sp = sp->next) {
  8433. setvar0(n->nfor.var, sp->text);
  8434. status = evaltree(n->nfor.body, flags);
  8435. if (skiploop() & ~SKIPCONT)
  8436. break;
  8437. }
  8438. loopnest--;
  8439. popstackmark(&smark);
  8440. return status;
  8441. }
  8442. static int
  8443. evalcase(union node *n, int flags)
  8444. {
  8445. union node *cp;
  8446. union node *patp;
  8447. struct arglist arglist;
  8448. struct stackmark smark;
  8449. int status = 0;
  8450. errlinno = lineno = n->ncase.linno;
  8451. if (funcline)
  8452. lineno -= funcline - 1;
  8453. setstackmark(&smark);
  8454. arglist.list = NULL;
  8455. arglist.lastp = &arglist.list;
  8456. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8457. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8458. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8459. if (casematch(patp, arglist.list->text)) {
  8460. /* Ensure body is non-empty as otherwise
  8461. * EV_EXIT may prevent us from setting the
  8462. * exit status.
  8463. */
  8464. if (evalskip == 0 && cp->nclist.body) {
  8465. status = evaltree(cp->nclist.body, flags);
  8466. }
  8467. goto out;
  8468. }
  8469. }
  8470. }
  8471. out:
  8472. popstackmark(&smark);
  8473. return status;
  8474. }
  8475. /*
  8476. * Kick off a subshell to evaluate a tree.
  8477. */
  8478. static int
  8479. evalsubshell(union node *n, int flags)
  8480. {
  8481. struct job *jp;
  8482. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8483. int status;
  8484. errlinno = lineno = n->nredir.linno;
  8485. if (funcline)
  8486. lineno -= funcline - 1;
  8487. expredir(n->nredir.redirect);
  8488. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8489. goto nofork;
  8490. INT_OFF;
  8491. if (backgnd == FORK_FG)
  8492. get_tty_state();
  8493. jp = makejob(/*n,*/ 1);
  8494. if (forkshell(jp, n, backgnd) == 0) {
  8495. /* child */
  8496. INT_ON;
  8497. flags |= EV_EXIT;
  8498. if (backgnd)
  8499. flags &= ~EV_TESTED;
  8500. nofork:
  8501. redirect(n->nredir.redirect, 0);
  8502. evaltreenr(n->nredir.n, flags);
  8503. /* never returns */
  8504. }
  8505. /* parent */
  8506. status = 0;
  8507. if (backgnd == FORK_FG)
  8508. status = waitforjob(jp);
  8509. INT_ON;
  8510. return status;
  8511. }
  8512. /*
  8513. * Compute the names of the files in a redirection list.
  8514. */
  8515. static void fixredir(union node *, const char *, int);
  8516. static void
  8517. expredir(union node *n)
  8518. {
  8519. union node *redir;
  8520. for (redir = n; redir; redir = redir->nfile.next) {
  8521. struct arglist fn;
  8522. fn.list = NULL;
  8523. fn.lastp = &fn.list;
  8524. switch (redir->type) {
  8525. case NFROMTO:
  8526. case NFROM:
  8527. case NTO:
  8528. #if BASH_REDIR_OUTPUT
  8529. case NTO2:
  8530. #endif
  8531. case NCLOBBER:
  8532. case NAPPEND:
  8533. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8534. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8535. #if BASH_REDIR_OUTPUT
  8536. store_expfname:
  8537. #endif
  8538. #if 0
  8539. // By the design of stack allocator, the loop of this kind:
  8540. // while true; do while true; do break; done </dev/null; done
  8541. // will look like a memory leak: ash plans to free expfname's
  8542. // of "/dev/null" as soon as it finishes running the loop
  8543. // (in this case, never).
  8544. // This "fix" is wrong:
  8545. if (redir->nfile.expfname)
  8546. stunalloc(redir->nfile.expfname);
  8547. // It results in corrupted state of stacked allocations.
  8548. #endif
  8549. redir->nfile.expfname = fn.list->text;
  8550. break;
  8551. case NFROMFD:
  8552. case NTOFD: /* >& */
  8553. if (redir->ndup.vname) {
  8554. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  8555. if (fn.list == NULL)
  8556. ash_msg_and_raise_error("redir error");
  8557. #if BASH_REDIR_OUTPUT
  8558. //FIXME: we used expandarg with different args!
  8559. if (!isdigit_str9(fn.list->text)) {
  8560. /* >&file, not >&fd */
  8561. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8562. ash_msg_and_raise_error("redir error");
  8563. redir->type = NTO2;
  8564. goto store_expfname;
  8565. }
  8566. #endif
  8567. fixredir(redir, fn.list->text, 1);
  8568. }
  8569. break;
  8570. }
  8571. }
  8572. }
  8573. /*
  8574. * Evaluate a pipeline. All the processes in the pipeline are children
  8575. * of the process creating the pipeline. (This differs from some versions
  8576. * of the shell, which make the last process in a pipeline the parent
  8577. * of all the rest.)
  8578. */
  8579. static int
  8580. evalpipe(union node *n, int flags)
  8581. {
  8582. struct job *jp;
  8583. struct nodelist *lp;
  8584. int pipelen;
  8585. int prevfd;
  8586. int pip[2];
  8587. int status = 0;
  8588. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8589. pipelen = 0;
  8590. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8591. pipelen++;
  8592. flags |= EV_EXIT;
  8593. INT_OFF;
  8594. if (n->npipe.pipe_backgnd == 0)
  8595. get_tty_state();
  8596. jp = makejob(/*n,*/ pipelen);
  8597. prevfd = -1;
  8598. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8599. prehash(lp->n);
  8600. pip[1] = -1;
  8601. if (lp->next) {
  8602. if (pipe(pip) < 0) {
  8603. close(prevfd);
  8604. ash_msg_and_raise_perror("can't create pipe");
  8605. }
  8606. }
  8607. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8608. /* child */
  8609. INT_ON;
  8610. if (pip[1] >= 0) {
  8611. close(pip[0]);
  8612. }
  8613. if (prevfd > 0) {
  8614. dup2(prevfd, 0);
  8615. close(prevfd);
  8616. }
  8617. if (pip[1] > 1) {
  8618. dup2(pip[1], 1);
  8619. close(pip[1]);
  8620. }
  8621. evaltreenr(lp->n, flags);
  8622. /* never returns */
  8623. }
  8624. /* parent */
  8625. if (prevfd >= 0)
  8626. close(prevfd);
  8627. prevfd = pip[0];
  8628. /* Don't want to trigger debugging */
  8629. if (pip[1] != -1)
  8630. close(pip[1]);
  8631. }
  8632. if (n->npipe.pipe_backgnd == 0) {
  8633. status = waitforjob(jp);
  8634. TRACE(("evalpipe: job done exit status %d\n", status));
  8635. }
  8636. INT_ON;
  8637. return status;
  8638. }
  8639. /*
  8640. * Controls whether the shell is interactive or not.
  8641. */
  8642. static void
  8643. setinteractive(int on)
  8644. {
  8645. static smallint is_interactive;
  8646. if (++on == is_interactive)
  8647. return;
  8648. is_interactive = on;
  8649. setsignal(SIGINT);
  8650. setsignal(SIGQUIT);
  8651. setsignal(SIGTERM);
  8652. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8653. if (is_interactive > 1) {
  8654. /* Looks like they want an interactive shell */
  8655. static smallint did_banner;
  8656. if (!did_banner) {
  8657. /* note: ash and hush share this string */
  8658. out1fmt("\n\n%s %s\n"
  8659. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8660. "\n",
  8661. bb_banner,
  8662. "built-in shell (ash)"
  8663. );
  8664. did_banner = 1;
  8665. }
  8666. }
  8667. #endif
  8668. }
  8669. static void
  8670. optschanged(void)
  8671. {
  8672. #if DEBUG
  8673. opentrace();
  8674. #endif
  8675. setinteractive(iflag);
  8676. setjobctl(mflag);
  8677. #if ENABLE_FEATURE_EDITING_VI
  8678. if (viflag)
  8679. line_input_state->flags |= VI_MODE;
  8680. else
  8681. line_input_state->flags &= ~VI_MODE;
  8682. #else
  8683. viflag = 0; /* forcibly keep the option off */
  8684. #endif
  8685. }
  8686. struct localvar_list {
  8687. struct localvar_list *next;
  8688. struct localvar *lv;
  8689. };
  8690. static struct localvar_list *localvar_stack;
  8691. /*
  8692. * Called after a function returns.
  8693. * Interrupts must be off.
  8694. */
  8695. static void
  8696. poplocalvars(int keep)
  8697. {
  8698. struct localvar_list *ll;
  8699. struct localvar *lvp, *next;
  8700. struct var *vp;
  8701. INT_OFF;
  8702. ll = localvar_stack;
  8703. localvar_stack = ll->next;
  8704. next = ll->lv;
  8705. free(ll);
  8706. while ((lvp = next) != NULL) {
  8707. next = lvp->next;
  8708. vp = lvp->vp;
  8709. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8710. if (keep) {
  8711. int bits = VSTRFIXED;
  8712. if (lvp->flags != VUNSET) {
  8713. if (vp->var_text == lvp->text)
  8714. bits |= VTEXTFIXED;
  8715. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8716. free((char*)lvp->text);
  8717. }
  8718. vp->flags &= ~bits;
  8719. vp->flags |= (lvp->flags & bits);
  8720. if ((vp->flags &
  8721. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8722. unsetvar(vp->var_text);
  8723. } else if (vp == NULL) { /* $- saved */
  8724. memcpy(optlist, lvp->text, sizeof(optlist));
  8725. free((char*)lvp->text);
  8726. optschanged();
  8727. } else if (lvp->flags == VUNSET) {
  8728. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8729. unsetvar(vp->var_text);
  8730. } else {
  8731. if (vp->var_func)
  8732. vp->var_func(var_end(lvp->text));
  8733. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8734. free((char*)vp->var_text);
  8735. vp->flags = lvp->flags;
  8736. vp->var_text = lvp->text;
  8737. }
  8738. free(lvp);
  8739. }
  8740. INT_ON;
  8741. }
  8742. /*
  8743. * Create a new localvar environment.
  8744. */
  8745. static struct localvar_list *
  8746. pushlocalvars(void)
  8747. {
  8748. struct localvar_list *ll;
  8749. INT_OFF;
  8750. ll = ckzalloc(sizeof(*ll));
  8751. /*ll->lv = NULL; - zalloc did it */
  8752. ll->next = localvar_stack;
  8753. localvar_stack = ll;
  8754. INT_ON;
  8755. return ll->next;
  8756. }
  8757. static void
  8758. unwindlocalvars(struct localvar_list *stop)
  8759. {
  8760. while (localvar_stack != stop)
  8761. poplocalvars(0);
  8762. }
  8763. static int
  8764. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8765. {
  8766. volatile struct shparam saveparam;
  8767. struct jmploc *volatile savehandler;
  8768. struct jmploc jmploc;
  8769. int e;
  8770. int savefuncline;
  8771. saveparam = shellparam;
  8772. savefuncline = funcline;
  8773. savehandler = exception_handler;
  8774. e = setjmp(jmploc.loc);
  8775. if (e) {
  8776. goto funcdone;
  8777. }
  8778. INT_OFF;
  8779. exception_handler = &jmploc;
  8780. shellparam.malloced = 0;
  8781. func->count++;
  8782. funcline = func->n.ndefun.linno;
  8783. INT_ON;
  8784. shellparam.nparam = argc - 1;
  8785. shellparam.p = argv + 1;
  8786. #if ENABLE_ASH_GETOPTS
  8787. shellparam.optind = 1;
  8788. shellparam.optoff = -1;
  8789. #endif
  8790. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  8791. funcdone:
  8792. INT_OFF;
  8793. funcline = savefuncline;
  8794. freefunc(func);
  8795. freeparam(&shellparam);
  8796. shellparam = saveparam;
  8797. exception_handler = savehandler;
  8798. INT_ON;
  8799. evalskip &= ~SKIPFUNC;
  8800. return e;
  8801. }
  8802. /*
  8803. * Make a variable a local variable. When a variable is made local, it's
  8804. * value and flags are saved in a localvar structure. The saved values
  8805. * will be restored when the shell function returns. We handle the name
  8806. * "-" as a special case: it makes changes to "set +-options" local
  8807. * (options will be restored on return from the function).
  8808. */
  8809. static void
  8810. mklocal(char *name)
  8811. {
  8812. struct localvar *lvp;
  8813. struct var **vpp;
  8814. struct var *vp;
  8815. char *eq = strchr(name, '=');
  8816. INT_OFF;
  8817. /* Cater for duplicate "local". Examples:
  8818. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8819. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8820. */
  8821. lvp = localvar_stack->lv;
  8822. while (lvp) {
  8823. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8824. if (eq)
  8825. setvareq(name, 0);
  8826. /* else:
  8827. * it's a duplicate "local VAR" declaration, do nothing
  8828. */
  8829. goto ret;
  8830. }
  8831. lvp = lvp->next;
  8832. }
  8833. lvp = ckzalloc(sizeof(*lvp));
  8834. if (LONE_DASH(name)) {
  8835. char *p;
  8836. p = ckmalloc(sizeof(optlist));
  8837. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8838. vp = NULL;
  8839. } else {
  8840. vpp = hashvar(name);
  8841. vp = *findvar(vpp, name);
  8842. if (vp == NULL) {
  8843. /* variable did not exist yet */
  8844. if (eq)
  8845. vp = setvareq(name, VSTRFIXED);
  8846. else
  8847. vp = setvar(name, NULL, VSTRFIXED);
  8848. lvp->flags = VUNSET;
  8849. } else {
  8850. lvp->text = vp->var_text;
  8851. lvp->flags = vp->flags;
  8852. /* make sure neither "struct var" nor string gets freed
  8853. * during (un)setting:
  8854. */
  8855. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8856. if (eq)
  8857. setvareq(name, 0);
  8858. else
  8859. /* "local VAR" unsets VAR: */
  8860. setvar0(name, NULL);
  8861. }
  8862. }
  8863. lvp->vp = vp;
  8864. lvp->next = localvar_stack->lv;
  8865. localvar_stack->lv = lvp;
  8866. ret:
  8867. INT_ON;
  8868. }
  8869. /*
  8870. * The "local" command.
  8871. */
  8872. static int FAST_FUNC
  8873. localcmd(int argc UNUSED_PARAM, char **argv)
  8874. {
  8875. char *name;
  8876. if (!localvar_stack)
  8877. ash_msg_and_raise_error("not in a function");
  8878. argv = argptr;
  8879. while ((name = *argv++) != NULL) {
  8880. mklocal(name);
  8881. }
  8882. return 0;
  8883. }
  8884. static int FAST_FUNC
  8885. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8886. {
  8887. return 1;
  8888. }
  8889. static int FAST_FUNC
  8890. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8891. {
  8892. return 0;
  8893. }
  8894. static int FAST_FUNC
  8895. execcmd(int argc UNUSED_PARAM, char **argv)
  8896. {
  8897. optionarg = NULL;
  8898. while (nextopt("a:") != '\0')
  8899. /* nextopt() sets optionarg to "-a ARGV0" */;
  8900. argv = argptr;
  8901. if (argv[0]) {
  8902. char *prog;
  8903. iflag = 0; /* exit on error */
  8904. mflag = 0;
  8905. optschanged();
  8906. /* We should set up signals for "exec CMD"
  8907. * the same way as for "CMD" without "exec".
  8908. * But optschanged->setinteractive->setsignal
  8909. * still thought we are a root shell. Therefore, for example,
  8910. * SIGQUIT is still set to IGN. Fix it:
  8911. */
  8912. shlvl++;
  8913. setsignal(SIGQUIT);
  8914. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  8915. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  8916. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  8917. prog = argv[0];
  8918. if (optionarg)
  8919. argv[0] = optionarg;
  8920. shellexec(prog, argv, pathval(), 0);
  8921. /* NOTREACHED */
  8922. }
  8923. return 0;
  8924. }
  8925. /*
  8926. * The return command.
  8927. */
  8928. static int FAST_FUNC
  8929. returncmd(int argc UNUSED_PARAM, char **argv)
  8930. {
  8931. /*
  8932. * If called outside a function, do what ksh does;
  8933. * skip the rest of the file.
  8934. */
  8935. evalskip = SKIPFUNC;
  8936. return argv[1] ? number(argv[1]) : exitstatus;
  8937. }
  8938. /* Forward declarations for builtintab[] */
  8939. static int breakcmd(int, char **) FAST_FUNC;
  8940. static int dotcmd(int, char **) FAST_FUNC;
  8941. static int evalcmd(int, char **, int) FAST_FUNC;
  8942. static int exitcmd(int, char **) FAST_FUNC;
  8943. static int exportcmd(int, char **) FAST_FUNC;
  8944. #if ENABLE_ASH_GETOPTS
  8945. static int getoptscmd(int, char **) FAST_FUNC;
  8946. #endif
  8947. #if ENABLE_ASH_HELP
  8948. static int helpcmd(int, char **) FAST_FUNC;
  8949. #endif
  8950. #if MAX_HISTORY
  8951. static int historycmd(int, char **) FAST_FUNC;
  8952. #endif
  8953. #if ENABLE_FEATURE_SH_MATH
  8954. static int letcmd(int, char **) FAST_FUNC;
  8955. #endif
  8956. static int readcmd(int, char **) FAST_FUNC;
  8957. static int setcmd(int, char **) FAST_FUNC;
  8958. static int shiftcmd(int, char **) FAST_FUNC;
  8959. static int timescmd(int, char **) FAST_FUNC;
  8960. static int trapcmd(int, char **) FAST_FUNC;
  8961. static int umaskcmd(int, char **) FAST_FUNC;
  8962. static int unsetcmd(int, char **) FAST_FUNC;
  8963. static int ulimitcmd(int, char **) FAST_FUNC;
  8964. #define BUILTIN_NOSPEC "0"
  8965. #define BUILTIN_SPECIAL "1"
  8966. #define BUILTIN_REGULAR "2"
  8967. #define BUILTIN_SPEC_REG "3"
  8968. #define BUILTIN_ASSIGN "4"
  8969. #define BUILTIN_SPEC_ASSG "5"
  8970. #define BUILTIN_REG_ASSG "6"
  8971. #define BUILTIN_SPEC_REG_ASSG "7"
  8972. /* Stubs for calling non-FAST_FUNC's */
  8973. #if ENABLE_ASH_ECHO
  8974. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8975. #endif
  8976. #if ENABLE_ASH_PRINTF
  8977. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8978. #endif
  8979. #if ENABLE_ASH_TEST || BASH_TEST2
  8980. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8981. #endif
  8982. /* Keep these in proper order since it is searched via bsearch() */
  8983. static const struct builtincmd builtintab[] = {
  8984. { BUILTIN_SPEC_REG "." , dotcmd },
  8985. { BUILTIN_SPEC_REG ":" , truecmd },
  8986. #if ENABLE_ASH_TEST
  8987. { BUILTIN_REGULAR "[" , testcmd },
  8988. #endif
  8989. #if BASH_TEST2
  8990. { BUILTIN_REGULAR "[[" , testcmd },
  8991. #endif
  8992. #if ENABLE_ASH_ALIAS
  8993. { BUILTIN_REG_ASSG "alias" , aliascmd },
  8994. #endif
  8995. #if JOBS
  8996. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  8997. #endif
  8998. { BUILTIN_SPEC_REG "break" , breakcmd },
  8999. { BUILTIN_REGULAR "cd" , cdcmd },
  9000. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9001. #if ENABLE_ASH_CMDCMD
  9002. { BUILTIN_REGULAR "command" , commandcmd },
  9003. #endif
  9004. { BUILTIN_SPEC_REG "continue", breakcmd },
  9005. #if ENABLE_ASH_ECHO
  9006. { BUILTIN_REGULAR "echo" , echocmd },
  9007. #endif
  9008. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9009. { BUILTIN_SPEC_REG "exec" , execcmd },
  9010. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9011. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9012. { BUILTIN_REGULAR "false" , falsecmd },
  9013. #if JOBS
  9014. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9015. #endif
  9016. #if ENABLE_ASH_GETOPTS
  9017. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9018. #endif
  9019. { BUILTIN_NOSPEC "hash" , hashcmd },
  9020. #if ENABLE_ASH_HELP
  9021. { BUILTIN_NOSPEC "help" , helpcmd },
  9022. #endif
  9023. #if MAX_HISTORY
  9024. { BUILTIN_NOSPEC "history" , historycmd },
  9025. #endif
  9026. #if JOBS
  9027. { BUILTIN_REGULAR "jobs" , jobscmd },
  9028. { BUILTIN_REGULAR "kill" , killcmd },
  9029. #endif
  9030. #if ENABLE_FEATURE_SH_MATH
  9031. { BUILTIN_NOSPEC "let" , letcmd },
  9032. #endif
  9033. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9034. #if ENABLE_ASH_PRINTF
  9035. { BUILTIN_REGULAR "printf" , printfcmd },
  9036. #endif
  9037. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  9038. { BUILTIN_REGULAR "read" , readcmd },
  9039. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9040. { BUILTIN_SPEC_REG "return" , returncmd },
  9041. { BUILTIN_SPEC_REG "set" , setcmd },
  9042. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9043. #if BASH_SOURCE
  9044. { BUILTIN_SPEC_REG "source" , dotcmd },
  9045. #endif
  9046. #if ENABLE_ASH_TEST
  9047. { BUILTIN_REGULAR "test" , testcmd },
  9048. #endif
  9049. { BUILTIN_SPEC_REG "times" , timescmd },
  9050. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9051. { BUILTIN_REGULAR "true" , truecmd },
  9052. { BUILTIN_NOSPEC "type" , typecmd },
  9053. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  9054. { BUILTIN_REGULAR "umask" , umaskcmd },
  9055. #if ENABLE_ASH_ALIAS
  9056. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9057. #endif
  9058. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9059. { BUILTIN_REGULAR "wait" , waitcmd },
  9060. };
  9061. /* Should match the above table! */
  9062. #define COMMANDCMD (builtintab + \
  9063. /* . : */ 2 + \
  9064. /* [ */ 1 * ENABLE_ASH_TEST + \
  9065. /* [[ */ 1 * BASH_TEST2 + \
  9066. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9067. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9068. /* break cd cddir */ 3)
  9069. #define EVALCMD (COMMANDCMD + \
  9070. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9071. /* continue */ 1 + \
  9072. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9073. 0)
  9074. #define EXECCMD (EVALCMD + \
  9075. /* eval */ 1)
  9076. /*
  9077. * Search the table of builtin commands.
  9078. */
  9079. static int
  9080. pstrcmp1(const void *a, const void *b)
  9081. {
  9082. return strcmp((char*)a, *(char**)b + 1);
  9083. }
  9084. static struct builtincmd *
  9085. find_builtin(const char *name)
  9086. {
  9087. struct builtincmd *bp;
  9088. bp = bsearch(
  9089. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9090. pstrcmp1
  9091. );
  9092. return bp;
  9093. }
  9094. /*
  9095. * Execute a simple command.
  9096. */
  9097. static void unwindfiles(struct parsefile *stop);
  9098. static int
  9099. isassignment(const char *p)
  9100. {
  9101. const char *q = endofname(p);
  9102. if (p == q)
  9103. return 0;
  9104. return *q == '=';
  9105. }
  9106. static int FAST_FUNC
  9107. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9108. {
  9109. /* Preserve exitstatus of a previous possible redirection
  9110. * as POSIX mandates */
  9111. return back_exitstatus;
  9112. }
  9113. static int
  9114. evalcommand(union node *cmd, int flags)
  9115. {
  9116. static const struct builtincmd null_bltin = {
  9117. "\0\0", bltincmd /* why three NULs? */
  9118. };
  9119. struct localvar_list *localvar_stop;
  9120. struct parsefile *file_stop;
  9121. struct redirtab *redir_stop;
  9122. struct stackmark smark;
  9123. union node *argp;
  9124. struct arglist arglist;
  9125. struct arglist varlist;
  9126. char **argv;
  9127. int argc;
  9128. const struct strlist *sp;
  9129. struct cmdentry cmdentry;
  9130. struct job *jp;
  9131. char *lastarg;
  9132. const char *path;
  9133. int spclbltin;
  9134. int status;
  9135. char **nargv;
  9136. smallint cmd_is_exec;
  9137. errlinno = lineno = cmd->ncmd.linno;
  9138. if (funcline)
  9139. lineno -= funcline - 1;
  9140. /* First expand the arguments. */
  9141. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9142. setstackmark(&smark);
  9143. localvar_stop = pushlocalvars();
  9144. file_stop = g_parsefile;
  9145. back_exitstatus = 0;
  9146. cmdentry.cmdtype = CMDBUILTIN;
  9147. cmdentry.u.cmd = &null_bltin;
  9148. varlist.lastp = &varlist.list;
  9149. *varlist.lastp = NULL;
  9150. arglist.lastp = &arglist.list;
  9151. *arglist.lastp = NULL;
  9152. argc = 0;
  9153. if (cmd->ncmd.args) {
  9154. struct builtincmd *bcmd;
  9155. smallint pseudovarflag;
  9156. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  9157. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  9158. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  9159. struct strlist **spp;
  9160. spp = arglist.lastp;
  9161. if (pseudovarflag && isassignment(argp->narg.text))
  9162. expandarg(argp, &arglist, EXP_VARTILDE);
  9163. else
  9164. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  9165. for (sp = *spp; sp; sp = sp->next)
  9166. argc++;
  9167. }
  9168. }
  9169. /* Reserve one extra spot at the front for shellexec. */
  9170. nargv = stalloc(sizeof(char *) * (argc + 2));
  9171. argv = ++nargv;
  9172. for (sp = arglist.list; sp; sp = sp->next) {
  9173. TRACE(("evalcommand arg: %s\n", sp->text));
  9174. *nargv++ = sp->text;
  9175. }
  9176. *nargv = NULL;
  9177. lastarg = NULL;
  9178. if (iflag && funcline == 0 && argc > 0)
  9179. lastarg = nargv[-1];
  9180. expredir(cmd->ncmd.redirect);
  9181. redir_stop = pushredir(cmd->ncmd.redirect);
  9182. preverrout_fd = 2;
  9183. if (BASH_XTRACEFD && xflag) {
  9184. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9185. * we do not emulate this. We only use its value.
  9186. */
  9187. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9188. if (xtracefd && is_number(xtracefd))
  9189. preverrout_fd = atoi(xtracefd);
  9190. }
  9191. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9192. path = vpath.var_text;
  9193. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9194. struct strlist **spp;
  9195. char *p;
  9196. spp = varlist.lastp;
  9197. expandarg(argp, &varlist, EXP_VARTILDE);
  9198. mklocal((*spp)->text);
  9199. /*
  9200. * Modify the command lookup path, if a PATH= assignment
  9201. * is present
  9202. */
  9203. p = (*spp)->text;
  9204. if (varcmp(p, path) == 0)
  9205. path = p;
  9206. }
  9207. /* Print the command if xflag is set. */
  9208. if (xflag) {
  9209. const char *pfx = "";
  9210. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9211. sp = varlist.list;
  9212. while (sp) {
  9213. char *varval = sp->text;
  9214. char *eq = strchrnul(varval, '=');
  9215. if (*eq)
  9216. eq++;
  9217. fdprintf(preverrout_fd, "%s%.*s%s",
  9218. pfx,
  9219. (int)(eq - varval), varval,
  9220. maybe_single_quote(eq)
  9221. );
  9222. sp = sp->next;
  9223. pfx = " ";
  9224. }
  9225. sp = arglist.list;
  9226. while (sp) {
  9227. fdprintf(preverrout_fd, "%s%s",
  9228. pfx,
  9229. /* always quote if matches reserved word: */
  9230. findkwd(sp->text)
  9231. ? single_quote(sp->text)
  9232. : maybe_single_quote(sp->text)
  9233. );
  9234. sp = sp->next;
  9235. pfx = " ";
  9236. }
  9237. safe_write(preverrout_fd, "\n", 1);
  9238. }
  9239. cmd_is_exec = 0;
  9240. spclbltin = -1;
  9241. /* Now locate the command. */
  9242. if (argc) {
  9243. int cmd_flag = DO_ERR;
  9244. #if ENABLE_ASH_CMDCMD
  9245. const char *oldpath = path + 5;
  9246. #endif
  9247. path += 5;
  9248. for (;;) {
  9249. find_command(argv[0], &cmdentry, cmd_flag, path);
  9250. if (cmdentry.cmdtype == CMDUNKNOWN) {
  9251. flush_stdout_stderr();
  9252. status = 127;
  9253. goto bail;
  9254. }
  9255. /* implement bltin and command here */
  9256. if (cmdentry.cmdtype != CMDBUILTIN)
  9257. break;
  9258. if (spclbltin < 0)
  9259. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9260. if (cmdentry.u.cmd == EXECCMD)
  9261. cmd_is_exec = 1;
  9262. #if ENABLE_ASH_CMDCMD
  9263. if (cmdentry.u.cmd == COMMANDCMD) {
  9264. path = oldpath;
  9265. nargv = parse_command_args(argv, &path);
  9266. if (!nargv)
  9267. break;
  9268. /* It's "command [-p] PROG ARGS" (that is, no -Vv).
  9269. * nargv => "PROG". path is updated if -p.
  9270. */
  9271. argc -= nargv - argv;
  9272. argv = nargv;
  9273. cmd_flag |= DO_NOFUNC;
  9274. } else
  9275. #endif
  9276. break;
  9277. }
  9278. }
  9279. if (status) {
  9280. bail:
  9281. exitstatus = status;
  9282. /* We have a redirection error. */
  9283. if (spclbltin > 0)
  9284. raise_exception(EXERROR);
  9285. goto out;
  9286. }
  9287. /* Execute the command. */
  9288. switch (cmdentry.cmdtype) {
  9289. default: {
  9290. #if ENABLE_FEATURE_SH_STANDALONE \
  9291. && ENABLE_FEATURE_SH_NOFORK \
  9292. && NUM_APPLETS > 1
  9293. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9294. * around run_nofork_applet() call.
  9295. * (2) Should this check also be done in forkshell()?
  9296. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9297. */
  9298. /* find_command() encodes applet_no as (-2 - applet_no) */
  9299. int applet_no = (- cmdentry.u.index - 2);
  9300. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9301. char **sv_environ;
  9302. INT_OFF;
  9303. sv_environ = environ;
  9304. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9305. /*
  9306. * Run <applet>_main().
  9307. * Signals (^C) can't interrupt here.
  9308. * Otherwise we can mangle stdio or malloc internal state.
  9309. * This makes applets which can run for a long time
  9310. * and/or wait for user input ineligible for NOFORK:
  9311. * for example, "yes" or "rm" (rm -i waits for input).
  9312. */
  9313. status = run_nofork_applet(applet_no, argv);
  9314. environ = sv_environ;
  9315. /*
  9316. * Try enabling NOFORK for "yes" applet.
  9317. * ^C _will_ stop it (write returns EINTR),
  9318. * but this causes stdout FILE to be stuck
  9319. * and needing clearerr(). What if other applets
  9320. * also can get EINTRs? Do we need to switch
  9321. * our signals to SA_RESTART?
  9322. */
  9323. /*clearerr(stdout);*/
  9324. INT_ON;
  9325. break;
  9326. }
  9327. #endif
  9328. /* Can we avoid forking? For example, very last command
  9329. * in a script or a subshell does not need forking,
  9330. * we can just exec it.
  9331. */
  9332. if (!(flags & EV_EXIT) || may_have_traps) {
  9333. /* No, forking off a child is necessary */
  9334. INT_OFF;
  9335. get_tty_state();
  9336. jp = makejob(/*cmd,*/ 1);
  9337. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9338. /* parent */
  9339. status = waitforjob(jp);
  9340. INT_ON;
  9341. TRACE(("forked child exited with %d\n", status));
  9342. break;
  9343. }
  9344. /* child */
  9345. FORCE_INT_ON;
  9346. /* fall through to exec'ing external program */
  9347. }
  9348. listsetvar(varlist.list, VEXPORT|VSTACK);
  9349. shellexec(argv[0], argv, path, cmdentry.u.index);
  9350. /* NOTREACHED */
  9351. } /* default */
  9352. case CMDBUILTIN:
  9353. if (spclbltin > 0 || argc == 0) {
  9354. poplocalvars(1);
  9355. if (cmd_is_exec && argc > 1)
  9356. listsetvar(varlist.list, VEXPORT);
  9357. }
  9358. /* Tight loop with builtins only:
  9359. * "while kill -0 $child; do true; done"
  9360. * will never exit even if $child died, unless we do this
  9361. * to reap the zombie and make kill detect that it's gone: */
  9362. dowait(DOWAIT_NONBLOCK, NULL);
  9363. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
  9364. if (exception_type == EXERROR && spclbltin <= 0) {
  9365. FORCE_INT_ON;
  9366. goto readstatus;
  9367. }
  9368. raise:
  9369. longjmp(exception_handler->loc, 1);
  9370. }
  9371. goto readstatus;
  9372. case CMDFUNCTION:
  9373. /* See above for the rationale */
  9374. dowait(DOWAIT_NONBLOCK, NULL);
  9375. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9376. goto raise;
  9377. readstatus:
  9378. status = exitstatus;
  9379. break;
  9380. } /* switch */
  9381. out:
  9382. if (cmd->ncmd.redirect)
  9383. popredir(/*drop:*/ cmd_is_exec);
  9384. unwindredir(redir_stop);
  9385. unwindfiles(file_stop);
  9386. unwindlocalvars(localvar_stop);
  9387. if (lastarg) {
  9388. /* dsl: I think this is intended to be used to support
  9389. * '_' in 'vi' command mode during line editing...
  9390. * However I implemented that within libedit itself.
  9391. */
  9392. setvar0("_", lastarg);
  9393. }
  9394. popstackmark(&smark);
  9395. return status;
  9396. }
  9397. static int
  9398. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9399. {
  9400. char *volatile savecmdname;
  9401. struct jmploc *volatile savehandler;
  9402. struct jmploc jmploc;
  9403. int status;
  9404. int i;
  9405. savecmdname = commandname;
  9406. savehandler = exception_handler;
  9407. i = setjmp(jmploc.loc);
  9408. if (i)
  9409. goto cmddone;
  9410. exception_handler = &jmploc;
  9411. commandname = argv[0];
  9412. argptr = argv + 1;
  9413. optptr = NULL; /* initialize nextopt */
  9414. if (cmd == EVALCMD)
  9415. status = evalcmd(argc, argv, flags);
  9416. else
  9417. status = (*cmd->builtin)(argc, argv);
  9418. flush_stdout_stderr();
  9419. status |= ferror(stdout);
  9420. exitstatus = status;
  9421. cmddone:
  9422. clearerr(stdout);
  9423. commandname = savecmdname;
  9424. exception_handler = savehandler;
  9425. return i;
  9426. }
  9427. static int
  9428. goodname(const char *p)
  9429. {
  9430. return endofname(p)[0] == '\0';
  9431. }
  9432. /*
  9433. * Search for a command. This is called before we fork so that the
  9434. * location of the command will be available in the parent as well as
  9435. * the child. The check for "goodname" is an overly conservative
  9436. * check that the name will not be subject to expansion.
  9437. */
  9438. static void
  9439. prehash(union node *n)
  9440. {
  9441. struct cmdentry entry;
  9442. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9443. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9444. }
  9445. /* ============ Builtin commands
  9446. *
  9447. * Builtin commands whose functions are closely tied to evaluation
  9448. * are implemented here.
  9449. */
  9450. /*
  9451. * Handle break and continue commands. Break, continue, and return are
  9452. * all handled by setting the evalskip flag. The evaluation routines
  9453. * above all check this flag, and if it is set they start skipping
  9454. * commands rather than executing them. The variable skipcount is
  9455. * the number of loops to break/continue, or the number of function
  9456. * levels to return. (The latter is always 1.) It should probably
  9457. * be an error to break out of more loops than exist, but it isn't
  9458. * in the standard shell so we don't make it one here.
  9459. */
  9460. static int FAST_FUNC
  9461. breakcmd(int argc UNUSED_PARAM, char **argv)
  9462. {
  9463. int n = argv[1] ? number(argv[1]) : 1;
  9464. if (n <= 0)
  9465. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9466. if (n > loopnest)
  9467. n = loopnest;
  9468. if (n > 0) {
  9469. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9470. skipcount = n;
  9471. }
  9472. return 0;
  9473. }
  9474. /*
  9475. * This implements the input routines used by the parser.
  9476. */
  9477. enum {
  9478. INPUT_PUSH_FILE = 1,
  9479. INPUT_NOFILE_OK = 2,
  9480. };
  9481. static smallint checkkwd;
  9482. /* values of checkkwd variable */
  9483. #define CHKALIAS 0x1
  9484. #define CHKKWD 0x2
  9485. #define CHKNL 0x4
  9486. #define CHKEOFMARK 0x8
  9487. /*
  9488. * Push a string back onto the input at this current parsefile level.
  9489. * We handle aliases this way.
  9490. */
  9491. #if !ENABLE_ASH_ALIAS
  9492. #define pushstring(s, ap) pushstring(s)
  9493. #endif
  9494. static void
  9495. pushstring(char *s, struct alias *ap)
  9496. {
  9497. struct strpush *sp;
  9498. int len;
  9499. len = strlen(s);
  9500. INT_OFF;
  9501. if (g_parsefile->strpush) {
  9502. sp = ckzalloc(sizeof(*sp));
  9503. sp->prev = g_parsefile->strpush;
  9504. } else {
  9505. sp = &(g_parsefile->basestrpush);
  9506. }
  9507. g_parsefile->strpush = sp;
  9508. sp->prev_string = g_parsefile->next_to_pgetc;
  9509. sp->prev_left_in_line = g_parsefile->left_in_line;
  9510. sp->unget = g_parsefile->unget;
  9511. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9512. #if ENABLE_ASH_ALIAS
  9513. sp->ap = ap;
  9514. if (ap) {
  9515. ap->flag |= ALIASINUSE;
  9516. sp->string = s;
  9517. }
  9518. #endif
  9519. g_parsefile->next_to_pgetc = s;
  9520. g_parsefile->left_in_line = len;
  9521. g_parsefile->unget = 0;
  9522. INT_ON;
  9523. }
  9524. static void
  9525. popstring(void)
  9526. {
  9527. struct strpush *sp = g_parsefile->strpush;
  9528. INT_OFF;
  9529. #if ENABLE_ASH_ALIAS
  9530. if (sp->ap) {
  9531. if (g_parsefile->next_to_pgetc[-1] == ' '
  9532. || g_parsefile->next_to_pgetc[-1] == '\t'
  9533. ) {
  9534. checkkwd |= CHKALIAS;
  9535. }
  9536. if (sp->string != sp->ap->val) {
  9537. free(sp->string);
  9538. }
  9539. sp->ap->flag &= ~ALIASINUSE;
  9540. if (sp->ap->flag & ALIASDEAD) {
  9541. unalias(sp->ap->name);
  9542. }
  9543. }
  9544. #endif
  9545. g_parsefile->next_to_pgetc = sp->prev_string;
  9546. g_parsefile->left_in_line = sp->prev_left_in_line;
  9547. g_parsefile->unget = sp->unget;
  9548. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9549. g_parsefile->strpush = sp->prev;
  9550. if (sp != &(g_parsefile->basestrpush))
  9551. free(sp);
  9552. INT_ON;
  9553. }
  9554. static int
  9555. preadfd(void)
  9556. {
  9557. int nr;
  9558. char *buf = g_parsefile->buf;
  9559. g_parsefile->next_to_pgetc = buf;
  9560. #if ENABLE_FEATURE_EDITING
  9561. retry:
  9562. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9563. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9564. else {
  9565. # if ENABLE_ASH_IDLE_TIMEOUT
  9566. int timeout = -1;
  9567. if (iflag) {
  9568. const char *tmout_var = lookupvar("TMOUT");
  9569. if (tmout_var) {
  9570. timeout = atoi(tmout_var) * 1000;
  9571. if (timeout <= 0)
  9572. timeout = -1;
  9573. }
  9574. }
  9575. line_input_state->timeout = timeout;
  9576. # endif
  9577. # if ENABLE_FEATURE_TAB_COMPLETION
  9578. line_input_state->path_lookup = pathval();
  9579. # endif
  9580. reinit_unicode_for_ash();
  9581. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9582. if (nr == 0) {
  9583. /* ^C pressed, "convert" to SIGINT */
  9584. write(STDOUT_FILENO, "^C", 2);
  9585. if (trap[SIGINT]) {
  9586. buf[0] = '\n';
  9587. buf[1] = '\0';
  9588. raise(SIGINT);
  9589. return 1;
  9590. }
  9591. exitstatus = 128 + SIGINT;
  9592. bb_putchar('\n');
  9593. goto retry;
  9594. }
  9595. if (nr < 0) {
  9596. if (errno == 0) {
  9597. /* Ctrl+D pressed */
  9598. nr = 0;
  9599. }
  9600. # if ENABLE_ASH_IDLE_TIMEOUT
  9601. else if (errno == EAGAIN && timeout > 0) {
  9602. puts("\007timed out waiting for input: auto-logout");
  9603. exitshell();
  9604. }
  9605. # endif
  9606. }
  9607. }
  9608. #else
  9609. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9610. #endif
  9611. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9612. if (nr < 0) {
  9613. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9614. int flags = fcntl(0, F_GETFL);
  9615. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9616. flags &= ~O_NONBLOCK;
  9617. if (fcntl(0, F_SETFL, flags) >= 0) {
  9618. out2str("sh: turning off NDELAY mode\n");
  9619. goto retry;
  9620. }
  9621. }
  9622. }
  9623. }
  9624. #endif
  9625. return nr;
  9626. }
  9627. /*
  9628. * Refill the input buffer and return the next input character:
  9629. *
  9630. * 1) If a string was pushed back on the input, pop it;
  9631. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9632. * or we are reading from a string so we can't refill the buffer,
  9633. * return EOF.
  9634. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9635. * 4) Process input up to the next newline, deleting nul characters.
  9636. */
  9637. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9638. #define pgetc_debug(...) ((void)0)
  9639. static int pgetc(void);
  9640. static int
  9641. preadbuffer(void)
  9642. {
  9643. char *q;
  9644. int more;
  9645. if (g_parsefile->strpush) {
  9646. #if ENABLE_ASH_ALIAS
  9647. if (g_parsefile->left_in_line == -1
  9648. && g_parsefile->strpush->ap
  9649. && g_parsefile->next_to_pgetc[-1] != ' '
  9650. && g_parsefile->next_to_pgetc[-1] != '\t'
  9651. ) {
  9652. pgetc_debug("preadbuffer PEOA");
  9653. return PEOA;
  9654. }
  9655. #endif
  9656. popstring();
  9657. return pgetc();
  9658. }
  9659. /* on both branches above g_parsefile->left_in_line < 0.
  9660. * "pgetc" needs refilling.
  9661. */
  9662. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9663. * pungetc() may increment it a few times.
  9664. * Assuming it won't increment it to less than -90.
  9665. */
  9666. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9667. pgetc_debug("preadbuffer PEOF1");
  9668. /* even in failure keep left_in_line and next_to_pgetc
  9669. * in lock step, for correct multi-layer pungetc.
  9670. * left_in_line was decremented before preadbuffer(),
  9671. * must inc next_to_pgetc: */
  9672. g_parsefile->next_to_pgetc++;
  9673. return PEOF;
  9674. }
  9675. more = g_parsefile->left_in_buffer;
  9676. if (more <= 0) {
  9677. flush_stdout_stderr();
  9678. again:
  9679. more = preadfd();
  9680. if (more <= 0) {
  9681. /* don't try reading again */
  9682. g_parsefile->left_in_line = -99;
  9683. pgetc_debug("preadbuffer PEOF2");
  9684. g_parsefile->next_to_pgetc++;
  9685. return PEOF;
  9686. }
  9687. }
  9688. /* Find out where's the end of line.
  9689. * Set g_parsefile->left_in_line
  9690. * and g_parsefile->left_in_buffer acordingly.
  9691. * NUL chars are deleted.
  9692. */
  9693. q = g_parsefile->next_to_pgetc;
  9694. for (;;) {
  9695. char c;
  9696. more--;
  9697. c = *q;
  9698. if (c == '\0') {
  9699. memmove(q, q + 1, more);
  9700. } else {
  9701. q++;
  9702. if (c == '\n') {
  9703. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9704. break;
  9705. }
  9706. }
  9707. if (more <= 0) {
  9708. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9709. if (g_parsefile->left_in_line < 0)
  9710. goto again;
  9711. break;
  9712. }
  9713. }
  9714. g_parsefile->left_in_buffer = more;
  9715. if (vflag) {
  9716. char save = *q;
  9717. *q = '\0';
  9718. out2str(g_parsefile->next_to_pgetc);
  9719. *q = save;
  9720. }
  9721. pgetc_debug("preadbuffer at %d:%p'%s'",
  9722. g_parsefile->left_in_line,
  9723. g_parsefile->next_to_pgetc,
  9724. g_parsefile->next_to_pgetc);
  9725. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9726. }
  9727. static void
  9728. nlprompt(void)
  9729. {
  9730. g_parsefile->linno++;
  9731. setprompt_if(doprompt, 2);
  9732. }
  9733. static void
  9734. nlnoprompt(void)
  9735. {
  9736. g_parsefile->linno++;
  9737. needprompt = doprompt;
  9738. }
  9739. static int
  9740. pgetc(void)
  9741. {
  9742. int c;
  9743. pgetc_debug("pgetc at %d:%p'%s'",
  9744. g_parsefile->left_in_line,
  9745. g_parsefile->next_to_pgetc,
  9746. g_parsefile->next_to_pgetc);
  9747. if (g_parsefile->unget)
  9748. return g_parsefile->lastc[--g_parsefile->unget];
  9749. if (--g_parsefile->left_in_line >= 0)
  9750. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9751. else
  9752. c = preadbuffer();
  9753. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9754. g_parsefile->lastc[0] = c;
  9755. return c;
  9756. }
  9757. #if ENABLE_ASH_ALIAS
  9758. static int
  9759. pgetc_without_PEOA(void)
  9760. {
  9761. int c;
  9762. do {
  9763. pgetc_debug("pgetc at %d:%p'%s'",
  9764. g_parsefile->left_in_line,
  9765. g_parsefile->next_to_pgetc,
  9766. g_parsefile->next_to_pgetc);
  9767. c = pgetc();
  9768. } while (c == PEOA);
  9769. return c;
  9770. }
  9771. #else
  9772. # define pgetc_without_PEOA() pgetc()
  9773. #endif
  9774. /*
  9775. * Undo a call to pgetc. Only two characters may be pushed back.
  9776. * PEOF may be pushed back.
  9777. */
  9778. static void
  9779. pungetc(void)
  9780. {
  9781. g_parsefile->unget++;
  9782. }
  9783. /* This one eats backslash+newline */
  9784. static int
  9785. pgetc_eatbnl(void)
  9786. {
  9787. int c;
  9788. while ((c = pgetc()) == '\\') {
  9789. if (pgetc() != '\n') {
  9790. pungetc();
  9791. break;
  9792. }
  9793. nlprompt();
  9794. }
  9795. return c;
  9796. }
  9797. struct synstack {
  9798. smalluint syntax;
  9799. uint8_t innerdq :1;
  9800. uint8_t varpushed :1;
  9801. uint8_t dblquote :1;
  9802. int varnest; /* levels of variables expansion */
  9803. int dqvarnest; /* levels of variables expansion within double quotes */
  9804. int parenlevel; /* levels of parens in arithmetic */
  9805. struct synstack *prev;
  9806. struct synstack *next;
  9807. };
  9808. static void
  9809. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  9810. {
  9811. memset(next, 0, sizeof(*next));
  9812. next->syntax = syntax;
  9813. next->next = *stack;
  9814. (*stack)->prev = next;
  9815. *stack = next;
  9816. }
  9817. static ALWAYS_INLINE void
  9818. synstack_pop(struct synstack **stack)
  9819. {
  9820. *stack = (*stack)->next;
  9821. }
  9822. /*
  9823. * To handle the "." command, a stack of input files is used. Pushfile
  9824. * adds a new entry to the stack and popfile restores the previous level.
  9825. */
  9826. static void
  9827. pushfile(void)
  9828. {
  9829. struct parsefile *pf;
  9830. pf = ckzalloc(sizeof(*pf));
  9831. pf->prev = g_parsefile;
  9832. pf->pf_fd = -1;
  9833. /*pf->strpush = NULL; - ckzalloc did it */
  9834. /*pf->basestrpush.prev = NULL;*/
  9835. /*pf->unget = 0;*/
  9836. g_parsefile = pf;
  9837. }
  9838. static void
  9839. popfile(void)
  9840. {
  9841. struct parsefile *pf = g_parsefile;
  9842. if (pf == &basepf)
  9843. return;
  9844. INT_OFF;
  9845. if (pf->pf_fd >= 0)
  9846. close(pf->pf_fd);
  9847. free(pf->buf);
  9848. while (pf->strpush)
  9849. popstring();
  9850. g_parsefile = pf->prev;
  9851. free(pf);
  9852. INT_ON;
  9853. }
  9854. static void
  9855. unwindfiles(struct parsefile *stop)
  9856. {
  9857. while (g_parsefile != stop)
  9858. popfile();
  9859. }
  9860. /*
  9861. * Return to top level.
  9862. */
  9863. static void
  9864. popallfiles(void)
  9865. {
  9866. unwindfiles(&basepf);
  9867. }
  9868. /*
  9869. * Close the file(s) that the shell is reading commands from. Called
  9870. * after a fork is done.
  9871. */
  9872. static void
  9873. closescript(void)
  9874. {
  9875. popallfiles();
  9876. if (g_parsefile->pf_fd > 0) {
  9877. close(g_parsefile->pf_fd);
  9878. g_parsefile->pf_fd = 0;
  9879. }
  9880. }
  9881. /*
  9882. * Like setinputfile, but takes an open file descriptor. Call this with
  9883. * interrupts off.
  9884. */
  9885. static void
  9886. setinputfd(int fd, int push)
  9887. {
  9888. if (push) {
  9889. pushfile();
  9890. g_parsefile->buf = NULL;
  9891. }
  9892. g_parsefile->pf_fd = fd;
  9893. if (g_parsefile->buf == NULL)
  9894. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9895. g_parsefile->left_in_buffer = 0;
  9896. g_parsefile->left_in_line = 0;
  9897. g_parsefile->linno = 1;
  9898. }
  9899. /*
  9900. * Set the input to take input from a file. If push is set, push the
  9901. * old input onto the stack first.
  9902. */
  9903. static int
  9904. setinputfile(const char *fname, int flags)
  9905. {
  9906. int fd;
  9907. INT_OFF;
  9908. fd = open(fname, O_RDONLY | O_CLOEXEC);
  9909. if (fd < 0) {
  9910. if (flags & INPUT_NOFILE_OK)
  9911. goto out;
  9912. exitstatus = 127;
  9913. ash_msg_and_raise_perror("can't open '%s'", fname);
  9914. }
  9915. if (fd < 10)
  9916. fd = savefd(fd);
  9917. else if (O_CLOEXEC == 0) /* old libc */
  9918. close_on_exec_on(fd);
  9919. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9920. out:
  9921. INT_ON;
  9922. return fd;
  9923. }
  9924. /*
  9925. * Like setinputfile, but takes input from a string.
  9926. */
  9927. static void
  9928. setinputstring(char *string)
  9929. {
  9930. INT_OFF;
  9931. pushfile();
  9932. g_parsefile->next_to_pgetc = string;
  9933. g_parsefile->left_in_line = strlen(string);
  9934. g_parsefile->buf = NULL;
  9935. g_parsefile->linno = 1;
  9936. INT_ON;
  9937. }
  9938. /*
  9939. * Routines to check for mail.
  9940. */
  9941. #if ENABLE_ASH_MAIL
  9942. /* Hash of mtimes of mailboxes */
  9943. static unsigned mailtime_hash;
  9944. /* Set if MAIL or MAILPATH is changed. */
  9945. static smallint mail_var_path_changed;
  9946. /*
  9947. * Print appropriate message(s) if mail has arrived.
  9948. * If mail_var_path_changed is set,
  9949. * then the value of MAIL has mail_var_path_changed,
  9950. * so we just update the values.
  9951. */
  9952. static void
  9953. chkmail(void)
  9954. {
  9955. const char *mpath;
  9956. char *p;
  9957. char *q;
  9958. unsigned new_hash;
  9959. struct stackmark smark;
  9960. struct stat statb;
  9961. setstackmark(&smark);
  9962. mpath = mpathset() ? mpathval() : mailval();
  9963. new_hash = 0;
  9964. for (;;) {
  9965. p = path_advance(&mpath, nullstr);
  9966. if (p == NULL)
  9967. break;
  9968. if (*p == '\0')
  9969. continue;
  9970. for (q = p; *q; q++)
  9971. continue;
  9972. #if DEBUG
  9973. if (q[-1] != '/')
  9974. abort();
  9975. #endif
  9976. q[-1] = '\0'; /* delete trailing '/' */
  9977. if (stat(p, &statb) < 0) {
  9978. continue;
  9979. }
  9980. /* Very simplistic "hash": just a sum of all mtimes */
  9981. new_hash += (unsigned)statb.st_mtime;
  9982. }
  9983. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  9984. if (mailtime_hash != 0)
  9985. out2str("you have mail\n");
  9986. mailtime_hash = new_hash;
  9987. }
  9988. mail_var_path_changed = 0;
  9989. popstackmark(&smark);
  9990. }
  9991. static void FAST_FUNC
  9992. changemail(const char *val UNUSED_PARAM)
  9993. {
  9994. mail_var_path_changed = 1;
  9995. }
  9996. #endif /* ASH_MAIL */
  9997. /* ============ ??? */
  9998. /*
  9999. * Set the shell parameters.
  10000. */
  10001. static void
  10002. setparam(char **argv)
  10003. {
  10004. char **newparam;
  10005. char **ap;
  10006. int nparam;
  10007. for (nparam = 0; argv[nparam]; nparam++)
  10008. continue;
  10009. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10010. while (*argv) {
  10011. *ap++ = ckstrdup(*argv++);
  10012. }
  10013. *ap = NULL;
  10014. freeparam(&shellparam);
  10015. shellparam.malloced = 1;
  10016. shellparam.nparam = nparam;
  10017. shellparam.p = newparam;
  10018. #if ENABLE_ASH_GETOPTS
  10019. shellparam.optind = 1;
  10020. shellparam.optoff = -1;
  10021. #endif
  10022. }
  10023. /*
  10024. * Process shell options. The global variable argptr contains a pointer
  10025. * to the argument list; we advance it past the options.
  10026. *
  10027. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10028. * For a non-interactive shell, an error condition encountered
  10029. * by a special built-in ... shall cause the shell to write a diagnostic message
  10030. * to standard error and exit as shown in the following table:
  10031. * Error Special Built-In
  10032. * ...
  10033. * Utility syntax error (option or operand error) Shall exit
  10034. * ...
  10035. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10036. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10037. * and shell continues), and people rely on this behavior!
  10038. * Testcase:
  10039. * set -o barfoo 2>/dev/null
  10040. * echo $?
  10041. *
  10042. * Oh well. Let's mimic that.
  10043. */
  10044. static int
  10045. plus_minus_o(char *name, int val)
  10046. {
  10047. int i;
  10048. if (name) {
  10049. for (i = 0; i < NOPTS; i++) {
  10050. if (strcmp(name, optnames(i)) == 0) {
  10051. optlist[i] = val;
  10052. return 0;
  10053. }
  10054. }
  10055. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10056. return 1;
  10057. }
  10058. for (i = 0; i < NOPTS; i++) {
  10059. if (val) {
  10060. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10061. } else {
  10062. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10063. }
  10064. }
  10065. return 0;
  10066. }
  10067. static void
  10068. setoption(int flag, int val)
  10069. {
  10070. int i;
  10071. for (i = 0; i < NOPTS; i++) {
  10072. if (optletters(i) == flag) {
  10073. optlist[i] = val;
  10074. return;
  10075. }
  10076. }
  10077. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10078. /* NOTREACHED */
  10079. }
  10080. static int
  10081. options(int cmdline, int *login_sh)
  10082. {
  10083. char *p;
  10084. int val;
  10085. int c;
  10086. if (cmdline)
  10087. minusc = NULL;
  10088. while ((p = *argptr) != NULL) {
  10089. c = *p++;
  10090. if (c != '-' && c != '+')
  10091. break;
  10092. argptr++;
  10093. val = 0; /* val = 0 if c == '+' */
  10094. if (c == '-') {
  10095. val = 1;
  10096. if (p[0] == '\0' || LONE_DASH(p)) {
  10097. if (!cmdline) {
  10098. /* "-" means turn off -x and -v */
  10099. if (p[0] == '\0')
  10100. xflag = vflag = 0;
  10101. /* "--" means reset params */
  10102. else if (*argptr == NULL)
  10103. setparam(argptr);
  10104. }
  10105. break; /* "-" or "--" terminates options */
  10106. }
  10107. }
  10108. /* first char was + or - */
  10109. while ((c = *p++) != '\0') {
  10110. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10111. if (c == 'c' && cmdline) {
  10112. minusc = p; /* command is after shell args */
  10113. } else if (c == 'o') {
  10114. if (plus_minus_o(*argptr, val)) {
  10115. /* it already printed err message */
  10116. return 1; /* error */
  10117. }
  10118. if (*argptr)
  10119. argptr++;
  10120. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  10121. if (login_sh)
  10122. *login_sh = 1;
  10123. /* bash does not accept +-login, we also won't */
  10124. } else if (cmdline && val && (c == '-')) { /* long options */
  10125. if (strcmp(p, "login") == 0) {
  10126. if (login_sh)
  10127. *login_sh = 1;
  10128. }
  10129. break;
  10130. } else {
  10131. setoption(c, val);
  10132. }
  10133. }
  10134. }
  10135. return 0;
  10136. }
  10137. /*
  10138. * The shift builtin command.
  10139. */
  10140. static int FAST_FUNC
  10141. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10142. {
  10143. int n;
  10144. char **ap1, **ap2;
  10145. n = 1;
  10146. if (argv[1])
  10147. n = number(argv[1]);
  10148. if (n > shellparam.nparam)
  10149. return 1;
  10150. INT_OFF;
  10151. shellparam.nparam -= n;
  10152. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10153. if (shellparam.malloced)
  10154. free(*ap1);
  10155. }
  10156. ap2 = shellparam.p;
  10157. while ((*ap2++ = *ap1++) != NULL)
  10158. continue;
  10159. #if ENABLE_ASH_GETOPTS
  10160. shellparam.optind = 1;
  10161. shellparam.optoff = -1;
  10162. #endif
  10163. INT_ON;
  10164. return 0;
  10165. }
  10166. /*
  10167. * POSIX requires that 'set' (but not export or readonly) output the
  10168. * variables in lexicographic order - by the locale's collating order (sigh).
  10169. * Maybe we could keep them in an ordered balanced binary tree
  10170. * instead of hashed lists.
  10171. * For now just roll 'em through qsort for printing...
  10172. */
  10173. static int
  10174. showvars(const char *sep_prefix, int on, int off)
  10175. {
  10176. const char *sep;
  10177. char **ep, **epend;
  10178. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10179. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10180. sep = *sep_prefix ? " " : sep_prefix;
  10181. for (; ep < epend; ep++) {
  10182. const char *p;
  10183. const char *q;
  10184. p = endofname(*ep);
  10185. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10186. * makes "export -p" to have output not suitable for "eval":
  10187. * import os
  10188. * os.environ["test-test"]="test"
  10189. * if os.fork() == 0:
  10190. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10191. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10192. */
  10193. q = nullstr;
  10194. if (*p == '=')
  10195. q = single_quote(++p);
  10196. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10197. }
  10198. return 0;
  10199. }
  10200. /*
  10201. * The set command builtin.
  10202. */
  10203. static int FAST_FUNC
  10204. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10205. {
  10206. int retval;
  10207. if (!argv[1])
  10208. return showvars(nullstr, 0, VUNSET);
  10209. INT_OFF;
  10210. retval = options(/*cmdline:*/ 0, NULL);
  10211. if (retval == 0) { /* if no parse error... */
  10212. optschanged();
  10213. if (*argptr != NULL) {
  10214. setparam(argptr);
  10215. }
  10216. }
  10217. INT_ON;
  10218. return retval;
  10219. }
  10220. #if ENABLE_ASH_RANDOM_SUPPORT
  10221. static void FAST_FUNC
  10222. change_random(const char *value)
  10223. {
  10224. uint32_t t;
  10225. if (value == NULL) {
  10226. /* "get", generate */
  10227. t = next_random(&random_gen);
  10228. /* set without recursion */
  10229. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10230. vrandom.flags &= ~VNOFUNC;
  10231. } else {
  10232. /* set/reset */
  10233. t = strtoul(value, NULL, 10);
  10234. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10235. }
  10236. }
  10237. #endif
  10238. #if ENABLE_ASH_GETOPTS
  10239. static int
  10240. getopts(char *optstr, char *optvar, char **optfirst)
  10241. {
  10242. char *p, *q;
  10243. char c = '?';
  10244. int done = 0;
  10245. char sbuf[2];
  10246. char **optnext;
  10247. int ind = shellparam.optind;
  10248. int off = shellparam.optoff;
  10249. sbuf[1] = '\0';
  10250. shellparam.optind = -1;
  10251. optnext = optfirst + ind - 1;
  10252. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10253. p = NULL;
  10254. else
  10255. p = optnext[-1] + off;
  10256. if (p == NULL || *p == '\0') {
  10257. /* Current word is done, advance */
  10258. p = *optnext;
  10259. if (p == NULL || *p != '-' || *++p == '\0') {
  10260. atend:
  10261. unsetvar("OPTARG");
  10262. p = NULL;
  10263. done = 1;
  10264. goto out;
  10265. }
  10266. optnext++;
  10267. if (LONE_DASH(p)) /* check for "--" */
  10268. goto atend;
  10269. }
  10270. c = *p++;
  10271. for (q = optstr; *q != c;) {
  10272. if (*q == '\0') {
  10273. /* OPTERR is a bashism */
  10274. const char *cp = lookupvar("OPTERR");
  10275. if ((cp && LONE_CHAR(cp, '0'))
  10276. || (optstr[0] == ':')
  10277. ) {
  10278. sbuf[0] = c;
  10279. /*sbuf[1] = '\0'; - already is */
  10280. setvar0("OPTARG", sbuf);
  10281. } else {
  10282. fprintf(stderr, "Illegal option -%c\n", c);
  10283. unsetvar("OPTARG");
  10284. }
  10285. c = '?';
  10286. goto out;
  10287. }
  10288. if (*++q == ':')
  10289. q++;
  10290. }
  10291. if (*++q == ':') {
  10292. if (*p == '\0' && (p = *optnext) == NULL) {
  10293. /* OPTERR is a bashism */
  10294. const char *cp = lookupvar("OPTERR");
  10295. if ((cp && LONE_CHAR(cp, '0'))
  10296. || (optstr[0] == ':')
  10297. ) {
  10298. sbuf[0] = c;
  10299. /*sbuf[1] = '\0'; - already is */
  10300. setvar0("OPTARG", sbuf);
  10301. c = ':';
  10302. } else {
  10303. fprintf(stderr, "No arg for -%c option\n", c);
  10304. unsetvar("OPTARG");
  10305. c = '?';
  10306. }
  10307. goto out;
  10308. }
  10309. if (p == *optnext)
  10310. optnext++;
  10311. setvar0("OPTARG", p);
  10312. p = NULL;
  10313. } else
  10314. setvar0("OPTARG", nullstr);
  10315. out:
  10316. ind = optnext - optfirst + 1;
  10317. setvar("OPTIND", itoa(ind), VNOFUNC);
  10318. sbuf[0] = c;
  10319. /*sbuf[1] = '\0'; - already is */
  10320. setvar0(optvar, sbuf);
  10321. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10322. shellparam.optind = ind;
  10323. return done;
  10324. }
  10325. /*
  10326. * The getopts builtin. Shellparam.optnext points to the next argument
  10327. * to be processed. Shellparam.optptr points to the next character to
  10328. * be processed in the current argument. If shellparam.optnext is NULL,
  10329. * then it's the first time getopts has been called.
  10330. */
  10331. static int FAST_FUNC
  10332. getoptscmd(int argc, char **argv)
  10333. {
  10334. char **optbase;
  10335. if (argc < 3)
  10336. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10337. if (argc == 3) {
  10338. optbase = shellparam.p;
  10339. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10340. shellparam.optind = 1;
  10341. shellparam.optoff = -1;
  10342. }
  10343. } else {
  10344. optbase = &argv[3];
  10345. if ((unsigned)shellparam.optind > argc - 2) {
  10346. shellparam.optind = 1;
  10347. shellparam.optoff = -1;
  10348. }
  10349. }
  10350. return getopts(argv[1], argv[2], optbase);
  10351. }
  10352. #endif /* ASH_GETOPTS */
  10353. /* ============ Shell parser */
  10354. struct heredoc {
  10355. struct heredoc *next; /* next here document in list */
  10356. union node *here; /* redirection node */
  10357. char *eofmark; /* string indicating end of input */
  10358. smallint striptabs; /* if set, strip leading tabs */
  10359. };
  10360. static smallint tokpushback; /* last token pushed back */
  10361. static smallint quoteflag; /* set if (part of) last token was quoted */
  10362. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10363. static struct heredoc *heredoclist; /* list of here documents to read */
  10364. static char *wordtext; /* text of last word returned by readtoken */
  10365. static struct nodelist *backquotelist;
  10366. static union node *redirnode;
  10367. static struct heredoc *heredoc;
  10368. static const char *
  10369. tokname(char *buf, int tok)
  10370. {
  10371. if (tok < TSEMI)
  10372. return tokname_array[tok];
  10373. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10374. return buf;
  10375. }
  10376. /* raise_error_unexpected_syntax:
  10377. * Called when an unexpected token is read during the parse. The argument
  10378. * is the token that is expected, or -1 if more than one type of token can
  10379. * occur at this point.
  10380. */
  10381. static void raise_error_unexpected_syntax(int) NORETURN;
  10382. static void
  10383. raise_error_unexpected_syntax(int token)
  10384. {
  10385. char msg[64];
  10386. char buf[16];
  10387. int l;
  10388. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10389. if (token >= 0)
  10390. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10391. raise_error_syntax(msg);
  10392. /* NOTREACHED */
  10393. }
  10394. /* parsing is heavily cross-recursive, need these forward decls */
  10395. static union node *andor(void);
  10396. static union node *pipeline(void);
  10397. static union node *parse_command(void);
  10398. static void parseheredoc(void);
  10399. static int peektoken(void);
  10400. static int readtoken(void);
  10401. static union node *
  10402. list(int nlflag)
  10403. {
  10404. union node *n1, *n2, *n3;
  10405. int tok;
  10406. n1 = NULL;
  10407. for (;;) {
  10408. switch (peektoken()) {
  10409. case TNL:
  10410. if (!(nlflag & 1))
  10411. break;
  10412. parseheredoc();
  10413. return n1;
  10414. case TEOF:
  10415. if (!n1 && (nlflag & 1))
  10416. n1 = NODE_EOF;
  10417. parseheredoc();
  10418. return n1;
  10419. }
  10420. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10421. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10422. return n1;
  10423. nlflag |= 2;
  10424. n2 = andor();
  10425. tok = readtoken();
  10426. if (tok == TBACKGND) {
  10427. if (n2->type == NPIPE) {
  10428. n2->npipe.pipe_backgnd = 1;
  10429. } else {
  10430. if (n2->type != NREDIR) {
  10431. n3 = stzalloc(sizeof(struct nredir));
  10432. n3->nredir.n = n2;
  10433. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10434. n2 = n3;
  10435. }
  10436. n2->type = NBACKGND;
  10437. }
  10438. }
  10439. if (n1 == NULL) {
  10440. n1 = n2;
  10441. } else {
  10442. n3 = stzalloc(sizeof(struct nbinary));
  10443. n3->type = NSEMI;
  10444. n3->nbinary.ch1 = n1;
  10445. n3->nbinary.ch2 = n2;
  10446. n1 = n3;
  10447. }
  10448. switch (tok) {
  10449. case TNL:
  10450. case TEOF:
  10451. tokpushback = 1;
  10452. /* fall through */
  10453. case TBACKGND:
  10454. case TSEMI:
  10455. break;
  10456. default:
  10457. if ((nlflag & 1))
  10458. raise_error_unexpected_syntax(-1);
  10459. tokpushback = 1;
  10460. return n1;
  10461. }
  10462. }
  10463. }
  10464. static union node *
  10465. andor(void)
  10466. {
  10467. union node *n1, *n2, *n3;
  10468. int t;
  10469. n1 = pipeline();
  10470. for (;;) {
  10471. t = readtoken();
  10472. if (t == TAND) {
  10473. t = NAND;
  10474. } else if (t == TOR) {
  10475. t = NOR;
  10476. } else {
  10477. tokpushback = 1;
  10478. return n1;
  10479. }
  10480. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10481. n2 = pipeline();
  10482. n3 = stzalloc(sizeof(struct nbinary));
  10483. n3->type = t;
  10484. n3->nbinary.ch1 = n1;
  10485. n3->nbinary.ch2 = n2;
  10486. n1 = n3;
  10487. }
  10488. }
  10489. static union node *
  10490. pipeline(void)
  10491. {
  10492. union node *n1, *n2, *pipenode;
  10493. struct nodelist *lp, *prev;
  10494. int negate;
  10495. negate = 0;
  10496. TRACE(("pipeline: entered\n"));
  10497. if (readtoken() == TNOT) {
  10498. negate = !negate;
  10499. checkkwd = CHKKWD | CHKALIAS;
  10500. } else
  10501. tokpushback = 1;
  10502. n1 = parse_command();
  10503. if (readtoken() == TPIPE) {
  10504. pipenode = stzalloc(sizeof(struct npipe));
  10505. pipenode->type = NPIPE;
  10506. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10507. lp = stzalloc(sizeof(struct nodelist));
  10508. pipenode->npipe.cmdlist = lp;
  10509. lp->n = n1;
  10510. do {
  10511. prev = lp;
  10512. lp = stzalloc(sizeof(struct nodelist));
  10513. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10514. lp->n = parse_command();
  10515. prev->next = lp;
  10516. } while (readtoken() == TPIPE);
  10517. lp->next = NULL;
  10518. n1 = pipenode;
  10519. }
  10520. tokpushback = 1;
  10521. if (negate) {
  10522. n2 = stzalloc(sizeof(struct nnot));
  10523. n2->type = NNOT;
  10524. n2->nnot.com = n1;
  10525. return n2;
  10526. }
  10527. return n1;
  10528. }
  10529. static union node *
  10530. makename(void)
  10531. {
  10532. union node *n;
  10533. n = stzalloc(sizeof(struct narg));
  10534. n->type = NARG;
  10535. /*n->narg.next = NULL; - stzalloc did it */
  10536. n->narg.text = wordtext;
  10537. n->narg.backquote = backquotelist;
  10538. return n;
  10539. }
  10540. static void
  10541. fixredir(union node *n, const char *text, int err)
  10542. {
  10543. int fd;
  10544. TRACE(("Fix redir %s %d\n", text, err));
  10545. if (!err)
  10546. n->ndup.vname = NULL;
  10547. fd = bb_strtou(text, NULL, 10);
  10548. if (!errno && fd >= 0)
  10549. n->ndup.dupfd = fd;
  10550. else if (LONE_DASH(text))
  10551. n->ndup.dupfd = -1;
  10552. else {
  10553. if (err)
  10554. raise_error_syntax("bad fd number");
  10555. n->ndup.vname = makename();
  10556. }
  10557. }
  10558. static void
  10559. parsefname(void)
  10560. {
  10561. union node *n = redirnode;
  10562. if (n->type == NHERE)
  10563. checkkwd = CHKEOFMARK;
  10564. if (readtoken() != TWORD)
  10565. raise_error_unexpected_syntax(-1);
  10566. if (n->type == NHERE) {
  10567. struct heredoc *here = heredoc;
  10568. struct heredoc *p;
  10569. if (quoteflag == 0)
  10570. n->type = NXHERE;
  10571. TRACE(("Here document %d\n", n->type));
  10572. rmescapes(wordtext, 0, NULL);
  10573. here->eofmark = wordtext;
  10574. here->next = NULL;
  10575. if (heredoclist == NULL)
  10576. heredoclist = here;
  10577. else {
  10578. for (p = heredoclist; p->next; p = p->next)
  10579. continue;
  10580. p->next = here;
  10581. }
  10582. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10583. fixredir(n, wordtext, 0);
  10584. } else {
  10585. n->nfile.fname = makename();
  10586. }
  10587. }
  10588. static union node *
  10589. simplecmd(void)
  10590. {
  10591. union node *args, **app;
  10592. union node *n = NULL;
  10593. union node *vars, **vpp;
  10594. union node **rpp, *redir;
  10595. int savecheckkwd;
  10596. int savelinno;
  10597. #if BASH_TEST2
  10598. smallint double_brackets_flag = 0;
  10599. #endif
  10600. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10601. args = NULL;
  10602. app = &args;
  10603. vars = NULL;
  10604. vpp = &vars;
  10605. redir = NULL;
  10606. rpp = &redir;
  10607. savecheckkwd = CHKALIAS;
  10608. savelinno = g_parsefile->linno;
  10609. for (;;) {
  10610. int t;
  10611. checkkwd = savecheckkwd;
  10612. t = readtoken();
  10613. switch (t) {
  10614. #if BASH_FUNCTION
  10615. case TFUNCTION:
  10616. if (peektoken() != TWORD)
  10617. raise_error_unexpected_syntax(TWORD);
  10618. function_flag = 1;
  10619. break;
  10620. #endif
  10621. #if BASH_TEST2
  10622. case TAND: /* "&&" */
  10623. case TOR: /* "||" */
  10624. if (!double_brackets_flag) {
  10625. tokpushback = 1;
  10626. goto out;
  10627. }
  10628. wordtext = (char *) (t == TAND ? "-a" : "-o");
  10629. #endif
  10630. case TWORD:
  10631. n = stzalloc(sizeof(struct narg));
  10632. n->type = NARG;
  10633. /*n->narg.next = NULL; - stzalloc did it */
  10634. n->narg.text = wordtext;
  10635. #if BASH_TEST2
  10636. if (strcmp("[[", wordtext) == 0)
  10637. double_brackets_flag = 1;
  10638. else if (strcmp("]]", wordtext) == 0)
  10639. double_brackets_flag = 0;
  10640. #endif
  10641. n->narg.backquote = backquotelist;
  10642. if (savecheckkwd && isassignment(wordtext)) {
  10643. *vpp = n;
  10644. vpp = &n->narg.next;
  10645. } else {
  10646. *app = n;
  10647. app = &n->narg.next;
  10648. savecheckkwd = 0;
  10649. }
  10650. #if BASH_FUNCTION
  10651. if (function_flag) {
  10652. checkkwd = CHKNL | CHKKWD;
  10653. switch (peektoken()) {
  10654. case TBEGIN:
  10655. case TIF:
  10656. case TCASE:
  10657. case TUNTIL:
  10658. case TWHILE:
  10659. case TFOR:
  10660. goto do_func;
  10661. case TLP:
  10662. function_flag = 0;
  10663. break;
  10664. # if BASH_TEST2
  10665. case TWORD:
  10666. if (strcmp("[[", wordtext) == 0)
  10667. goto do_func;
  10668. /* fall through */
  10669. # endif
  10670. default:
  10671. raise_error_unexpected_syntax(-1);
  10672. }
  10673. }
  10674. #endif
  10675. break;
  10676. case TREDIR:
  10677. *rpp = n = redirnode;
  10678. rpp = &n->nfile.next;
  10679. parsefname(); /* read name of redirection file */
  10680. break;
  10681. case TLP:
  10682. IF_BASH_FUNCTION(do_func:)
  10683. if (args && app == &args->narg.next
  10684. && !vars && !redir
  10685. ) {
  10686. struct builtincmd *bcmd;
  10687. const char *name;
  10688. /* We have a function */
  10689. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10690. raise_error_unexpected_syntax(TRP);
  10691. name = n->narg.text;
  10692. if (!goodname(name)
  10693. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10694. ) {
  10695. raise_error_syntax("bad function name");
  10696. }
  10697. n->type = NDEFUN;
  10698. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10699. n->ndefun.text = n->narg.text;
  10700. n->ndefun.linno = g_parsefile->linno;
  10701. n->ndefun.body = parse_command();
  10702. return n;
  10703. }
  10704. IF_BASH_FUNCTION(function_flag = 0;)
  10705. /* fall through */
  10706. default:
  10707. tokpushback = 1;
  10708. goto out;
  10709. }
  10710. }
  10711. out:
  10712. *app = NULL;
  10713. *vpp = NULL;
  10714. *rpp = NULL;
  10715. n = stzalloc(sizeof(struct ncmd));
  10716. if (NCMD != 0)
  10717. n->type = NCMD;
  10718. n->ncmd.linno = savelinno;
  10719. n->ncmd.args = args;
  10720. n->ncmd.assign = vars;
  10721. n->ncmd.redirect = redir;
  10722. return n;
  10723. }
  10724. static union node *
  10725. parse_command(void)
  10726. {
  10727. union node *n1, *n2;
  10728. union node *ap, **app;
  10729. union node *cp, **cpp;
  10730. union node *redir, **rpp;
  10731. union node **rpp2;
  10732. int t;
  10733. int savelinno;
  10734. redir = NULL;
  10735. rpp2 = &redir;
  10736. savelinno = g_parsefile->linno;
  10737. switch (readtoken()) {
  10738. default:
  10739. raise_error_unexpected_syntax(-1);
  10740. /* NOTREACHED */
  10741. case TIF:
  10742. n1 = stzalloc(sizeof(struct nif));
  10743. n1->type = NIF;
  10744. n1->nif.test = list(0);
  10745. if (readtoken() != TTHEN)
  10746. raise_error_unexpected_syntax(TTHEN);
  10747. n1->nif.ifpart = list(0);
  10748. n2 = n1;
  10749. while (readtoken() == TELIF) {
  10750. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10751. n2 = n2->nif.elsepart;
  10752. n2->type = NIF;
  10753. n2->nif.test = list(0);
  10754. if (readtoken() != TTHEN)
  10755. raise_error_unexpected_syntax(TTHEN);
  10756. n2->nif.ifpart = list(0);
  10757. }
  10758. if (lasttoken == TELSE)
  10759. n2->nif.elsepart = list(0);
  10760. else {
  10761. n2->nif.elsepart = NULL;
  10762. tokpushback = 1;
  10763. }
  10764. t = TFI;
  10765. break;
  10766. case TWHILE:
  10767. case TUNTIL: {
  10768. int got;
  10769. n1 = stzalloc(sizeof(struct nbinary));
  10770. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10771. n1->nbinary.ch1 = list(0);
  10772. got = readtoken();
  10773. if (got != TDO) {
  10774. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10775. got == TWORD ? wordtext : ""));
  10776. raise_error_unexpected_syntax(TDO);
  10777. }
  10778. n1->nbinary.ch2 = list(0);
  10779. t = TDONE;
  10780. break;
  10781. }
  10782. case TFOR:
  10783. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10784. raise_error_syntax("bad for loop variable");
  10785. n1 = stzalloc(sizeof(struct nfor));
  10786. n1->type = NFOR;
  10787. n1->nfor.linno = savelinno;
  10788. n1->nfor.var = wordtext;
  10789. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10790. if (readtoken() == TIN) {
  10791. app = &ap;
  10792. while (readtoken() == TWORD) {
  10793. n2 = stzalloc(sizeof(struct narg));
  10794. n2->type = NARG;
  10795. /*n2->narg.next = NULL; - stzalloc did it */
  10796. n2->narg.text = wordtext;
  10797. n2->narg.backquote = backquotelist;
  10798. *app = n2;
  10799. app = &n2->narg.next;
  10800. }
  10801. *app = NULL;
  10802. n1->nfor.args = ap;
  10803. if (lasttoken != TNL && lasttoken != TSEMI)
  10804. raise_error_unexpected_syntax(-1);
  10805. } else {
  10806. n2 = stzalloc(sizeof(struct narg));
  10807. n2->type = NARG;
  10808. /*n2->narg.next = NULL; - stzalloc did it */
  10809. n2->narg.text = (char *)dolatstr;
  10810. /*n2->narg.backquote = NULL;*/
  10811. n1->nfor.args = n2;
  10812. /*
  10813. * Newline or semicolon here is optional (but note
  10814. * that the original Bourne shell only allowed NL).
  10815. */
  10816. if (lasttoken != TSEMI)
  10817. tokpushback = 1;
  10818. }
  10819. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10820. if (readtoken() != TDO)
  10821. raise_error_unexpected_syntax(TDO);
  10822. n1->nfor.body = list(0);
  10823. t = TDONE;
  10824. break;
  10825. case TCASE:
  10826. n1 = stzalloc(sizeof(struct ncase));
  10827. n1->type = NCASE;
  10828. n1->ncase.linno = savelinno;
  10829. if (readtoken() != TWORD)
  10830. raise_error_unexpected_syntax(TWORD);
  10831. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10832. n2->type = NARG;
  10833. /*n2->narg.next = NULL; - stzalloc did it */
  10834. n2->narg.text = wordtext;
  10835. n2->narg.backquote = backquotelist;
  10836. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10837. if (readtoken() != TIN)
  10838. raise_error_unexpected_syntax(TIN);
  10839. cpp = &n1->ncase.cases;
  10840. next_case:
  10841. checkkwd = CHKNL | CHKKWD;
  10842. t = readtoken();
  10843. while (t != TESAC) {
  10844. if (lasttoken == TLP)
  10845. readtoken();
  10846. *cpp = cp = stzalloc(sizeof(struct nclist));
  10847. cp->type = NCLIST;
  10848. app = &cp->nclist.pattern;
  10849. for (;;) {
  10850. *app = ap = stzalloc(sizeof(struct narg));
  10851. ap->type = NARG;
  10852. /*ap->narg.next = NULL; - stzalloc did it */
  10853. ap->narg.text = wordtext;
  10854. ap->narg.backquote = backquotelist;
  10855. if (readtoken() != TPIPE)
  10856. break;
  10857. app = &ap->narg.next;
  10858. readtoken();
  10859. }
  10860. //ap->narg.next = NULL;
  10861. if (lasttoken != TRP)
  10862. raise_error_unexpected_syntax(TRP);
  10863. cp->nclist.body = list(2);
  10864. cpp = &cp->nclist.next;
  10865. checkkwd = CHKNL | CHKKWD;
  10866. t = readtoken();
  10867. if (t != TESAC) {
  10868. if (t != TENDCASE)
  10869. raise_error_unexpected_syntax(TENDCASE);
  10870. goto next_case;
  10871. }
  10872. }
  10873. *cpp = NULL;
  10874. goto redir;
  10875. case TLP:
  10876. n1 = stzalloc(sizeof(struct nredir));
  10877. n1->type = NSUBSHELL;
  10878. n1->nredir.linno = savelinno;
  10879. n1->nredir.n = list(0);
  10880. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10881. t = TRP;
  10882. break;
  10883. case TBEGIN:
  10884. n1 = list(0);
  10885. t = TEND;
  10886. break;
  10887. IF_BASH_FUNCTION(case TFUNCTION:)
  10888. case TWORD:
  10889. case TREDIR:
  10890. tokpushback = 1;
  10891. return simplecmd();
  10892. }
  10893. if (readtoken() != t)
  10894. raise_error_unexpected_syntax(t);
  10895. redir:
  10896. /* Now check for redirection which may follow command */
  10897. checkkwd = CHKKWD | CHKALIAS;
  10898. rpp = rpp2;
  10899. while (readtoken() == TREDIR) {
  10900. *rpp = n2 = redirnode;
  10901. rpp = &n2->nfile.next;
  10902. parsefname();
  10903. }
  10904. tokpushback = 1;
  10905. *rpp = NULL;
  10906. if (redir) {
  10907. if (n1->type != NSUBSHELL) {
  10908. n2 = stzalloc(sizeof(struct nredir));
  10909. n2->type = NREDIR;
  10910. n2->nredir.linno = savelinno;
  10911. n2->nredir.n = n1;
  10912. n1 = n2;
  10913. }
  10914. n1->nredir.redirect = redir;
  10915. }
  10916. return n1;
  10917. }
  10918. #if BASH_DOLLAR_SQUOTE
  10919. static int
  10920. decode_dollar_squote(void)
  10921. {
  10922. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  10923. int c, cnt;
  10924. char *p;
  10925. char buf[4];
  10926. c = pgetc();
  10927. p = strchr(C_escapes, c);
  10928. if (p) {
  10929. buf[0] = c;
  10930. p = buf;
  10931. cnt = 3;
  10932. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  10933. do {
  10934. c = pgetc();
  10935. *++p = c;
  10936. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  10937. pungetc();
  10938. } else if (c == 'x') { /* \xHH */
  10939. do {
  10940. c = pgetc();
  10941. *++p = c;
  10942. } while (isxdigit(c) && --cnt);
  10943. pungetc();
  10944. if (cnt == 3) { /* \x but next char is "bad" */
  10945. c = 'x';
  10946. goto unrecognized;
  10947. }
  10948. } else { /* simple seq like \\ or \t */
  10949. p++;
  10950. }
  10951. *p = '\0';
  10952. p = buf;
  10953. c = bb_process_escape_sequence((void*)&p);
  10954. } else { /* unrecognized "\z": print both chars unless ' or " */
  10955. if (c != '\'' && c != '"') {
  10956. unrecognized:
  10957. c |= 0x100; /* "please encode \, then me" */
  10958. }
  10959. }
  10960. return c;
  10961. }
  10962. #endif
  10963. /* Used by expandstr to get here-doc like behaviour. */
  10964. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  10965. static ALWAYS_INLINE int
  10966. realeofmark(const char *eofmark)
  10967. {
  10968. return eofmark && eofmark != FAKEEOFMARK;
  10969. }
  10970. /*
  10971. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  10972. * is not NULL, read a here document. In the latter case, eofmark is the
  10973. * word which marks the end of the document and striptabs is true if
  10974. * leading tabs should be stripped from the document. The argument c
  10975. * is the first character of the input token or document.
  10976. *
  10977. * Because C does not have internal subroutines, I have simulated them
  10978. * using goto's to implement the subroutine linkage. The following macros
  10979. * will run code that appears at the end of readtoken1.
  10980. */
  10981. #define CHECKEND() {goto checkend; checkend_return:;}
  10982. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  10983. #define PARSESUB() {goto parsesub; parsesub_return:;}
  10984. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  10985. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  10986. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  10987. static int
  10988. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  10989. {
  10990. /* NB: syntax parameter fits into smallint */
  10991. /* c parameter is an unsigned char or PEOF or PEOA */
  10992. char *out;
  10993. size_t len;
  10994. struct nodelist *bqlist;
  10995. smallint quotef;
  10996. smallint oldstyle;
  10997. smallint pssyntax; /* we are expanding a prompt string */
  10998. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  10999. /* syntax stack */
  11000. struct synstack synbase = { };
  11001. struct synstack *synstack = &synbase;
  11002. #if ENABLE_ASH_EXPAND_PRMT
  11003. pssyntax = (syntax == PSSYNTAX);
  11004. if (pssyntax)
  11005. syntax = DQSYNTAX;
  11006. #else
  11007. pssyntax = 0; /* constant */
  11008. #endif
  11009. synstack->syntax = syntax;
  11010. if (syntax == DQSYNTAX)
  11011. synstack->dblquote = 1;
  11012. quotef = 0;
  11013. bqlist = NULL;
  11014. STARTSTACKSTR(out);
  11015. loop:
  11016. /* For each line, until end of word */
  11017. CHECKEND(); /* set c to PEOF if at end of here document */
  11018. for (;;) { /* until end of line or end of word */
  11019. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11020. switch (SIT(c, synstack->syntax)) {
  11021. case CNL: /* '\n' */
  11022. if (synstack->syntax == BASESYNTAX
  11023. && !synstack->varnest
  11024. ) {
  11025. goto endword; /* exit outer loop */
  11026. }
  11027. USTPUTC(c, out);
  11028. nlprompt();
  11029. c = pgetc();
  11030. goto loop; /* continue outer loop */
  11031. case CWORD:
  11032. USTPUTC(c, out);
  11033. break;
  11034. case CCTL:
  11035. #if BASH_DOLLAR_SQUOTE
  11036. if (c == '\\' && bash_dollar_squote) {
  11037. c = decode_dollar_squote();
  11038. if (c == '\0') {
  11039. /* skip $'\000', $'\x00' (like bash) */
  11040. break;
  11041. }
  11042. if (c & 0x100) {
  11043. /* Unknown escape. Encode as '\z' */
  11044. c = (unsigned char)c;
  11045. if (eofmark == NULL || synstack->dblquote)
  11046. USTPUTC(CTLESC, out);
  11047. USTPUTC('\\', out);
  11048. }
  11049. }
  11050. #endif
  11051. if (!eofmark || synstack->dblquote || synstack->varnest)
  11052. USTPUTC(CTLESC, out);
  11053. USTPUTC(c, out);
  11054. break;
  11055. case CBACK: /* backslash */
  11056. c = pgetc_without_PEOA();
  11057. if (c == PEOF) {
  11058. USTPUTC(CTLESC, out);
  11059. USTPUTC('\\', out);
  11060. pungetc();
  11061. } else if (c == '\n') {
  11062. nlprompt();
  11063. } else {
  11064. if (pssyntax && c == '$') {
  11065. USTPUTC(CTLESC, out);
  11066. USTPUTC('\\', out);
  11067. }
  11068. /* Backslash is retained if we are in "str"
  11069. * and next char isn't dquote-special.
  11070. */
  11071. if (synstack->dblquote
  11072. && c != '\\'
  11073. && c != '`'
  11074. && c != '$'
  11075. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11076. && (c != '}' || !synstack->varnest)
  11077. ) {
  11078. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11079. USTPUTC('\\', out);
  11080. }
  11081. USTPUTC(CTLESC, out);
  11082. USTPUTC(c, out);
  11083. quotef = 1;
  11084. }
  11085. break;
  11086. case CSQUOTE:
  11087. synstack->syntax = SQSYNTAX;
  11088. quotemark:
  11089. if (eofmark == NULL) {
  11090. USTPUTC(CTLQUOTEMARK, out);
  11091. }
  11092. break;
  11093. case CDQUOTE:
  11094. synstack->syntax = DQSYNTAX;
  11095. synstack->dblquote = 1;
  11096. toggledq:
  11097. if (synstack->varnest)
  11098. synstack->innerdq ^= 1;
  11099. goto quotemark;
  11100. case CENDQUOTE:
  11101. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11102. if (eofmark != NULL && synstack->varnest == 0) {
  11103. USTPUTC(c, out);
  11104. break;
  11105. }
  11106. if (synstack->dqvarnest == 0) {
  11107. synstack->syntax = BASESYNTAX;
  11108. synstack->dblquote = 0;
  11109. }
  11110. quotef = 1;
  11111. if (c == '"')
  11112. goto toggledq;
  11113. goto quotemark;
  11114. case CVAR: /* '$' */
  11115. PARSESUB(); /* parse substitution */
  11116. break;
  11117. case CENDVAR: /* '}' */
  11118. if (!synstack->innerdq && synstack->varnest > 0) {
  11119. if (!--synstack->varnest && synstack->varpushed)
  11120. synstack_pop(&synstack);
  11121. else if (synstack->dqvarnest > 0)
  11122. synstack->dqvarnest--;
  11123. c = CTLENDVAR;
  11124. }
  11125. USTPUTC(c, out);
  11126. break;
  11127. #if ENABLE_FEATURE_SH_MATH
  11128. case CLP: /* '(' in arithmetic */
  11129. synstack->parenlevel++;
  11130. USTPUTC(c, out);
  11131. break;
  11132. case CRP: /* ')' in arithmetic */
  11133. if (synstack->parenlevel > 0) {
  11134. synstack->parenlevel--;
  11135. } else {
  11136. if (pgetc_eatbnl() == ')') {
  11137. c = CTLENDARI;
  11138. synstack_pop(&synstack);
  11139. } else {
  11140. /*
  11141. * unbalanced parens
  11142. * (don't 2nd guess - no error)
  11143. */
  11144. pungetc();
  11145. }
  11146. }
  11147. USTPUTC(c, out);
  11148. break;
  11149. #endif
  11150. case CBQUOTE: /* '`' */
  11151. if (checkkwd & CHKEOFMARK) {
  11152. quotef = 1;
  11153. USTPUTC('`', out);
  11154. break;
  11155. }
  11156. PARSEBACKQOLD();
  11157. break;
  11158. case CENDFILE:
  11159. goto endword; /* exit outer loop */
  11160. case CIGN:
  11161. break;
  11162. default:
  11163. if (synstack->varnest == 0) {
  11164. #if BASH_REDIR_OUTPUT
  11165. if (c == '&') {
  11166. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11167. if (pgetc() == '>')
  11168. c = 0x100 + '>'; /* flag &> */
  11169. pungetc();
  11170. }
  11171. #endif
  11172. goto endword; /* exit outer loop */
  11173. }
  11174. IF_ASH_ALIAS(if (c != PEOA))
  11175. USTPUTC(c, out);
  11176. }
  11177. c = pgetc();
  11178. } /* for (;;) */
  11179. endword:
  11180. #if ENABLE_FEATURE_SH_MATH
  11181. if (synstack->syntax == ARISYNTAX)
  11182. raise_error_syntax("missing '))'");
  11183. #endif
  11184. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11185. raise_error_syntax("unterminated quoted string");
  11186. if (synstack->varnest != 0) {
  11187. /* { */
  11188. raise_error_syntax("missing '}'");
  11189. }
  11190. USTPUTC('\0', out);
  11191. len = out - (char *)stackblock();
  11192. out = stackblock();
  11193. if (eofmark == NULL) {
  11194. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11195. && quotef == 0
  11196. ) {
  11197. if (isdigit_str9(out)) {
  11198. PARSEREDIR(); /* passed as params: out, c */
  11199. lasttoken = TREDIR;
  11200. return lasttoken;
  11201. }
  11202. /* else: non-number X seen, interpret it
  11203. * as "NNNX>file" = "NNNX >file" */
  11204. }
  11205. pungetc();
  11206. }
  11207. quoteflag = quotef;
  11208. backquotelist = bqlist;
  11209. grabstackblock(len);
  11210. wordtext = out;
  11211. lasttoken = TWORD;
  11212. return lasttoken;
  11213. /* end of readtoken routine */
  11214. /*
  11215. * Check to see whether we are at the end of the here document. When this
  11216. * is called, c is set to the first character of the next input line. If
  11217. * we are at the end of the here document, this routine sets the c to PEOF.
  11218. */
  11219. checkend: {
  11220. if (realeofmark(eofmark)) {
  11221. int markloc;
  11222. char *p;
  11223. #if ENABLE_ASH_ALIAS
  11224. if (c == PEOA)
  11225. c = pgetc_without_PEOA();
  11226. #endif
  11227. if (striptabs) {
  11228. while (c == '\t') {
  11229. c = pgetc_without_PEOA();
  11230. }
  11231. }
  11232. markloc = out - (char *)stackblock();
  11233. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11234. if (c != *p)
  11235. goto more_heredoc;
  11236. c = pgetc_without_PEOA();
  11237. }
  11238. if (c == '\n' || c == PEOF) {
  11239. c = PEOF;
  11240. g_parsefile->linno++;
  11241. needprompt = doprompt;
  11242. } else {
  11243. int len_here;
  11244. more_heredoc:
  11245. p = (char *)stackblock() + markloc + 1;
  11246. len_here = out - p;
  11247. if (len_here) {
  11248. len_here -= (c >= PEOF);
  11249. c = p[-1];
  11250. if (len_here) {
  11251. char *str;
  11252. str = alloca(len_here + 1);
  11253. *(char *)mempcpy(str, p, len_here) = '\0';
  11254. pushstring(str, NULL);
  11255. }
  11256. }
  11257. }
  11258. STADJUST((char *)stackblock() + markloc - out, out);
  11259. }
  11260. goto checkend_return;
  11261. }
  11262. /*
  11263. * Parse a redirection operator. The variable "out" points to a string
  11264. * specifying the fd to be redirected. The variable "c" contains the
  11265. * first character of the redirection operator.
  11266. */
  11267. parseredir: {
  11268. /* out is already checked to be a valid number or "" */
  11269. int fd = (*out == '\0' ? -1 : atoi(out));
  11270. union node *np;
  11271. np = stzalloc(sizeof(struct nfile));
  11272. if (c == '>') {
  11273. np->nfile.fd = 1;
  11274. c = pgetc_eatbnl();
  11275. if (c == '>')
  11276. np->type = NAPPEND;
  11277. else if (c == '|')
  11278. np->type = NCLOBBER;
  11279. else if (c == '&')
  11280. np->type = NTOFD;
  11281. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11282. else {
  11283. np->type = NTO;
  11284. pungetc();
  11285. }
  11286. }
  11287. #if BASH_REDIR_OUTPUT
  11288. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11289. np->nfile.fd = 1;
  11290. pgetc(); /* this is '>', no need to check */
  11291. np->type = NTO2;
  11292. }
  11293. #endif
  11294. else { /* c == '<' */
  11295. /*np->nfile.fd = 0; - stzalloc did it */
  11296. c = pgetc_eatbnl();
  11297. switch (c) {
  11298. case '<':
  11299. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11300. np = stzalloc(sizeof(struct nhere));
  11301. /*np->nfile.fd = 0; - stzalloc did it */
  11302. }
  11303. np->type = NHERE;
  11304. heredoc = stzalloc(sizeof(struct heredoc));
  11305. heredoc->here = np;
  11306. c = pgetc_eatbnl();
  11307. if (c == '-') {
  11308. heredoc->striptabs = 1;
  11309. } else {
  11310. /*heredoc->striptabs = 0; - stzalloc did it */
  11311. pungetc();
  11312. }
  11313. break;
  11314. case '&':
  11315. np->type = NFROMFD;
  11316. break;
  11317. case '>':
  11318. np->type = NFROMTO;
  11319. break;
  11320. default:
  11321. np->type = NFROM;
  11322. pungetc();
  11323. break;
  11324. }
  11325. }
  11326. if (fd >= 0)
  11327. np->nfile.fd = fd;
  11328. redirnode = np;
  11329. goto parseredir_return;
  11330. }
  11331. /*
  11332. * Parse a substitution. At this point, we have read the dollar sign
  11333. * and nothing else.
  11334. */
  11335. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11336. * (assuming ascii char codes, as the original implementation did) */
  11337. #define is_special(c) \
  11338. (((unsigned)(c) - 33 < 32) \
  11339. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11340. parsesub: {
  11341. unsigned char subtype;
  11342. int typeloc;
  11343. c = pgetc_eatbnl();
  11344. if ((checkkwd & CHKEOFMARK)
  11345. || c > 255 /* PEOA or PEOF */
  11346. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11347. ) {
  11348. #if BASH_DOLLAR_SQUOTE
  11349. if (synstack->syntax != DQSYNTAX && c == '\'')
  11350. bash_dollar_squote = 1;
  11351. else
  11352. #endif
  11353. USTPUTC('$', out);
  11354. pungetc();
  11355. } else if (c == '(') {
  11356. /* $(command) or $((arith)) */
  11357. if (pgetc_eatbnl() == '(') {
  11358. #if ENABLE_FEATURE_SH_MATH
  11359. PARSEARITH();
  11360. #else
  11361. raise_error_syntax("support for $((arith)) is disabled");
  11362. #endif
  11363. } else {
  11364. pungetc();
  11365. PARSEBACKQNEW();
  11366. }
  11367. } else {
  11368. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11369. smalluint newsyn = synstack->syntax;
  11370. USTPUTC(CTLVAR, out);
  11371. typeloc = out - (char *)stackblock();
  11372. STADJUST(1, out);
  11373. subtype = VSNORMAL;
  11374. if (c == '{') {
  11375. c = pgetc_eatbnl();
  11376. subtype = 0;
  11377. }
  11378. varname:
  11379. if (is_name(c)) {
  11380. /* $[{[#]]NAME[}] */
  11381. do {
  11382. STPUTC(c, out);
  11383. c = pgetc_eatbnl();
  11384. } while (is_in_name(c));
  11385. } else if (isdigit(c)) {
  11386. /* $[{[#]]NUM[}] */
  11387. do {
  11388. STPUTC(c, out);
  11389. c = pgetc_eatbnl();
  11390. } while (isdigit(c));
  11391. } else if (c != '}') {
  11392. /* $[{[#]]<specialchar>[}] */
  11393. int cc = c;
  11394. c = pgetc_eatbnl();
  11395. if (!subtype && cc == '#') {
  11396. subtype = VSLENGTH;
  11397. if (c == '_' || isalnum(c))
  11398. goto varname;
  11399. cc = c;
  11400. c = pgetc_eatbnl();
  11401. if (cc == '}' || c != '}') {
  11402. pungetc();
  11403. subtype = 0;
  11404. c = cc;
  11405. cc = '#';
  11406. }
  11407. }
  11408. if (!is_special(cc)) {
  11409. if (subtype == VSLENGTH)
  11410. subtype = 0;
  11411. goto badsub;
  11412. }
  11413. USTPUTC(cc, out);
  11414. } else
  11415. goto badsub;
  11416. if (c != '}' && subtype == VSLENGTH) {
  11417. /* ${#VAR didn't end with } */
  11418. goto badsub;
  11419. }
  11420. if (subtype == 0) {
  11421. static const char types[] ALIGN1 = "}-+?=";
  11422. /* ${VAR...} but not $VAR or ${#VAR} */
  11423. /* c == first char after VAR */
  11424. int cc = c;
  11425. switch (c) {
  11426. case ':':
  11427. c = pgetc_eatbnl();
  11428. #if BASH_SUBSTR
  11429. /* This check is only needed to not misinterpret
  11430. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11431. * constructs.
  11432. */
  11433. if (!strchr(types, c)) {
  11434. subtype = VSSUBSTR;
  11435. pungetc();
  11436. break; /* "goto badsub" is bigger (!) */
  11437. }
  11438. #endif
  11439. subtype = VSNUL;
  11440. /*FALLTHROUGH*/
  11441. default: {
  11442. const char *p = strchr(types, c);
  11443. if (p == NULL)
  11444. break;
  11445. subtype |= p - types + VSNORMAL;
  11446. break;
  11447. }
  11448. case '%':
  11449. case '#':
  11450. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11451. c = pgetc_eatbnl();
  11452. if (c == cc)
  11453. subtype++;
  11454. else
  11455. pungetc();
  11456. newsyn = BASESYNTAX;
  11457. break;
  11458. #if BASH_PATTERN_SUBST
  11459. case '/':
  11460. /* ${v/[/]pattern/repl} */
  11461. //TODO: encode pattern and repl separately.
  11462. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11463. // are broken (should print "ONE")
  11464. subtype = VSREPLACE;
  11465. newsyn = BASESYNTAX;
  11466. c = pgetc_eatbnl();
  11467. if (c != '/')
  11468. goto badsub;
  11469. subtype++; /* VSREPLACEALL */
  11470. break;
  11471. #endif
  11472. }
  11473. } else {
  11474. badsub:
  11475. pungetc();
  11476. }
  11477. if (newsyn == ARISYNTAX)
  11478. newsyn = DQSYNTAX;
  11479. if ((newsyn != synstack->syntax || synstack->innerdq)
  11480. && subtype != VSNORMAL
  11481. ) {
  11482. synstack_push(&synstack,
  11483. synstack->prev ?: alloca(sizeof(*synstack)),
  11484. newsyn);
  11485. synstack->varpushed = 1;
  11486. synstack->dblquote = newsyn != BASESYNTAX;
  11487. }
  11488. ((unsigned char *)stackblock())[typeloc] = subtype;
  11489. if (subtype != VSNORMAL) {
  11490. synstack->varnest++;
  11491. if (synstack->dblquote)
  11492. synstack->dqvarnest++;
  11493. }
  11494. STPUTC('=', out);
  11495. }
  11496. goto parsesub_return;
  11497. }
  11498. /*
  11499. * Called to parse command substitutions. Newstyle is set if the command
  11500. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11501. * list of commands (passed by reference), and savelen is the number of
  11502. * characters on the top of the stack which must be preserved.
  11503. */
  11504. parsebackq: {
  11505. struct nodelist **nlpp;
  11506. union node *n;
  11507. char *str;
  11508. size_t savelen;
  11509. smallint saveprompt = 0;
  11510. str = NULL;
  11511. savelen = out - (char *)stackblock();
  11512. if (savelen > 0) {
  11513. /*
  11514. * FIXME: this can allocate very large block on stack and SEGV.
  11515. * Example:
  11516. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11517. * allocates 100kb for every command subst. With about
  11518. * a hundred command substitutions stack overflows.
  11519. * With larger prepended string, SEGV happens sooner.
  11520. */
  11521. str = alloca(savelen);
  11522. memcpy(str, stackblock(), savelen);
  11523. }
  11524. if (oldstyle) {
  11525. /* We must read until the closing backquote, giving special
  11526. * treatment to some slashes, and then push the string and
  11527. * reread it as input, interpreting it normally.
  11528. */
  11529. char *pout;
  11530. size_t psavelen;
  11531. char *pstr;
  11532. STARTSTACKSTR(pout);
  11533. for (;;) {
  11534. int pc;
  11535. setprompt_if(needprompt, 2);
  11536. pc = pgetc_eatbnl();
  11537. switch (pc) {
  11538. case '`':
  11539. goto done;
  11540. case '\\':
  11541. pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
  11542. if (pc != '\\' && pc != '`' && pc != '$'
  11543. && (!synstack->dblquote || pc != '"')
  11544. ) {
  11545. STPUTC('\\', pout);
  11546. }
  11547. if (pc <= 255 /* not PEOA or PEOF */) {
  11548. break;
  11549. }
  11550. /* fall through */
  11551. case PEOF:
  11552. IF_ASH_ALIAS(case PEOA:)
  11553. raise_error_syntax("EOF in backquote substitution");
  11554. case '\n':
  11555. nlnoprompt();
  11556. break;
  11557. default:
  11558. break;
  11559. }
  11560. STPUTC(pc, pout);
  11561. }
  11562. done:
  11563. STPUTC('\0', pout);
  11564. psavelen = pout - (char *)stackblock();
  11565. if (psavelen > 0) {
  11566. pstr = grabstackstr(pout);
  11567. setinputstring(pstr);
  11568. }
  11569. }
  11570. nlpp = &bqlist;
  11571. while (*nlpp)
  11572. nlpp = &(*nlpp)->next;
  11573. *nlpp = stzalloc(sizeof(**nlpp));
  11574. /* (*nlpp)->next = NULL; - stzalloc did it */
  11575. if (oldstyle) {
  11576. saveprompt = doprompt;
  11577. doprompt = 0;
  11578. }
  11579. n = list(2);
  11580. if (oldstyle)
  11581. doprompt = saveprompt;
  11582. else if (readtoken() != TRP)
  11583. raise_error_unexpected_syntax(TRP);
  11584. (*nlpp)->n = n;
  11585. if (oldstyle) {
  11586. /*
  11587. * Start reading from old file again, ignoring any pushed back
  11588. * tokens left from the backquote parsing
  11589. */
  11590. popfile();
  11591. tokpushback = 0;
  11592. }
  11593. while (stackblocksize() <= savelen)
  11594. growstackblock();
  11595. STARTSTACKSTR(out);
  11596. if (str) {
  11597. memcpy(out, str, savelen);
  11598. STADJUST(savelen, out);
  11599. }
  11600. USTPUTC(CTLBACKQ, out);
  11601. if (oldstyle)
  11602. goto parsebackq_oldreturn;
  11603. goto parsebackq_newreturn;
  11604. }
  11605. #if ENABLE_FEATURE_SH_MATH
  11606. /*
  11607. * Parse an arithmetic expansion (indicate start of one and set state)
  11608. */
  11609. parsearith: {
  11610. synstack_push(&synstack,
  11611. synstack->prev ?: alloca(sizeof(*synstack)),
  11612. ARISYNTAX);
  11613. synstack->dblquote = 1;
  11614. USTPUTC(CTLARI, out);
  11615. goto parsearith_return;
  11616. }
  11617. #endif
  11618. } /* end of readtoken */
  11619. /*
  11620. * Read the next input token.
  11621. * If the token is a word, we set backquotelist to the list of cmds in
  11622. * backquotes. We set quoteflag to true if any part of the word was
  11623. * quoted.
  11624. * If the token is TREDIR, then we set redirnode to a structure containing
  11625. * the redirection.
  11626. *
  11627. * [Change comment: here documents and internal procedures]
  11628. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11629. * word parsing code into a separate routine. In this case, readtoken
  11630. * doesn't need to have any internal procedures, but parseword does.
  11631. * We could also make parseoperator in essence the main routine, and
  11632. * have parseword (readtoken1?) handle both words and redirection.]
  11633. */
  11634. #define NEW_xxreadtoken
  11635. #ifdef NEW_xxreadtoken
  11636. /* singles must be first! */
  11637. static const char xxreadtoken_chars[7] ALIGN1 = {
  11638. '\n', '(', ')', /* singles */
  11639. '&', '|', ';', /* doubles */
  11640. 0
  11641. };
  11642. #define xxreadtoken_singles 3
  11643. #define xxreadtoken_doubles 3
  11644. static const char xxreadtoken_tokens[] ALIGN1 = {
  11645. TNL, TLP, TRP, /* only single occurrence allowed */
  11646. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11647. TEOF, /* corresponds to trailing nul */
  11648. TAND, TOR, TENDCASE /* if double occurrence */
  11649. };
  11650. static int
  11651. xxreadtoken(void)
  11652. {
  11653. int c;
  11654. if (tokpushback) {
  11655. tokpushback = 0;
  11656. return lasttoken;
  11657. }
  11658. setprompt_if(needprompt, 2);
  11659. for (;;) { /* until token or start of word found */
  11660. c = pgetc_eatbnl();
  11661. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11662. continue;
  11663. if (c == '#') {
  11664. while ((c = pgetc()) != '\n' && c != PEOF)
  11665. continue;
  11666. pungetc();
  11667. } else if (c == '\\') {
  11668. break; /* return readtoken1(...) */
  11669. } else {
  11670. const char *p;
  11671. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11672. if (c != PEOF) {
  11673. if (c == '\n') {
  11674. nlnoprompt();
  11675. }
  11676. p = strchr(xxreadtoken_chars, c);
  11677. if (p == NULL)
  11678. break; /* return readtoken1(...) */
  11679. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11680. int cc = pgetc_eatbnl();
  11681. if (cc == c) { /* double occurrence? */
  11682. p += xxreadtoken_doubles + 1;
  11683. } else {
  11684. pungetc();
  11685. #if BASH_REDIR_OUTPUT
  11686. if (c == '&' && cc == '>') /* &> */
  11687. break; /* return readtoken1(...) */
  11688. #endif
  11689. }
  11690. }
  11691. }
  11692. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11693. return lasttoken;
  11694. }
  11695. } /* for (;;) */
  11696. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11697. }
  11698. #else /* old xxreadtoken */
  11699. #define RETURN(token) return lasttoken = token
  11700. static int
  11701. xxreadtoken(void)
  11702. {
  11703. int c;
  11704. if (tokpushback) {
  11705. tokpushback = 0;
  11706. return lasttoken;
  11707. }
  11708. setprompt_if(needprompt, 2);
  11709. for (;;) { /* until token or start of word found */
  11710. c = pgetc_eatbnl();
  11711. switch (c) {
  11712. case ' ': case '\t':
  11713. IF_ASH_ALIAS(case PEOA:)
  11714. continue;
  11715. case '#':
  11716. while ((c = pgetc()) != '\n' && c != PEOF)
  11717. continue;
  11718. pungetc();
  11719. continue;
  11720. case '\n':
  11721. nlnoprompt();
  11722. RETURN(TNL);
  11723. case PEOF:
  11724. RETURN(TEOF);
  11725. case '&':
  11726. if (pgetc_eatbnl() == '&')
  11727. RETURN(TAND);
  11728. pungetc();
  11729. RETURN(TBACKGND);
  11730. case '|':
  11731. if (pgetc_eatbnl() == '|')
  11732. RETURN(TOR);
  11733. pungetc();
  11734. RETURN(TPIPE);
  11735. case ';':
  11736. if (pgetc_eatbnl() == ';')
  11737. RETURN(TENDCASE);
  11738. pungetc();
  11739. RETURN(TSEMI);
  11740. case '(':
  11741. RETURN(TLP);
  11742. case ')':
  11743. RETURN(TRP);
  11744. }
  11745. break;
  11746. }
  11747. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11748. #undef RETURN
  11749. }
  11750. #endif /* old xxreadtoken */
  11751. static int
  11752. readtoken(void)
  11753. {
  11754. int t;
  11755. int kwd = checkkwd;
  11756. #if DEBUG
  11757. smallint alreadyseen = tokpushback;
  11758. #endif
  11759. #if ENABLE_ASH_ALIAS
  11760. top:
  11761. #endif
  11762. t = xxreadtoken();
  11763. /*
  11764. * eat newlines
  11765. */
  11766. if (kwd & CHKNL) {
  11767. while (t == TNL) {
  11768. parseheredoc();
  11769. t = xxreadtoken();
  11770. }
  11771. }
  11772. if (t != TWORD || quoteflag) {
  11773. goto out;
  11774. }
  11775. /*
  11776. * check for keywords
  11777. */
  11778. if (kwd & CHKKWD) {
  11779. const char *const *pp;
  11780. pp = findkwd(wordtext);
  11781. if (pp) {
  11782. lasttoken = t = pp - tokname_array;
  11783. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11784. goto out;
  11785. }
  11786. }
  11787. if (checkkwd & CHKALIAS) {
  11788. #if ENABLE_ASH_ALIAS
  11789. struct alias *ap;
  11790. ap = lookupalias(wordtext, 1);
  11791. if (ap != NULL) {
  11792. if (*ap->val) {
  11793. pushstring(ap->val, ap);
  11794. }
  11795. goto top;
  11796. }
  11797. #endif
  11798. }
  11799. out:
  11800. checkkwd = 0;
  11801. #if DEBUG
  11802. if (!alreadyseen)
  11803. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11804. else
  11805. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11806. #endif
  11807. return t;
  11808. }
  11809. static int
  11810. peektoken(void)
  11811. {
  11812. int t;
  11813. t = readtoken();
  11814. tokpushback = 1;
  11815. return t;
  11816. }
  11817. /*
  11818. * Read and parse a command. Returns NODE_EOF on end of file.
  11819. * (NULL is a valid parse tree indicating a blank line.)
  11820. */
  11821. static union node *
  11822. parsecmd(int interact)
  11823. {
  11824. tokpushback = 0;
  11825. checkkwd = 0;
  11826. heredoclist = 0;
  11827. doprompt = interact;
  11828. setprompt_if(doprompt, doprompt);
  11829. needprompt = 0;
  11830. return list(1);
  11831. }
  11832. /*
  11833. * Input any here documents.
  11834. */
  11835. static void
  11836. parseheredoc(void)
  11837. {
  11838. struct heredoc *here;
  11839. union node *n;
  11840. here = heredoclist;
  11841. heredoclist = NULL;
  11842. while (here) {
  11843. tokpushback = 0;
  11844. setprompt_if(needprompt, 2);
  11845. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11846. here->eofmark, here->striptabs);
  11847. n = stzalloc(sizeof(struct narg));
  11848. n->narg.type = NARG;
  11849. /*n->narg.next = NULL; - stzalloc did it */
  11850. n->narg.text = wordtext;
  11851. n->narg.backquote = backquotelist;
  11852. here->here->nhere.doc = n;
  11853. here = here->next;
  11854. }
  11855. }
  11856. static const char *
  11857. expandstr(const char *ps, int syntax_type)
  11858. {
  11859. union node n;
  11860. int saveprompt;
  11861. /* XXX Fix (char *) cast. */
  11862. setinputstring((char *)ps);
  11863. saveprompt = doprompt;
  11864. doprompt = 0;
  11865. /* readtoken1() might die horribly.
  11866. * Try a prompt with syntactically wrong command:
  11867. * PS1='$(date "+%H:%M:%S) > '
  11868. */
  11869. {
  11870. volatile int saveint;
  11871. struct jmploc *volatile savehandler = exception_handler;
  11872. struct jmploc jmploc;
  11873. SAVE_INT(saveint);
  11874. if (setjmp(jmploc.loc) == 0) {
  11875. exception_handler = &jmploc;
  11876. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  11877. }
  11878. exception_handler = savehandler;
  11879. RESTORE_INT(saveint);
  11880. }
  11881. doprompt = saveprompt;
  11882. popfile();
  11883. n.narg.type = NARG;
  11884. n.narg.next = NULL;
  11885. n.narg.text = wordtext;
  11886. n.narg.backquote = backquotelist;
  11887. expandarg(&n, NULL, EXP_QUOTED);
  11888. return stackblock();
  11889. }
  11890. static inline int
  11891. parser_eof(void)
  11892. {
  11893. return tokpushback && lasttoken == TEOF;
  11894. }
  11895. /*
  11896. * Execute a command or commands contained in a string.
  11897. */
  11898. static int
  11899. evalstring(char *s, int flags)
  11900. {
  11901. struct jmploc *volatile savehandler;
  11902. struct jmploc jmploc;
  11903. int ex;
  11904. union node *n;
  11905. struct stackmark smark;
  11906. int status;
  11907. s = sstrdup(s);
  11908. setinputstring(s);
  11909. setstackmark(&smark);
  11910. status = 0;
  11911. /* On exception inside execution loop, we must popfile().
  11912. * Try interactively:
  11913. * readonly a=a
  11914. * command eval "a=b" # throws "is read only" error
  11915. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  11916. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  11917. */
  11918. savehandler = exception_handler;
  11919. ex = setjmp(jmploc.loc);
  11920. if (ex)
  11921. goto out;
  11922. exception_handler = &jmploc;
  11923. while ((n = parsecmd(0)) != NODE_EOF) {
  11924. int i;
  11925. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  11926. if (n)
  11927. status = i;
  11928. popstackmark(&smark);
  11929. if (evalskip)
  11930. break;
  11931. }
  11932. out:
  11933. popstackmark(&smark);
  11934. popfile();
  11935. stunalloc(s);
  11936. exception_handler = savehandler;
  11937. if (ex)
  11938. longjmp(exception_handler->loc, ex);
  11939. return status;
  11940. }
  11941. /*
  11942. * The eval command.
  11943. */
  11944. static int FAST_FUNC
  11945. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  11946. {
  11947. char *p;
  11948. char *concat;
  11949. if (argv[1]) {
  11950. p = argv[1];
  11951. argv += 2;
  11952. if (argv[0]) {
  11953. STARTSTACKSTR(concat);
  11954. for (;;) {
  11955. concat = stack_putstr(p, concat);
  11956. p = *argv++;
  11957. if (p == NULL)
  11958. break;
  11959. STPUTC(' ', concat);
  11960. }
  11961. STPUTC('\0', concat);
  11962. p = grabstackstr(concat);
  11963. }
  11964. return evalstring(p, flags & EV_TESTED);
  11965. }
  11966. return 0;
  11967. }
  11968. /*
  11969. * Read and execute commands.
  11970. * "Top" is nonzero for the top level command loop;
  11971. * it turns on prompting if the shell is interactive.
  11972. */
  11973. static int
  11974. cmdloop(int top)
  11975. {
  11976. union node *n;
  11977. struct stackmark smark;
  11978. int inter;
  11979. int status = 0;
  11980. int numeof = 0;
  11981. TRACE(("cmdloop(%d) called\n", top));
  11982. for (;;) {
  11983. int skip;
  11984. setstackmark(&smark);
  11985. #if JOBS
  11986. if (doing_jobctl)
  11987. showjobs(SHOW_CHANGED|SHOW_STDERR);
  11988. #endif
  11989. inter = 0;
  11990. if (iflag && top) {
  11991. inter++;
  11992. chkmail();
  11993. }
  11994. n = parsecmd(inter);
  11995. #if DEBUG
  11996. if (DEBUG > 2 && debug && (n != NODE_EOF))
  11997. showtree(n);
  11998. #endif
  11999. if (n == NODE_EOF) {
  12000. if (!top || numeof >= 50)
  12001. break;
  12002. if (!stoppedjobs()) {
  12003. if (!Iflag)
  12004. break;
  12005. out2str("\nUse \"exit\" to leave shell.\n");
  12006. }
  12007. numeof++;
  12008. } else if (nflag == 0) {
  12009. int i;
  12010. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12011. job_warning >>= 1;
  12012. numeof = 0;
  12013. i = evaltree(n, 0);
  12014. if (n)
  12015. status = i;
  12016. }
  12017. popstackmark(&smark);
  12018. skip = evalskip;
  12019. if (skip) {
  12020. evalskip &= ~SKIPFUNC;
  12021. break;
  12022. }
  12023. }
  12024. return status;
  12025. }
  12026. /*
  12027. * Take commands from a file. To be compatible we should do a path
  12028. * search for the file, which is necessary to find sub-commands.
  12029. */
  12030. static char *
  12031. find_dot_file(char *name)
  12032. {
  12033. char *fullname;
  12034. const char *path = pathval();
  12035. struct stat statb;
  12036. /* don't try this for absolute or relative paths */
  12037. if (strchr(name, '/'))
  12038. return name;
  12039. while ((fullname = path_advance(&path, name)) != NULL) {
  12040. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  12041. /*
  12042. * Don't bother freeing here, since it will
  12043. * be freed by the caller.
  12044. */
  12045. return fullname;
  12046. }
  12047. if (fullname != name)
  12048. stunalloc(fullname);
  12049. }
  12050. /* not found in PATH */
  12051. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12052. return name;
  12053. #else
  12054. ash_msg_and_raise_error("%s: not found", name);
  12055. /* NOTREACHED */
  12056. #endif
  12057. }
  12058. static int FAST_FUNC
  12059. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12060. {
  12061. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12062. int status = 0;
  12063. char *fullname;
  12064. char **argv;
  12065. char *args_need_save;
  12066. volatile struct shparam saveparam;
  12067. //???
  12068. // struct strlist *sp;
  12069. // for (sp = cmdenviron; sp; sp = sp->next)
  12070. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12071. nextopt(nullstr); /* handle possible "--" */
  12072. argv = argptr;
  12073. if (!argv[0]) {
  12074. /* bash says: "bash: .: filename argument required" */
  12075. return 2; /* bash compat */
  12076. }
  12077. /* This aborts if file isn't found, which is POSIXly correct.
  12078. * bash returns exitcode 1 instead.
  12079. */
  12080. fullname = find_dot_file(argv[0]);
  12081. argv++;
  12082. args_need_save = argv[0];
  12083. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12084. int argc;
  12085. saveparam = shellparam;
  12086. shellparam.malloced = 0;
  12087. argc = 1;
  12088. while (argv[argc])
  12089. argc++;
  12090. shellparam.nparam = argc;
  12091. shellparam.p = argv;
  12092. };
  12093. /* This aborts if file can't be opened, which is POSIXly correct.
  12094. * bash returns exitcode 1 instead.
  12095. */
  12096. setinputfile(fullname, INPUT_PUSH_FILE);
  12097. commandname = fullname;
  12098. status = cmdloop(0);
  12099. popfile();
  12100. if (args_need_save) {
  12101. freeparam(&shellparam);
  12102. shellparam = saveparam;
  12103. };
  12104. return status;
  12105. }
  12106. static int FAST_FUNC
  12107. exitcmd(int argc UNUSED_PARAM, char **argv)
  12108. {
  12109. if (stoppedjobs())
  12110. return 0;
  12111. if (argv[1])
  12112. exitstatus = number(argv[1]);
  12113. raise_exception(EXEXIT);
  12114. /* NOTREACHED */
  12115. }
  12116. /*
  12117. * Read a file containing shell functions.
  12118. */
  12119. static void
  12120. readcmdfile(char *name)
  12121. {
  12122. setinputfile(name, INPUT_PUSH_FILE);
  12123. cmdloop(0);
  12124. popfile();
  12125. }
  12126. /* ============ find_command inplementation */
  12127. /*
  12128. * Resolve a command name. If you change this routine, you may have to
  12129. * change the shellexec routine as well.
  12130. */
  12131. static void
  12132. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12133. {
  12134. struct tblentry *cmdp;
  12135. int idx;
  12136. int prev;
  12137. char *fullname;
  12138. struct stat statb;
  12139. int e;
  12140. int updatetbl;
  12141. struct builtincmd *bcmd;
  12142. /* If name contains a slash, don't use PATH or hash table */
  12143. if (strchr(name, '/') != NULL) {
  12144. entry->u.index = -1;
  12145. if (act & DO_ABS) {
  12146. while (stat(name, &statb) < 0) {
  12147. #ifdef SYSV
  12148. if (errno == EINTR)
  12149. continue;
  12150. #endif
  12151. entry->cmdtype = CMDUNKNOWN;
  12152. return;
  12153. }
  12154. }
  12155. entry->cmdtype = CMDNORMAL;
  12156. return;
  12157. }
  12158. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12159. updatetbl = (path == pathval());
  12160. if (!updatetbl) {
  12161. act |= DO_ALTPATH;
  12162. if (strstr(path, "%builtin") != NULL)
  12163. act |= DO_ALTBLTIN;
  12164. }
  12165. /* If name is in the table, check answer will be ok */
  12166. cmdp = cmdlookup(name, 0);
  12167. if (cmdp != NULL) {
  12168. int bit;
  12169. switch (cmdp->cmdtype) {
  12170. default:
  12171. #if DEBUG
  12172. abort();
  12173. #endif
  12174. case CMDNORMAL:
  12175. bit = DO_ALTPATH;
  12176. break;
  12177. case CMDFUNCTION:
  12178. bit = DO_NOFUNC;
  12179. break;
  12180. case CMDBUILTIN:
  12181. bit = DO_ALTBLTIN;
  12182. break;
  12183. }
  12184. if (act & bit) {
  12185. updatetbl = 0;
  12186. cmdp = NULL;
  12187. } else if (cmdp->rehash == 0)
  12188. /* if not invalidated by cd, we're done */
  12189. goto success;
  12190. }
  12191. /* If %builtin not in path, check for builtin next */
  12192. bcmd = find_builtin(name);
  12193. if (bcmd) {
  12194. if (IS_BUILTIN_REGULAR(bcmd))
  12195. goto builtin_success;
  12196. if (act & DO_ALTPATH) {
  12197. if (!(act & DO_ALTBLTIN))
  12198. goto builtin_success;
  12199. } else if (builtinloc <= 0) {
  12200. goto builtin_success;
  12201. }
  12202. }
  12203. #if ENABLE_FEATURE_SH_STANDALONE
  12204. {
  12205. int applet_no = find_applet_by_name(name);
  12206. if (applet_no >= 0) {
  12207. entry->cmdtype = CMDNORMAL;
  12208. entry->u.index = -2 - applet_no;
  12209. return;
  12210. }
  12211. }
  12212. #endif
  12213. /* We have to search path. */
  12214. prev = -1; /* where to start */
  12215. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12216. if (cmdp->cmdtype == CMDBUILTIN)
  12217. prev = builtinloc;
  12218. else
  12219. prev = cmdp->param.index;
  12220. }
  12221. e = ENOENT;
  12222. idx = -1;
  12223. loop:
  12224. while ((fullname = path_advance(&path, name)) != NULL) {
  12225. stunalloc(fullname);
  12226. /* NB: code below will still use fullname
  12227. * despite it being "unallocated" */
  12228. idx++;
  12229. if (pathopt) {
  12230. if (prefix(pathopt, "builtin")) {
  12231. if (bcmd)
  12232. goto builtin_success;
  12233. continue;
  12234. }
  12235. if ((act & DO_NOFUNC)
  12236. || !prefix(pathopt, "func")
  12237. ) { /* ignore unimplemented options */
  12238. continue;
  12239. }
  12240. }
  12241. /* if rehash, don't redo absolute path names */
  12242. if (fullname[0] == '/' && idx <= prev) {
  12243. if (idx < prev)
  12244. continue;
  12245. TRACE(("searchexec \"%s\": no change\n", name));
  12246. goto success;
  12247. }
  12248. while (stat(fullname, &statb) < 0) {
  12249. #ifdef SYSV
  12250. if (errno == EINTR)
  12251. continue;
  12252. #endif
  12253. if (errno != ENOENT && errno != ENOTDIR)
  12254. e = errno;
  12255. goto loop;
  12256. }
  12257. e = EACCES; /* if we fail, this will be the error */
  12258. if (!S_ISREG(statb.st_mode))
  12259. continue;
  12260. if (pathopt) { /* this is a %func directory */
  12261. stalloc(strlen(fullname) + 1);
  12262. /* NB: stalloc will return space pointed by fullname
  12263. * (because we don't have any intervening allocations
  12264. * between stunalloc above and this stalloc) */
  12265. readcmdfile(fullname);
  12266. cmdp = cmdlookup(name, 0);
  12267. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12268. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12269. stunalloc(fullname);
  12270. goto success;
  12271. }
  12272. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12273. if (!updatetbl) {
  12274. entry->cmdtype = CMDNORMAL;
  12275. entry->u.index = idx;
  12276. return;
  12277. }
  12278. INT_OFF;
  12279. cmdp = cmdlookup(name, 1);
  12280. cmdp->cmdtype = CMDNORMAL;
  12281. cmdp->param.index = idx;
  12282. INT_ON;
  12283. goto success;
  12284. }
  12285. /* We failed. If there was an entry for this command, delete it */
  12286. if (cmdp && updatetbl)
  12287. delete_cmd_entry();
  12288. if (act & DO_ERR) {
  12289. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12290. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12291. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12292. char *argv[3];
  12293. argv[0] = (char*) "command_not_found_handle";
  12294. argv[1] = name;
  12295. argv[2] = NULL;
  12296. evalfun(hookp->param.func, 2, argv, 0);
  12297. entry->cmdtype = CMDUNKNOWN;
  12298. return;
  12299. }
  12300. #endif
  12301. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12302. }
  12303. entry->cmdtype = CMDUNKNOWN;
  12304. return;
  12305. builtin_success:
  12306. if (!updatetbl) {
  12307. entry->cmdtype = CMDBUILTIN;
  12308. entry->u.cmd = bcmd;
  12309. return;
  12310. }
  12311. INT_OFF;
  12312. cmdp = cmdlookup(name, 1);
  12313. cmdp->cmdtype = CMDBUILTIN;
  12314. cmdp->param.cmd = bcmd;
  12315. INT_ON;
  12316. success:
  12317. cmdp->rehash = 0;
  12318. entry->cmdtype = cmdp->cmdtype;
  12319. entry->u = cmdp->param;
  12320. }
  12321. /*
  12322. * The trap builtin.
  12323. */
  12324. static int FAST_FUNC
  12325. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12326. {
  12327. char *action;
  12328. char **ap;
  12329. int signo, exitcode;
  12330. nextopt(nullstr);
  12331. ap = argptr;
  12332. if (!*ap) {
  12333. for (signo = 0; signo < NSIG; signo++) {
  12334. char *tr = trap_ptr[signo];
  12335. if (tr) {
  12336. /* note: bash adds "SIG", but only if invoked
  12337. * as "bash". If called as "sh", or if set -o posix,
  12338. * then it prints short signal names.
  12339. * We are printing short names: */
  12340. out1fmt("trap -- %s %s\n",
  12341. single_quote(tr),
  12342. get_signame(signo));
  12343. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12344. * In this case, we will exit very soon, no need to free(). */
  12345. /* if (trap_ptr != trap && tp[0]) */
  12346. /* free(tr); */
  12347. }
  12348. }
  12349. /*
  12350. if (trap_ptr != trap) {
  12351. free(trap_ptr);
  12352. trap_ptr = trap;
  12353. }
  12354. */
  12355. return 0;
  12356. }
  12357. /* Why the second check?
  12358. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12359. * In this case, NUM is signal no, not an action.
  12360. */
  12361. action = NULL;
  12362. if (ap[1] && !is_number(ap[0]))
  12363. action = *ap++;
  12364. exitcode = 0;
  12365. while (*ap) {
  12366. signo = get_signum(*ap);
  12367. if (signo < 0) {
  12368. /* Mimic bash message exactly */
  12369. ash_msg("%s: invalid signal specification", *ap);
  12370. exitcode = 1;
  12371. goto next;
  12372. }
  12373. INT_OFF;
  12374. if (action) {
  12375. if (LONE_DASH(action))
  12376. action = NULL;
  12377. else {
  12378. if (action[0]) /* not NULL and not "" and not "-" */
  12379. may_have_traps = 1;
  12380. action = ckstrdup(action);
  12381. }
  12382. }
  12383. free(trap[signo]);
  12384. trap[signo] = action;
  12385. if (signo != 0)
  12386. setsignal(signo);
  12387. INT_ON;
  12388. next:
  12389. ap++;
  12390. }
  12391. return exitcode;
  12392. }
  12393. /* ============ Builtins */
  12394. #if ENABLE_ASH_HELP
  12395. static int FAST_FUNC
  12396. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12397. {
  12398. unsigned col;
  12399. unsigned i;
  12400. out1fmt(
  12401. "Built-in commands:\n"
  12402. "------------------\n");
  12403. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12404. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12405. builtintab[i].name + 1);
  12406. if (col > 60) {
  12407. out1fmt("\n");
  12408. col = 0;
  12409. }
  12410. }
  12411. # if ENABLE_FEATURE_SH_STANDALONE
  12412. {
  12413. const char *a = applet_names;
  12414. while (*a) {
  12415. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12416. if (col > 60) {
  12417. out1fmt("\n");
  12418. col = 0;
  12419. }
  12420. while (*a++ != '\0')
  12421. continue;
  12422. }
  12423. }
  12424. # endif
  12425. newline_and_flush(stdout);
  12426. return EXIT_SUCCESS;
  12427. }
  12428. #endif
  12429. #if MAX_HISTORY
  12430. static int FAST_FUNC
  12431. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12432. {
  12433. show_history(line_input_state);
  12434. return EXIT_SUCCESS;
  12435. }
  12436. #endif
  12437. /*
  12438. * The export and readonly commands.
  12439. */
  12440. static int FAST_FUNC
  12441. exportcmd(int argc UNUSED_PARAM, char **argv)
  12442. {
  12443. struct var *vp;
  12444. char *name;
  12445. const char *p;
  12446. char **aptr;
  12447. char opt;
  12448. int flag;
  12449. int flag_off;
  12450. /* "readonly" in bash accepts, but ignores -n.
  12451. * We do the same: it saves a conditional in nextopt's param.
  12452. */
  12453. flag_off = 0;
  12454. while ((opt = nextopt("np")) != '\0') {
  12455. if (opt == 'n')
  12456. flag_off = VEXPORT;
  12457. }
  12458. flag = VEXPORT;
  12459. if (argv[0][0] == 'r') {
  12460. flag = VREADONLY;
  12461. flag_off = 0; /* readonly ignores -n */
  12462. }
  12463. flag_off = ~flag_off;
  12464. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12465. {
  12466. aptr = argptr;
  12467. name = *aptr;
  12468. if (name) {
  12469. do {
  12470. p = strchr(name, '=');
  12471. if (p != NULL) {
  12472. p++;
  12473. } else {
  12474. vp = *findvar(hashvar(name), name);
  12475. if (vp) {
  12476. vp->flags = ((vp->flags | flag) & flag_off);
  12477. continue;
  12478. }
  12479. }
  12480. setvar(name, p, (flag & flag_off));
  12481. } while ((name = *++aptr) != NULL);
  12482. return 0;
  12483. }
  12484. }
  12485. /* No arguments. Show the list of exported or readonly vars.
  12486. * -n is ignored.
  12487. */
  12488. showvars(argv[0], flag, 0);
  12489. return 0;
  12490. }
  12491. /*
  12492. * Delete a function if it exists.
  12493. */
  12494. static void
  12495. unsetfunc(const char *name)
  12496. {
  12497. struct tblentry *cmdp;
  12498. cmdp = cmdlookup(name, 0);
  12499. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12500. delete_cmd_entry();
  12501. }
  12502. /*
  12503. * The unset builtin command. We unset the function before we unset the
  12504. * variable to allow a function to be unset when there is a readonly variable
  12505. * with the same name.
  12506. */
  12507. static int FAST_FUNC
  12508. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12509. {
  12510. char **ap;
  12511. int i;
  12512. int flag = 0;
  12513. while ((i = nextopt("vf")) != 0) {
  12514. flag = i;
  12515. }
  12516. for (ap = argptr; *ap; ap++) {
  12517. if (flag != 'f') {
  12518. unsetvar(*ap);
  12519. continue;
  12520. }
  12521. if (flag != 'v')
  12522. unsetfunc(*ap);
  12523. }
  12524. return 0;
  12525. }
  12526. static const unsigned char timescmd_str[] ALIGN1 = {
  12527. ' ', offsetof(struct tms, tms_utime),
  12528. '\n', offsetof(struct tms, tms_stime),
  12529. ' ', offsetof(struct tms, tms_cutime),
  12530. '\n', offsetof(struct tms, tms_cstime),
  12531. 0
  12532. };
  12533. static int FAST_FUNC
  12534. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12535. {
  12536. unsigned clk_tck;
  12537. const unsigned char *p;
  12538. struct tms buf;
  12539. clk_tck = bb_clk_tck();
  12540. times(&buf);
  12541. p = timescmd_str;
  12542. do {
  12543. unsigned sec, frac;
  12544. unsigned long t;
  12545. t = *(clock_t *)(((char *) &buf) + p[1]);
  12546. sec = t / clk_tck;
  12547. frac = t % clk_tck;
  12548. out1fmt("%um%u.%03us%c",
  12549. sec / 60, sec % 60,
  12550. (frac * 1000) / clk_tck,
  12551. p[0]);
  12552. p += 2;
  12553. } while (*p);
  12554. return 0;
  12555. }
  12556. #if ENABLE_FEATURE_SH_MATH
  12557. /*
  12558. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12559. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12560. *
  12561. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12562. */
  12563. static int FAST_FUNC
  12564. letcmd(int argc UNUSED_PARAM, char **argv)
  12565. {
  12566. arith_t i;
  12567. argv++;
  12568. if (!*argv)
  12569. ash_msg_and_raise_error("expression expected");
  12570. do {
  12571. i = ash_arith(*argv);
  12572. } while (*++argv);
  12573. return !i;
  12574. }
  12575. #endif
  12576. /*
  12577. * The read builtin. Options:
  12578. * -r Do not interpret '\' specially
  12579. * -s Turn off echo (tty only)
  12580. * -n NCHARS Read NCHARS max
  12581. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12582. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12583. * -u FD Read from given FD instead of fd 0
  12584. * -d DELIM End on DELIM char, not newline
  12585. * This uses unbuffered input, which may be avoidable in some cases.
  12586. * TODO: bash also has:
  12587. * -a ARRAY Read into array[0],[1],etc
  12588. * -e Use line editing (tty only)
  12589. */
  12590. static int FAST_FUNC
  12591. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12592. {
  12593. struct builtin_read_params params;
  12594. const char *r;
  12595. int i;
  12596. memset(&params, 0, sizeof(params));
  12597. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12598. switch (i) {
  12599. case 'p':
  12600. params.opt_p = optionarg;
  12601. break;
  12602. case 'n':
  12603. params.opt_n = optionarg;
  12604. break;
  12605. case 's':
  12606. params.read_flags |= BUILTIN_READ_SILENT;
  12607. break;
  12608. case 't':
  12609. params.opt_t = optionarg;
  12610. break;
  12611. case 'r':
  12612. params.read_flags |= BUILTIN_READ_RAW;
  12613. break;
  12614. case 'u':
  12615. params.opt_u = optionarg;
  12616. break;
  12617. #if BASH_READ_D
  12618. case 'd':
  12619. params.opt_d = optionarg;
  12620. break;
  12621. #endif
  12622. default:
  12623. break;
  12624. }
  12625. }
  12626. params.argv = argptr;
  12627. params.setvar = setvar0;
  12628. params.ifs = bltinlookup("IFS"); /* can be NULL */
  12629. /* "read -s" needs to save/restore termios, can't allow ^C
  12630. * to jump out of it.
  12631. */
  12632. again:
  12633. INT_OFF;
  12634. r = shell_builtin_read(&params);
  12635. INT_ON;
  12636. if ((uintptr_t)r == 1 && errno == EINTR) {
  12637. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12638. * Correct behavior is to not exit "read"
  12639. */
  12640. if (pending_sig == 0)
  12641. goto again;
  12642. }
  12643. if ((uintptr_t)r > 1)
  12644. ash_msg_and_raise_error(r);
  12645. return (uintptr_t)r;
  12646. }
  12647. static int FAST_FUNC
  12648. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12649. {
  12650. static const char permuser[3] ALIGN1 = "ogu";
  12651. mode_t mask;
  12652. int symbolic_mode = 0;
  12653. while (nextopt("S") != '\0') {
  12654. symbolic_mode = 1;
  12655. }
  12656. INT_OFF;
  12657. mask = umask(0);
  12658. umask(mask);
  12659. INT_ON;
  12660. if (*argptr == NULL) {
  12661. if (symbolic_mode) {
  12662. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12663. char *p = buf;
  12664. int i;
  12665. i = 2;
  12666. for (;;) {
  12667. *p++ = ',';
  12668. *p++ = permuser[i];
  12669. *p++ = '=';
  12670. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12671. if (!(mask & 0400)) *p++ = 'r';
  12672. if (!(mask & 0200)) *p++ = 'w';
  12673. if (!(mask & 0100)) *p++ = 'x';
  12674. mask <<= 3;
  12675. if (--i < 0)
  12676. break;
  12677. }
  12678. *p = '\0';
  12679. puts(buf + 1);
  12680. } else {
  12681. out1fmt("%04o\n", mask);
  12682. }
  12683. } else {
  12684. char *modestr = *argptr;
  12685. /* numeric umasks are taken as-is */
  12686. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12687. if (!isdigit(modestr[0]))
  12688. mask ^= 0777;
  12689. mask = bb_parse_mode(modestr, mask);
  12690. if ((unsigned)mask > 0777) {
  12691. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12692. }
  12693. if (!isdigit(modestr[0]))
  12694. mask ^= 0777;
  12695. umask(mask);
  12696. }
  12697. return 0;
  12698. }
  12699. static int FAST_FUNC
  12700. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12701. {
  12702. return shell_builtin_ulimit(argv);
  12703. }
  12704. /* ============ main() and helpers */
  12705. /*
  12706. * Called to exit the shell.
  12707. */
  12708. static void
  12709. exitshell(void)
  12710. {
  12711. struct jmploc loc;
  12712. char *p;
  12713. int status;
  12714. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12715. save_history(line_input_state);
  12716. #endif
  12717. status = exitstatus;
  12718. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  12719. if (setjmp(loc.loc)) {
  12720. if (exception_type == EXEXIT)
  12721. status = exitstatus;
  12722. goto out;
  12723. }
  12724. exception_handler = &loc;
  12725. p = trap[0];
  12726. if (p) {
  12727. trap[0] = NULL;
  12728. evalskip = 0;
  12729. evalstring(p, 0);
  12730. /*free(p); - we'll exit soon */
  12731. }
  12732. out:
  12733. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12734. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12735. */
  12736. setjobctl(0);
  12737. flush_stdout_stderr();
  12738. _exit(status);
  12739. /* NOTREACHED */
  12740. }
  12741. /* Don't inline: conserve stack of caller from having our locals too */
  12742. static NOINLINE void
  12743. init(void)
  12744. {
  12745. /* we will never free this */
  12746. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12747. basepf.linno = 1;
  12748. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  12749. setsignal(SIGCHLD);
  12750. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  12751. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  12752. */
  12753. signal(SIGHUP, SIG_DFL);
  12754. {
  12755. char **envp;
  12756. const char *p;
  12757. initvar();
  12758. for (envp = environ; envp && *envp; envp++) {
  12759. /* Used to have
  12760. * p = endofname(*envp);
  12761. * if (p != *envp && *p == '=') {
  12762. * here to weed out badly-named variables, but this breaks
  12763. * scenarios where people do want them passed to children:
  12764. * import os
  12765. * os.environ["test-test"]="test"
  12766. * if os.fork() == 0:
  12767. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  12768. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  12769. */
  12770. if (strchr(*envp, '=')) {
  12771. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12772. }
  12773. }
  12774. setvareq((char*)defifsvar, VTEXTFIXED);
  12775. setvareq((char*)defoptindvar, VTEXTFIXED);
  12776. setvar0("PPID", utoa(getppid()));
  12777. #if BASH_SHLVL_VAR
  12778. p = lookupvar("SHLVL");
  12779. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12780. #endif
  12781. #if BASH_HOSTNAME_VAR
  12782. if (!lookupvar("HOSTNAME")) {
  12783. struct utsname uts;
  12784. uname(&uts);
  12785. setvar0("HOSTNAME", uts.nodename);
  12786. }
  12787. #endif
  12788. p = lookupvar("PWD");
  12789. if (p) {
  12790. struct stat st1, st2;
  12791. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12792. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12793. ) {
  12794. p = NULL;
  12795. }
  12796. }
  12797. setpwd(p, 0);
  12798. }
  12799. }
  12800. //usage:#define ash_trivial_usage
  12801. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  12802. //usage:#define ash_full_usage "\n\n"
  12803. //usage: "Unix shell interpreter"
  12804. /*
  12805. * Process the shell command line arguments.
  12806. */
  12807. static int
  12808. procargs(char **argv)
  12809. {
  12810. int i;
  12811. const char *xminusc;
  12812. char **xargv;
  12813. int login_sh;
  12814. xargv = argv;
  12815. login_sh = xargv[0] && xargv[0][0] == '-';
  12816. #if NUM_SCRIPTS > 0
  12817. if (minusc)
  12818. goto setarg0;
  12819. #endif
  12820. arg0 = xargv[0];
  12821. /* if (xargv[0]) - mmm, this is always true! */
  12822. xargv++;
  12823. argptr = xargv;
  12824. for (i = 0; i < NOPTS; i++)
  12825. optlist[i] = 2;
  12826. if (options(/*cmdline:*/ 1, &login_sh)) {
  12827. /* it already printed err message */
  12828. raise_exception(EXERROR);
  12829. }
  12830. xargv = argptr;
  12831. xminusc = minusc;
  12832. if (*xargv == NULL) {
  12833. if (xminusc)
  12834. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  12835. sflag = 1;
  12836. }
  12837. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  12838. iflag = 1;
  12839. if (mflag == 2)
  12840. mflag = iflag;
  12841. for (i = 0; i < NOPTS; i++)
  12842. if (optlist[i] == 2)
  12843. optlist[i] = 0;
  12844. #if DEBUG == 2
  12845. debug = 1;
  12846. #endif
  12847. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  12848. if (xminusc) {
  12849. minusc = *xargv++;
  12850. if (*xargv)
  12851. goto setarg0;
  12852. } else if (!sflag) {
  12853. setinputfile(*xargv, 0);
  12854. setarg0:
  12855. arg0 = *xargv++;
  12856. commandname = arg0;
  12857. }
  12858. shellparam.p = xargv;
  12859. #if ENABLE_ASH_GETOPTS
  12860. shellparam.optind = 1;
  12861. shellparam.optoff = -1;
  12862. #endif
  12863. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  12864. while (*xargv) {
  12865. shellparam.nparam++;
  12866. xargv++;
  12867. }
  12868. optschanged();
  12869. return login_sh;
  12870. }
  12871. /*
  12872. * Read /etc/profile, ~/.profile, $ENV.
  12873. */
  12874. static void
  12875. read_profile(const char *name)
  12876. {
  12877. name = expandstr(name, DQSYNTAX);
  12878. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  12879. return;
  12880. cmdloop(0);
  12881. popfile();
  12882. }
  12883. /*
  12884. * This routine is called when an error or an interrupt occurs in an
  12885. * interactive shell and control is returned to the main command loop.
  12886. * (In dash, this function is auto-generated by build machinery).
  12887. */
  12888. static void
  12889. reset(void)
  12890. {
  12891. /* from eval.c: */
  12892. evalskip = 0;
  12893. loopnest = 0;
  12894. /* from expand.c: */
  12895. ifsfree();
  12896. /* from input.c: */
  12897. g_parsefile->left_in_buffer = 0;
  12898. g_parsefile->left_in_line = 0; /* clear input buffer */
  12899. popallfiles();
  12900. /* from redir.c: */
  12901. unwindredir(NULL);
  12902. /* from var.c: */
  12903. unwindlocalvars(NULL);
  12904. }
  12905. #if PROFILE
  12906. static short profile_buf[16384];
  12907. extern int etext();
  12908. #endif
  12909. /*
  12910. * Main routine. We initialize things, parse the arguments, execute
  12911. * profiles if we're a login shell, and then call cmdloop to execute
  12912. * commands. The setjmp call sets up the location to jump to when an
  12913. * exception occurs. When an exception occurs the variable "state"
  12914. * is used to figure out how far we had gotten.
  12915. */
  12916. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12917. #if NUM_SCRIPTS > 0
  12918. int ash_main(int argc, char **argv)
  12919. #else
  12920. int ash_main(int argc UNUSED_PARAM, char **argv)
  12921. #endif
  12922. /* note: 'argc' is used only if embedded scripts are enabled */
  12923. {
  12924. volatile smallint state;
  12925. struct jmploc jmploc;
  12926. struct stackmark smark;
  12927. int login_sh;
  12928. /* Initialize global data */
  12929. INIT_G_misc();
  12930. INIT_G_memstack();
  12931. INIT_G_var();
  12932. #if ENABLE_ASH_ALIAS
  12933. INIT_G_alias();
  12934. #endif
  12935. INIT_G_cmdtable();
  12936. #if PROFILE
  12937. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12938. #endif
  12939. #if ENABLE_FEATURE_EDITING
  12940. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12941. #endif
  12942. state = 0;
  12943. if (setjmp(jmploc.loc)) {
  12944. smallint e;
  12945. smallint s;
  12946. reset();
  12947. e = exception_type;
  12948. s = state;
  12949. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  12950. exitshell();
  12951. }
  12952. if (e == EXINT) {
  12953. newline_and_flush(stderr);
  12954. }
  12955. popstackmark(&smark);
  12956. FORCE_INT_ON; /* enable interrupts */
  12957. if (s == 1)
  12958. goto state1;
  12959. if (s == 2)
  12960. goto state2;
  12961. if (s == 3)
  12962. goto state3;
  12963. goto state4;
  12964. }
  12965. exception_handler = &jmploc;
  12966. rootpid = getpid();
  12967. init();
  12968. setstackmark(&smark);
  12969. #if NUM_SCRIPTS > 0
  12970. if (argc < 0)
  12971. /* Non-NULL minusc tells procargs that an embedded script is being run */
  12972. minusc = get_script_content(-argc - 1);
  12973. #endif
  12974. login_sh = procargs(argv);
  12975. #if DEBUG
  12976. TRACE(("Shell args: "));
  12977. trace_puts_args(argv);
  12978. #endif
  12979. if (login_sh) {
  12980. const char *hp;
  12981. state = 1;
  12982. read_profile("/etc/profile");
  12983. state1:
  12984. state = 2;
  12985. hp = lookupvar("HOME");
  12986. if (hp)
  12987. read_profile("$HOME/.profile");
  12988. }
  12989. state2:
  12990. state = 3;
  12991. if (
  12992. #ifndef linux
  12993. getuid() == geteuid() && getgid() == getegid() &&
  12994. #endif
  12995. iflag
  12996. ) {
  12997. const char *shinit = lookupvar("ENV");
  12998. if (shinit != NULL && *shinit != '\0')
  12999. read_profile(shinit);
  13000. }
  13001. popstackmark(&smark);
  13002. state3:
  13003. state = 4;
  13004. if (minusc) {
  13005. /* evalstring pushes parsefile stack.
  13006. * Ensure we don't falsely claim that 0 (stdin)
  13007. * is one of stacked source fds.
  13008. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13009. // if (!sflag) g_parsefile->pf_fd = -1;
  13010. // ^^ not necessary since now we special-case fd 0
  13011. // in save_fd_on_redirect()
  13012. evalstring(minusc, sflag ? 0 : EV_EXIT);
  13013. }
  13014. if (sflag || minusc == NULL) {
  13015. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13016. if (iflag) {
  13017. const char *hp = lookupvar("HISTFILE");
  13018. if (!hp) {
  13019. hp = lookupvar("HOME");
  13020. if (hp) {
  13021. INT_OFF;
  13022. hp = concat_path_file(hp, ".ash_history");
  13023. setvar0("HISTFILE", hp);
  13024. free((char*)hp);
  13025. INT_ON;
  13026. hp = lookupvar("HISTFILE");
  13027. }
  13028. }
  13029. if (hp)
  13030. line_input_state->hist_file = hp;
  13031. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13032. hp = lookupvar("HISTFILESIZE");
  13033. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13034. # endif
  13035. }
  13036. #endif
  13037. state4: /* XXX ??? - why isn't this before the "if" statement */
  13038. cmdloop(1);
  13039. }
  13040. #if PROFILE
  13041. monitor(0);
  13042. #endif
  13043. #ifdef GPROF
  13044. {
  13045. extern void _mcleanup(void);
  13046. _mcleanup();
  13047. }
  13048. #endif
  13049. TRACE(("End of main reached\n"));
  13050. exitshell();
  13051. /* NOTREACHED */
  13052. }
  13053. /*-
  13054. * Copyright (c) 1989, 1991, 1993, 1994
  13055. * The Regents of the University of California. All rights reserved.
  13056. *
  13057. * This code is derived from software contributed to Berkeley by
  13058. * Kenneth Almquist.
  13059. *
  13060. * Redistribution and use in source and binary forms, with or without
  13061. * modification, are permitted provided that the following conditions
  13062. * are met:
  13063. * 1. Redistributions of source code must retain the above copyright
  13064. * notice, this list of conditions and the following disclaimer.
  13065. * 2. Redistributions in binary form must reproduce the above copyright
  13066. * notice, this list of conditions and the following disclaimer in the
  13067. * documentation and/or other materials provided with the distribution.
  13068. * 3. Neither the name of the University nor the names of its contributors
  13069. * may be used to endorse or promote products derived from this software
  13070. * without specific prior written permission.
  13071. *
  13072. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13073. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13074. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13075. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13076. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13077. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13078. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13079. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13080. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13081. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13082. * SUCH DAMAGE.
  13083. */