ash.c 322 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357
  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. #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
  221. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  222. /* Bionic at least up to version 24 has no glob() */
  223. # undef ENABLE_ASH_INTERNAL_GLOB
  224. # define ENABLE_ASH_INTERNAL_GLOB 1
  225. #endif
  226. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  227. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  228. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  229. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  230. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  231. # error fails to match dirname, subsequently not expanding <pattern> in it.
  232. // Testcase:
  233. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  234. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  235. #endif
  236. #if !ENABLE_ASH_INTERNAL_GLOB
  237. # include <glob.h>
  238. #endif
  239. #include "unicode.h"
  240. #include "shell_common.h"
  241. #if ENABLE_FEATURE_SH_MATH
  242. # include "math.h"
  243. #else
  244. typedef long arith_t;
  245. # define ARITH_FMT "%ld"
  246. #endif
  247. #if ENABLE_ASH_RANDOM_SUPPORT
  248. # include "random.h"
  249. #else
  250. # define CLEAR_RANDOM_T(rnd) ((void)0)
  251. #endif
  252. #include "NUM_APPLETS.h"
  253. #if NUM_APPLETS == 1
  254. /* STANDALONE does not make sense, and won't compile */
  255. # undef CONFIG_FEATURE_SH_STANDALONE
  256. # undef ENABLE_FEATURE_SH_STANDALONE
  257. # undef IF_FEATURE_SH_STANDALONE
  258. # undef IF_NOT_FEATURE_SH_STANDALONE
  259. # define ENABLE_FEATURE_SH_STANDALONE 0
  260. # define IF_FEATURE_SH_STANDALONE(...)
  261. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  262. #endif
  263. #ifndef F_DUPFD_CLOEXEC
  264. # define F_DUPFD_CLOEXEC F_DUPFD
  265. #endif
  266. #ifndef O_CLOEXEC
  267. # define O_CLOEXEC 0
  268. #endif
  269. #ifndef PIPE_BUF
  270. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  271. #endif
  272. #if !BB_MMU
  273. # error "Do not even bother, ash will not run on NOMMU machine"
  274. #endif
  275. /* We use a trick to have more optimized code (fewer pointer reloads):
  276. * ash.c: extern struct globals *const ash_ptr_to_globals;
  277. * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
  278. * This way, compiler in ash.c knows the pointer can not change.
  279. *
  280. * However, this may break on weird arches or toolchains. In this case,
  281. * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
  282. * this optimization.
  283. */
  284. #ifndef BB_GLOBAL_CONST
  285. # define BB_GLOBAL_CONST const
  286. #endif
  287. /* ============ Hash table sizes. Configurable. */
  288. #define VTABSIZE 39
  289. #define ATABSIZE 39
  290. #define CMDTABLESIZE 31 /* should be prime */
  291. /* ============ Shell options */
  292. static const char *const optletters_optnames[] = {
  293. "e" "errexit",
  294. "f" "noglob",
  295. "I" "ignoreeof",
  296. "i" "interactive",
  297. "m" "monitor",
  298. "n" "noexec",
  299. "s" "stdin",
  300. "x" "xtrace",
  301. "v" "verbose",
  302. "C" "noclobber",
  303. "a" "allexport",
  304. "b" "notify",
  305. "u" "nounset",
  306. "\0" "vi"
  307. #if BASH_PIPEFAIL
  308. ,"\0" "pipefail"
  309. #endif
  310. #if DEBUG
  311. ,"\0" "nolog"
  312. ,"\0" "debug"
  313. #endif
  314. };
  315. #define optletters(n) optletters_optnames[n][0]
  316. #define optnames(n) (optletters_optnames[n] + 1)
  317. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  318. /* ============ Misc data */
  319. #define msg_illnum "Illegal number: %s"
  320. /*
  321. * We enclose jmp_buf in a structure so that we can declare pointers to
  322. * jump locations. The global variable handler contains the location to
  323. * jump to when an exception occurs, and the global variable exception_type
  324. * contains a code identifying the exception. To implement nested
  325. * exception handlers, the user should save the value of handler on entry
  326. * to an inner scope, set handler to point to a jmploc structure for the
  327. * inner scope, and restore handler on exit from the scope.
  328. */
  329. struct jmploc {
  330. jmp_buf loc;
  331. };
  332. struct globals_misc {
  333. uint8_t exitstatus; /* exit status of last command */
  334. uint8_t back_exitstatus;/* exit status of backquoted command */
  335. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  336. int rootpid; /* pid of main shell */
  337. /* shell level: 0 for the main shell, 1 for its children, and so on */
  338. int shlvl;
  339. #define rootshell (!shlvl)
  340. int errlinno;
  341. char *minusc; /* argument to -c option */
  342. char *curdir; // = nullstr; /* current working directory */
  343. char *physdir; // = nullstr; /* physical working directory */
  344. char *arg0; /* value of $0 */
  345. struct jmploc *exception_handler;
  346. volatile int suppress_int; /* counter */
  347. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  348. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  349. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  350. smallint exception_type; /* kind of exception (0..5) */
  351. /* exceptions */
  352. #define EXINT 0 /* SIGINT received */
  353. #define EXERROR 1 /* a generic error */
  354. #define EXEXIT 4 /* exit the shell */
  355. char nullstr[1]; /* zero length string */
  356. char optlist[NOPTS];
  357. #define eflag optlist[0]
  358. #define fflag optlist[1]
  359. #define Iflag optlist[2]
  360. #define iflag optlist[3]
  361. #define mflag optlist[4]
  362. #define nflag optlist[5]
  363. #define sflag optlist[6]
  364. #define xflag optlist[7]
  365. #define vflag optlist[8]
  366. #define Cflag optlist[9]
  367. #define aflag optlist[10]
  368. #define bflag optlist[11]
  369. #define uflag optlist[12]
  370. #define viflag optlist[13]
  371. #if BASH_PIPEFAIL
  372. # define pipefail optlist[14]
  373. #else
  374. # define pipefail 0
  375. #endif
  376. #if DEBUG
  377. # define nolog optlist[14 + BASH_PIPEFAIL]
  378. # define debug optlist[15 + BASH_PIPEFAIL]
  379. #endif
  380. /* trap handler commands */
  381. /*
  382. * Sigmode records the current value of the signal handlers for the various
  383. * modes. A value of zero means that the current handler is not known.
  384. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  385. */
  386. char sigmode[NSIG - 1];
  387. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  388. #define S_CATCH 2 /* signal is caught */
  389. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  390. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  391. /* indicates specified signal received */
  392. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  393. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  394. char *trap[NSIG];
  395. char **trap_ptr; /* used only by "trap hack" */
  396. /* Rarely referenced stuff */
  397. #if ENABLE_ASH_RANDOM_SUPPORT
  398. random_t random_gen;
  399. #endif
  400. pid_t backgndpid; /* pid of last background process */
  401. };
  402. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  403. #define G_misc (*ash_ptr_to_globals_misc)
  404. #define exitstatus (G_misc.exitstatus )
  405. #define back_exitstatus (G_misc.back_exitstatus )
  406. #define job_warning (G_misc.job_warning)
  407. #define rootpid (G_misc.rootpid )
  408. #define shlvl (G_misc.shlvl )
  409. #define errlinno (G_misc.errlinno )
  410. #define minusc (G_misc.minusc )
  411. #define curdir (G_misc.curdir )
  412. #define physdir (G_misc.physdir )
  413. #define arg0 (G_misc.arg0 )
  414. #define exception_handler (G_misc.exception_handler)
  415. #define exception_type (G_misc.exception_type )
  416. #define suppress_int (G_misc.suppress_int )
  417. #define pending_int (G_misc.pending_int )
  418. #define got_sigchld (G_misc.got_sigchld )
  419. #define pending_sig (G_misc.pending_sig )
  420. #define nullstr (G_misc.nullstr )
  421. #define optlist (G_misc.optlist )
  422. #define sigmode (G_misc.sigmode )
  423. #define gotsig (G_misc.gotsig )
  424. #define may_have_traps (G_misc.may_have_traps )
  425. #define trap (G_misc.trap )
  426. #define trap_ptr (G_misc.trap_ptr )
  427. #define random_gen (G_misc.random_gen )
  428. #define backgndpid (G_misc.backgndpid )
  429. #define INIT_G_misc() do { \
  430. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  431. barrier(); \
  432. curdir = nullstr; \
  433. physdir = nullstr; \
  434. trap_ptr = trap; \
  435. } while (0)
  436. /* ============ DEBUG */
  437. #if DEBUG
  438. static void trace_printf(const char *fmt, ...);
  439. static void trace_vprintf(const char *fmt, va_list va);
  440. # define TRACE(param) trace_printf param
  441. # define TRACEV(param) trace_vprintf param
  442. # define close(fd) do { \
  443. int dfd = (fd); \
  444. if (close(dfd) < 0) \
  445. bb_error_msg("bug on %d: closing %d(0x%x)", \
  446. __LINE__, dfd, dfd); \
  447. } while (0)
  448. #else
  449. # define TRACE(param)
  450. # define TRACEV(param)
  451. #endif
  452. /* ============ Utility functions */
  453. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  454. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  455. static int
  456. isdigit_str9(const char *str)
  457. {
  458. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  459. while (--maxlen && isdigit(*str))
  460. str++;
  461. return (*str == '\0');
  462. }
  463. static const char *
  464. var_end(const char *var)
  465. {
  466. while (*var)
  467. if (*var++ == '=')
  468. break;
  469. return var;
  470. }
  471. /* ============ Interrupts / exceptions */
  472. static void exitshell(void) NORETURN;
  473. /*
  474. * These macros allow the user to suspend the handling of interrupt signals
  475. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  476. * much more efficient and portable. (But hacking the kernel is so much
  477. * more fun than worrying about efficiency and portability. :-))
  478. */
  479. #if DEBUG_INTONOFF
  480. # define INT_OFF do { \
  481. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  482. suppress_int++; \
  483. barrier(); \
  484. } while (0)
  485. #else
  486. # define INT_OFF do { \
  487. suppress_int++; \
  488. barrier(); \
  489. } while (0)
  490. #endif
  491. /*
  492. * Called to raise an exception. Since C doesn't include exceptions, we
  493. * just do a longjmp to the exception handler. The type of exception is
  494. * stored in the global variable "exception_type".
  495. */
  496. static void raise_exception(int) NORETURN;
  497. static void
  498. raise_exception(int e)
  499. {
  500. #if DEBUG
  501. if (exception_handler == NULL)
  502. abort();
  503. #endif
  504. INT_OFF;
  505. exception_type = e;
  506. longjmp(exception_handler->loc, 1);
  507. }
  508. #if DEBUG
  509. #define raise_exception(e) do { \
  510. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  511. raise_exception(e); \
  512. } while (0)
  513. #endif
  514. /*
  515. * Called when a SIGINT is received. (If the user specifies
  516. * that SIGINT is to be trapped or ignored using the trap builtin, then
  517. * this routine is not called.) Suppressint is nonzero when interrupts
  518. * are held using the INT_OFF macro. (The test for iflag is just
  519. * defensive programming.)
  520. */
  521. static void raise_interrupt(void) NORETURN;
  522. static void
  523. raise_interrupt(void)
  524. {
  525. pending_int = 0;
  526. /* Signal is not automatically unmasked after it is raised,
  527. * do it ourself - unmask all signals */
  528. sigprocmask_allsigs(SIG_UNBLOCK);
  529. /* pending_sig = 0; - now done in signal_handler() */
  530. if (!(rootshell && iflag)) {
  531. /* Kill ourself with SIGINT */
  532. signal(SIGINT, SIG_DFL);
  533. raise(SIGINT);
  534. }
  535. /* bash: ^C even on empty command line sets $? */
  536. exitstatus = SIGINT + 128;
  537. raise_exception(EXINT);
  538. /* NOTREACHED */
  539. }
  540. #if DEBUG
  541. #define raise_interrupt() do { \
  542. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  543. raise_interrupt(); \
  544. } while (0)
  545. #endif
  546. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  547. int_on(void)
  548. {
  549. barrier();
  550. if (--suppress_int == 0 && pending_int) {
  551. raise_interrupt();
  552. }
  553. }
  554. #if DEBUG_INTONOFF
  555. # define INT_ON do { \
  556. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  557. int_on(); \
  558. } while (0)
  559. #else
  560. # define INT_ON int_on()
  561. #endif
  562. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  563. force_int_on(void)
  564. {
  565. barrier();
  566. suppress_int = 0;
  567. if (pending_int)
  568. raise_interrupt();
  569. }
  570. #define FORCE_INT_ON force_int_on()
  571. #define SAVE_INT(v) ((v) = suppress_int)
  572. #define RESTORE_INT(v) do { \
  573. barrier(); \
  574. suppress_int = (v); \
  575. if (suppress_int == 0 && pending_int) \
  576. raise_interrupt(); \
  577. } while (0)
  578. /* ============ Stdout/stderr output */
  579. static void
  580. outstr(const char *p, FILE *file)
  581. {
  582. INT_OFF;
  583. fputs(p, file);
  584. INT_ON;
  585. }
  586. static void
  587. flush_stdout_stderr(void)
  588. {
  589. INT_OFF;
  590. fflush_all();
  591. INT_ON;
  592. }
  593. /* Was called outcslow(c,FILE*), but c was always '\n' */
  594. static void
  595. newline_and_flush(FILE *dest)
  596. {
  597. INT_OFF;
  598. putc('\n', dest);
  599. fflush(dest);
  600. INT_ON;
  601. }
  602. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  603. static int
  604. out1fmt(const char *fmt, ...)
  605. {
  606. va_list ap;
  607. int r;
  608. INT_OFF;
  609. va_start(ap, fmt);
  610. r = vprintf(fmt, ap);
  611. va_end(ap);
  612. INT_ON;
  613. return r;
  614. }
  615. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  616. static int
  617. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  618. {
  619. va_list ap;
  620. int ret;
  621. INT_OFF;
  622. va_start(ap, fmt);
  623. ret = vsnprintf(outbuf, length, fmt, ap);
  624. va_end(ap);
  625. INT_ON;
  626. return ret;
  627. }
  628. static void
  629. out1str(const char *p)
  630. {
  631. outstr(p, stdout);
  632. }
  633. static void
  634. out2str(const char *p)
  635. {
  636. outstr(p, stderr);
  637. flush_stdout_stderr();
  638. }
  639. /* ============ Parser structures */
  640. /* control characters in argument strings */
  641. #define CTL_FIRST CTLESC
  642. #define CTLESC ((unsigned char)'\201') /* escape next character */
  643. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  644. #define CTLENDVAR ((unsigned char)'\203')
  645. #define CTLBACKQ ((unsigned char)'\204')
  646. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  647. #define CTLENDARI ((unsigned char)'\207')
  648. #define CTLQUOTEMARK ((unsigned char)'\210')
  649. #define CTL_LAST CTLQUOTEMARK
  650. /* variable substitution byte (follows CTLVAR) */
  651. #define VSTYPE 0x0f /* type of variable substitution */
  652. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  653. /* values of VSTYPE field */
  654. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  655. #define VSMINUS 0x2 /* ${var-text} */
  656. #define VSPLUS 0x3 /* ${var+text} */
  657. #define VSQUESTION 0x4 /* ${var?message} */
  658. #define VSASSIGN 0x5 /* ${var=text} */
  659. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  660. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  661. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  662. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  663. #define VSLENGTH 0xa /* ${#var} */
  664. #if BASH_SUBSTR
  665. #define VSSUBSTR 0xc /* ${var:position:length} */
  666. #endif
  667. #if BASH_PATTERN_SUBST
  668. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  669. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  670. #endif
  671. static const char dolatstr[] ALIGN1 = {
  672. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  673. };
  674. #define DOLATSTRLEN 6
  675. #define NCMD 0
  676. #define NPIPE 1
  677. #define NREDIR 2
  678. #define NBACKGND 3
  679. #define NSUBSHELL 4
  680. #define NAND 5
  681. #define NOR 6
  682. #define NSEMI 7
  683. #define NIF 8
  684. #define NWHILE 9
  685. #define NUNTIL 10
  686. #define NFOR 11
  687. #define NCASE 12
  688. #define NCLIST 13
  689. #define NDEFUN 14
  690. #define NARG 15
  691. #define NTO 16
  692. #if BASH_REDIR_OUTPUT
  693. #define NTO2 17
  694. #endif
  695. #define NCLOBBER 18
  696. #define NFROM 19
  697. #define NFROMTO 20
  698. #define NAPPEND 21
  699. #define NTOFD 22
  700. #define NFROMFD 23
  701. #define NHERE 24
  702. #define NXHERE 25
  703. #define NNOT 26
  704. #define N_NUMBER 27
  705. union node;
  706. struct ncmd {
  707. smallint type; /* Nxxxx */
  708. int linno;
  709. union node *assign;
  710. union node *args;
  711. union node *redirect;
  712. };
  713. struct npipe {
  714. smallint type;
  715. smallint pipe_backgnd;
  716. struct nodelist *cmdlist;
  717. };
  718. struct nredir {
  719. smallint type;
  720. int linno;
  721. union node *n;
  722. union node *redirect;
  723. };
  724. struct nbinary {
  725. smallint type;
  726. union node *ch1;
  727. union node *ch2;
  728. };
  729. struct nif {
  730. smallint type;
  731. union node *test;
  732. union node *ifpart;
  733. union node *elsepart;
  734. };
  735. struct nfor {
  736. smallint type;
  737. int linno;
  738. union node *args;
  739. union node *body;
  740. char *var;
  741. };
  742. struct ncase {
  743. smallint type;
  744. int linno;
  745. union node *expr;
  746. union node *cases;
  747. };
  748. struct nclist {
  749. smallint type;
  750. union node *next;
  751. union node *pattern;
  752. union node *body;
  753. };
  754. struct ndefun {
  755. smallint type;
  756. int linno;
  757. char *text;
  758. union node *body;
  759. };
  760. struct narg {
  761. smallint type;
  762. union node *next;
  763. char *text;
  764. struct nodelist *backquote;
  765. };
  766. /* nfile and ndup layout must match!
  767. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  768. * that it is actually NTO2 (>&file), and change its type.
  769. */
  770. struct nfile {
  771. smallint type;
  772. union node *next;
  773. int fd;
  774. int _unused_dupfd;
  775. union node *fname;
  776. char *expfname;
  777. };
  778. struct ndup {
  779. smallint type;
  780. union node *next;
  781. int fd;
  782. int dupfd;
  783. union node *vname;
  784. char *_unused_expfname;
  785. };
  786. struct nhere {
  787. smallint type;
  788. union node *next;
  789. int fd;
  790. union node *doc;
  791. };
  792. struct nnot {
  793. smallint type;
  794. union node *com;
  795. };
  796. union node {
  797. smallint type;
  798. struct ncmd ncmd;
  799. struct npipe npipe;
  800. struct nredir nredir;
  801. struct nbinary nbinary;
  802. struct nif nif;
  803. struct nfor nfor;
  804. struct ncase ncase;
  805. struct nclist nclist;
  806. struct ndefun ndefun;
  807. struct narg narg;
  808. struct nfile nfile;
  809. struct ndup ndup;
  810. struct nhere nhere;
  811. struct nnot nnot;
  812. };
  813. /*
  814. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  815. * It must be distinct from NULL.
  816. */
  817. #define NODE_EOF ((union node *) -1L)
  818. struct nodelist {
  819. struct nodelist *next;
  820. union node *n;
  821. };
  822. struct funcnode {
  823. int count;
  824. union node n;
  825. };
  826. /*
  827. * Free a parse tree.
  828. */
  829. static void
  830. freefunc(struct funcnode *f)
  831. {
  832. if (f && --f->count < 0)
  833. free(f);
  834. }
  835. /* ============ Debugging output */
  836. #if DEBUG
  837. static FILE *tracefile;
  838. static void
  839. trace_printf(const char *fmt, ...)
  840. {
  841. va_list va;
  842. if (debug != 1)
  843. return;
  844. if (DEBUG_TIME)
  845. fprintf(tracefile, "%u ", (int) time(NULL));
  846. if (DEBUG_PID)
  847. fprintf(tracefile, "[%u] ", (int) getpid());
  848. if (DEBUG_SIG)
  849. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  850. va_start(va, fmt);
  851. vfprintf(tracefile, fmt, va);
  852. va_end(va);
  853. }
  854. static void
  855. trace_vprintf(const char *fmt, va_list va)
  856. {
  857. if (debug != 1)
  858. return;
  859. vfprintf(tracefile, fmt, va);
  860. fprintf(tracefile, "\n");
  861. }
  862. static void
  863. trace_puts(const char *s)
  864. {
  865. if (debug != 1)
  866. return;
  867. fputs(s, tracefile);
  868. }
  869. static void
  870. trace_puts_quoted(char *s)
  871. {
  872. char *p;
  873. char c;
  874. if (debug != 1)
  875. return;
  876. putc('"', tracefile);
  877. for (p = s; *p; p++) {
  878. switch ((unsigned char)*p) {
  879. case '\n': c = 'n'; goto backslash;
  880. case '\t': c = 't'; goto backslash;
  881. case '\r': c = 'r'; goto backslash;
  882. case '\"': c = '\"'; goto backslash;
  883. case '\\': c = '\\'; goto backslash;
  884. case CTLESC: c = 'e'; goto backslash;
  885. case CTLVAR: c = 'v'; goto backslash;
  886. case CTLBACKQ: c = 'q'; goto backslash;
  887. backslash:
  888. putc('\\', tracefile);
  889. putc(c, tracefile);
  890. break;
  891. default:
  892. if (*p >= ' ' && *p <= '~')
  893. putc(*p, tracefile);
  894. else {
  895. putc('\\', tracefile);
  896. putc((*p >> 6) & 03, tracefile);
  897. putc((*p >> 3) & 07, tracefile);
  898. putc(*p & 07, tracefile);
  899. }
  900. break;
  901. }
  902. }
  903. putc('"', tracefile);
  904. }
  905. static void
  906. trace_puts_args(char **ap)
  907. {
  908. if (debug != 1)
  909. return;
  910. if (!*ap)
  911. return;
  912. while (1) {
  913. trace_puts_quoted(*ap);
  914. if (!*++ap) {
  915. putc('\n', tracefile);
  916. break;
  917. }
  918. putc(' ', tracefile);
  919. }
  920. }
  921. static void
  922. opentrace(void)
  923. {
  924. char s[100];
  925. #ifdef O_APPEND
  926. int flags;
  927. #endif
  928. if (debug != 1) {
  929. if (tracefile)
  930. fflush(tracefile);
  931. /* leave open because libedit might be using it */
  932. return;
  933. }
  934. strcpy(s, "./trace");
  935. if (tracefile) {
  936. if (!freopen(s, "a", tracefile)) {
  937. fprintf(stderr, "Can't re-open %s\n", s);
  938. debug = 0;
  939. return;
  940. }
  941. } else {
  942. tracefile = fopen(s, "a");
  943. if (tracefile == NULL) {
  944. fprintf(stderr, "Can't open %s\n", s);
  945. debug = 0;
  946. return;
  947. }
  948. }
  949. #ifdef O_APPEND
  950. flags = fcntl(fileno(tracefile), F_GETFL);
  951. if (flags >= 0)
  952. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  953. #endif
  954. setlinebuf(tracefile);
  955. fputs("\nTracing started.\n", tracefile);
  956. }
  957. static void
  958. indent(int amount, char *pfx, FILE *fp)
  959. {
  960. int i;
  961. for (i = 0; i < amount; i++) {
  962. if (pfx && i == amount - 1)
  963. fputs(pfx, fp);
  964. putc('\t', fp);
  965. }
  966. }
  967. /* little circular references here... */
  968. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  969. static void
  970. sharg(union node *arg, FILE *fp)
  971. {
  972. char *p;
  973. struct nodelist *bqlist;
  974. unsigned char subtype;
  975. if (arg->type != NARG) {
  976. out1fmt("<node type %d>\n", arg->type);
  977. abort();
  978. }
  979. bqlist = arg->narg.backquote;
  980. for (p = arg->narg.text; *p; p++) {
  981. switch ((unsigned char)*p) {
  982. case CTLESC:
  983. p++;
  984. putc(*p, fp);
  985. break;
  986. case CTLVAR:
  987. putc('$', fp);
  988. putc('{', fp);
  989. subtype = *++p;
  990. if (subtype == VSLENGTH)
  991. putc('#', fp);
  992. while (*p != '=') {
  993. putc(*p, fp);
  994. p++;
  995. }
  996. if (subtype & VSNUL)
  997. putc(':', fp);
  998. switch (subtype & VSTYPE) {
  999. case VSNORMAL:
  1000. putc('}', fp);
  1001. break;
  1002. case VSMINUS:
  1003. putc('-', fp);
  1004. break;
  1005. case VSPLUS:
  1006. putc('+', fp);
  1007. break;
  1008. case VSQUESTION:
  1009. putc('?', fp);
  1010. break;
  1011. case VSASSIGN:
  1012. putc('=', fp);
  1013. break;
  1014. case VSTRIMLEFT:
  1015. putc('#', fp);
  1016. break;
  1017. case VSTRIMLEFTMAX:
  1018. putc('#', fp);
  1019. putc('#', fp);
  1020. break;
  1021. case VSTRIMRIGHT:
  1022. putc('%', fp);
  1023. break;
  1024. case VSTRIMRIGHTMAX:
  1025. putc('%', fp);
  1026. putc('%', fp);
  1027. break;
  1028. case VSLENGTH:
  1029. break;
  1030. default:
  1031. out1fmt("<subtype %d>", subtype);
  1032. }
  1033. break;
  1034. case CTLENDVAR:
  1035. putc('}', fp);
  1036. break;
  1037. case CTLBACKQ:
  1038. putc('$', fp);
  1039. putc('(', fp);
  1040. shtree(bqlist->n, -1, NULL, fp);
  1041. putc(')', fp);
  1042. break;
  1043. default:
  1044. putc(*p, fp);
  1045. break;
  1046. }
  1047. }
  1048. }
  1049. static void
  1050. shcmd(union node *cmd, FILE *fp)
  1051. {
  1052. union node *np;
  1053. int first;
  1054. const char *s;
  1055. int dftfd;
  1056. first = 1;
  1057. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1058. if (!first)
  1059. putc(' ', fp);
  1060. sharg(np, fp);
  1061. first = 0;
  1062. }
  1063. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1064. if (!first)
  1065. putc(' ', fp);
  1066. dftfd = 0;
  1067. switch (np->nfile.type) {
  1068. case NTO: s = ">>"+1; dftfd = 1; break;
  1069. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1070. case NAPPEND: s = ">>"; dftfd = 1; break;
  1071. #if BASH_REDIR_OUTPUT
  1072. case NTO2:
  1073. #endif
  1074. case NTOFD: s = ">&"; dftfd = 1; break;
  1075. case NFROM: s = "<"; break;
  1076. case NFROMFD: s = "<&"; break;
  1077. case NFROMTO: s = "<>"; break;
  1078. default: s = "*error*"; break;
  1079. }
  1080. if (np->nfile.fd != dftfd)
  1081. fprintf(fp, "%d", np->nfile.fd);
  1082. fputs(s, fp);
  1083. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1084. fprintf(fp, "%d", np->ndup.dupfd);
  1085. } else {
  1086. sharg(np->nfile.fname, fp);
  1087. }
  1088. first = 0;
  1089. }
  1090. }
  1091. static void
  1092. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1093. {
  1094. struct nodelist *lp;
  1095. const char *s;
  1096. if (n == NULL)
  1097. return;
  1098. indent(ind, pfx, fp);
  1099. if (n == NODE_EOF) {
  1100. fputs("<EOF>", fp);
  1101. return;
  1102. }
  1103. switch (n->type) {
  1104. case NSEMI:
  1105. s = "; ";
  1106. goto binop;
  1107. case NAND:
  1108. s = " && ";
  1109. goto binop;
  1110. case NOR:
  1111. s = " || ";
  1112. binop:
  1113. shtree(n->nbinary.ch1, ind, NULL, fp);
  1114. /* if (ind < 0) */
  1115. fputs(s, fp);
  1116. shtree(n->nbinary.ch2, ind, NULL, fp);
  1117. break;
  1118. case NCMD:
  1119. shcmd(n, fp);
  1120. if (ind >= 0)
  1121. putc('\n', fp);
  1122. break;
  1123. case NPIPE:
  1124. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1125. shtree(lp->n, 0, NULL, fp);
  1126. if (lp->next)
  1127. fputs(" | ", fp);
  1128. }
  1129. if (n->npipe.pipe_backgnd)
  1130. fputs(" &", fp);
  1131. if (ind >= 0)
  1132. putc('\n', fp);
  1133. break;
  1134. default:
  1135. fprintf(fp, "<node type %d>", n->type);
  1136. if (ind >= 0)
  1137. putc('\n', fp);
  1138. break;
  1139. }
  1140. }
  1141. static void
  1142. showtree(union node *n)
  1143. {
  1144. trace_puts("showtree called\n");
  1145. shtree(n, 1, NULL, stderr);
  1146. }
  1147. #endif /* DEBUG */
  1148. /* ============ Parser data */
  1149. /*
  1150. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1151. */
  1152. struct strlist {
  1153. struct strlist *next;
  1154. char *text;
  1155. };
  1156. struct alias;
  1157. struct strpush {
  1158. struct strpush *prev; /* preceding string on stack */
  1159. char *prev_string;
  1160. int prev_left_in_line;
  1161. #if ENABLE_ASH_ALIAS
  1162. struct alias *ap; /* if push was associated with an alias */
  1163. #endif
  1164. char *string; /* remember the string since it may change */
  1165. /* Remember last two characters for pungetc. */
  1166. int lastc[2];
  1167. /* Number of outstanding calls to pungetc. */
  1168. int unget;
  1169. };
  1170. /*
  1171. * The parsefile structure pointed to by the global variable parsefile
  1172. * contains information about the current file being read.
  1173. */
  1174. struct parsefile {
  1175. struct parsefile *prev; /* preceding file on stack */
  1176. int linno; /* current line */
  1177. int pf_fd; /* file descriptor (or -1 if string) */
  1178. int left_in_line; /* number of chars left in this line */
  1179. int left_in_buffer; /* number of chars left in this buffer past the line */
  1180. char *next_to_pgetc; /* next char in buffer */
  1181. char *buf; /* input buffer */
  1182. struct strpush *strpush; /* for pushing strings at this level */
  1183. struct strpush basestrpush; /* so pushing one is fast */
  1184. /* Remember last two characters for pungetc. */
  1185. int lastc[2];
  1186. /* Number of outstanding calls to pungetc. */
  1187. int unget;
  1188. };
  1189. static struct parsefile basepf; /* top level input file */
  1190. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1191. static char *commandname; /* currently executing command */
  1192. /* ============ Message printing */
  1193. static void
  1194. ash_vmsg(const char *msg, va_list ap)
  1195. {
  1196. fprintf(stderr, "%s: ", arg0);
  1197. if (commandname) {
  1198. if (strcmp(arg0, commandname))
  1199. fprintf(stderr, "%s: ", commandname);
  1200. if (!iflag || g_parsefile->pf_fd > 0)
  1201. fprintf(stderr, "line %d: ", errlinno);
  1202. }
  1203. vfprintf(stderr, msg, ap);
  1204. newline_and_flush(stderr);
  1205. }
  1206. /*
  1207. * Exverror is called to raise the error exception. If the second argument
  1208. * is not NULL then error prints an error message using printf style
  1209. * formatting. It then raises the error exception.
  1210. */
  1211. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1212. static void
  1213. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1214. {
  1215. #if DEBUG
  1216. if (msg) {
  1217. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1218. TRACEV((msg, ap));
  1219. } else
  1220. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1221. if (msg)
  1222. #endif
  1223. ash_vmsg(msg, ap);
  1224. flush_stdout_stderr();
  1225. raise_exception(cond);
  1226. /* NOTREACHED */
  1227. }
  1228. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1229. static void
  1230. ash_msg_and_raise_error(const char *msg, ...)
  1231. {
  1232. va_list ap;
  1233. exitstatus = 2;
  1234. va_start(ap, msg);
  1235. ash_vmsg_and_raise(EXERROR, msg, ap);
  1236. /* NOTREACHED */
  1237. va_end(ap);
  1238. }
  1239. /*
  1240. * 'fmt' must be a string literal.
  1241. */
  1242. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1243. static void raise_error_syntax(const char *) NORETURN;
  1244. static void
  1245. raise_error_syntax(const char *msg)
  1246. {
  1247. errlinno = g_parsefile->linno;
  1248. ash_msg_and_raise_error("syntax error: %s", msg);
  1249. /* NOTREACHED */
  1250. }
  1251. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1252. static void
  1253. ash_msg_and_raise(int cond, const char *msg, ...)
  1254. {
  1255. va_list ap;
  1256. va_start(ap, msg);
  1257. ash_vmsg_and_raise(cond, msg, ap);
  1258. /* NOTREACHED */
  1259. va_end(ap);
  1260. }
  1261. /*
  1262. * error/warning routines for external builtins
  1263. */
  1264. static void
  1265. ash_msg(const char *fmt, ...)
  1266. {
  1267. va_list ap;
  1268. va_start(ap, fmt);
  1269. ash_vmsg(fmt, ap);
  1270. va_end(ap);
  1271. }
  1272. /*
  1273. * Return a string describing an error. The returned string may be a
  1274. * pointer to a static buffer that will be overwritten on the next call.
  1275. * Action describes the operation that got the error.
  1276. */
  1277. static const char *
  1278. errmsg(int e, const char *em)
  1279. {
  1280. if (e == ENOENT || e == ENOTDIR) {
  1281. return em;
  1282. }
  1283. return strerror(e);
  1284. }
  1285. /* ============ Memory allocation */
  1286. #if 0
  1287. /* I consider these wrappers nearly useless:
  1288. * ok, they return you to nearest exception handler, but
  1289. * how much memory do you leak in the process, making
  1290. * memory starvation worse?
  1291. */
  1292. static void *
  1293. ckrealloc(void * p, size_t nbytes)
  1294. {
  1295. p = realloc(p, nbytes);
  1296. if (!p)
  1297. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1298. return p;
  1299. }
  1300. static void *
  1301. ckmalloc(size_t nbytes)
  1302. {
  1303. return ckrealloc(NULL, nbytes);
  1304. }
  1305. static void *
  1306. ckzalloc(size_t nbytes)
  1307. {
  1308. return memset(ckmalloc(nbytes), 0, nbytes);
  1309. }
  1310. static char *
  1311. ckstrdup(const char *s)
  1312. {
  1313. char *p = strdup(s);
  1314. if (!p)
  1315. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1316. return p;
  1317. }
  1318. #else
  1319. /* Using bbox equivalents. They exit if out of memory */
  1320. # define ckrealloc xrealloc
  1321. # define ckmalloc xmalloc
  1322. # define ckzalloc xzalloc
  1323. # define ckstrdup xstrdup
  1324. #endif
  1325. /*
  1326. * It appears that grabstackstr() will barf with such alignments
  1327. * because stalloc() will return a string allocated in a new stackblock.
  1328. */
  1329. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1330. enum {
  1331. /* Most machines require the value returned from malloc to be aligned
  1332. * in some way. The following macro will get this right
  1333. * on many machines. */
  1334. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1335. /* Minimum size of a block */
  1336. MINSIZE = SHELL_ALIGN(504),
  1337. };
  1338. struct stack_block {
  1339. struct stack_block *prev;
  1340. char space[MINSIZE];
  1341. };
  1342. struct stackmark {
  1343. struct stack_block *stackp;
  1344. char *stacknxt;
  1345. size_t stacknleft;
  1346. };
  1347. struct globals_memstack {
  1348. struct stack_block *g_stackp; // = &stackbase;
  1349. char *g_stacknxt; // = stackbase.space;
  1350. char *sstrend; // = stackbase.space + MINSIZE;
  1351. size_t g_stacknleft; // = MINSIZE;
  1352. struct stack_block stackbase;
  1353. };
  1354. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1355. #define G_memstack (*ash_ptr_to_globals_memstack)
  1356. #define g_stackp (G_memstack.g_stackp )
  1357. #define g_stacknxt (G_memstack.g_stacknxt )
  1358. #define sstrend (G_memstack.sstrend )
  1359. #define g_stacknleft (G_memstack.g_stacknleft)
  1360. #define stackbase (G_memstack.stackbase )
  1361. #define INIT_G_memstack() do { \
  1362. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1363. barrier(); \
  1364. g_stackp = &stackbase; \
  1365. g_stacknxt = stackbase.space; \
  1366. g_stacknleft = MINSIZE; \
  1367. sstrend = stackbase.space + MINSIZE; \
  1368. } while (0)
  1369. #define stackblock() ((void *)g_stacknxt)
  1370. #define stackblocksize() g_stacknleft
  1371. /*
  1372. * Parse trees for commands are allocated in lifo order, so we use a stack
  1373. * to make this more efficient, and also to avoid all sorts of exception
  1374. * handling code to handle interrupts in the middle of a parse.
  1375. *
  1376. * The size 504 was chosen because the Ultrix malloc handles that size
  1377. * well.
  1378. */
  1379. static void *
  1380. stalloc(size_t nbytes)
  1381. {
  1382. char *p;
  1383. size_t aligned;
  1384. aligned = SHELL_ALIGN(nbytes);
  1385. if (aligned > g_stacknleft) {
  1386. size_t len;
  1387. size_t blocksize;
  1388. struct stack_block *sp;
  1389. blocksize = aligned;
  1390. if (blocksize < MINSIZE)
  1391. blocksize = MINSIZE;
  1392. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1393. if (len < blocksize)
  1394. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1395. INT_OFF;
  1396. sp = ckmalloc(len);
  1397. sp->prev = g_stackp;
  1398. g_stacknxt = sp->space;
  1399. g_stacknleft = blocksize;
  1400. sstrend = g_stacknxt + blocksize;
  1401. g_stackp = sp;
  1402. INT_ON;
  1403. }
  1404. p = g_stacknxt;
  1405. g_stacknxt += aligned;
  1406. g_stacknleft -= aligned;
  1407. return p;
  1408. }
  1409. static void *
  1410. stzalloc(size_t nbytes)
  1411. {
  1412. return memset(stalloc(nbytes), 0, nbytes);
  1413. }
  1414. static void
  1415. stunalloc(void *p)
  1416. {
  1417. #if DEBUG
  1418. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1419. write(STDERR_FILENO, "stunalloc\n", 10);
  1420. abort();
  1421. }
  1422. #endif
  1423. g_stacknleft += g_stacknxt - (char *)p;
  1424. g_stacknxt = p;
  1425. }
  1426. /*
  1427. * Like strdup but works with the ash stack.
  1428. */
  1429. static char *
  1430. sstrdup(const char *p)
  1431. {
  1432. size_t len = strlen(p) + 1;
  1433. return memcpy(stalloc(len), p, len);
  1434. }
  1435. static ALWAYS_INLINE void
  1436. grabstackblock(size_t len)
  1437. {
  1438. stalloc(len);
  1439. }
  1440. static void
  1441. pushstackmark(struct stackmark *mark, size_t len)
  1442. {
  1443. mark->stackp = g_stackp;
  1444. mark->stacknxt = g_stacknxt;
  1445. mark->stacknleft = g_stacknleft;
  1446. grabstackblock(len);
  1447. }
  1448. static void
  1449. setstackmark(struct stackmark *mark)
  1450. {
  1451. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1452. }
  1453. static void
  1454. popstackmark(struct stackmark *mark)
  1455. {
  1456. struct stack_block *sp;
  1457. if (!mark->stackp)
  1458. return;
  1459. INT_OFF;
  1460. while (g_stackp != mark->stackp) {
  1461. sp = g_stackp;
  1462. g_stackp = sp->prev;
  1463. free(sp);
  1464. }
  1465. g_stacknxt = mark->stacknxt;
  1466. g_stacknleft = mark->stacknleft;
  1467. sstrend = mark->stacknxt + mark->stacknleft;
  1468. INT_ON;
  1469. }
  1470. /*
  1471. * When the parser reads in a string, it wants to stick the string on the
  1472. * stack and only adjust the stack pointer when it knows how big the
  1473. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1474. * of space on top of the stack and stackblocklen returns the length of
  1475. * this block. Growstackblock will grow this space by at least one byte,
  1476. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1477. * part of the block that has been used.
  1478. */
  1479. static void
  1480. growstackblock(void)
  1481. {
  1482. size_t newlen;
  1483. newlen = g_stacknleft * 2;
  1484. if (newlen < g_stacknleft)
  1485. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1486. if (newlen < 128)
  1487. newlen += 128;
  1488. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1489. struct stack_block *sp;
  1490. struct stack_block *prevstackp;
  1491. size_t grosslen;
  1492. INT_OFF;
  1493. sp = g_stackp;
  1494. prevstackp = sp->prev;
  1495. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1496. sp = ckrealloc(sp, grosslen);
  1497. sp->prev = prevstackp;
  1498. g_stackp = sp;
  1499. g_stacknxt = sp->space;
  1500. g_stacknleft = newlen;
  1501. sstrend = sp->space + newlen;
  1502. INT_ON;
  1503. } else {
  1504. char *oldspace = g_stacknxt;
  1505. size_t oldlen = g_stacknleft;
  1506. char *p = stalloc(newlen);
  1507. /* free the space we just allocated */
  1508. g_stacknxt = memcpy(p, oldspace, oldlen);
  1509. g_stacknleft += newlen;
  1510. }
  1511. }
  1512. /*
  1513. * The following routines are somewhat easier to use than the above.
  1514. * The user declares a variable of type STACKSTR, which may be declared
  1515. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1516. * the user uses the macro STPUTC to add characters to the string. In
  1517. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1518. * grown as necessary. When the user is done, she can just leave the
  1519. * string there and refer to it using stackblock(). Or she can allocate
  1520. * the space for it using grabstackstr(). If it is necessary to allow
  1521. * someone else to use the stack temporarily and then continue to grow
  1522. * the string, the user should use grabstack to allocate the space, and
  1523. * then call ungrabstr(p) to return to the previous mode of operation.
  1524. *
  1525. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1526. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1527. * is space for at least one character.
  1528. */
  1529. static void *
  1530. growstackstr(void)
  1531. {
  1532. size_t len = stackblocksize();
  1533. growstackblock();
  1534. return (char *)stackblock() + len;
  1535. }
  1536. /*
  1537. * Called from CHECKSTRSPACE.
  1538. */
  1539. static char *
  1540. makestrspace(size_t newlen, char *p)
  1541. {
  1542. size_t len = p - g_stacknxt;
  1543. size_t size;
  1544. for (;;) {
  1545. size_t nleft;
  1546. size = stackblocksize();
  1547. nleft = size - len;
  1548. if (nleft >= newlen)
  1549. break;
  1550. growstackblock();
  1551. }
  1552. return (char *)stackblock() + len;
  1553. }
  1554. static char *
  1555. stack_nputstr(const char *s, size_t n, char *p)
  1556. {
  1557. p = makestrspace(n, p);
  1558. p = (char *)mempcpy(p, s, n);
  1559. return p;
  1560. }
  1561. static char *
  1562. stack_putstr(const char *s, char *p)
  1563. {
  1564. return stack_nputstr(s, strlen(s), p);
  1565. }
  1566. static char *
  1567. _STPUTC(int c, char *p)
  1568. {
  1569. if (p == sstrend)
  1570. p = growstackstr();
  1571. *p++ = c;
  1572. return p;
  1573. }
  1574. #define STARTSTACKSTR(p) ((p) = stackblock())
  1575. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1576. #define CHECKSTRSPACE(n, p) do { \
  1577. char *q = (p); \
  1578. size_t l = (n); \
  1579. size_t m = sstrend - q; \
  1580. if (l > m) \
  1581. (p) = makestrspace(l, q); \
  1582. } while (0)
  1583. #define USTPUTC(c, p) (*(p)++ = (c))
  1584. #define STACKSTRNUL(p) do { \
  1585. if ((p) == sstrend) \
  1586. (p) = growstackstr(); \
  1587. *(p) = '\0'; \
  1588. } while (0)
  1589. #define STUNPUTC(p) (--(p))
  1590. #define STTOPC(p) ((p)[-1])
  1591. #define STADJUST(amount, p) ((p) += (amount))
  1592. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1593. #define ungrabstackstr(s, p) stunalloc(s)
  1594. #define stackstrend() ((void *)sstrend)
  1595. /* ============ String helpers */
  1596. /*
  1597. * prefix -- see if pfx is a prefix of string.
  1598. */
  1599. static char *
  1600. prefix(const char *string, const char *pfx)
  1601. {
  1602. while (*pfx) {
  1603. if (*pfx++ != *string++)
  1604. return NULL;
  1605. }
  1606. return (char *) string;
  1607. }
  1608. /*
  1609. * Check for a valid number. This should be elsewhere.
  1610. */
  1611. static int
  1612. is_number(const char *p)
  1613. {
  1614. do {
  1615. if (!isdigit(*p))
  1616. return 0;
  1617. } while (*++p != '\0');
  1618. return 1;
  1619. }
  1620. /*
  1621. * Convert a string of digits to an integer, printing an error message on
  1622. * failure.
  1623. */
  1624. static int
  1625. number(const char *s)
  1626. {
  1627. if (!is_number(s))
  1628. ash_msg_and_raise_error(msg_illnum, s);
  1629. return atoi(s);
  1630. }
  1631. /*
  1632. * Produce a single quoted string suitable as input to the shell.
  1633. * The return string is allocated on the stack.
  1634. */
  1635. static char *
  1636. single_quote(const char *s)
  1637. {
  1638. char *p;
  1639. STARTSTACKSTR(p);
  1640. do {
  1641. char *q;
  1642. size_t len;
  1643. len = strchrnul(s, '\'') - s;
  1644. q = p = makestrspace(len + 3, p);
  1645. *q++ = '\'';
  1646. q = (char *)mempcpy(q, s, len);
  1647. *q++ = '\'';
  1648. s += len;
  1649. STADJUST(q - p, p);
  1650. if (*s != '\'')
  1651. break;
  1652. len = 0;
  1653. do len++; while (*++s == '\'');
  1654. q = p = makestrspace(len + 3, p);
  1655. *q++ = '"';
  1656. q = (char *)mempcpy(q, s - len, len);
  1657. *q++ = '"';
  1658. STADJUST(q - p, p);
  1659. } while (*s);
  1660. USTPUTC('\0', p);
  1661. return stackblock();
  1662. }
  1663. /*
  1664. * Produce a possibly single quoted string suitable as input to the shell.
  1665. * If quoting was done, the return string is allocated on the stack,
  1666. * otherwise a pointer to the original string is returned.
  1667. */
  1668. static const char *
  1669. maybe_single_quote(const char *s)
  1670. {
  1671. const char *p = s;
  1672. while (*p) {
  1673. /* Assuming ACSII */
  1674. /* quote ctrl_chars space !"#$%&'()* */
  1675. if (*p < '+')
  1676. goto need_quoting;
  1677. /* quote ;<=>? */
  1678. if (*p >= ';' && *p <= '?')
  1679. goto need_quoting;
  1680. /* quote `[\ */
  1681. if (*p == '`')
  1682. goto need_quoting;
  1683. if (*p == '[')
  1684. goto need_quoting;
  1685. if (*p == '\\')
  1686. goto need_quoting;
  1687. /* quote {|}~ DEL and high bytes */
  1688. if (*p > 'z')
  1689. goto need_quoting;
  1690. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1691. /* TODO: maybe avoid quoting % */
  1692. p++;
  1693. }
  1694. return s;
  1695. need_quoting:
  1696. return single_quote(s);
  1697. }
  1698. /* ============ nextopt */
  1699. static char **argptr; /* argument list for builtin commands */
  1700. static char *optionarg; /* set by nextopt (like getopt) */
  1701. static char *optptr; /* used by nextopt */
  1702. /*
  1703. * XXX - should get rid of. Have all builtins use getopt(3).
  1704. * The library getopt must have the BSD extension static variable
  1705. * "optreset", otherwise it can't be used within the shell safely.
  1706. *
  1707. * Standard option processing (a la getopt) for builtin routines.
  1708. * The only argument that is passed to nextopt is the option string;
  1709. * the other arguments are unnecessary. It returns the character,
  1710. * or '\0' on end of input.
  1711. */
  1712. static int
  1713. nextopt(const char *optstring)
  1714. {
  1715. char *p;
  1716. const char *q;
  1717. char c;
  1718. p = optptr;
  1719. if (p == NULL || *p == '\0') {
  1720. /* We ate entire "-param", take next one */
  1721. p = *argptr;
  1722. if (p == NULL)
  1723. return '\0';
  1724. if (*p != '-')
  1725. return '\0';
  1726. if (*++p == '\0') /* just "-" ? */
  1727. return '\0';
  1728. argptr++;
  1729. if (LONE_DASH(p)) /* "--" ? */
  1730. return '\0';
  1731. /* p => next "-param" */
  1732. }
  1733. /* p => some option char in the middle of a "-param" */
  1734. c = *p++;
  1735. for (q = optstring; *q != c;) {
  1736. if (*q == '\0')
  1737. ash_msg_and_raise_error("illegal option -%c", c);
  1738. if (*++q == ':')
  1739. q++;
  1740. }
  1741. if (*++q == ':') {
  1742. if (*p == '\0') {
  1743. p = *argptr++;
  1744. if (p == NULL)
  1745. ash_msg_and_raise_error("no arg for -%c option", c);
  1746. }
  1747. optionarg = p;
  1748. p = NULL;
  1749. }
  1750. optptr = p;
  1751. return c;
  1752. }
  1753. /* ============ Shell variables */
  1754. struct shparam {
  1755. int nparam; /* # of positional parameters (without $0) */
  1756. #if ENABLE_ASH_GETOPTS
  1757. int optind; /* next parameter to be processed by getopts */
  1758. int optoff; /* used by getopts */
  1759. #endif
  1760. unsigned char malloced; /* if parameter list dynamically allocated */
  1761. char **p; /* parameter list */
  1762. };
  1763. /*
  1764. * Free the list of positional parameters.
  1765. */
  1766. static void
  1767. freeparam(volatile struct shparam *param)
  1768. {
  1769. if (param->malloced) {
  1770. char **ap, **ap1;
  1771. ap = ap1 = param->p;
  1772. while (*ap)
  1773. free(*ap++);
  1774. free(ap1);
  1775. }
  1776. }
  1777. #if ENABLE_ASH_GETOPTS
  1778. static void FAST_FUNC getoptsreset(const char *value);
  1779. #endif
  1780. struct var {
  1781. struct var *next; /* next entry in hash list */
  1782. int flags; /* flags are defined above */
  1783. const char *var_text; /* name=value */
  1784. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1785. /* the variable gets set/unset */
  1786. };
  1787. struct localvar {
  1788. struct localvar *next; /* next local variable in list */
  1789. struct var *vp; /* the variable that was made local */
  1790. int flags; /* saved flags */
  1791. const char *text; /* saved text */
  1792. };
  1793. /* flags */
  1794. #define VEXPORT 0x01 /* variable is exported */
  1795. #define VREADONLY 0x02 /* variable cannot be modified */
  1796. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1797. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1798. #define VSTACK 0x10 /* text is allocated on the stack */
  1799. #define VUNSET 0x20 /* the variable is not set */
  1800. #define VNOFUNC 0x40 /* don't call the callback function */
  1801. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1802. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1803. #if ENABLE_ASH_RANDOM_SUPPORT
  1804. # define VDYNAMIC 0x200 /* dynamic variable */
  1805. #else
  1806. # define VDYNAMIC 0
  1807. #endif
  1808. /* Need to be before varinit_data[] */
  1809. #if ENABLE_LOCALE_SUPPORT
  1810. static void FAST_FUNC
  1811. change_lc_all(const char *value)
  1812. {
  1813. if (value && *value != '\0')
  1814. setlocale(LC_ALL, value);
  1815. }
  1816. static void FAST_FUNC
  1817. change_lc_ctype(const char *value)
  1818. {
  1819. if (value && *value != '\0')
  1820. setlocale(LC_CTYPE, value);
  1821. }
  1822. #endif
  1823. #if ENABLE_ASH_MAIL
  1824. static void chkmail(void);
  1825. static void changemail(const char *var_value) FAST_FUNC;
  1826. #else
  1827. # define chkmail() ((void)0)
  1828. #endif
  1829. static void changepath(const char *) FAST_FUNC;
  1830. #if ENABLE_ASH_RANDOM_SUPPORT
  1831. static void change_random(const char *) FAST_FUNC;
  1832. #endif
  1833. static const struct {
  1834. int flags;
  1835. const char *var_text;
  1836. void (*var_func)(const char *) FAST_FUNC;
  1837. } varinit_data[] = {
  1838. /*
  1839. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1840. * some environment strings may be constant.
  1841. */
  1842. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1843. #if ENABLE_ASH_MAIL
  1844. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1845. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1846. #endif
  1847. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1848. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1849. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1850. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1851. #if ENABLE_ASH_GETOPTS
  1852. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1853. #endif
  1854. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1855. #if ENABLE_ASH_RANDOM_SUPPORT
  1856. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1857. #endif
  1858. #if ENABLE_LOCALE_SUPPORT
  1859. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1860. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1861. #endif
  1862. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1863. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1864. #endif
  1865. };
  1866. struct redirtab;
  1867. struct globals_var {
  1868. struct shparam shellparam; /* $@ current positional parameters */
  1869. struct redirtab *redirlist;
  1870. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1871. struct var *vartab[VTABSIZE];
  1872. struct var varinit[ARRAY_SIZE(varinit_data)];
  1873. int lineno;
  1874. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1875. };
  1876. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1877. #define G_var (*ash_ptr_to_globals_var)
  1878. #define shellparam (G_var.shellparam )
  1879. //#define redirlist (G_var.redirlist )
  1880. #define preverrout_fd (G_var.preverrout_fd)
  1881. #define vartab (G_var.vartab )
  1882. #define varinit (G_var.varinit )
  1883. #define lineno (G_var.lineno )
  1884. #define linenovar (G_var.linenovar )
  1885. #define vifs varinit[0]
  1886. #if ENABLE_ASH_MAIL
  1887. # define vmail (&vifs)[1]
  1888. # define vmpath (&vmail)[1]
  1889. # define vpath (&vmpath)[1]
  1890. #else
  1891. # define vpath (&vifs)[1]
  1892. #endif
  1893. #define vps1 (&vpath)[1]
  1894. #define vps2 (&vps1)[1]
  1895. #define vps4 (&vps2)[1]
  1896. #if ENABLE_ASH_GETOPTS
  1897. # define voptind (&vps4)[1]
  1898. # define vlineno (&voptind)[1]
  1899. # if ENABLE_ASH_RANDOM_SUPPORT
  1900. # define vrandom (&vlineno)[1]
  1901. # endif
  1902. #else
  1903. # define vlineno (&vps4)[1]
  1904. # if ENABLE_ASH_RANDOM_SUPPORT
  1905. # define vrandom (&vlineno)[1]
  1906. # endif
  1907. #endif
  1908. #define INIT_G_var() do { \
  1909. unsigned i; \
  1910. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1911. barrier(); \
  1912. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1913. varinit[i].flags = varinit_data[i].flags; \
  1914. varinit[i].var_text = varinit_data[i].var_text; \
  1915. varinit[i].var_func = varinit_data[i].var_func; \
  1916. } \
  1917. strcpy(linenovar, "LINENO="); \
  1918. vlineno.var_text = linenovar; \
  1919. } while (0)
  1920. /*
  1921. * The following macros access the values of the above variables.
  1922. * They have to skip over the name. They return the null string
  1923. * for unset variables.
  1924. */
  1925. #define ifsval() (vifs.var_text + 4)
  1926. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1927. #if ENABLE_ASH_MAIL
  1928. # define mailval() (vmail.var_text + 5)
  1929. # define mpathval() (vmpath.var_text + 9)
  1930. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1931. #endif
  1932. #define pathval() (vpath.var_text + 5)
  1933. #define ps1val() (vps1.var_text + 4)
  1934. #define ps2val() (vps2.var_text + 4)
  1935. #define ps4val() (vps4.var_text + 4)
  1936. #if ENABLE_ASH_GETOPTS
  1937. # define optindval() (voptind.var_text + 7)
  1938. #endif
  1939. #if ENABLE_ASH_GETOPTS
  1940. static void FAST_FUNC
  1941. getoptsreset(const char *value)
  1942. {
  1943. shellparam.optind = 1;
  1944. if (is_number(value))
  1945. shellparam.optind = number(value) ?: 1;
  1946. shellparam.optoff = -1;
  1947. }
  1948. #endif
  1949. /*
  1950. * Compares two strings up to the first = or '\0'. The first
  1951. * string must be terminated by '='; the second may be terminated by
  1952. * either '=' or '\0'.
  1953. */
  1954. static int
  1955. varcmp(const char *p, const char *q)
  1956. {
  1957. int c, d;
  1958. while ((c = *p) == (d = *q)) {
  1959. if (c == '\0' || c == '=')
  1960. goto out;
  1961. p++;
  1962. q++;
  1963. }
  1964. if (c == '=')
  1965. c = '\0';
  1966. if (d == '=')
  1967. d = '\0';
  1968. out:
  1969. return c - d;
  1970. }
  1971. /*
  1972. * Find the appropriate entry in the hash table from the name.
  1973. */
  1974. static struct var **
  1975. hashvar(const char *p)
  1976. {
  1977. unsigned hashval;
  1978. hashval = ((unsigned char) *p) << 4;
  1979. while (*p && *p != '=')
  1980. hashval += (unsigned char) *p++;
  1981. return &vartab[hashval % VTABSIZE];
  1982. }
  1983. static int
  1984. vpcmp(const void *a, const void *b)
  1985. {
  1986. return varcmp(*(const char **)a, *(const char **)b);
  1987. }
  1988. /*
  1989. * This routine initializes the builtin variables.
  1990. */
  1991. static void
  1992. initvar(void)
  1993. {
  1994. struct var *vp;
  1995. struct var *end;
  1996. struct var **vpp;
  1997. /*
  1998. * PS1 depends on uid
  1999. */
  2000. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2001. vps1.var_text = "PS1=\\w \\$ ";
  2002. #else
  2003. if (!geteuid())
  2004. vps1.var_text = "PS1=# ";
  2005. #endif
  2006. vp = varinit;
  2007. end = vp + ARRAY_SIZE(varinit);
  2008. do {
  2009. vpp = hashvar(vp->var_text);
  2010. vp->next = *vpp;
  2011. *vpp = vp;
  2012. } while (++vp < end);
  2013. }
  2014. static struct var **
  2015. findvar(struct var **vpp, const char *name)
  2016. {
  2017. for (; *vpp; vpp = &(*vpp)->next) {
  2018. if (varcmp((*vpp)->var_text, name) == 0) {
  2019. break;
  2020. }
  2021. }
  2022. return vpp;
  2023. }
  2024. /*
  2025. * Find the value of a variable. Returns NULL if not set.
  2026. */
  2027. static const char* FAST_FUNC
  2028. lookupvar(const char *name)
  2029. {
  2030. struct var *v;
  2031. v = *findvar(hashvar(name), name);
  2032. if (v) {
  2033. #if ENABLE_ASH_RANDOM_SUPPORT
  2034. /*
  2035. * Dynamic variables are implemented roughly the same way they are
  2036. * in bash. Namely, they're "special" so long as they aren't unset.
  2037. * As soon as they're unset, they're no longer dynamic, and dynamic
  2038. * lookup will no longer happen at that point. -- PFM.
  2039. */
  2040. if (v->flags & VDYNAMIC)
  2041. v->var_func(NULL);
  2042. #endif
  2043. if (!(v->flags & VUNSET)) {
  2044. if (v == &vlineno && v->var_text == linenovar) {
  2045. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2046. }
  2047. return var_end(v->var_text);
  2048. }
  2049. }
  2050. return NULL;
  2051. }
  2052. #if ENABLE_UNICODE_SUPPORT
  2053. static void
  2054. reinit_unicode_for_ash(void)
  2055. {
  2056. /* Unicode support should be activated even if LANG is set
  2057. * _during_ shell execution, not only if it was set when
  2058. * shell was started. Therefore, re-check LANG every time:
  2059. */
  2060. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2061. || ENABLE_UNICODE_USING_LOCALE
  2062. ) {
  2063. const char *s = lookupvar("LC_ALL");
  2064. if (!s) s = lookupvar("LC_CTYPE");
  2065. if (!s) s = lookupvar("LANG");
  2066. reinit_unicode(s);
  2067. }
  2068. }
  2069. #else
  2070. # define reinit_unicode_for_ash() ((void)0)
  2071. #endif
  2072. /*
  2073. * Search the environment of a builtin command.
  2074. */
  2075. static ALWAYS_INLINE const char *
  2076. bltinlookup(const char *name)
  2077. {
  2078. return lookupvar(name);
  2079. }
  2080. /*
  2081. * Same as setvar except that the variable and value are passed in
  2082. * the first argument as name=value. Since the first argument will
  2083. * be actually stored in the table, it should not be a string that
  2084. * will go away.
  2085. * Called with interrupts off.
  2086. */
  2087. static struct var *
  2088. setvareq(char *s, int flags)
  2089. {
  2090. struct var *vp, **vpp;
  2091. vpp = hashvar(s);
  2092. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2093. vpp = findvar(vpp, s);
  2094. vp = *vpp;
  2095. if (vp) {
  2096. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2097. const char *n;
  2098. if (flags & VNOSAVE)
  2099. free(s);
  2100. n = vp->var_text;
  2101. exitstatus = 1;
  2102. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2103. }
  2104. if (flags & VNOSET)
  2105. goto out;
  2106. if (vp->var_func && !(flags & VNOFUNC))
  2107. vp->var_func(var_end(s));
  2108. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2109. free((char*)vp->var_text);
  2110. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2111. *vpp = vp->next;
  2112. free(vp);
  2113. out_free:
  2114. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2115. free(s);
  2116. goto out;
  2117. }
  2118. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2119. } else {
  2120. /* variable s is not found */
  2121. if (flags & VNOSET)
  2122. goto out;
  2123. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2124. goto out_free;
  2125. vp = ckzalloc(sizeof(*vp));
  2126. vp->next = *vpp;
  2127. /*vp->func = NULL; - ckzalloc did it */
  2128. *vpp = vp;
  2129. }
  2130. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2131. s = ckstrdup(s);
  2132. vp->var_text = s;
  2133. vp->flags = flags;
  2134. out:
  2135. return vp;
  2136. }
  2137. /*
  2138. * Set the value of a variable. The flags argument is ored with the
  2139. * flags of the variable. If val is NULL, the variable is unset.
  2140. */
  2141. static struct var *
  2142. setvar(const char *name, const char *val, int flags)
  2143. {
  2144. const char *q;
  2145. char *p;
  2146. char *nameeq;
  2147. size_t namelen;
  2148. size_t vallen;
  2149. struct var *vp;
  2150. q = endofname(name);
  2151. p = strchrnul(q, '=');
  2152. namelen = p - name;
  2153. if (!namelen || p != q)
  2154. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2155. vallen = 0;
  2156. if (val == NULL) {
  2157. flags |= VUNSET;
  2158. } else {
  2159. vallen = strlen(val);
  2160. }
  2161. INT_OFF;
  2162. nameeq = ckzalloc(namelen + vallen + 2);
  2163. p = mempcpy(nameeq, name, namelen);
  2164. if (val) {
  2165. *p++ = '=';
  2166. memcpy(p, val, vallen);
  2167. }
  2168. vp = setvareq(nameeq, flags | VNOSAVE);
  2169. INT_ON;
  2170. return vp;
  2171. }
  2172. static void FAST_FUNC
  2173. setvar0(const char *name, const char *val)
  2174. {
  2175. setvar(name, val, 0);
  2176. }
  2177. /*
  2178. * Unset the specified variable.
  2179. */
  2180. static void
  2181. unsetvar(const char *s)
  2182. {
  2183. setvar(s, NULL, 0);
  2184. }
  2185. /*
  2186. * Process a linked list of variable assignments.
  2187. */
  2188. static void
  2189. listsetvar(struct strlist *list_set_var, int flags)
  2190. {
  2191. struct strlist *lp = list_set_var;
  2192. if (!lp)
  2193. return;
  2194. INT_OFF;
  2195. do {
  2196. setvareq(lp->text, flags);
  2197. lp = lp->next;
  2198. } while (lp);
  2199. INT_ON;
  2200. }
  2201. /*
  2202. * Generate a list of variables satisfying the given conditions.
  2203. */
  2204. #if !ENABLE_FEATURE_SH_NOFORK
  2205. # define listvars(on, off, lp, end) listvars(on, off, end)
  2206. #endif
  2207. static char **
  2208. listvars(int on, int off, struct strlist *lp, char ***end)
  2209. {
  2210. struct var **vpp;
  2211. struct var *vp;
  2212. char **ep;
  2213. int mask;
  2214. STARTSTACKSTR(ep);
  2215. vpp = vartab;
  2216. mask = on | off;
  2217. do {
  2218. for (vp = *vpp; vp; vp = vp->next) {
  2219. if ((vp->flags & mask) == on) {
  2220. #if ENABLE_FEATURE_SH_NOFORK
  2221. /* If variable with the same name is both
  2222. * exported and temporarily set for a command:
  2223. * export ZVAR=5
  2224. * ZVAR=6 printenv
  2225. * then "ZVAR=6" will be both in vartab and
  2226. * lp lists. Do not pass it twice to printenv.
  2227. */
  2228. struct strlist *lp1 = lp;
  2229. while (lp1) {
  2230. if (strcmp(lp1->text, vp->var_text) == 0)
  2231. goto skip;
  2232. lp1 = lp1->next;
  2233. }
  2234. #endif
  2235. if (ep == stackstrend())
  2236. ep = growstackstr();
  2237. *ep++ = (char*)vp->var_text;
  2238. #if ENABLE_FEATURE_SH_NOFORK
  2239. skip: ;
  2240. #endif
  2241. }
  2242. }
  2243. } while (++vpp < vartab + VTABSIZE);
  2244. #if ENABLE_FEATURE_SH_NOFORK
  2245. while (lp) {
  2246. if (ep == stackstrend())
  2247. ep = growstackstr();
  2248. *ep++ = lp->text;
  2249. lp = lp->next;
  2250. }
  2251. #endif
  2252. if (ep == stackstrend())
  2253. ep = growstackstr();
  2254. if (end)
  2255. *end = ep;
  2256. *ep++ = NULL;
  2257. return grabstackstr(ep);
  2258. }
  2259. /* ============ Path search helper
  2260. *
  2261. * The variable path (passed by reference) should be set to the start
  2262. * of the path before the first call; path_advance will update
  2263. * this value as it proceeds. Successive calls to path_advance will return
  2264. * the possible path expansions in sequence. If an option (indicated by
  2265. * a percent sign) appears in the path entry then the global variable
  2266. * pathopt will be set to point to it; otherwise pathopt will be set to
  2267. * NULL.
  2268. */
  2269. static const char *pathopt; /* set by path_advance */
  2270. static char *
  2271. path_advance(const char **path, const char *name)
  2272. {
  2273. const char *p;
  2274. char *q;
  2275. const char *start;
  2276. size_t len;
  2277. if (*path == NULL)
  2278. return NULL;
  2279. start = *path;
  2280. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2281. continue;
  2282. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2283. while (stackblocksize() < len)
  2284. growstackblock();
  2285. q = stackblock();
  2286. if (p != start) {
  2287. q = mempcpy(q, start, p - start);
  2288. *q++ = '/';
  2289. }
  2290. strcpy(q, name);
  2291. pathopt = NULL;
  2292. if (*p == '%') {
  2293. pathopt = ++p;
  2294. while (*p && *p != ':')
  2295. p++;
  2296. }
  2297. if (*p == ':')
  2298. *path = p + 1;
  2299. else
  2300. *path = NULL;
  2301. return stalloc(len);
  2302. }
  2303. /* ============ Prompt */
  2304. static smallint doprompt; /* if set, prompt the user */
  2305. static smallint needprompt; /* true if interactive and at start of line */
  2306. #if ENABLE_FEATURE_EDITING
  2307. static line_input_t *line_input_state;
  2308. static const char *cmdedit_prompt;
  2309. static void
  2310. putprompt(const char *s)
  2311. {
  2312. if (ENABLE_ASH_EXPAND_PRMT) {
  2313. free((char*)cmdedit_prompt);
  2314. cmdedit_prompt = ckstrdup(s);
  2315. return;
  2316. }
  2317. cmdedit_prompt = s;
  2318. }
  2319. #else
  2320. static void
  2321. putprompt(const char *s)
  2322. {
  2323. out2str(s);
  2324. }
  2325. #endif
  2326. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2327. static const char *expandstr(const char *ps, int syntax_type);
  2328. /* Values for syntax param */
  2329. #define BASESYNTAX 0 /* not in quotes */
  2330. #define DQSYNTAX 1 /* in double quotes */
  2331. #define SQSYNTAX 2 /* in single quotes */
  2332. #define ARISYNTAX 3 /* in arithmetic */
  2333. #if ENABLE_ASH_EXPAND_PRMT
  2334. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2335. #endif
  2336. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2337. /*
  2338. * called by editline -- any expansions to the prompt should be added here.
  2339. */
  2340. static void
  2341. setprompt_if(smallint do_set, int whichprompt)
  2342. {
  2343. const char *prompt;
  2344. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2345. if (!do_set)
  2346. return;
  2347. needprompt = 0;
  2348. switch (whichprompt) {
  2349. case 1:
  2350. prompt = ps1val();
  2351. break;
  2352. case 2:
  2353. prompt = ps2val();
  2354. break;
  2355. default: /* 0 */
  2356. prompt = nullstr;
  2357. }
  2358. #if ENABLE_ASH_EXPAND_PRMT
  2359. pushstackmark(&smark, stackblocksize());
  2360. putprompt(expandstr(prompt, PSSYNTAX));
  2361. popstackmark(&smark);
  2362. #else
  2363. putprompt(prompt);
  2364. #endif
  2365. }
  2366. /* ============ The cd and pwd commands */
  2367. #define CD_PHYSICAL 1
  2368. #define CD_PRINT 2
  2369. static int
  2370. cdopt(void)
  2371. {
  2372. int flags = 0;
  2373. int i, j;
  2374. j = 'L';
  2375. while ((i = nextopt("LP")) != '\0') {
  2376. if (i != j) {
  2377. flags ^= CD_PHYSICAL;
  2378. j = i;
  2379. }
  2380. }
  2381. return flags;
  2382. }
  2383. /*
  2384. * Update curdir (the name of the current directory) in response to a
  2385. * cd command.
  2386. */
  2387. static const char *
  2388. updatepwd(const char *dir)
  2389. {
  2390. char *new;
  2391. char *p;
  2392. char *cdcomppath;
  2393. const char *lim;
  2394. cdcomppath = sstrdup(dir);
  2395. STARTSTACKSTR(new);
  2396. if (*dir != '/') {
  2397. if (curdir == nullstr)
  2398. return 0;
  2399. new = stack_putstr(curdir, new);
  2400. }
  2401. new = makestrspace(strlen(dir) + 2, new);
  2402. lim = (char *)stackblock() + 1;
  2403. if (*dir != '/') {
  2404. if (new[-1] != '/')
  2405. USTPUTC('/', new);
  2406. if (new > lim && *lim == '/')
  2407. lim++;
  2408. } else {
  2409. USTPUTC('/', new);
  2410. cdcomppath++;
  2411. if (dir[1] == '/' && dir[2] != '/') {
  2412. USTPUTC('/', new);
  2413. cdcomppath++;
  2414. lim++;
  2415. }
  2416. }
  2417. p = strtok(cdcomppath, "/");
  2418. while (p) {
  2419. switch (*p) {
  2420. case '.':
  2421. if (p[1] == '.' && p[2] == '\0') {
  2422. while (new > lim) {
  2423. STUNPUTC(new);
  2424. if (new[-1] == '/')
  2425. break;
  2426. }
  2427. break;
  2428. }
  2429. if (p[1] == '\0')
  2430. break;
  2431. /* fall through */
  2432. default:
  2433. new = stack_putstr(p, new);
  2434. USTPUTC('/', new);
  2435. }
  2436. p = strtok(NULL, "/");
  2437. }
  2438. if (new > lim)
  2439. STUNPUTC(new);
  2440. *new = 0;
  2441. return stackblock();
  2442. }
  2443. /*
  2444. * Find out what the current directory is. If we already know the current
  2445. * directory, this routine returns immediately.
  2446. */
  2447. static char *
  2448. getpwd(void)
  2449. {
  2450. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2451. return dir ? dir : nullstr;
  2452. }
  2453. static void
  2454. setpwd(const char *val, int setold)
  2455. {
  2456. char *oldcur, *dir;
  2457. oldcur = dir = curdir;
  2458. if (setold) {
  2459. setvar("OLDPWD", oldcur, VEXPORT);
  2460. }
  2461. INT_OFF;
  2462. if (physdir != nullstr) {
  2463. if (physdir != oldcur)
  2464. free(physdir);
  2465. physdir = nullstr;
  2466. }
  2467. if (oldcur == val || !val) {
  2468. char *s = getpwd();
  2469. physdir = s;
  2470. if (!val)
  2471. dir = s;
  2472. } else
  2473. dir = ckstrdup(val);
  2474. if (oldcur != dir && oldcur != nullstr) {
  2475. free(oldcur);
  2476. }
  2477. curdir = dir;
  2478. INT_ON;
  2479. setvar("PWD", dir, VEXPORT);
  2480. }
  2481. static void hashcd(void);
  2482. /*
  2483. * Actually do the chdir. We also call hashcd to let other routines
  2484. * know that the current directory has changed.
  2485. */
  2486. static int
  2487. docd(const char *dest, int flags)
  2488. {
  2489. const char *dir = NULL;
  2490. int err;
  2491. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2492. INT_OFF;
  2493. if (!(flags & CD_PHYSICAL)) {
  2494. dir = updatepwd(dest);
  2495. if (dir)
  2496. dest = dir;
  2497. }
  2498. err = chdir(dest);
  2499. if (err)
  2500. goto out;
  2501. setpwd(dir, 1);
  2502. hashcd();
  2503. out:
  2504. INT_ON;
  2505. return err;
  2506. }
  2507. static int FAST_FUNC
  2508. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2509. {
  2510. const char *dest;
  2511. const char *path;
  2512. const char *p;
  2513. char c;
  2514. struct stat statb;
  2515. int flags;
  2516. flags = cdopt();
  2517. dest = *argptr;
  2518. if (!dest)
  2519. dest = bltinlookup("HOME");
  2520. else if (LONE_DASH(dest)) {
  2521. dest = bltinlookup("OLDPWD");
  2522. flags |= CD_PRINT;
  2523. }
  2524. if (!dest)
  2525. dest = nullstr;
  2526. if (*dest == '/')
  2527. goto step6;
  2528. if (*dest == '.') {
  2529. c = dest[1];
  2530. dotdot:
  2531. switch (c) {
  2532. case '\0':
  2533. case '/':
  2534. goto step6;
  2535. case '.':
  2536. c = dest[2];
  2537. if (c != '.')
  2538. goto dotdot;
  2539. }
  2540. }
  2541. if (!*dest)
  2542. dest = ".";
  2543. path = bltinlookup("CDPATH");
  2544. while (path) {
  2545. c = *path;
  2546. p = path_advance(&path, dest);
  2547. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2548. if (c && c != ':')
  2549. flags |= CD_PRINT;
  2550. docd:
  2551. if (!docd(p, flags))
  2552. goto out;
  2553. goto err;
  2554. }
  2555. }
  2556. step6:
  2557. p = dest;
  2558. goto docd;
  2559. err:
  2560. ash_msg_and_raise_perror("can't cd to %s", dest);
  2561. /* NOTREACHED */
  2562. out:
  2563. if (flags & CD_PRINT)
  2564. out1fmt("%s\n", curdir);
  2565. return 0;
  2566. }
  2567. static int FAST_FUNC
  2568. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2569. {
  2570. int flags;
  2571. const char *dir = curdir;
  2572. flags = cdopt();
  2573. if (flags) {
  2574. if (physdir == nullstr)
  2575. setpwd(dir, 0);
  2576. dir = physdir;
  2577. }
  2578. out1fmt("%s\n", dir);
  2579. return 0;
  2580. }
  2581. /* ============ ... */
  2582. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2583. /* Syntax classes */
  2584. #define CWORD 0 /* character is nothing special */
  2585. #define CNL 1 /* newline character */
  2586. #define CBACK 2 /* a backslash character */
  2587. #define CSQUOTE 3 /* single quote */
  2588. #define CDQUOTE 4 /* double quote */
  2589. #define CENDQUOTE 5 /* a terminating quote */
  2590. #define CBQUOTE 6 /* backwards single quote */
  2591. #define CVAR 7 /* a dollar sign */
  2592. #define CENDVAR 8 /* a '}' character */
  2593. #define CLP 9 /* a left paren in arithmetic */
  2594. #define CRP 10 /* a right paren in arithmetic */
  2595. #define CENDFILE 11 /* end of file */
  2596. #define CCTL 12 /* like CWORD, except it must be escaped */
  2597. #define CSPCL 13 /* these terminate a word */
  2598. #define CIGN 14 /* character should be ignored */
  2599. #define PEOF 256
  2600. #if ENABLE_ASH_ALIAS
  2601. # define PEOA 257
  2602. #endif
  2603. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2604. #if ENABLE_FEATURE_SH_MATH
  2605. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2606. #else
  2607. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2608. #endif
  2609. static const uint16_t S_I_T[] ALIGN2 = {
  2610. #if ENABLE_ASH_ALIAS
  2611. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2612. #endif
  2613. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2614. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2615. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2616. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2617. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2618. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2619. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2620. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2621. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2622. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2623. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2624. #if !USE_SIT_FUNCTION
  2625. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2626. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2627. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2628. #endif
  2629. #undef SIT_ITEM
  2630. };
  2631. /* Constants below must match table above */
  2632. enum {
  2633. #if ENABLE_ASH_ALIAS
  2634. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2635. #endif
  2636. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2637. CNL_CNL_CNL_CNL , /* 2 */
  2638. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2639. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2640. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2641. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2642. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2643. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2644. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2645. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2646. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2647. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2648. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2649. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2650. };
  2651. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2652. * caller must ensure proper cast on it if c is *char_ptr!
  2653. */
  2654. #if USE_SIT_FUNCTION
  2655. static int
  2656. SIT(int c, int syntax)
  2657. {
  2658. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2659. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2660. /*
  2661. * This causes '/' to be prepended with CTLESC in dquoted string,
  2662. * making "./file"* treated incorrectly because we feed
  2663. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2664. * The "homegrown" glob implementation is okay with that,
  2665. * but glibc one isn't. With '/' always treated as CWORD,
  2666. * both work fine.
  2667. */
  2668. # if ENABLE_ASH_ALIAS
  2669. static const uint8_t syntax_index_table[] ALIGN1 = {
  2670. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2671. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2672. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2673. 11, 3 /* "}~" */
  2674. };
  2675. # else
  2676. static const uint8_t syntax_index_table[] ALIGN1 = {
  2677. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2678. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2679. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2680. 10, 2 /* "}~" */
  2681. };
  2682. # endif
  2683. const char *s;
  2684. int indx;
  2685. if (c == PEOF)
  2686. return CENDFILE;
  2687. # if ENABLE_ASH_ALIAS
  2688. if (c == PEOA)
  2689. indx = 0;
  2690. else
  2691. # endif
  2692. {
  2693. /* Cast is purely for paranoia here,
  2694. * just in case someone passed signed char to us */
  2695. if ((unsigned char)c >= CTL_FIRST
  2696. && (unsigned char)c <= CTL_LAST
  2697. ) {
  2698. return CCTL;
  2699. }
  2700. s = strchrnul(spec_symbls, c);
  2701. if (*s == '\0')
  2702. return CWORD;
  2703. indx = syntax_index_table[s - spec_symbls];
  2704. }
  2705. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2706. }
  2707. #else /* !USE_SIT_FUNCTION */
  2708. static const uint8_t syntax_index_table[] ALIGN1 = {
  2709. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2710. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2711. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2712. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2713. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2714. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2715. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2716. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2717. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2718. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2719. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2720. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2721. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2722. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2723. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2724. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2725. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2726. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2727. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2728. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2729. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2730. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2731. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2732. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2733. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2734. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2735. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2736. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2737. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2738. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2739. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2740. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2741. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2742. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2743. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2744. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2745. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2746. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2747. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2748. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2749. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2750. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2751. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2752. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2753. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2755. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2756. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2757. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2758. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2759. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2760. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2761. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2762. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2763. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2764. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2765. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2766. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2767. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2768. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2769. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2770. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2771. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2772. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2773. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2774. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2775. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2781. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2803. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2804. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2805. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2808. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2831. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2832. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2833. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2835. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2836. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2837. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2838. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2839. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2840. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2841. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2842. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2843. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2844. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2845. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2846. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2847. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2848. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2897. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2899. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2902. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2903. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2904. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2905. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2906. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2922. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2923. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2924. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2925. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2926. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2927. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2928. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2929. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2930. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2931. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2932. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2933. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2934. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2935. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2936. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2937. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2967. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2968. # if ENABLE_ASH_ALIAS
  2969. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2970. # endif
  2971. };
  2972. #if 1
  2973. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2974. #else /* debug version, caught one signed char bug */
  2975. # define SIT(c, syntax) \
  2976. ({ \
  2977. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  2978. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2979. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  2980. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2981. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  2982. })
  2983. #endif
  2984. #endif /* !USE_SIT_FUNCTION */
  2985. /* ============ Alias handling */
  2986. #if ENABLE_ASH_ALIAS
  2987. #define ALIASINUSE 1
  2988. #define ALIASDEAD 2
  2989. struct alias {
  2990. struct alias *next;
  2991. char *name;
  2992. char *val;
  2993. int flag;
  2994. };
  2995. static struct alias **atab; // [ATABSIZE];
  2996. #define INIT_G_alias() do { \
  2997. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2998. } while (0)
  2999. static struct alias **
  3000. __lookupalias(const char *name)
  3001. {
  3002. unsigned int hashval;
  3003. struct alias **app;
  3004. const char *p;
  3005. unsigned int ch;
  3006. p = name;
  3007. ch = (unsigned char)*p;
  3008. hashval = ch << 4;
  3009. while (ch) {
  3010. hashval += ch;
  3011. ch = (unsigned char)*++p;
  3012. }
  3013. app = &atab[hashval % ATABSIZE];
  3014. for (; *app; app = &(*app)->next) {
  3015. if (strcmp(name, (*app)->name) == 0) {
  3016. break;
  3017. }
  3018. }
  3019. return app;
  3020. }
  3021. static struct alias *
  3022. lookupalias(const char *name, int check)
  3023. {
  3024. struct alias *ap = *__lookupalias(name);
  3025. if (check && ap && (ap->flag & ALIASINUSE))
  3026. return NULL;
  3027. return ap;
  3028. }
  3029. static struct alias *
  3030. freealias(struct alias *ap)
  3031. {
  3032. struct alias *next;
  3033. if (ap->flag & ALIASINUSE) {
  3034. ap->flag |= ALIASDEAD;
  3035. return ap;
  3036. }
  3037. next = ap->next;
  3038. free(ap->name);
  3039. free(ap->val);
  3040. free(ap);
  3041. return next;
  3042. }
  3043. static void
  3044. setalias(const char *name, const char *val)
  3045. {
  3046. struct alias *ap, **app;
  3047. app = __lookupalias(name);
  3048. ap = *app;
  3049. INT_OFF;
  3050. if (ap) {
  3051. if (!(ap->flag & ALIASINUSE)) {
  3052. free(ap->val);
  3053. }
  3054. ap->val = ckstrdup(val);
  3055. ap->flag &= ~ALIASDEAD;
  3056. } else {
  3057. /* not found */
  3058. ap = ckzalloc(sizeof(struct alias));
  3059. ap->name = ckstrdup(name);
  3060. ap->val = ckstrdup(val);
  3061. /*ap->flag = 0; - ckzalloc did it */
  3062. /*ap->next = NULL;*/
  3063. *app = ap;
  3064. }
  3065. INT_ON;
  3066. }
  3067. static int
  3068. unalias(const char *name)
  3069. {
  3070. struct alias **app;
  3071. app = __lookupalias(name);
  3072. if (*app) {
  3073. INT_OFF;
  3074. *app = freealias(*app);
  3075. INT_ON;
  3076. return 0;
  3077. }
  3078. return 1;
  3079. }
  3080. static void
  3081. rmaliases(void)
  3082. {
  3083. struct alias *ap, **app;
  3084. int i;
  3085. INT_OFF;
  3086. for (i = 0; i < ATABSIZE; i++) {
  3087. app = &atab[i];
  3088. for (ap = *app; ap; ap = *app) {
  3089. *app = freealias(*app);
  3090. if (ap == *app) {
  3091. app = &ap->next;
  3092. }
  3093. }
  3094. }
  3095. INT_ON;
  3096. }
  3097. static void
  3098. printalias(const struct alias *ap)
  3099. {
  3100. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3101. }
  3102. /*
  3103. * TODO - sort output
  3104. */
  3105. static int FAST_FUNC
  3106. aliascmd(int argc UNUSED_PARAM, char **argv)
  3107. {
  3108. char *n, *v;
  3109. int ret = 0;
  3110. struct alias *ap;
  3111. if (!argv[1]) {
  3112. int i;
  3113. for (i = 0; i < ATABSIZE; i++) {
  3114. for (ap = atab[i]; ap; ap = ap->next) {
  3115. printalias(ap);
  3116. }
  3117. }
  3118. return 0;
  3119. }
  3120. while ((n = *++argv) != NULL) {
  3121. v = strchr(n+1, '=');
  3122. if (v == NULL) { /* n+1: funny ksh stuff */
  3123. ap = *__lookupalias(n);
  3124. if (ap == NULL) {
  3125. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3126. ret = 1;
  3127. } else
  3128. printalias(ap);
  3129. } else {
  3130. *v++ = '\0';
  3131. setalias(n, v);
  3132. }
  3133. }
  3134. return ret;
  3135. }
  3136. static int FAST_FUNC
  3137. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3138. {
  3139. int i;
  3140. while (nextopt("a") != '\0') {
  3141. rmaliases();
  3142. return 0;
  3143. }
  3144. for (i = 0; *argptr; argptr++) {
  3145. if (unalias(*argptr)) {
  3146. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3147. i = 1;
  3148. }
  3149. }
  3150. return i;
  3151. }
  3152. #endif /* ASH_ALIAS */
  3153. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3154. #define FORK_FG 0
  3155. #define FORK_BG 1
  3156. #define FORK_NOJOB 2
  3157. /* mode flags for showjob(s) */
  3158. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3159. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3160. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3161. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3162. /*
  3163. * A job structure contains information about a job. A job is either a
  3164. * single process or a set of processes contained in a pipeline. In the
  3165. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3166. * array of pids.
  3167. */
  3168. struct procstat {
  3169. pid_t ps_pid; /* process id */
  3170. int ps_status; /* last process status from wait() */
  3171. char *ps_cmd; /* text of command being run */
  3172. };
  3173. struct job {
  3174. struct procstat ps0; /* status of process */
  3175. struct procstat *ps; /* status of processes when more than one */
  3176. #if JOBS
  3177. int stopstatus; /* status of a stopped job */
  3178. #endif
  3179. unsigned nprocs; /* number of processes */
  3180. #define JOBRUNNING 0 /* at least one proc running */
  3181. #define JOBSTOPPED 1 /* all procs are stopped */
  3182. #define JOBDONE 2 /* all procs are completed */
  3183. unsigned
  3184. state: 8,
  3185. #if JOBS
  3186. sigint: 1, /* job was killed by SIGINT */
  3187. jobctl: 1, /* job running under job control */
  3188. #endif
  3189. waited: 1, /* true if this entry has been waited for */
  3190. used: 1, /* true if this entry is in used */
  3191. changed: 1; /* true if status has changed */
  3192. struct job *prev_job; /* previous job */
  3193. };
  3194. static struct job *makejob(/*union node *,*/ int);
  3195. static int forkshell(struct job *, union node *, int);
  3196. static int waitforjob(struct job *);
  3197. #if !JOBS
  3198. enum { doing_jobctl = 0 };
  3199. #define setjobctl(on) do {} while (0)
  3200. #else
  3201. static smallint doing_jobctl; //references:8
  3202. static void setjobctl(int);
  3203. #endif
  3204. /*
  3205. * Ignore a signal.
  3206. */
  3207. static void
  3208. ignoresig(int signo)
  3209. {
  3210. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3211. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3212. /* No, need to do it */
  3213. signal(signo, SIG_IGN);
  3214. }
  3215. sigmode[signo - 1] = S_HARD_IGN;
  3216. }
  3217. /*
  3218. * Only one usage site - in setsignal()
  3219. */
  3220. static void
  3221. signal_handler(int signo)
  3222. {
  3223. if (signo == SIGCHLD) {
  3224. got_sigchld = 1;
  3225. if (!trap[SIGCHLD])
  3226. return;
  3227. }
  3228. gotsig[signo - 1] = 1;
  3229. pending_sig = signo;
  3230. if (signo == SIGINT && !trap[SIGINT]) {
  3231. if (!suppress_int) {
  3232. pending_sig = 0;
  3233. raise_interrupt(); /* does not return */
  3234. }
  3235. pending_int = 1;
  3236. }
  3237. }
  3238. /*
  3239. * Set the signal handler for the specified signal. The routine figures
  3240. * out what it should be set to.
  3241. */
  3242. static void
  3243. setsignal(int signo)
  3244. {
  3245. char *t;
  3246. char cur_act, new_act;
  3247. struct sigaction act;
  3248. t = trap[signo];
  3249. new_act = S_DFL;
  3250. if (t != NULL) { /* trap for this sig is set */
  3251. new_act = S_CATCH;
  3252. if (t[0] == '\0') /* trap is "": ignore this sig */
  3253. new_act = S_IGN;
  3254. }
  3255. if (rootshell && new_act == S_DFL) {
  3256. switch (signo) {
  3257. case SIGINT:
  3258. if (iflag || minusc || sflag == 0)
  3259. new_act = S_CATCH;
  3260. break;
  3261. case SIGQUIT:
  3262. #if DEBUG
  3263. if (debug)
  3264. break;
  3265. #endif
  3266. /* man bash:
  3267. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3268. * commands run by bash have signal handlers
  3269. * set to the values inherited by the shell
  3270. * from its parent". */
  3271. new_act = S_IGN;
  3272. break;
  3273. case SIGTERM:
  3274. if (iflag)
  3275. new_act = S_IGN;
  3276. break;
  3277. #if JOBS
  3278. case SIGTSTP:
  3279. case SIGTTOU:
  3280. if (mflag)
  3281. new_act = S_IGN;
  3282. break;
  3283. #endif
  3284. }
  3285. }
  3286. /* if !rootshell, we reset SIGQUIT to DFL,
  3287. * whereas we have to restore it to what shell got on entry.
  3288. * This is handled by the fact that if signal was IGNored on entry,
  3289. * then cur_act is S_HARD_IGN and we never change its sigaction
  3290. * (see code below).
  3291. */
  3292. if (signo == SIGCHLD)
  3293. new_act = S_CATCH;
  3294. t = &sigmode[signo - 1];
  3295. cur_act = *t;
  3296. if (cur_act == 0) {
  3297. /* current setting is not yet known */
  3298. if (sigaction(signo, NULL, &act)) {
  3299. /* pretend it worked; maybe we should give a warning,
  3300. * but other shells don't. We don't alter sigmode,
  3301. * so we retry every time.
  3302. * btw, in Linux it never fails. --vda */
  3303. return;
  3304. }
  3305. if (act.sa_handler == SIG_IGN) {
  3306. cur_act = S_HARD_IGN;
  3307. if (mflag
  3308. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3309. ) {
  3310. cur_act = S_IGN; /* don't hard ignore these */
  3311. }
  3312. }
  3313. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3314. /* installing SIG_DFL over SIG_DFL is a no-op */
  3315. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3316. *t = S_DFL;
  3317. return;
  3318. }
  3319. }
  3320. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3321. return;
  3322. *t = new_act;
  3323. act.sa_handler = SIG_DFL;
  3324. switch (new_act) {
  3325. case S_CATCH:
  3326. act.sa_handler = signal_handler;
  3327. break;
  3328. case S_IGN:
  3329. act.sa_handler = SIG_IGN;
  3330. break;
  3331. }
  3332. /* flags and mask matter only if !DFL and !IGN, but we do it
  3333. * for all cases for more deterministic behavior:
  3334. */
  3335. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3336. sigfillset(&act.sa_mask);
  3337. sigaction_set(signo, &act);
  3338. }
  3339. /* mode flags for set_curjob */
  3340. #define CUR_DELETE 2
  3341. #define CUR_RUNNING 1
  3342. #define CUR_STOPPED 0
  3343. #if JOBS
  3344. /* pgrp of shell on invocation */
  3345. static int initialpgrp; //references:2
  3346. static int ttyfd = -1; //5
  3347. #endif
  3348. /* array of jobs */
  3349. static struct job *jobtab; //5
  3350. /* size of array */
  3351. static unsigned njobs; //4
  3352. /* current job */
  3353. static struct job *curjob; //lots
  3354. /* number of presumed living untracked jobs */
  3355. static int jobless; //4
  3356. #if 0
  3357. /* Bash has a feature: it restores termios after a successful wait for
  3358. * a foreground job which had at least one stopped or sigkilled member.
  3359. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3360. * properly restoring tty state. Should we do this too?
  3361. * A reproducer: ^Z an interactive python:
  3362. *
  3363. * # python
  3364. * Python 2.7.12 (...)
  3365. * >>> ^Z
  3366. * { python leaves tty in -icanon -echo state. We do survive that... }
  3367. * [1]+ Stopped python
  3368. * { ...however, next program (python #2) does not survive it well: }
  3369. * # python
  3370. * Python 2.7.12 (...)
  3371. * >>> Traceback (most recent call last):
  3372. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3373. * File "<stdin>", line 1, in <module>
  3374. * NameError: name 'qwerty' is not defined
  3375. *
  3376. * The implementation below is modeled on bash code and seems to work.
  3377. * However, I'm not sure we should do this. For one: what if I'd fg
  3378. * the stopped python instead? It'll be confused by "restored" tty state.
  3379. */
  3380. static struct termios shell_tty_info;
  3381. static void
  3382. get_tty_state(void)
  3383. {
  3384. if (rootshell && ttyfd >= 0)
  3385. tcgetattr(ttyfd, &shell_tty_info);
  3386. }
  3387. static void
  3388. set_tty_state(void)
  3389. {
  3390. /* if (rootshell) - caller ensures this */
  3391. if (ttyfd >= 0)
  3392. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3393. }
  3394. static int
  3395. job_signal_status(struct job *jp)
  3396. {
  3397. int status;
  3398. unsigned i;
  3399. struct procstat *ps = jp->ps;
  3400. for (i = 0; i < jp->nprocs; i++) {
  3401. status = ps[i].ps_status;
  3402. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3403. return status;
  3404. }
  3405. return 0;
  3406. }
  3407. static void
  3408. restore_tty_if_stopped_or_signaled(struct job *jp)
  3409. {
  3410. //TODO: check what happens if we come from waitforjob() in expbackq()
  3411. if (rootshell) {
  3412. int s = job_signal_status(jp);
  3413. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3414. set_tty_state();
  3415. }
  3416. }
  3417. #else
  3418. # define get_tty_state() ((void)0)
  3419. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3420. #endif
  3421. static void
  3422. set_curjob(struct job *jp, unsigned mode)
  3423. {
  3424. struct job *jp1;
  3425. struct job **jpp, **curp;
  3426. /* first remove from list */
  3427. jpp = curp = &curjob;
  3428. while (1) {
  3429. jp1 = *jpp;
  3430. if (jp1 == jp)
  3431. break;
  3432. jpp = &jp1->prev_job;
  3433. }
  3434. *jpp = jp1->prev_job;
  3435. /* Then re-insert in correct position */
  3436. jpp = curp;
  3437. switch (mode) {
  3438. default:
  3439. #if DEBUG
  3440. abort();
  3441. #endif
  3442. case CUR_DELETE:
  3443. /* job being deleted */
  3444. break;
  3445. case CUR_RUNNING:
  3446. /* newly created job or backgrounded job,
  3447. * put after all stopped jobs.
  3448. */
  3449. while (1) {
  3450. jp1 = *jpp;
  3451. #if JOBS
  3452. if (!jp1 || jp1->state != JOBSTOPPED)
  3453. #endif
  3454. break;
  3455. jpp = &jp1->prev_job;
  3456. }
  3457. /* FALLTHROUGH */
  3458. #if JOBS
  3459. case CUR_STOPPED:
  3460. #endif
  3461. /* newly stopped job - becomes curjob */
  3462. jp->prev_job = *jpp;
  3463. *jpp = jp;
  3464. break;
  3465. }
  3466. }
  3467. #if JOBS || DEBUG
  3468. static int
  3469. jobno(const struct job *jp)
  3470. {
  3471. return jp - jobtab + 1;
  3472. }
  3473. #endif
  3474. /*
  3475. * Convert a job name to a job structure.
  3476. */
  3477. #if !JOBS
  3478. #define getjob(name, getctl) getjob(name)
  3479. #endif
  3480. static struct job *
  3481. getjob(const char *name, int getctl)
  3482. {
  3483. struct job *jp;
  3484. struct job *found;
  3485. const char *err_msg = "%s: no such job";
  3486. unsigned num;
  3487. int c;
  3488. const char *p;
  3489. char *(*match)(const char *, const char *);
  3490. jp = curjob;
  3491. p = name;
  3492. if (!p)
  3493. goto currentjob;
  3494. if (*p != '%')
  3495. goto err;
  3496. c = *++p;
  3497. if (!c)
  3498. goto currentjob;
  3499. if (!p[1]) {
  3500. if (c == '+' || c == '%') {
  3501. currentjob:
  3502. err_msg = "No current job";
  3503. goto check;
  3504. }
  3505. if (c == '-') {
  3506. if (jp)
  3507. jp = jp->prev_job;
  3508. err_msg = "No previous job";
  3509. check:
  3510. if (!jp)
  3511. goto err;
  3512. goto gotit;
  3513. }
  3514. }
  3515. if (is_number(p)) {
  3516. num = atoi(p);
  3517. if (num > 0 && num <= njobs) {
  3518. jp = jobtab + num - 1;
  3519. if (jp->used)
  3520. goto gotit;
  3521. goto err;
  3522. }
  3523. }
  3524. match = prefix;
  3525. if (*p == '?') {
  3526. match = strstr;
  3527. p++;
  3528. }
  3529. found = NULL;
  3530. while (jp) {
  3531. if (match(jp->ps[0].ps_cmd, p)) {
  3532. if (found)
  3533. goto err;
  3534. found = jp;
  3535. err_msg = "%s: ambiguous";
  3536. }
  3537. jp = jp->prev_job;
  3538. }
  3539. if (!found)
  3540. goto err;
  3541. jp = found;
  3542. gotit:
  3543. #if JOBS
  3544. err_msg = "job %s not created under job control";
  3545. if (getctl && jp->jobctl == 0)
  3546. goto err;
  3547. #endif
  3548. return jp;
  3549. err:
  3550. ash_msg_and_raise_error(err_msg, name);
  3551. }
  3552. /*
  3553. * Mark a job structure as unused.
  3554. */
  3555. static void
  3556. freejob(struct job *jp)
  3557. {
  3558. struct procstat *ps;
  3559. int i;
  3560. INT_OFF;
  3561. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3562. if (ps->ps_cmd != nullstr)
  3563. free(ps->ps_cmd);
  3564. }
  3565. if (jp->ps != &jp->ps0)
  3566. free(jp->ps);
  3567. jp->used = 0;
  3568. set_curjob(jp, CUR_DELETE);
  3569. INT_ON;
  3570. }
  3571. #if JOBS
  3572. static void
  3573. xtcsetpgrp(int fd, pid_t pgrp)
  3574. {
  3575. if (tcsetpgrp(fd, pgrp))
  3576. ash_msg_and_raise_perror("can't set tty process group");
  3577. }
  3578. /*
  3579. * Turn job control on and off.
  3580. *
  3581. * Note: This code assumes that the third arg to ioctl is a character
  3582. * pointer, which is true on Berkeley systems but not System V. Since
  3583. * System V doesn't have job control yet, this isn't a problem now.
  3584. *
  3585. * Called with interrupts off.
  3586. */
  3587. static void
  3588. setjobctl(int on)
  3589. {
  3590. int fd;
  3591. int pgrp;
  3592. if (on == doing_jobctl || rootshell == 0)
  3593. return;
  3594. if (on) {
  3595. int ofd;
  3596. ofd = fd = open(_PATH_TTY, O_RDWR);
  3597. if (fd < 0) {
  3598. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3599. * That sometimes helps to acquire controlling tty.
  3600. * Obviously, a workaround for bugs when someone
  3601. * failed to provide a controlling tty to bash! :) */
  3602. fd = 2;
  3603. while (!isatty(fd))
  3604. if (--fd < 0)
  3605. goto out;
  3606. }
  3607. /* fd is a tty at this point */
  3608. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3609. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3610. close(ofd);
  3611. if (fd < 0)
  3612. goto out; /* F_DUPFD failed */
  3613. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3614. close_on_exec_on(fd);
  3615. while (1) { /* while we are in the background */
  3616. pgrp = tcgetpgrp(fd);
  3617. if (pgrp < 0) {
  3618. out:
  3619. ash_msg("can't access tty; job control turned off");
  3620. mflag = on = 0;
  3621. goto close;
  3622. }
  3623. if (pgrp == getpgrp())
  3624. break;
  3625. killpg(0, SIGTTIN);
  3626. }
  3627. initialpgrp = pgrp;
  3628. setsignal(SIGTSTP);
  3629. setsignal(SIGTTOU);
  3630. setsignal(SIGTTIN);
  3631. pgrp = rootpid;
  3632. setpgid(0, pgrp);
  3633. xtcsetpgrp(fd, pgrp);
  3634. } else {
  3635. /* turning job control off */
  3636. fd = ttyfd;
  3637. pgrp = initialpgrp;
  3638. /* was xtcsetpgrp, but this can make exiting ash
  3639. * loop forever if pty is already deleted */
  3640. tcsetpgrp(fd, pgrp);
  3641. setpgid(0, pgrp);
  3642. setsignal(SIGTSTP);
  3643. setsignal(SIGTTOU);
  3644. setsignal(SIGTTIN);
  3645. close:
  3646. if (fd >= 0)
  3647. close(fd);
  3648. fd = -1;
  3649. }
  3650. ttyfd = fd;
  3651. doing_jobctl = on;
  3652. }
  3653. static int FAST_FUNC
  3654. killcmd(int argc, char **argv)
  3655. {
  3656. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3657. int i = 1;
  3658. do {
  3659. if (argv[i][0] == '%') {
  3660. /*
  3661. * "kill %N" - job kill
  3662. * Converting to pgrp / pid kill
  3663. */
  3664. struct job *jp;
  3665. char *dst;
  3666. int j, n;
  3667. jp = getjob(argv[i], 0);
  3668. /*
  3669. * In jobs started under job control, we signal
  3670. * entire process group by kill -PGRP_ID.
  3671. * This happens, f.e., in interactive shell.
  3672. *
  3673. * Otherwise, we signal each child via
  3674. * kill PID1 PID2 PID3.
  3675. * Testcases:
  3676. * sh -c 'sleep 1|sleep 1 & kill %1'
  3677. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3678. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3679. */
  3680. n = jp->nprocs; /* can't be 0 (I hope) */
  3681. if (jp->jobctl)
  3682. n = 1;
  3683. dst = alloca(n * sizeof(int)*4);
  3684. argv[i] = dst;
  3685. for (j = 0; j < n; j++) {
  3686. struct procstat *ps = &jp->ps[j];
  3687. /* Skip non-running and not-stopped members
  3688. * (i.e. dead members) of the job
  3689. */
  3690. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3691. continue;
  3692. /*
  3693. * kill_main has matching code to expect
  3694. * leading space. Needed to not confuse
  3695. * negative pids with "kill -SIGNAL_NO" syntax
  3696. */
  3697. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3698. }
  3699. *dst = '\0';
  3700. }
  3701. } while (argv[++i]);
  3702. }
  3703. return kill_main(argc, argv);
  3704. }
  3705. static void
  3706. showpipe(struct job *jp /*, FILE *out*/)
  3707. {
  3708. struct procstat *ps;
  3709. struct procstat *psend;
  3710. psend = jp->ps + jp->nprocs;
  3711. for (ps = jp->ps + 1; ps < psend; ps++)
  3712. printf(" | %s", ps->ps_cmd);
  3713. newline_and_flush(stdout);
  3714. flush_stdout_stderr();
  3715. }
  3716. static int
  3717. restartjob(struct job *jp, int mode)
  3718. {
  3719. struct procstat *ps;
  3720. int i;
  3721. int status;
  3722. pid_t pgid;
  3723. INT_OFF;
  3724. if (jp->state == JOBDONE)
  3725. goto out;
  3726. jp->state = JOBRUNNING;
  3727. pgid = jp->ps[0].ps_pid;
  3728. if (mode == FORK_FG) {
  3729. get_tty_state();
  3730. xtcsetpgrp(ttyfd, pgid);
  3731. }
  3732. killpg(pgid, SIGCONT);
  3733. ps = jp->ps;
  3734. i = jp->nprocs;
  3735. do {
  3736. if (WIFSTOPPED(ps->ps_status)) {
  3737. ps->ps_status = -1;
  3738. }
  3739. ps++;
  3740. } while (--i);
  3741. out:
  3742. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3743. INT_ON;
  3744. return status;
  3745. }
  3746. static int FAST_FUNC
  3747. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3748. {
  3749. struct job *jp;
  3750. int mode;
  3751. int retval;
  3752. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3753. nextopt(nullstr);
  3754. argv = argptr;
  3755. do {
  3756. jp = getjob(*argv, 1);
  3757. if (mode == FORK_BG) {
  3758. set_curjob(jp, CUR_RUNNING);
  3759. printf("[%d] ", jobno(jp));
  3760. }
  3761. out1str(jp->ps[0].ps_cmd);
  3762. showpipe(jp /*, stdout*/);
  3763. retval = restartjob(jp, mode);
  3764. } while (*argv && *++argv);
  3765. return retval;
  3766. }
  3767. #endif
  3768. static int
  3769. sprint_status48(char *s, int status, int sigonly)
  3770. {
  3771. int col;
  3772. int st;
  3773. col = 0;
  3774. if (!WIFEXITED(status)) {
  3775. #if JOBS
  3776. if (WIFSTOPPED(status))
  3777. st = WSTOPSIG(status);
  3778. else
  3779. #endif
  3780. st = WTERMSIG(status);
  3781. if (sigonly) {
  3782. if (st == SIGINT || st == SIGPIPE)
  3783. goto out;
  3784. #if JOBS
  3785. if (WIFSTOPPED(status))
  3786. goto out;
  3787. #endif
  3788. }
  3789. st &= 0x7f;
  3790. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3791. col = fmtstr(s, 32, strsignal(st));
  3792. if (WCOREDUMP(status)) {
  3793. strcpy(s + col, " (core dumped)");
  3794. col += sizeof(" (core dumped)")-1;
  3795. }
  3796. } else if (!sigonly) {
  3797. st = WEXITSTATUS(status);
  3798. col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3799. }
  3800. out:
  3801. return col;
  3802. }
  3803. static int
  3804. wait_block_or_sig(int *status)
  3805. {
  3806. int pid;
  3807. do {
  3808. sigset_t mask;
  3809. /* Poll all children for changes in their state */
  3810. got_sigchld = 0;
  3811. /* if job control is active, accept stopped processes too */
  3812. pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
  3813. if (pid != 0)
  3814. break; /* Error (e.g. EINTR, ECHILD) or pid */
  3815. /* Children exist, but none are ready. Sleep until interesting signal */
  3816. #if 1
  3817. sigfillset(&mask);
  3818. sigprocmask2(SIG_SETMASK, &mask); /* mask is updated */
  3819. while (!got_sigchld && !pending_sig)
  3820. sigsuspend(&mask);
  3821. sigprocmask(SIG_SETMASK, &mask, NULL);
  3822. #else /* unsafe: a signal can set pending_sig after check, but before pause() */
  3823. while (!got_sigchld && !pending_sig)
  3824. pause();
  3825. #endif
  3826. /* If it was SIGCHLD, poll children again */
  3827. } while (got_sigchld);
  3828. return pid;
  3829. }
  3830. #define DOWAIT_NONBLOCK 0
  3831. #define DOWAIT_BLOCK 1
  3832. #define DOWAIT_BLOCK_OR_SIG 2
  3833. #if BASH_WAIT_N
  3834. # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
  3835. #endif
  3836. static int
  3837. dowait(int block, struct job *job)
  3838. {
  3839. int pid;
  3840. int status;
  3841. struct job *jp;
  3842. struct job *thisjob;
  3843. #if BASH_WAIT_N
  3844. bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
  3845. block = (block & ~DOWAIT_JOBSTATUS);
  3846. #endif
  3847. TRACE(("dowait(0x%x) called\n", block));
  3848. /* It's wrong to call waitpid() outside of INT_OFF region:
  3849. * signal can arrive just after syscall return and handler can
  3850. * longjmp away, losing stop/exit notification processing.
  3851. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3852. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3853. *
  3854. * However, for "wait" builtin it is wrong to simply call waitpid()
  3855. * in INT_OFF region: "wait" needs to wait for any running job
  3856. * to change state, but should exit on any trap too.
  3857. * In INT_OFF region, a signal just before syscall entry can set
  3858. * pending_sig variables, but we can't check them, and we would
  3859. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3860. *
  3861. * Because of this, we run inside INT_OFF, but use a special routine
  3862. * which combines waitpid() and sigsuspend().
  3863. * This is the reason why we need to have a handler for SIGCHLD:
  3864. * SIG_DFL handler does not wake sigsuspend().
  3865. */
  3866. INT_OFF;
  3867. if (block == DOWAIT_BLOCK_OR_SIG) {
  3868. pid = wait_block_or_sig(&status);
  3869. } else {
  3870. int wait_flags = 0;
  3871. if (block == DOWAIT_NONBLOCK)
  3872. wait_flags = WNOHANG;
  3873. /* if job control is active, accept stopped processes too */
  3874. if (doing_jobctl)
  3875. wait_flags |= WUNTRACED;
  3876. /* NB: _not_ safe_waitpid, we need to detect EINTR */
  3877. pid = waitpid(-1, &status, wait_flags);
  3878. }
  3879. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3880. pid, status, errno, strerror(errno)));
  3881. thisjob = NULL;
  3882. if (pid <= 0)
  3883. goto out;
  3884. for (jp = curjob; jp; jp = jp->prev_job) {
  3885. int jobstate;
  3886. struct procstat *ps;
  3887. struct procstat *psend;
  3888. if (jp->state == JOBDONE)
  3889. continue;
  3890. jobstate = JOBDONE;
  3891. ps = jp->ps;
  3892. psend = ps + jp->nprocs;
  3893. do {
  3894. if (ps->ps_pid == pid) {
  3895. TRACE(("Job %d: changing status of proc %d "
  3896. "from 0x%x to 0x%x\n",
  3897. jobno(jp), pid, ps->ps_status, status));
  3898. ps->ps_status = status;
  3899. thisjob = jp;
  3900. }
  3901. if (ps->ps_status == -1)
  3902. jobstate = JOBRUNNING;
  3903. #if JOBS
  3904. if (jobstate == JOBRUNNING)
  3905. continue;
  3906. if (WIFSTOPPED(ps->ps_status)) {
  3907. jp->stopstatus = ps->ps_status;
  3908. jobstate = JOBSTOPPED;
  3909. }
  3910. #endif
  3911. } while (++ps < psend);
  3912. if (!thisjob)
  3913. continue;
  3914. /* Found the job where one of its processes changed its state.
  3915. * Is there at least one live and running process in this job? */
  3916. if (jobstate != JOBRUNNING) {
  3917. /* No. All live processes in the job are stopped
  3918. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3919. */
  3920. thisjob->changed = 1;
  3921. if (thisjob->state != jobstate) {
  3922. TRACE(("Job %d: changing state from %d to %d\n",
  3923. jobno(thisjob), thisjob->state, jobstate));
  3924. thisjob->state = jobstate;
  3925. #if JOBS
  3926. if (jobstate == JOBSTOPPED)
  3927. set_curjob(thisjob, CUR_STOPPED);
  3928. #endif
  3929. }
  3930. }
  3931. goto out;
  3932. }
  3933. /* The process wasn't found in job list */
  3934. #if JOBS
  3935. if (!WIFSTOPPED(status))
  3936. jobless--;
  3937. #endif
  3938. out:
  3939. INT_ON;
  3940. #if BASH_WAIT_N
  3941. if (want_jobexitstatus) {
  3942. pid = -1;
  3943. if (thisjob && thisjob->state == JOBDONE)
  3944. pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
  3945. }
  3946. #endif
  3947. if (thisjob && thisjob == job) {
  3948. char s[48 + 1];
  3949. int len;
  3950. len = sprint_status48(s, status, 1);
  3951. if (len) {
  3952. s[len] = '\n';
  3953. s[len + 1] = '\0';
  3954. out2str(s);
  3955. }
  3956. }
  3957. return pid;
  3958. }
  3959. #if JOBS
  3960. static void
  3961. showjob(struct job *jp, int mode)
  3962. {
  3963. struct procstat *ps;
  3964. struct procstat *psend;
  3965. int col;
  3966. int indent_col;
  3967. char s[16 + 16 + 48];
  3968. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  3969. ps = jp->ps;
  3970. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3971. /* just output process (group) id of pipeline */
  3972. fprintf(out, "%d\n", ps->ps_pid);
  3973. return;
  3974. }
  3975. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3976. indent_col = col;
  3977. if (jp == curjob)
  3978. s[col - 3] = '+';
  3979. else if (curjob && jp == curjob->prev_job)
  3980. s[col - 3] = '-';
  3981. if (mode & SHOW_PIDS)
  3982. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3983. psend = ps + jp->nprocs;
  3984. if (jp->state == JOBRUNNING) {
  3985. strcpy(s + col, "Running");
  3986. col += sizeof("Running") - 1;
  3987. } else {
  3988. int status = psend[-1].ps_status;
  3989. if (jp->state == JOBSTOPPED)
  3990. status = jp->stopstatus;
  3991. col += sprint_status48(s + col, status, 0);
  3992. }
  3993. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3994. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3995. * or prints several "PID | <cmdN>" lines,
  3996. * depending on SHOW_PIDS bit.
  3997. * We do not print status of individual processes
  3998. * between PID and <cmdN>. bash does it, but not very well:
  3999. * first line shows overall job status, not process status,
  4000. * making it impossible to know 1st process status.
  4001. */
  4002. goto start;
  4003. do {
  4004. /* for each process */
  4005. s[0] = '\0';
  4006. col = 33;
  4007. if (mode & SHOW_PIDS)
  4008. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  4009. start:
  4010. fprintf(out, "%s%*c%s%s",
  4011. s,
  4012. 33 - col >= 0 ? 33 - col : 0, ' ',
  4013. ps == jp->ps ? "" : "| ",
  4014. ps->ps_cmd
  4015. );
  4016. } while (++ps != psend);
  4017. newline_and_flush(out);
  4018. jp->changed = 0;
  4019. if (jp->state == JOBDONE) {
  4020. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4021. freejob(jp);
  4022. }
  4023. }
  4024. /*
  4025. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4026. * statuses have changed since the last call to showjobs.
  4027. */
  4028. static void
  4029. showjobs(int mode)
  4030. {
  4031. struct job *jp;
  4032. TRACE(("showjobs(0x%x) called\n", mode));
  4033. /* Handle all finished jobs */
  4034. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4035. continue;
  4036. for (jp = curjob; jp; jp = jp->prev_job) {
  4037. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4038. showjob(jp, mode);
  4039. }
  4040. }
  4041. }
  4042. static int FAST_FUNC
  4043. jobscmd(int argc UNUSED_PARAM, char **argv)
  4044. {
  4045. int mode, m;
  4046. mode = 0;
  4047. while ((m = nextopt("lp")) != '\0') {
  4048. if (m == 'l')
  4049. mode |= SHOW_PIDS;
  4050. else
  4051. mode |= SHOW_ONLY_PGID;
  4052. }
  4053. argv = argptr;
  4054. if (*argv) {
  4055. do
  4056. showjob(getjob(*argv, 0), mode);
  4057. while (*++argv);
  4058. } else {
  4059. showjobs(mode);
  4060. }
  4061. return 0;
  4062. }
  4063. #endif /* JOBS */
  4064. /* Called only on finished or stopped jobs (no members are running) */
  4065. static int
  4066. getstatus(struct job *job)
  4067. {
  4068. int status;
  4069. int retval;
  4070. struct procstat *ps;
  4071. /* Fetch last member's status */
  4072. ps = job->ps + job->nprocs - 1;
  4073. status = ps->ps_status;
  4074. if (pipefail) {
  4075. /* "set -o pipefail" mode: use last _nonzero_ status */
  4076. while (status == 0 && --ps >= job->ps)
  4077. status = ps->ps_status;
  4078. }
  4079. retval = WEXITSTATUS(status);
  4080. if (!WIFEXITED(status)) {
  4081. #if JOBS
  4082. retval = WSTOPSIG(status);
  4083. if (!WIFSTOPPED(status))
  4084. #endif
  4085. {
  4086. /* XXX: limits number of signals */
  4087. retval = WTERMSIG(status);
  4088. #if JOBS
  4089. if (retval == SIGINT)
  4090. job->sigint = 1;
  4091. #endif
  4092. }
  4093. retval += 128;
  4094. }
  4095. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4096. jobno(job), job->nprocs, status, retval));
  4097. return retval;
  4098. }
  4099. static int FAST_FUNC
  4100. waitcmd(int argc UNUSED_PARAM, char **argv)
  4101. {
  4102. struct job *job;
  4103. int retval;
  4104. struct job *jp;
  4105. #if BASH_WAIT_N
  4106. int status;
  4107. char one = nextopt("n");
  4108. #else
  4109. nextopt(nullstr);
  4110. #endif
  4111. retval = 0;
  4112. argv = argptr;
  4113. if (!argv[0]) {
  4114. /* wait for all jobs / one job if -n */
  4115. for (;;) {
  4116. jp = curjob;
  4117. #if BASH_WAIT_N
  4118. if (one && !jp)
  4119. /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
  4120. retval = 127;
  4121. #endif
  4122. while (1) {
  4123. if (!jp) /* no running procs */
  4124. goto ret;
  4125. if (jp->state == JOBRUNNING)
  4126. break;
  4127. jp->waited = 1;
  4128. jp = jp->prev_job;
  4129. }
  4130. /* man bash:
  4131. * "When bash is waiting for an asynchronous command via
  4132. * the wait builtin, the reception of a signal for which a trap
  4133. * has been set will cause the wait builtin to return immediately
  4134. * with an exit status greater than 128, immediately after which
  4135. * the trap is executed."
  4136. */
  4137. #if BASH_WAIT_N
  4138. status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
  4139. #else
  4140. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4141. #endif
  4142. /* if child sends us a signal *and immediately exits*,
  4143. * dowait() returns pid > 0. Check this case,
  4144. * not "if (dowait() < 0)"!
  4145. */
  4146. if (pending_sig)
  4147. goto sigout;
  4148. #if BASH_WAIT_N
  4149. if (one) {
  4150. /* wait -n waits for one _job_, not one _process_.
  4151. * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
  4152. * should wait for 2 seconds. Not 1 or 3.
  4153. */
  4154. if (status != -1 && !WIFSTOPPED(status)) {
  4155. retval = WEXITSTATUS(status);
  4156. if (WIFSIGNALED(status))
  4157. retval = WTERMSIG(status) + 128;
  4158. goto ret;
  4159. }
  4160. }
  4161. #endif
  4162. }
  4163. }
  4164. retval = 127;
  4165. do {
  4166. if (**argv != '%') {
  4167. pid_t pid = number(*argv);
  4168. job = curjob;
  4169. while (1) {
  4170. if (!job)
  4171. goto repeat;
  4172. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4173. break;
  4174. job = job->prev_job;
  4175. }
  4176. } else {
  4177. job = getjob(*argv, 0);
  4178. }
  4179. /* loop until process terminated or stopped */
  4180. while (job->state == JOBRUNNING) {
  4181. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4182. if (pending_sig)
  4183. goto sigout;
  4184. }
  4185. job->waited = 1;
  4186. retval = getstatus(job);
  4187. repeat: ;
  4188. } while (*++argv);
  4189. ret:
  4190. return retval;
  4191. sigout:
  4192. retval = 128 + pending_sig;
  4193. return retval;
  4194. }
  4195. static struct job *
  4196. growjobtab(void)
  4197. {
  4198. size_t len;
  4199. ptrdiff_t offset;
  4200. struct job *jp, *jq;
  4201. len = njobs * sizeof(*jp);
  4202. jq = jobtab;
  4203. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4204. offset = (char *)jp - (char *)jq;
  4205. if (offset) {
  4206. /* Relocate pointers */
  4207. size_t l = len;
  4208. jq = (struct job *)((char *)jq + l);
  4209. while (l) {
  4210. l -= sizeof(*jp);
  4211. jq--;
  4212. #define joff(p) ((struct job *)((char *)(p) + l))
  4213. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4214. if (joff(jp)->ps == &jq->ps0)
  4215. jmove(joff(jp)->ps);
  4216. if (joff(jp)->prev_job)
  4217. jmove(joff(jp)->prev_job);
  4218. }
  4219. if (curjob)
  4220. jmove(curjob);
  4221. #undef joff
  4222. #undef jmove
  4223. }
  4224. njobs += 4;
  4225. jobtab = jp;
  4226. jp = (struct job *)((char *)jp + len);
  4227. jq = jp + 3;
  4228. do {
  4229. jq->used = 0;
  4230. } while (--jq >= jp);
  4231. return jp;
  4232. }
  4233. /*
  4234. * Return a new job structure.
  4235. * Called with interrupts off.
  4236. */
  4237. static struct job *
  4238. makejob(/*union node *node,*/ int nprocs)
  4239. {
  4240. int i;
  4241. struct job *jp;
  4242. for (i = njobs, jp = jobtab; ; jp++) {
  4243. if (--i < 0) {
  4244. jp = growjobtab();
  4245. break;
  4246. }
  4247. if (jp->used == 0)
  4248. break;
  4249. if (jp->state != JOBDONE || !jp->waited)
  4250. continue;
  4251. #if JOBS
  4252. if (doing_jobctl)
  4253. continue;
  4254. #endif
  4255. freejob(jp);
  4256. break;
  4257. }
  4258. memset(jp, 0, sizeof(*jp));
  4259. #if JOBS
  4260. /* jp->jobctl is a bitfield.
  4261. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4262. if (doing_jobctl)
  4263. jp->jobctl = 1;
  4264. #endif
  4265. jp->prev_job = curjob;
  4266. curjob = jp;
  4267. jp->used = 1;
  4268. jp->ps = &jp->ps0;
  4269. if (nprocs > 1) {
  4270. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4271. }
  4272. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4273. jobno(jp)));
  4274. return jp;
  4275. }
  4276. #if JOBS
  4277. /*
  4278. * Return a string identifying a command (to be printed by the
  4279. * jobs command).
  4280. */
  4281. static char *cmdnextc;
  4282. static void
  4283. cmdputs(const char *s)
  4284. {
  4285. static const char vstype[VSTYPE + 1][3] = {
  4286. "", "}", "-", "+", "?", "=",
  4287. "%", "%%", "#", "##"
  4288. IF_BASH_SUBSTR(, ":")
  4289. IF_BASH_PATTERN_SUBST(, "/", "//")
  4290. };
  4291. const char *p, *str;
  4292. char cc[2];
  4293. char *nextc;
  4294. unsigned char c;
  4295. unsigned char subtype = 0;
  4296. int quoted = 0;
  4297. cc[1] = '\0';
  4298. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4299. p = s;
  4300. while ((c = *p++) != '\0') {
  4301. str = NULL;
  4302. switch (c) {
  4303. case CTLESC:
  4304. c = *p++;
  4305. break;
  4306. case CTLVAR:
  4307. subtype = *p++;
  4308. if ((subtype & VSTYPE) == VSLENGTH)
  4309. str = "${#";
  4310. else
  4311. str = "${";
  4312. goto dostr;
  4313. case CTLENDVAR:
  4314. str = "\"}" + !(quoted & 1);
  4315. quoted >>= 1;
  4316. subtype = 0;
  4317. goto dostr;
  4318. case CTLBACKQ:
  4319. str = "$(...)";
  4320. goto dostr;
  4321. #if ENABLE_FEATURE_SH_MATH
  4322. case CTLARI:
  4323. str = "$((";
  4324. goto dostr;
  4325. case CTLENDARI:
  4326. str = "))";
  4327. goto dostr;
  4328. #endif
  4329. case CTLQUOTEMARK:
  4330. quoted ^= 1;
  4331. c = '"';
  4332. break;
  4333. case '=':
  4334. if (subtype == 0)
  4335. break;
  4336. if ((subtype & VSTYPE) != VSNORMAL)
  4337. quoted <<= 1;
  4338. str = vstype[subtype & VSTYPE];
  4339. if (subtype & VSNUL)
  4340. c = ':';
  4341. else
  4342. goto checkstr;
  4343. break;
  4344. case '\'':
  4345. case '\\':
  4346. case '"':
  4347. case '$':
  4348. /* These can only happen inside quotes */
  4349. cc[0] = c;
  4350. str = cc;
  4351. //FIXME:
  4352. // $ true $$ &
  4353. // $ <cr>
  4354. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4355. c = '\\';
  4356. break;
  4357. default:
  4358. break;
  4359. }
  4360. USTPUTC(c, nextc);
  4361. checkstr:
  4362. if (!str)
  4363. continue;
  4364. dostr:
  4365. while ((c = *str++) != '\0') {
  4366. USTPUTC(c, nextc);
  4367. }
  4368. } /* while *p++ not NUL */
  4369. if (quoted & 1) {
  4370. USTPUTC('"', nextc);
  4371. }
  4372. *nextc = 0;
  4373. cmdnextc = nextc;
  4374. }
  4375. /* cmdtxt() and cmdlist() call each other */
  4376. static void cmdtxt(union node *n);
  4377. static void
  4378. cmdlist(union node *np, int sep)
  4379. {
  4380. for (; np; np = np->narg.next) {
  4381. if (!sep)
  4382. cmdputs(" ");
  4383. cmdtxt(np);
  4384. if (sep && np->narg.next)
  4385. cmdputs(" ");
  4386. }
  4387. }
  4388. static void
  4389. cmdtxt(union node *n)
  4390. {
  4391. union node *np;
  4392. struct nodelist *lp;
  4393. const char *p;
  4394. if (!n)
  4395. return;
  4396. switch (n->type) {
  4397. default:
  4398. #if DEBUG
  4399. abort();
  4400. #endif
  4401. case NPIPE:
  4402. lp = n->npipe.cmdlist;
  4403. for (;;) {
  4404. cmdtxt(lp->n);
  4405. lp = lp->next;
  4406. if (!lp)
  4407. break;
  4408. cmdputs(" | ");
  4409. }
  4410. break;
  4411. case NSEMI:
  4412. p = "; ";
  4413. goto binop;
  4414. case NAND:
  4415. p = " && ";
  4416. goto binop;
  4417. case NOR:
  4418. p = " || ";
  4419. binop:
  4420. cmdtxt(n->nbinary.ch1);
  4421. cmdputs(p);
  4422. n = n->nbinary.ch2;
  4423. goto donode;
  4424. case NREDIR:
  4425. case NBACKGND:
  4426. n = n->nredir.n;
  4427. goto donode;
  4428. case NNOT:
  4429. cmdputs("!");
  4430. n = n->nnot.com;
  4431. donode:
  4432. cmdtxt(n);
  4433. break;
  4434. case NIF:
  4435. cmdputs("if ");
  4436. cmdtxt(n->nif.test);
  4437. cmdputs("; then ");
  4438. if (n->nif.elsepart) {
  4439. cmdtxt(n->nif.ifpart);
  4440. cmdputs("; else ");
  4441. n = n->nif.elsepart;
  4442. } else {
  4443. n = n->nif.ifpart;
  4444. }
  4445. p = "; fi";
  4446. goto dotail;
  4447. case NSUBSHELL:
  4448. cmdputs("(");
  4449. n = n->nredir.n;
  4450. p = ")";
  4451. goto dotail;
  4452. case NWHILE:
  4453. p = "while ";
  4454. goto until;
  4455. case NUNTIL:
  4456. p = "until ";
  4457. until:
  4458. cmdputs(p);
  4459. cmdtxt(n->nbinary.ch1);
  4460. n = n->nbinary.ch2;
  4461. p = "; done";
  4462. dodo:
  4463. cmdputs("; do ");
  4464. dotail:
  4465. cmdtxt(n);
  4466. goto dotail2;
  4467. case NFOR:
  4468. cmdputs("for ");
  4469. cmdputs(n->nfor.var);
  4470. cmdputs(" in ");
  4471. cmdlist(n->nfor.args, 1);
  4472. n = n->nfor.body;
  4473. p = "; done";
  4474. goto dodo;
  4475. case NDEFUN:
  4476. cmdputs(n->ndefun.text);
  4477. p = "() { ... }";
  4478. goto dotail2;
  4479. case NCMD:
  4480. cmdlist(n->ncmd.args, 1);
  4481. cmdlist(n->ncmd.redirect, 0);
  4482. break;
  4483. case NARG:
  4484. p = n->narg.text;
  4485. dotail2:
  4486. cmdputs(p);
  4487. break;
  4488. case NHERE:
  4489. case NXHERE:
  4490. p = "<<...";
  4491. goto dotail2;
  4492. case NCASE:
  4493. cmdputs("case ");
  4494. cmdputs(n->ncase.expr->narg.text);
  4495. cmdputs(" in ");
  4496. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4497. cmdtxt(np->nclist.pattern);
  4498. cmdputs(") ");
  4499. cmdtxt(np->nclist.body);
  4500. cmdputs(";; ");
  4501. }
  4502. p = "esac";
  4503. goto dotail2;
  4504. case NTO:
  4505. p = ">";
  4506. goto redir;
  4507. case NCLOBBER:
  4508. p = ">|";
  4509. goto redir;
  4510. case NAPPEND:
  4511. p = ">>";
  4512. goto redir;
  4513. #if BASH_REDIR_OUTPUT
  4514. case NTO2:
  4515. #endif
  4516. case NTOFD:
  4517. p = ">&";
  4518. goto redir;
  4519. case NFROM:
  4520. p = "<";
  4521. goto redir;
  4522. case NFROMFD:
  4523. p = "<&";
  4524. goto redir;
  4525. case NFROMTO:
  4526. p = "<>";
  4527. redir:
  4528. cmdputs(utoa(n->nfile.fd));
  4529. cmdputs(p);
  4530. if (n->type == NTOFD || n->type == NFROMFD) {
  4531. if (n->ndup.dupfd >= 0)
  4532. cmdputs(utoa(n->ndup.dupfd));
  4533. else
  4534. cmdputs("-");
  4535. break;
  4536. }
  4537. n = n->nfile.fname;
  4538. goto donode;
  4539. }
  4540. }
  4541. static char *
  4542. commandtext(union node *n)
  4543. {
  4544. char *name;
  4545. STARTSTACKSTR(cmdnextc);
  4546. cmdtxt(n);
  4547. name = stackblock();
  4548. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4549. return ckstrdup(name);
  4550. }
  4551. #endif /* JOBS */
  4552. /*
  4553. * Fork off a subshell. If we are doing job control, give the subshell its
  4554. * own process group. Jp is a job structure that the job is to be added to.
  4555. * N is the command that will be evaluated by the child. Both jp and n may
  4556. * be NULL. The mode parameter can be one of the following:
  4557. * FORK_FG - Fork off a foreground process.
  4558. * FORK_BG - Fork off a background process.
  4559. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4560. * process group even if job control is on.
  4561. *
  4562. * When job control is turned off, background processes have their standard
  4563. * input redirected to /dev/null (except for the second and later processes
  4564. * in a pipeline).
  4565. *
  4566. * Called with interrupts off.
  4567. */
  4568. /*
  4569. * Clear traps on a fork.
  4570. */
  4571. static void
  4572. clear_traps(void)
  4573. {
  4574. char **tp;
  4575. INT_OFF;
  4576. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4577. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4578. if (trap_ptr == trap)
  4579. free(*tp);
  4580. /* else: it "belongs" to trap_ptr vector, don't free */
  4581. *tp = NULL;
  4582. if ((tp - trap) != 0)
  4583. setsignal(tp - trap);
  4584. }
  4585. }
  4586. may_have_traps = 0;
  4587. INT_ON;
  4588. }
  4589. /* Lives far away from here, needed for forkchild */
  4590. static void closescript(void);
  4591. /* Called after fork(), in child */
  4592. /* jp and n are NULL when called by openhere() for heredoc support */
  4593. static NOINLINE void
  4594. forkchild(struct job *jp, union node *n, int mode)
  4595. {
  4596. int oldlvl;
  4597. TRACE(("Child shell %d\n", getpid()));
  4598. oldlvl = shlvl;
  4599. shlvl++;
  4600. /* man bash: "Non-builtin commands run by bash have signal handlers
  4601. * set to the values inherited by the shell from its parent".
  4602. * Do we do it correctly? */
  4603. closescript();
  4604. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4605. && n && n->type == NCMD /* is it single cmd? */
  4606. /* && n->ncmd.args->type == NARG - always true? */
  4607. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4608. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4609. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4610. ) {
  4611. TRACE(("Trap hack\n"));
  4612. /* Awful hack for `trap` or $(trap).
  4613. *
  4614. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4615. * contains an example where "trap" is executed in a subshell:
  4616. *
  4617. * save_traps=$(trap)
  4618. * ...
  4619. * eval "$save_traps"
  4620. *
  4621. * Standard does not say that "trap" in subshell shall print
  4622. * parent shell's traps. It only says that its output
  4623. * must have suitable form, but then, in the above example
  4624. * (which is not supposed to be normative), it implies that.
  4625. *
  4626. * bash (and probably other shell) does implement it
  4627. * (traps are reset to defaults, but "trap" still shows them),
  4628. * but as a result, "trap" logic is hopelessly messed up:
  4629. *
  4630. * # trap
  4631. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4632. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4633. * # true | trap <--- trap is in subshell - no output (ditto)
  4634. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4635. * trap -- 'echo Ho' SIGWINCH
  4636. * # echo `(trap)` <--- in subshell in subshell - output
  4637. * trap -- 'echo Ho' SIGWINCH
  4638. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4639. * trap -- 'echo Ho' SIGWINCH
  4640. *
  4641. * The rules when to forget and when to not forget traps
  4642. * get really complex and nonsensical.
  4643. *
  4644. * Our solution: ONLY bare $(trap) or `trap` is special.
  4645. */
  4646. /* Save trap handler strings for trap builtin to print */
  4647. trap_ptr = xmemdup(trap, sizeof(trap));
  4648. /* Fall through into clearing traps */
  4649. }
  4650. clear_traps();
  4651. #if JOBS
  4652. /* do job control only in root shell */
  4653. doing_jobctl = 0;
  4654. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4655. pid_t pgrp;
  4656. if (jp->nprocs == 0)
  4657. pgrp = getpid();
  4658. else
  4659. pgrp = jp->ps[0].ps_pid;
  4660. /* this can fail because we are doing it in the parent also */
  4661. setpgid(0, pgrp);
  4662. if (mode == FORK_FG)
  4663. xtcsetpgrp(ttyfd, pgrp);
  4664. setsignal(SIGTSTP);
  4665. setsignal(SIGTTOU);
  4666. } else
  4667. #endif
  4668. if (mode == FORK_BG) {
  4669. /* man bash: "When job control is not in effect,
  4670. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4671. ignoresig(SIGINT);
  4672. ignoresig(SIGQUIT);
  4673. if (jp->nprocs == 0) {
  4674. close(0);
  4675. if (open(bb_dev_null, O_RDONLY) != 0)
  4676. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4677. }
  4678. }
  4679. if (oldlvl == 0) {
  4680. if (iflag) { /* why if iflag only? */
  4681. setsignal(SIGINT);
  4682. setsignal(SIGTERM);
  4683. }
  4684. /* man bash:
  4685. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4686. * commands run by bash have signal handlers
  4687. * set to the values inherited by the shell
  4688. * from its parent".
  4689. * Take care of the second rule: */
  4690. setsignal(SIGQUIT);
  4691. }
  4692. #if JOBS
  4693. if (n && n->type == NCMD
  4694. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4695. ) {
  4696. TRACE(("Job hack\n"));
  4697. /* "jobs": we do not want to clear job list for it,
  4698. * instead we remove only _its_ own_ job from job list.
  4699. * This makes "jobs .... | cat" more useful.
  4700. */
  4701. freejob(curjob);
  4702. return;
  4703. }
  4704. #endif
  4705. for (jp = curjob; jp; jp = jp->prev_job)
  4706. freejob(jp);
  4707. jobless = 0;
  4708. }
  4709. /* Called after fork(), in parent */
  4710. #if !JOBS
  4711. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4712. #endif
  4713. static void
  4714. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4715. {
  4716. TRACE(("In parent shell: child = %d\n", pid));
  4717. if (!jp) {
  4718. /* jp is NULL when called by openhere() for heredoc support */
  4719. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4720. continue;
  4721. jobless++;
  4722. return;
  4723. }
  4724. #if JOBS
  4725. if (mode != FORK_NOJOB && jp->jobctl) {
  4726. int pgrp;
  4727. if (jp->nprocs == 0)
  4728. pgrp = pid;
  4729. else
  4730. pgrp = jp->ps[0].ps_pid;
  4731. /* This can fail because we are doing it in the child also */
  4732. setpgid(pid, pgrp);
  4733. }
  4734. #endif
  4735. if (mode == FORK_BG) {
  4736. backgndpid = pid; /* set $! */
  4737. set_curjob(jp, CUR_RUNNING);
  4738. }
  4739. if (jp) {
  4740. struct procstat *ps = &jp->ps[jp->nprocs++];
  4741. ps->ps_pid = pid;
  4742. ps->ps_status = -1;
  4743. ps->ps_cmd = nullstr;
  4744. #if JOBS
  4745. if (doing_jobctl && n)
  4746. ps->ps_cmd = commandtext(n);
  4747. #endif
  4748. }
  4749. }
  4750. /* jp and n are NULL when called by openhere() for heredoc support */
  4751. static int
  4752. forkshell(struct job *jp, union node *n, int mode)
  4753. {
  4754. int pid;
  4755. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4756. pid = fork();
  4757. if (pid < 0) {
  4758. TRACE(("Fork failed, errno=%d", errno));
  4759. if (jp)
  4760. freejob(jp);
  4761. ash_msg_and_raise_perror("can't fork");
  4762. }
  4763. if (pid == 0) {
  4764. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4765. forkchild(jp, n, mode);
  4766. } else {
  4767. forkparent(jp, n, mode, pid);
  4768. }
  4769. return pid;
  4770. }
  4771. /*
  4772. * Wait for job to finish.
  4773. *
  4774. * Under job control we have the problem that while a child process
  4775. * is running interrupts generated by the user are sent to the child
  4776. * but not to the shell. This means that an infinite loop started by
  4777. * an interactive user may be hard to kill. With job control turned off,
  4778. * an interactive user may place an interactive program inside a loop.
  4779. * If the interactive program catches interrupts, the user doesn't want
  4780. * these interrupts to also abort the loop. The approach we take here
  4781. * is to have the shell ignore interrupt signals while waiting for a
  4782. * foreground process to terminate, and then send itself an interrupt
  4783. * signal if the child process was terminated by an interrupt signal.
  4784. * Unfortunately, some programs want to do a bit of cleanup and then
  4785. * exit on interrupt; unless these processes terminate themselves by
  4786. * sending a signal to themselves (instead of calling exit) they will
  4787. * confuse this approach.
  4788. *
  4789. * Called with interrupts off.
  4790. */
  4791. static int
  4792. waitforjob(struct job *jp)
  4793. {
  4794. int st;
  4795. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4796. INT_OFF;
  4797. while (jp->state == JOBRUNNING) {
  4798. /* In non-interactive shells, we _can_ get
  4799. * a keyboard signal here and be EINTRed,
  4800. * but we just loop back, waiting for command to complete.
  4801. *
  4802. * man bash:
  4803. * "If bash is waiting for a command to complete and receives
  4804. * a signal for which a trap has been set, the trap
  4805. * will not be executed until the command completes."
  4806. *
  4807. * Reality is that even if trap is not set, bash
  4808. * will not act on the signal until command completes.
  4809. * Try this. sleep5intoff.c:
  4810. * #include <signal.h>
  4811. * #include <unistd.h>
  4812. * int main() {
  4813. * sigset_t set;
  4814. * sigemptyset(&set);
  4815. * sigaddset(&set, SIGINT);
  4816. * sigaddset(&set, SIGQUIT);
  4817. * sigprocmask(SIG_BLOCK, &set, NULL);
  4818. * sleep(5);
  4819. * return 0;
  4820. * }
  4821. * $ bash -c './sleep5intoff; echo hi'
  4822. * ^C^C^C^C <--- pressing ^C once a second
  4823. * $ _
  4824. * $ bash -c './sleep5intoff; echo hi'
  4825. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4826. * $ _
  4827. */
  4828. dowait(DOWAIT_BLOCK, jp);
  4829. }
  4830. INT_ON;
  4831. st = getstatus(jp);
  4832. #if JOBS
  4833. if (jp->jobctl) {
  4834. xtcsetpgrp(ttyfd, rootpid);
  4835. restore_tty_if_stopped_or_signaled(jp);
  4836. /*
  4837. * This is truly gross.
  4838. * If we're doing job control, then we did a TIOCSPGRP which
  4839. * caused us (the shell) to no longer be in the controlling
  4840. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4841. * intuit from the subprocess exit status whether a SIGINT
  4842. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4843. */
  4844. if (jp->sigint) /* TODO: do the same with all signals */
  4845. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4846. }
  4847. if (jp->state == JOBDONE)
  4848. #endif
  4849. freejob(jp);
  4850. return st;
  4851. }
  4852. /*
  4853. * return 1 if there are stopped jobs, otherwise 0
  4854. */
  4855. static int
  4856. stoppedjobs(void)
  4857. {
  4858. struct job *jp;
  4859. int retval;
  4860. retval = 0;
  4861. if (job_warning)
  4862. goto out;
  4863. jp = curjob;
  4864. if (jp && jp->state == JOBSTOPPED) {
  4865. out2str("You have stopped jobs.\n");
  4866. job_warning = 2;
  4867. retval++;
  4868. }
  4869. out:
  4870. return retval;
  4871. }
  4872. /*
  4873. * Code for dealing with input/output redirection.
  4874. */
  4875. #undef EMPTY
  4876. #undef CLOSED
  4877. #define EMPTY -2 /* marks an unused slot in redirtab */
  4878. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4879. /*
  4880. * Handle here documents. Normally we fork off a process to write the
  4881. * data to a pipe. If the document is short, we can stuff the data in
  4882. * the pipe without forking.
  4883. */
  4884. /* openhere needs this forward reference */
  4885. static void expandhere(union node *arg, int fd);
  4886. static int
  4887. openhere(union node *redir)
  4888. {
  4889. int pip[2];
  4890. size_t len = 0;
  4891. if (pipe(pip) < 0)
  4892. ash_msg_and_raise_perror("can't create pipe");
  4893. if (redir->type == NHERE) {
  4894. len = strlen(redir->nhere.doc->narg.text);
  4895. if (len <= PIPE_BUF) {
  4896. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4897. goto out;
  4898. }
  4899. }
  4900. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4901. /* child */
  4902. close(pip[0]);
  4903. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4904. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4905. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4906. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4907. signal(SIGPIPE, SIG_DFL);
  4908. if (redir->type == NHERE)
  4909. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4910. else /* NXHERE */
  4911. expandhere(redir->nhere.doc, pip[1]);
  4912. _exit(EXIT_SUCCESS);
  4913. }
  4914. out:
  4915. close(pip[1]);
  4916. return pip[0];
  4917. }
  4918. static int
  4919. openredirect(union node *redir)
  4920. {
  4921. struct stat sb;
  4922. char *fname;
  4923. int f;
  4924. switch (redir->nfile.type) {
  4925. /* Can't happen, our single caller does this itself */
  4926. // case NTOFD:
  4927. // case NFROMFD:
  4928. // return -1;
  4929. case NHERE:
  4930. case NXHERE:
  4931. return openhere(redir);
  4932. }
  4933. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4934. * allocated space. Do it only when we know it is safe.
  4935. */
  4936. fname = redir->nfile.expfname;
  4937. switch (redir->nfile.type) {
  4938. default:
  4939. #if DEBUG
  4940. abort();
  4941. #endif
  4942. case NFROM:
  4943. f = open(fname, O_RDONLY);
  4944. if (f < 0)
  4945. goto eopen;
  4946. break;
  4947. case NFROMTO:
  4948. f = open(fname, O_RDWR|O_CREAT, 0666);
  4949. if (f < 0)
  4950. goto ecreate;
  4951. break;
  4952. case NTO:
  4953. #if BASH_REDIR_OUTPUT
  4954. case NTO2:
  4955. #endif
  4956. /* Take care of noclobber mode. */
  4957. if (Cflag) {
  4958. if (stat(fname, &sb) < 0) {
  4959. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4960. if (f < 0)
  4961. goto ecreate;
  4962. } else if (!S_ISREG(sb.st_mode)) {
  4963. f = open(fname, O_WRONLY, 0666);
  4964. if (f < 0)
  4965. goto ecreate;
  4966. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  4967. close(f);
  4968. errno = EEXIST;
  4969. goto ecreate;
  4970. }
  4971. } else {
  4972. errno = EEXIST;
  4973. goto ecreate;
  4974. }
  4975. break;
  4976. }
  4977. /* FALLTHROUGH */
  4978. case NCLOBBER:
  4979. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4980. if (f < 0)
  4981. goto ecreate;
  4982. break;
  4983. case NAPPEND:
  4984. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4985. if (f < 0)
  4986. goto ecreate;
  4987. break;
  4988. }
  4989. return f;
  4990. ecreate:
  4991. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4992. eopen:
  4993. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4994. }
  4995. /*
  4996. * Copy a file descriptor to be >= 10. Throws exception on error.
  4997. */
  4998. static int
  4999. savefd(int from)
  5000. {
  5001. int newfd;
  5002. int err;
  5003. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  5004. err = newfd < 0 ? errno : 0;
  5005. if (err != EBADF) {
  5006. if (err)
  5007. ash_msg_and_raise_perror("%d", from);
  5008. close(from);
  5009. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5010. close_on_exec_on(newfd);
  5011. }
  5012. return newfd;
  5013. }
  5014. static int
  5015. dup2_or_raise(int from, int to)
  5016. {
  5017. int newfd;
  5018. newfd = (from != to) ? dup2(from, to) : to;
  5019. if (newfd < 0) {
  5020. /* Happens when source fd is not open: try "echo >&99" */
  5021. ash_msg_and_raise_perror("%d", from);
  5022. }
  5023. return newfd;
  5024. }
  5025. static int
  5026. dup_CLOEXEC(int fd, int avoid_fd)
  5027. {
  5028. int newfd;
  5029. repeat:
  5030. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5031. if (newfd >= 0) {
  5032. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  5033. close_on_exec_on(newfd);
  5034. } else { /* newfd < 0 */
  5035. if (errno == EBUSY)
  5036. goto repeat;
  5037. if (errno == EINTR)
  5038. goto repeat;
  5039. }
  5040. return newfd;
  5041. }
  5042. static int
  5043. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5044. {
  5045. int newfd;
  5046. repeat:
  5047. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5048. if (newfd < 0) {
  5049. if (errno == EBUSY)
  5050. goto repeat;
  5051. if (errno == EINTR)
  5052. goto repeat;
  5053. /* fd was not open? */
  5054. if (errno == EBADF)
  5055. return fd;
  5056. ash_msg_and_raise_perror("%d", newfd);
  5057. }
  5058. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5059. close_on_exec_on(newfd);
  5060. close(fd);
  5061. return newfd;
  5062. }
  5063. /* Struct def and variable are moved down to the first usage site */
  5064. struct squirrel {
  5065. int orig_fd;
  5066. int moved_to;
  5067. };
  5068. struct redirtab {
  5069. struct redirtab *next;
  5070. int pair_count;
  5071. struct squirrel two_fd[];
  5072. };
  5073. #define redirlist (G_var.redirlist)
  5074. static void
  5075. add_squirrel_closed(struct redirtab *sq, int fd)
  5076. {
  5077. int i;
  5078. if (!sq)
  5079. return;
  5080. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5081. /* If we collide with an already moved fd... */
  5082. if (fd == sq->two_fd[i].orig_fd) {
  5083. /* Examples:
  5084. * "echo 3>FILE 3>&- 3>FILE"
  5085. * "echo 3>&- 3>FILE"
  5086. * No need for last redirect to insert
  5087. * another "need to close 3" indicator.
  5088. */
  5089. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5090. return;
  5091. }
  5092. }
  5093. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5094. sq->two_fd[i].orig_fd = fd;
  5095. sq->two_fd[i].moved_to = CLOSED;
  5096. }
  5097. static int
  5098. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5099. {
  5100. int i, new_fd;
  5101. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5102. avoid_fd = 9;
  5103. #if JOBS
  5104. if (fd == ttyfd) {
  5105. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5106. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5107. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5108. return 1; /* "we closed fd" */
  5109. }
  5110. #endif
  5111. /* Are we called from redirect(0)? E.g. redirect
  5112. * in a forked child. No need to save fds,
  5113. * we aren't going to use them anymore, ok to trash.
  5114. */
  5115. if (!sq)
  5116. return 0;
  5117. /* If this one of script's fds? */
  5118. if (fd != 0) {
  5119. struct parsefile *pf = g_parsefile;
  5120. while (pf) {
  5121. /* We skip fd == 0 case because of the following:
  5122. * $ ash # running ash interactively
  5123. * $ . ./script.sh
  5124. * and in script.sh: "exec 9>&0".
  5125. * Even though top-level pf_fd _is_ 0,
  5126. * it's still ok to use it: "read" builtin uses it,
  5127. * why should we cripple "exec" builtin?
  5128. */
  5129. if (fd == pf->pf_fd) {
  5130. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5131. return 1; /* "we closed fd" */
  5132. }
  5133. pf = pf->prev;
  5134. }
  5135. }
  5136. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5137. /* First: do we collide with some already moved fds? */
  5138. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5139. /* If we collide with an already moved fd... */
  5140. if (fd == sq->two_fd[i].moved_to) {
  5141. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5142. sq->two_fd[i].moved_to = new_fd;
  5143. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5144. if (new_fd < 0) /* what? */
  5145. xfunc_die();
  5146. return 0; /* "we did not close fd" */
  5147. }
  5148. if (fd == sq->two_fd[i].orig_fd) {
  5149. /* Example: echo Hello >/dev/null 1>&2 */
  5150. TRACE(("redirect_fd %d: already moved\n", fd));
  5151. return 0; /* "we did not close fd" */
  5152. }
  5153. }
  5154. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5155. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5156. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5157. if (new_fd < 0) {
  5158. if (errno != EBADF)
  5159. xfunc_die();
  5160. /* new_fd = CLOSED; - already is -1 */
  5161. }
  5162. sq->two_fd[i].moved_to = new_fd;
  5163. sq->two_fd[i].orig_fd = fd;
  5164. /* if we move stderr, let "set -x" code know */
  5165. if (fd == preverrout_fd)
  5166. preverrout_fd = new_fd;
  5167. return 0; /* "we did not close fd" */
  5168. }
  5169. static int
  5170. internally_opened_fd(int fd, struct redirtab *sq)
  5171. {
  5172. int i;
  5173. #if JOBS
  5174. if (fd == ttyfd)
  5175. return 1;
  5176. #endif
  5177. /* If this one of script's fds? */
  5178. if (fd != 0) {
  5179. struct parsefile *pf = g_parsefile;
  5180. while (pf) {
  5181. if (fd == pf->pf_fd)
  5182. return 1;
  5183. pf = pf->prev;
  5184. }
  5185. }
  5186. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5187. if (fd == sq->two_fd[i].moved_to)
  5188. return 1;
  5189. }
  5190. return 0;
  5191. }
  5192. /*
  5193. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5194. * old file descriptors are stashed away so that the redirection can be
  5195. * undone by calling popredir.
  5196. */
  5197. /* flags passed to redirect */
  5198. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5199. static void
  5200. redirect(union node *redir, int flags)
  5201. {
  5202. struct redirtab *sv;
  5203. if (!redir)
  5204. return;
  5205. sv = NULL;
  5206. INT_OFF;
  5207. if (flags & REDIR_PUSH)
  5208. sv = redirlist;
  5209. do {
  5210. int fd;
  5211. int newfd;
  5212. int close_fd;
  5213. int closed;
  5214. fd = redir->nfile.fd;
  5215. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5216. //bb_error_msg("doing %d > %d", fd, newfd);
  5217. newfd = redir->ndup.dupfd;
  5218. close_fd = -1;
  5219. } else {
  5220. newfd = openredirect(redir); /* always >= 0 */
  5221. if (fd == newfd) {
  5222. /* open() gave us precisely the fd we wanted.
  5223. * This means that this fd was not busy
  5224. * (not opened to anywhere).
  5225. * Remember to close it on restore:
  5226. */
  5227. add_squirrel_closed(sv, fd);
  5228. continue;
  5229. }
  5230. close_fd = newfd;
  5231. }
  5232. if (fd == newfd)
  5233. continue;
  5234. /* if "N>FILE": move newfd to fd */
  5235. /* if "N>&M": dup newfd to fd */
  5236. /* if "N>&-": close fd (newfd is -1) */
  5237. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5238. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5239. if (newfd == -1) {
  5240. /* "N>&-" means "close me" */
  5241. if (!closed) {
  5242. /* ^^^ optimization: saving may already
  5243. * have closed it. If not... */
  5244. close(fd);
  5245. }
  5246. } else {
  5247. /* if newfd is a script fd or saved fd, simulate EBADF */
  5248. if (internally_opened_fd(newfd, sv)) {
  5249. errno = EBADF;
  5250. ash_msg_and_raise_perror("%d", newfd);
  5251. }
  5252. dup2_or_raise(newfd, fd);
  5253. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5254. close(close_fd);
  5255. #if BASH_REDIR_OUTPUT
  5256. if (redir->nfile.type == NTO2 && fd == 1) {
  5257. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5258. fd = 2;
  5259. newfd = 1;
  5260. close_fd = -1;
  5261. goto redirect_more;
  5262. }
  5263. #endif
  5264. }
  5265. } while ((redir = redir->nfile.next) != NULL);
  5266. INT_ON;
  5267. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5268. #define REDIR_SAVEFD2 0
  5269. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5270. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5271. // not only for calls with flags containing REDIR_SAVEFD2.
  5272. // We do this unconditionally (see save_fd_on_redirect()).
  5273. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5274. // preverrout_fd = copied_fd2;
  5275. }
  5276. static int
  5277. redirectsafe(union node *redir, int flags)
  5278. {
  5279. int err;
  5280. volatile int saveint;
  5281. struct jmploc *volatile savehandler = exception_handler;
  5282. struct jmploc jmploc;
  5283. SAVE_INT(saveint);
  5284. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5285. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5286. if (!err) {
  5287. exception_handler = &jmploc;
  5288. redirect(redir, flags);
  5289. }
  5290. exception_handler = savehandler;
  5291. if (err && exception_type != EXERROR)
  5292. longjmp(exception_handler->loc, 1);
  5293. RESTORE_INT(saveint);
  5294. return err;
  5295. }
  5296. static struct redirtab*
  5297. pushredir(union node *redir)
  5298. {
  5299. struct redirtab *sv;
  5300. int i;
  5301. if (!redir)
  5302. return redirlist;
  5303. i = 0;
  5304. do {
  5305. i++;
  5306. #if BASH_REDIR_OUTPUT
  5307. if (redir->nfile.type == NTO2)
  5308. i++;
  5309. #endif
  5310. redir = redir->nfile.next;
  5311. } while (redir);
  5312. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5313. sv->pair_count = i;
  5314. while (--i >= 0)
  5315. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5316. sv->next = redirlist;
  5317. redirlist = sv;
  5318. return sv->next;
  5319. }
  5320. /*
  5321. * Undo the effects of the last redirection.
  5322. */
  5323. static void
  5324. popredir(int drop)
  5325. {
  5326. struct redirtab *rp;
  5327. int i;
  5328. if (redirlist == NULL)
  5329. return;
  5330. INT_OFF;
  5331. rp = redirlist;
  5332. for (i = 0; i < rp->pair_count; i++) {
  5333. int fd = rp->two_fd[i].orig_fd;
  5334. int copy = rp->two_fd[i].moved_to;
  5335. if (copy == CLOSED) {
  5336. if (!drop)
  5337. close(fd);
  5338. continue;
  5339. }
  5340. if (copy != EMPTY) {
  5341. if (!drop) {
  5342. /*close(fd);*/
  5343. dup2_or_raise(copy, fd);
  5344. }
  5345. close(copy);
  5346. }
  5347. }
  5348. redirlist = rp->next;
  5349. free(rp);
  5350. INT_ON;
  5351. }
  5352. static void
  5353. unwindredir(struct redirtab *stop)
  5354. {
  5355. while (redirlist != stop)
  5356. popredir(/*drop:*/ 0);
  5357. }
  5358. /* ============ Routines to expand arguments to commands
  5359. *
  5360. * We have to deal with backquotes, shell variables, and file metacharacters.
  5361. */
  5362. #if ENABLE_FEATURE_SH_MATH
  5363. static arith_t
  5364. ash_arith(const char *s)
  5365. {
  5366. arith_state_t math_state;
  5367. arith_t result;
  5368. math_state.lookupvar = lookupvar;
  5369. math_state.setvar = setvar0;
  5370. //math_state.endofname = endofname;
  5371. INT_OFF;
  5372. result = arith(&math_state, s);
  5373. if (math_state.errmsg)
  5374. ash_msg_and_raise_error(math_state.errmsg);
  5375. INT_ON;
  5376. return result;
  5377. }
  5378. #endif
  5379. #if BASH_SUBSTR
  5380. # if ENABLE_FEATURE_SH_MATH
  5381. static int substr_atoi(const char *s)
  5382. {
  5383. arith_t t = ash_arith(s);
  5384. if (sizeof(t) > sizeof(int)) {
  5385. /* clamp very large or very large negative nums for ${v:N:M}:
  5386. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5387. */
  5388. if (t > INT_MAX)
  5389. t = INT_MAX;
  5390. if (t < INT_MIN)
  5391. t = INT_MIN;
  5392. }
  5393. return t;
  5394. }
  5395. # else
  5396. # define substr_atoi(s) number(s)
  5397. # endif
  5398. #endif
  5399. /*
  5400. * expandarg flags
  5401. */
  5402. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5403. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5404. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5405. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5406. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5407. * POSIX says for this case:
  5408. * Pathname expansion shall not be performed on the word by a
  5409. * non-interactive shell; an interactive shell may perform it, but shall
  5410. * do so only when the expansion would result in one word.
  5411. * Currently, our code complies to the above rule by never globbing
  5412. * redirection filenames.
  5413. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5414. * (this means that on a typical Linux distro, bash almost always
  5415. * performs globbing, and thus diverges from what we do).
  5416. */
  5417. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5418. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5419. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5420. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5421. /*
  5422. * rmescape() flags
  5423. */
  5424. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5425. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5426. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5427. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5428. /* Add CTLESC when necessary. */
  5429. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5430. /* Do not skip NUL characters. */
  5431. #define QUOTES_KEEPNUL EXP_TILDE
  5432. /*
  5433. * Structure specifying which parts of the string should be searched
  5434. * for IFS characters.
  5435. */
  5436. struct ifsregion {
  5437. struct ifsregion *next; /* next region in list */
  5438. int begoff; /* offset of start of region */
  5439. int endoff; /* offset of end of region */
  5440. int nulonly; /* search for nul bytes only */
  5441. };
  5442. struct arglist {
  5443. struct strlist *list;
  5444. struct strlist **lastp;
  5445. };
  5446. /* output of current string */
  5447. static char *expdest;
  5448. /* list of back quote expressions */
  5449. static struct nodelist *argbackq;
  5450. /* first struct in list of ifs regions */
  5451. static struct ifsregion ifsfirst;
  5452. /* last struct in list */
  5453. static struct ifsregion *ifslastp;
  5454. /* holds expanded arg list */
  5455. static struct arglist exparg;
  5456. /*
  5457. * Our own itoa().
  5458. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5459. */
  5460. static int
  5461. cvtnum(arith_t num)
  5462. {
  5463. int len;
  5464. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5465. len = sizeof(arith_t) * 3;
  5466. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5467. if (sizeof(arith_t) < 4) len += 2;
  5468. expdest = makestrspace(len, expdest);
  5469. len = fmtstr(expdest, len, ARITH_FMT, num);
  5470. STADJUST(len, expdest);
  5471. return len;
  5472. }
  5473. /*
  5474. * Break the argument string into pieces based upon IFS and add the
  5475. * strings to the argument list. The regions of the string to be
  5476. * searched for IFS characters have been stored by recordregion.
  5477. */
  5478. static void
  5479. ifsbreakup(char *string, struct arglist *arglist)
  5480. {
  5481. struct ifsregion *ifsp;
  5482. struct strlist *sp;
  5483. char *start;
  5484. char *p;
  5485. char *q;
  5486. const char *ifs, *realifs;
  5487. int ifsspc;
  5488. int nulonly;
  5489. start = string;
  5490. if (ifslastp != NULL) {
  5491. ifsspc = 0;
  5492. nulonly = 0;
  5493. realifs = ifsset() ? ifsval() : defifs;
  5494. ifsp = &ifsfirst;
  5495. do {
  5496. int afternul;
  5497. p = string + ifsp->begoff;
  5498. afternul = nulonly;
  5499. nulonly = ifsp->nulonly;
  5500. ifs = nulonly ? nullstr : realifs;
  5501. ifsspc = 0;
  5502. while (p < string + ifsp->endoff) {
  5503. q = p;
  5504. if ((unsigned char)*p == CTLESC)
  5505. p++;
  5506. if (!strchr(ifs, *p)) {
  5507. p++;
  5508. continue;
  5509. }
  5510. if (!(afternul || nulonly))
  5511. ifsspc = (strchr(defifs, *p) != NULL);
  5512. /* Ignore IFS whitespace at start */
  5513. if (q == start && ifsspc) {
  5514. p++;
  5515. start = p;
  5516. continue;
  5517. }
  5518. *q = '\0';
  5519. sp = stzalloc(sizeof(*sp));
  5520. sp->text = start;
  5521. *arglist->lastp = sp;
  5522. arglist->lastp = &sp->next;
  5523. p++;
  5524. if (!nulonly) {
  5525. for (;;) {
  5526. if (p >= string + ifsp->endoff) {
  5527. break;
  5528. }
  5529. q = p;
  5530. if ((unsigned char)*p == CTLESC)
  5531. p++;
  5532. if (strchr(ifs, *p) == NULL) {
  5533. p = q;
  5534. break;
  5535. }
  5536. if (strchr(defifs, *p) == NULL) {
  5537. if (ifsspc) {
  5538. p++;
  5539. ifsspc = 0;
  5540. } else {
  5541. p = q;
  5542. break;
  5543. }
  5544. } else
  5545. p++;
  5546. }
  5547. }
  5548. start = p;
  5549. } /* while */
  5550. ifsp = ifsp->next;
  5551. } while (ifsp != NULL);
  5552. if (nulonly)
  5553. goto add;
  5554. }
  5555. if (!*start)
  5556. return;
  5557. add:
  5558. sp = stzalloc(sizeof(*sp));
  5559. sp->text = start;
  5560. *arglist->lastp = sp;
  5561. arglist->lastp = &sp->next;
  5562. }
  5563. static void
  5564. ifsfree(void)
  5565. {
  5566. struct ifsregion *p = ifsfirst.next;
  5567. if (!p)
  5568. goto out;
  5569. INT_OFF;
  5570. do {
  5571. struct ifsregion *ifsp;
  5572. ifsp = p->next;
  5573. free(p);
  5574. p = ifsp;
  5575. } while (p);
  5576. ifsfirst.next = NULL;
  5577. INT_ON;
  5578. out:
  5579. ifslastp = NULL;
  5580. }
  5581. static size_t
  5582. esclen(const char *start, const char *p)
  5583. {
  5584. size_t esc = 0;
  5585. while (p > start && (unsigned char)*--p == CTLESC) {
  5586. esc++;
  5587. }
  5588. return esc;
  5589. }
  5590. /*
  5591. * Remove any CTLESC characters from a string.
  5592. */
  5593. #if !BASH_PATTERN_SUBST
  5594. #define rmescapes(str, flag, slash_position) \
  5595. rmescapes(str, flag)
  5596. #endif
  5597. static char *
  5598. rmescapes(char *str, int flag, int *slash_position)
  5599. {
  5600. static const char qchars[] ALIGN1 = {
  5601. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5602. char *p, *q, *r;
  5603. unsigned protect_against_glob;
  5604. unsigned globbing;
  5605. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5606. if (!p)
  5607. return str;
  5608. q = p;
  5609. r = str;
  5610. if (flag & RMESCAPE_ALLOC) {
  5611. size_t len = p - str;
  5612. size_t fulllen = len + strlen(p) + 1;
  5613. if (flag & RMESCAPE_GROW) {
  5614. int strloc = str - (char *)stackblock();
  5615. r = makestrspace(fulllen, expdest);
  5616. /* p and str may be invalidated by makestrspace */
  5617. str = (char *)stackblock() + strloc;
  5618. p = str + len;
  5619. } else if (flag & RMESCAPE_HEAP) {
  5620. r = ckmalloc(fulllen);
  5621. } else {
  5622. r = stalloc(fulllen);
  5623. }
  5624. q = r;
  5625. if (len > 0) {
  5626. q = (char *)mempcpy(q, str, len);
  5627. }
  5628. }
  5629. globbing = flag & RMESCAPE_GLOB;
  5630. protect_against_glob = globbing;
  5631. while (*p) {
  5632. if ((unsigned char)*p == CTLQUOTEMARK) {
  5633. // Note: protect_against_glob only affect whether
  5634. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5635. p++;
  5636. protect_against_glob = globbing;
  5637. continue;
  5638. }
  5639. if (*p == '\\') {
  5640. /* naked back slash */
  5641. protect_against_glob = 0;
  5642. goto copy;
  5643. }
  5644. if ((unsigned char)*p == CTLESC) {
  5645. p++;
  5646. #if DEBUG
  5647. if (*p == '\0')
  5648. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5649. #endif
  5650. if (protect_against_glob) {
  5651. /*
  5652. * We used to trust glob() and fnmatch() to eat
  5653. * superfluous escapes (\z where z has no
  5654. * special meaning anyway). But this causes
  5655. * bugs such as string of one greek letter rho
  5656. * (unicode-encoded as two bytes "cf,81")
  5657. * getting encoded as "cf,CTLESC,81"
  5658. * and here, converted to "cf,\,81" -
  5659. * which does not go well with some flavors
  5660. * of fnmatch() in unicode locales
  5661. * (for example, glibc <= 2.22).
  5662. *
  5663. * Lets add "\" only on the chars which need it.
  5664. * Testcases for less obvious chars are shown.
  5665. */
  5666. if (*p == '*'
  5667. || *p == '?'
  5668. || *p == '['
  5669. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5670. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5671. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5672. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5673. /* Some libc support [^negate], that's why "^" also needs love */
  5674. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5675. ) {
  5676. *q++ = '\\';
  5677. }
  5678. }
  5679. }
  5680. #if BASH_PATTERN_SUBST
  5681. else if (slash_position && p == str + *slash_position) {
  5682. /* stop handling globbing */
  5683. globbing = 0;
  5684. *slash_position = q - r;
  5685. slash_position = NULL;
  5686. }
  5687. #endif
  5688. protect_against_glob = globbing;
  5689. copy:
  5690. *q++ = *p++;
  5691. }
  5692. *q = '\0';
  5693. if (flag & RMESCAPE_GROW) {
  5694. expdest = r;
  5695. STADJUST(q - r + 1, expdest);
  5696. }
  5697. return r;
  5698. }
  5699. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5700. /*
  5701. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5702. *
  5703. * Returns an stalloced string.
  5704. */
  5705. static char *
  5706. preglob(const char *pattern, int flag)
  5707. {
  5708. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5709. }
  5710. /*
  5711. * Put a string on the stack.
  5712. */
  5713. static void
  5714. memtodest(const char *p, size_t len, int syntax, int quotes)
  5715. {
  5716. char *q;
  5717. if (!len)
  5718. return;
  5719. q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
  5720. do {
  5721. unsigned char c = *p++;
  5722. if (c) {
  5723. if (quotes & QUOTES_ESC) {
  5724. int n = SIT(c, syntax);
  5725. if (n == CCTL
  5726. || (syntax != BASESYNTAX && n == CBACK)
  5727. ) {
  5728. USTPUTC(CTLESC, q);
  5729. }
  5730. }
  5731. } else if (!(quotes & QUOTES_KEEPNUL))
  5732. continue;
  5733. USTPUTC(c, q);
  5734. } while (--len);
  5735. expdest = q;
  5736. }
  5737. static size_t
  5738. strtodest(const char *p, int syntax, int quotes)
  5739. {
  5740. size_t len = strlen(p);
  5741. memtodest(p, len, syntax, quotes);
  5742. return len;
  5743. }
  5744. /*
  5745. * Record the fact that we have to scan this region of the
  5746. * string for IFS characters.
  5747. */
  5748. static void
  5749. recordregion(int start, int end, int nulonly)
  5750. {
  5751. struct ifsregion *ifsp;
  5752. if (ifslastp == NULL) {
  5753. ifsp = &ifsfirst;
  5754. } else {
  5755. INT_OFF;
  5756. ifsp = ckzalloc(sizeof(*ifsp));
  5757. /*ifsp->next = NULL; - ckzalloc did it */
  5758. ifslastp->next = ifsp;
  5759. INT_ON;
  5760. }
  5761. ifslastp = ifsp;
  5762. ifslastp->begoff = start;
  5763. ifslastp->endoff = end;
  5764. ifslastp->nulonly = nulonly;
  5765. }
  5766. static void
  5767. removerecordregions(int endoff)
  5768. {
  5769. if (ifslastp == NULL)
  5770. return;
  5771. if (ifsfirst.endoff > endoff) {
  5772. while (ifsfirst.next) {
  5773. struct ifsregion *ifsp;
  5774. INT_OFF;
  5775. ifsp = ifsfirst.next->next;
  5776. free(ifsfirst.next);
  5777. ifsfirst.next = ifsp;
  5778. INT_ON;
  5779. }
  5780. if (ifsfirst.begoff > endoff) {
  5781. ifslastp = NULL;
  5782. } else {
  5783. ifslastp = &ifsfirst;
  5784. ifsfirst.endoff = endoff;
  5785. }
  5786. return;
  5787. }
  5788. ifslastp = &ifsfirst;
  5789. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5790. ifslastp = ifslastp->next;
  5791. while (ifslastp->next) {
  5792. struct ifsregion *ifsp;
  5793. INT_OFF;
  5794. ifsp = ifslastp->next->next;
  5795. free(ifslastp->next);
  5796. ifslastp->next = ifsp;
  5797. INT_ON;
  5798. }
  5799. if (ifslastp->endoff > endoff)
  5800. ifslastp->endoff = endoff;
  5801. }
  5802. static char *
  5803. exptilde(char *startp, char *p, int flags)
  5804. {
  5805. unsigned char c;
  5806. char *name;
  5807. struct passwd *pw;
  5808. const char *home;
  5809. int quotes = flags & QUOTES_ESC;
  5810. name = p + 1;
  5811. while ((c = *++p) != '\0') {
  5812. switch (c) {
  5813. case CTLESC:
  5814. return startp;
  5815. case CTLQUOTEMARK:
  5816. return startp;
  5817. case ':':
  5818. if (flags & EXP_VARTILDE)
  5819. goto done;
  5820. break;
  5821. case '/':
  5822. case CTLENDVAR:
  5823. goto done;
  5824. }
  5825. }
  5826. done:
  5827. *p = '\0';
  5828. if (*name == '\0') {
  5829. home = lookupvar("HOME");
  5830. } else {
  5831. pw = getpwnam(name);
  5832. if (pw == NULL)
  5833. goto lose;
  5834. home = pw->pw_dir;
  5835. }
  5836. if (!home || !*home)
  5837. goto lose;
  5838. *p = c;
  5839. strtodest(home, SQSYNTAX, quotes);
  5840. return p;
  5841. lose:
  5842. *p = c;
  5843. return startp;
  5844. }
  5845. /*
  5846. * Execute a command inside back quotes. If it's a builtin command, we
  5847. * want to save its output in a block obtained from malloc. Otherwise
  5848. * we fork off a subprocess and get the output of the command via a pipe.
  5849. * Should be called with interrupts off.
  5850. */
  5851. struct backcmd { /* result of evalbackcmd */
  5852. int fd; /* file descriptor to read from */
  5853. int nleft; /* number of chars in buffer */
  5854. char *buf; /* buffer */
  5855. struct job *jp; /* job structure for command */
  5856. };
  5857. /* These forward decls are needed to use "eval" code for backticks handling: */
  5858. /* flags in argument to evaltree */
  5859. #define EV_EXIT 01 /* exit after evaluating tree */
  5860. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5861. static int evaltree(union node *, int);
  5862. /* An evaltree() which is known to never return.
  5863. * Used to use an alias:
  5864. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5865. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5866. */
  5867. static ALWAYS_INLINE NORETURN void
  5868. evaltreenr(union node *n, int flags)
  5869. {
  5870. evaltree(n, flags);
  5871. bb_unreachable(abort());
  5872. /* NOTREACHED */
  5873. }
  5874. static void FAST_FUNC
  5875. evalbackcmd(union node *n, struct backcmd *result)
  5876. {
  5877. int pip[2];
  5878. struct job *jp;
  5879. result->fd = -1;
  5880. result->buf = NULL;
  5881. result->nleft = 0;
  5882. result->jp = NULL;
  5883. if (n == NULL) {
  5884. goto out;
  5885. }
  5886. if (pipe(pip) < 0)
  5887. ash_msg_and_raise_perror("can't create pipe");
  5888. jp = makejob(/*n,*/ 1);
  5889. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5890. /* child */
  5891. FORCE_INT_ON;
  5892. close(pip[0]);
  5893. if (pip[1] != 1) {
  5894. /*close(1);*/
  5895. dup2_or_raise(pip[1], 1);
  5896. close(pip[1]);
  5897. }
  5898. /* TODO: eflag clearing makes the following not abort:
  5899. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5900. * which is what bash does (unless it is in POSIX mode).
  5901. * dash deleted "eflag = 0" line in the commit
  5902. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5903. * [EVAL] Don't clear eflag in evalbackcmd
  5904. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5905. */
  5906. eflag = 0;
  5907. ifsfree();
  5908. evaltreenr(n, EV_EXIT);
  5909. /* NOTREACHED */
  5910. }
  5911. /* parent */
  5912. close(pip[1]);
  5913. result->fd = pip[0];
  5914. result->jp = jp;
  5915. out:
  5916. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5917. result->fd, result->buf, result->nleft, result->jp));
  5918. }
  5919. /*
  5920. * Expand stuff in backwards quotes.
  5921. */
  5922. static void
  5923. expbackq(union node *cmd, int flag)
  5924. {
  5925. struct backcmd in;
  5926. int i;
  5927. char buf[128];
  5928. char *p;
  5929. char *dest;
  5930. int startloc;
  5931. int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5932. struct stackmark smark;
  5933. INT_OFF;
  5934. startloc = expdest - (char *)stackblock();
  5935. pushstackmark(&smark, startloc);
  5936. evalbackcmd(cmd, &in);
  5937. popstackmark(&smark);
  5938. p = in.buf;
  5939. i = in.nleft;
  5940. if (i == 0)
  5941. goto read;
  5942. for (;;) {
  5943. memtodest(p, i, syntax, flag & QUOTES_ESC);
  5944. read:
  5945. if (in.fd < 0)
  5946. break;
  5947. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  5948. TRACE(("expbackq: read returns %d\n", i));
  5949. if (i <= 0)
  5950. break;
  5951. p = buf;
  5952. }
  5953. free(in.buf);
  5954. if (in.fd >= 0) {
  5955. close(in.fd);
  5956. back_exitstatus = waitforjob(in.jp);
  5957. }
  5958. INT_ON;
  5959. /* Eat all trailing newlines */
  5960. dest = expdest;
  5961. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5962. STUNPUTC(dest);
  5963. expdest = dest;
  5964. if (!(flag & EXP_QUOTED))
  5965. recordregion(startloc, dest - (char *)stackblock(), 0);
  5966. TRACE(("evalbackq: size:%d:'%.*s'\n",
  5967. (int)((dest - (char *)stackblock()) - startloc),
  5968. (int)((dest - (char *)stackblock()) - startloc),
  5969. stackblock() + startloc));
  5970. }
  5971. #if ENABLE_FEATURE_SH_MATH
  5972. /*
  5973. * Expand arithmetic expression. Backup to start of expression,
  5974. * evaluate, place result in (backed up) result, adjust string position.
  5975. */
  5976. static void
  5977. expari(int flag)
  5978. {
  5979. char *p, *start;
  5980. int begoff;
  5981. int len;
  5982. /* ifsfree(); */
  5983. /*
  5984. * This routine is slightly over-complicated for
  5985. * efficiency. Next we scan backwards looking for the
  5986. * start of arithmetic.
  5987. */
  5988. start = stackblock();
  5989. p = expdest - 1;
  5990. *p = '\0';
  5991. p--;
  5992. while (1) {
  5993. int esc;
  5994. while ((unsigned char)*p != CTLARI) {
  5995. p--;
  5996. #if DEBUG
  5997. if (p < start) {
  5998. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5999. }
  6000. #endif
  6001. }
  6002. esc = esclen(start, p);
  6003. if (!(esc % 2)) {
  6004. break;
  6005. }
  6006. p -= esc + 1;
  6007. }
  6008. begoff = p - start;
  6009. removerecordregions(begoff);
  6010. expdest = p;
  6011. if (flag & QUOTES_ESC)
  6012. rmescapes(p + 1, 0, NULL);
  6013. len = cvtnum(ash_arith(p + 1));
  6014. if (!(flag & EXP_QUOTED))
  6015. recordregion(begoff, begoff + len, 0);
  6016. }
  6017. #endif
  6018. /* argstr needs it */
  6019. static char *evalvar(char *p, int flags);
  6020. /*
  6021. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  6022. * characters to allow for further processing. Otherwise treat
  6023. * $@ like $* since no splitting will be performed.
  6024. */
  6025. static void
  6026. argstr(char *p, int flags)
  6027. {
  6028. static const char spclchars[] ALIGN1 = {
  6029. '=',
  6030. ':',
  6031. CTLQUOTEMARK,
  6032. CTLENDVAR,
  6033. CTLESC,
  6034. CTLVAR,
  6035. CTLBACKQ,
  6036. #if ENABLE_FEATURE_SH_MATH
  6037. CTLENDARI,
  6038. #endif
  6039. '\0'
  6040. };
  6041. const char *reject = spclchars;
  6042. int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6043. int inquotes;
  6044. size_t length;
  6045. int startloc;
  6046. if (!(flags & EXP_VARTILDE)) {
  6047. reject += 2;
  6048. } else if (flags & EXP_VARTILDE2) {
  6049. reject++;
  6050. }
  6051. inquotes = 0;
  6052. length = 0;
  6053. if (flags & EXP_TILDE) {
  6054. char *q;
  6055. flags &= ~EXP_TILDE;
  6056. tilde:
  6057. q = p;
  6058. if (*q == '~')
  6059. p = exptilde(p, q, flags);
  6060. }
  6061. start:
  6062. startloc = expdest - (char *)stackblock();
  6063. for (;;) {
  6064. unsigned char c;
  6065. length += strcspn(p + length, reject);
  6066. c = p[length];
  6067. if (c) {
  6068. if (!(c & 0x80)
  6069. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6070. ) {
  6071. /* c == '=' || c == ':' || c == CTLENDARI */
  6072. length++;
  6073. }
  6074. }
  6075. if (length > 0) {
  6076. int newloc;
  6077. expdest = stack_nputstr(p, length, expdest);
  6078. newloc = expdest - (char *)stackblock();
  6079. if (breakall && !inquotes && newloc > startloc) {
  6080. recordregion(startloc, newloc, 0);
  6081. }
  6082. startloc = newloc;
  6083. }
  6084. p += length + 1;
  6085. length = 0;
  6086. switch (c) {
  6087. case '\0':
  6088. goto breakloop;
  6089. case '=':
  6090. if (flags & EXP_VARTILDE2) {
  6091. p--;
  6092. continue;
  6093. }
  6094. flags |= EXP_VARTILDE2;
  6095. reject++;
  6096. /* fall through */
  6097. case ':':
  6098. /*
  6099. * sort of a hack - expand tildes in variable
  6100. * assignments (after the first '=' and after ':'s).
  6101. */
  6102. if (*--p == '~') {
  6103. goto tilde;
  6104. }
  6105. continue;
  6106. }
  6107. switch (c) {
  6108. case CTLENDVAR: /* ??? */
  6109. goto breakloop;
  6110. case CTLQUOTEMARK:
  6111. /* "$@" syntax adherence hack */
  6112. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6113. p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
  6114. goto start;
  6115. }
  6116. inquotes ^= EXP_QUOTED;
  6117. addquote:
  6118. if (flags & QUOTES_ESC) {
  6119. p--;
  6120. length++;
  6121. startloc++;
  6122. }
  6123. break;
  6124. case CTLESC:
  6125. startloc++;
  6126. length++;
  6127. goto addquote;
  6128. case CTLVAR:
  6129. TRACE(("argstr: evalvar('%s')\n", p));
  6130. p = evalvar(p, flags | inquotes);
  6131. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6132. goto start;
  6133. case CTLBACKQ:
  6134. expbackq(argbackq->n, flags | inquotes);
  6135. argbackq = argbackq->next;
  6136. goto start;
  6137. #if ENABLE_FEATURE_SH_MATH
  6138. case CTLENDARI:
  6139. p--;
  6140. expari(flags | inquotes);
  6141. goto start;
  6142. #endif
  6143. }
  6144. }
  6145. breakloop: ;
  6146. }
  6147. static char *
  6148. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6149. char *pattern, int quotes, int zero)
  6150. {
  6151. char *loc, *loc2;
  6152. char c;
  6153. loc = startp;
  6154. loc2 = rmesc;
  6155. do {
  6156. int match;
  6157. const char *s = loc2;
  6158. c = *loc2;
  6159. if (zero) {
  6160. *loc2 = '\0';
  6161. s = rmesc;
  6162. }
  6163. match = pmatch(pattern, s);
  6164. *loc2 = c;
  6165. if (match)
  6166. return loc;
  6167. if (quotes && (unsigned char)*loc == CTLESC)
  6168. loc++;
  6169. loc++;
  6170. loc2++;
  6171. } while (c);
  6172. return NULL;
  6173. }
  6174. static char *
  6175. scanright(char *startp, char *rmesc, char *rmescend,
  6176. char *pattern, int quotes, int match_at_start)
  6177. {
  6178. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6179. int try2optimize = match_at_start;
  6180. #endif
  6181. int esc = 0;
  6182. char *loc;
  6183. char *loc2;
  6184. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6185. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6186. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6187. * Logic:
  6188. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6189. * and on each iteration they go back two/one char until they reach the beginning.
  6190. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6191. */
  6192. /* TODO: document in what other circumstances we are called. */
  6193. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6194. int match;
  6195. char c = *loc2;
  6196. const char *s = loc2;
  6197. if (match_at_start) {
  6198. *loc2 = '\0';
  6199. s = rmesc;
  6200. }
  6201. match = pmatch(pattern, s);
  6202. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6203. *loc2 = c;
  6204. if (match)
  6205. return loc;
  6206. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6207. if (try2optimize) {
  6208. /* Maybe we can optimize this:
  6209. * if pattern ends with unescaped *, we can avoid checking
  6210. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6211. * it won't match truncated "raw_value_of_" strings too.
  6212. */
  6213. unsigned plen = strlen(pattern);
  6214. /* Does it end with "*"? */
  6215. if (plen != 0 && pattern[--plen] == '*') {
  6216. /* "xxxx*" is not escaped */
  6217. /* "xxx\*" is escaped */
  6218. /* "xx\\*" is not escaped */
  6219. /* "x\\\*" is escaped */
  6220. int slashes = 0;
  6221. while (plen != 0 && pattern[--plen] == '\\')
  6222. slashes++;
  6223. if (!(slashes & 1))
  6224. break; /* ends with unescaped "*" */
  6225. }
  6226. try2optimize = 0;
  6227. }
  6228. #endif
  6229. loc--;
  6230. if (quotes) {
  6231. if (--esc < 0) {
  6232. esc = esclen(startp, loc);
  6233. }
  6234. if (esc % 2) {
  6235. esc--;
  6236. loc--;
  6237. }
  6238. }
  6239. }
  6240. return NULL;
  6241. }
  6242. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6243. static void
  6244. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6245. {
  6246. const char *msg;
  6247. const char *tail;
  6248. tail = nullstr;
  6249. msg = "parameter not set";
  6250. if (umsg) {
  6251. if ((unsigned char)*end == CTLENDVAR) {
  6252. if (varflags & VSNUL)
  6253. tail = " or null";
  6254. } else {
  6255. msg = umsg;
  6256. }
  6257. }
  6258. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6259. }
  6260. static const char *
  6261. subevalvar(char *p, char *varname, int strloc, int subtype,
  6262. int startloc, int varflags, int flag)
  6263. {
  6264. struct nodelist *saveargbackq = argbackq;
  6265. int quotes = flag & QUOTES_ESC;
  6266. char *startp;
  6267. char *loc;
  6268. char *rmesc, *rmescend;
  6269. char *str;
  6270. int amount, resetloc;
  6271. int argstr_flags;
  6272. IF_BASH_PATTERN_SUBST(int workloc;)
  6273. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6274. IF_BASH_PATTERN_SUBST(char *repl;)
  6275. int zero;
  6276. char *(*scan)(char*, char*, char*, char*, int, int);
  6277. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  6278. // p, varname, strloc, subtype, startloc, varflags, quotes);
  6279. #if BASH_PATTERN_SUBST
  6280. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6281. * argstr() call expands possible variable references in pattern:
  6282. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6283. */
  6284. repl = NULL;
  6285. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6286. /* Find '/' and replace with NUL */
  6287. repl = p;
  6288. /* The pattern can't be empty.
  6289. * IOW: if the first char after "${v//" is a slash,
  6290. * it does not terminate the pattern - it's the first char of the pattern:
  6291. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6292. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6293. */
  6294. if (*repl == '/')
  6295. repl++;
  6296. for (;;) {
  6297. if (*repl == '\0') {
  6298. repl = NULL;
  6299. break;
  6300. }
  6301. if (*repl == '/') {
  6302. *repl = '\0';
  6303. break;
  6304. }
  6305. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6306. if ((unsigned char)*repl == CTLESC && repl[1])
  6307. repl++;
  6308. repl++;
  6309. }
  6310. }
  6311. #endif
  6312. argstr_flags = EXP_TILDE;
  6313. if (subtype != VSASSIGN
  6314. && subtype != VSQUESTION
  6315. #if BASH_SUBSTR
  6316. && subtype != VSSUBSTR
  6317. #endif
  6318. ) {
  6319. /* EXP_CASE keeps CTLESC's */
  6320. argstr_flags = EXP_TILDE | EXP_CASE;
  6321. }
  6322. argstr(p, argstr_flags);
  6323. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6324. #if BASH_PATTERN_SUBST
  6325. slash_pos = -1;
  6326. if (repl) {
  6327. slash_pos = expdest - ((char *)stackblock() + strloc);
  6328. STPUTC('/', expdest);
  6329. //bb_error_msg("repl+1:'%s'", repl + 1);
  6330. argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6331. *repl = '/';
  6332. }
  6333. #endif
  6334. STPUTC('\0', expdest);
  6335. argbackq = saveargbackq;
  6336. startp = (char *)stackblock() + startloc;
  6337. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6338. switch (subtype) {
  6339. case VSASSIGN:
  6340. setvar0(varname, startp);
  6341. amount = startp - expdest;
  6342. STADJUST(amount, expdest);
  6343. return startp;
  6344. case VSQUESTION:
  6345. varunset(p, varname, startp, varflags);
  6346. /* NOTREACHED */
  6347. #if BASH_SUBSTR
  6348. case VSSUBSTR: {
  6349. int pos, len, orig_len;
  6350. char *colon;
  6351. loc = str = stackblock() + strloc;
  6352. /* Read POS in ${var:POS:LEN} */
  6353. colon = strchr(loc, ':');
  6354. if (colon) *colon = '\0';
  6355. pos = substr_atoi(loc);
  6356. if (colon) *colon = ':';
  6357. /* Read LEN in ${var:POS:LEN} */
  6358. len = str - startp - 1;
  6359. /* *loc != '\0', guaranteed by parser */
  6360. if (quotes) {
  6361. char *ptr;
  6362. /* Adjust the length by the number of escapes */
  6363. for (ptr = startp; ptr < (str - 1); ptr++) {
  6364. if ((unsigned char)*ptr == CTLESC) {
  6365. len--;
  6366. ptr++;
  6367. }
  6368. }
  6369. }
  6370. orig_len = len;
  6371. if (*loc++ == ':') {
  6372. /* ${var::LEN} */
  6373. len = substr_atoi(loc);
  6374. } else {
  6375. /* Skip POS in ${var:POS:LEN} */
  6376. len = orig_len;
  6377. while (*loc && *loc != ':')
  6378. loc++;
  6379. if (*loc++ == ':')
  6380. len = substr_atoi(loc);
  6381. }
  6382. if (pos < 0) {
  6383. /* ${VAR:$((-n)):l} starts n chars from the end */
  6384. pos = orig_len + pos;
  6385. }
  6386. if ((unsigned)pos >= orig_len) {
  6387. /* apart from obvious ${VAR:999999:l},
  6388. * covers ${VAR:$((-9999999)):l} - result is ""
  6389. * (bash compat)
  6390. */
  6391. pos = 0;
  6392. len = 0;
  6393. }
  6394. if (len < 0) {
  6395. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6396. len = (orig_len - pos) + len;
  6397. }
  6398. if ((unsigned)len > (orig_len - pos))
  6399. len = orig_len - pos;
  6400. for (str = startp; pos; str++, pos--) {
  6401. if (quotes && (unsigned char)*str == CTLESC)
  6402. str++;
  6403. }
  6404. for (loc = startp; len; len--) {
  6405. if (quotes && (unsigned char)*str == CTLESC)
  6406. *loc++ = *str++;
  6407. *loc++ = *str++;
  6408. }
  6409. *loc = '\0';
  6410. amount = loc - expdest;
  6411. STADJUST(amount, expdest);
  6412. return loc;
  6413. }
  6414. #endif /* BASH_SUBSTR */
  6415. }
  6416. resetloc = expdest - (char *)stackblock();
  6417. #if BASH_PATTERN_SUBST
  6418. repl = NULL;
  6419. /* We'll comeback here if we grow the stack while handling
  6420. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6421. * stack will need rebasing, and we'll need to remove our work
  6422. * areas each time
  6423. */
  6424. restart:
  6425. #endif
  6426. amount = expdest - ((char *)stackblock() + resetloc);
  6427. STADJUST(-amount, expdest);
  6428. startp = (char *)stackblock() + startloc;
  6429. rmesc = startp;
  6430. rmescend = (char *)stackblock() + strloc;
  6431. //bb_error_msg("str7:'%s'", rmescend);
  6432. if (quotes) {
  6433. //TODO: how to handle slash_pos here if string changes (shortens?)
  6434. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6435. if (rmesc != startp) {
  6436. rmescend = expdest;
  6437. startp = (char *)stackblock() + startloc;
  6438. }
  6439. }
  6440. rmescend--;
  6441. str = (char *)stackblock() + strloc;
  6442. /*
  6443. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6444. * The result is a_\_z_c (not a\_\_z_c)!
  6445. *
  6446. * The search pattern and replace string treat backslashes differently!
  6447. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6448. * and string. It's only used on the first call.
  6449. */
  6450. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6451. rmescapes(str, RMESCAPE_GLOB,
  6452. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6453. );
  6454. #if BASH_PATTERN_SUBST
  6455. workloc = expdest - (char *)stackblock();
  6456. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6457. int len;
  6458. char *idx, *end;
  6459. if (!repl) {
  6460. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6461. repl = nullstr;
  6462. if (slash_pos >= 0) {
  6463. repl = str + slash_pos;
  6464. *repl++ = '\0';
  6465. }
  6466. }
  6467. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6468. /* If there's no pattern to match, return the expansion unmolested */
  6469. if (str[0] == '\0')
  6470. return NULL;
  6471. len = 0;
  6472. idx = startp;
  6473. end = str - 1;
  6474. while (idx < end) {
  6475. try_to_match:
  6476. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6477. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6478. if (!loc) {
  6479. /* No match, advance */
  6480. char *restart_detect = stackblock();
  6481. skip_matching:
  6482. STPUTC(*idx, expdest);
  6483. if (quotes && (unsigned char)*idx == CTLESC) {
  6484. idx++;
  6485. len++;
  6486. STPUTC(*idx, expdest);
  6487. }
  6488. if (stackblock() != restart_detect)
  6489. goto restart;
  6490. idx++;
  6491. len++;
  6492. rmesc++;
  6493. /* continue; - prone to quadratic behavior, smarter code: */
  6494. if (idx >= end)
  6495. break;
  6496. if (str[0] == '*') {
  6497. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6498. * it would never match "ong_string" etc, no point in trying.
  6499. */
  6500. goto skip_matching;
  6501. }
  6502. goto try_to_match;
  6503. }
  6504. if (subtype == VSREPLACEALL) {
  6505. while (idx < loc) {
  6506. if (quotes && (unsigned char)*idx == CTLESC)
  6507. idx++;
  6508. idx++;
  6509. rmesc++;
  6510. }
  6511. } else {
  6512. idx = loc;
  6513. }
  6514. //bb_error_msg("repl:'%s'", repl);
  6515. for (loc = (char*)repl; *loc; loc++) {
  6516. char *restart_detect = stackblock();
  6517. if (quotes && *loc == '\\') {
  6518. STPUTC(CTLESC, expdest);
  6519. len++;
  6520. }
  6521. STPUTC(*loc, expdest);
  6522. if (stackblock() != restart_detect)
  6523. goto restart;
  6524. len++;
  6525. }
  6526. if (subtype == VSREPLACE) {
  6527. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6528. while (*idx) {
  6529. char *restart_detect = stackblock();
  6530. STPUTC(*idx, expdest);
  6531. if (stackblock() != restart_detect)
  6532. goto restart;
  6533. len++;
  6534. idx++;
  6535. }
  6536. break;
  6537. }
  6538. }
  6539. /* We've put the replaced text into a buffer at workloc, now
  6540. * move it to the right place and adjust the stack.
  6541. */
  6542. STPUTC('\0', expdest);
  6543. startp = (char *)stackblock() + startloc;
  6544. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6545. //bb_error_msg("startp:'%s'", startp);
  6546. amount = expdest - (startp + len);
  6547. STADJUST(-amount, expdest);
  6548. return startp;
  6549. }
  6550. #endif /* BASH_PATTERN_SUBST */
  6551. subtype -= VSTRIMRIGHT;
  6552. #if DEBUG
  6553. if (subtype < 0 || subtype > 7)
  6554. abort();
  6555. #endif
  6556. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6557. zero = subtype >> 1;
  6558. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6559. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6560. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6561. if (loc) {
  6562. if (zero) {
  6563. memmove(startp, loc, str - loc);
  6564. loc = startp + (str - loc) - 1;
  6565. }
  6566. *loc = '\0';
  6567. amount = loc - expdest;
  6568. STADJUST(amount, expdest);
  6569. }
  6570. return loc;
  6571. }
  6572. /*
  6573. * Add the value of a specialized variable to the stack string.
  6574. * name parameter (examples):
  6575. * ash -c 'echo $1' name:'1='
  6576. * ash -c 'echo $qwe' name:'qwe='
  6577. * ash -c 'echo $$' name:'$='
  6578. * ash -c 'echo ${$}' name:'$='
  6579. * ash -c 'echo ${$##q}' name:'$=q'
  6580. * ash -c 'echo ${#$}' name:'$='
  6581. * note: examples with bad shell syntax:
  6582. * ash -c 'echo ${#$1}' name:'$=1'
  6583. * ash -c 'echo ${#1#}' name:'1=#'
  6584. */
  6585. static NOINLINE ssize_t
  6586. varvalue(char *name, int varflags, int flags, int quoted)
  6587. {
  6588. const char *p;
  6589. int num;
  6590. int i;
  6591. ssize_t len = 0;
  6592. int sep;
  6593. int subtype = varflags & VSTYPE;
  6594. int discard = subtype == VSPLUS || subtype == VSLENGTH;
  6595. int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
  6596. int syntax;
  6597. sep = (flags & EXP_FULL) << CHAR_BIT;
  6598. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  6599. switch (*name) {
  6600. case '$':
  6601. num = rootpid;
  6602. goto numvar;
  6603. case '?':
  6604. num = exitstatus;
  6605. goto numvar;
  6606. case '#':
  6607. num = shellparam.nparam;
  6608. goto numvar;
  6609. case '!':
  6610. num = backgndpid;
  6611. if (num == 0)
  6612. return -1;
  6613. numvar:
  6614. len = cvtnum(num);
  6615. goto check_1char_name;
  6616. case '-':
  6617. expdest = makestrspace(NOPTS, expdest);
  6618. for (i = NOPTS - 1; i >= 0; i--) {
  6619. if (optlist[i] && optletters(i)) {
  6620. USTPUTC(optletters(i), expdest);
  6621. len++;
  6622. }
  6623. }
  6624. check_1char_name:
  6625. #if 0
  6626. /* handles cases similar to ${#$1} */
  6627. if (name[2] != '\0')
  6628. raise_error_syntax("bad substitution");
  6629. #endif
  6630. break;
  6631. case '@':
  6632. if (quoted && sep)
  6633. goto param;
  6634. /* fall through */
  6635. case '*': {
  6636. char **ap;
  6637. char sepc;
  6638. char c;
  6639. /* We will set c to 0 or ~0 depending on whether
  6640. * we're doing field splitting. We won't do field
  6641. * splitting if either we're quoted or sep is zero.
  6642. *
  6643. * Instead of testing (quoted || !sep) the following
  6644. * trick optimises away any branches by using the
  6645. * fact that EXP_QUOTED (which is the only bit that
  6646. * can be set in quoted) is the same as EXP_FULL <<
  6647. * CHAR_BIT (which is the only bit that can be set
  6648. * in sep).
  6649. */
  6650. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6651. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6652. #endif
  6653. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6654. sep &= ~quoted;
  6655. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6656. param:
  6657. sepc = sep;
  6658. ap = shellparam.p;
  6659. if (!ap)
  6660. return -1;
  6661. while ((p = *ap++) != NULL) {
  6662. len += strtodest(p, syntax, quotes);
  6663. if (*ap && sep) {
  6664. len++;
  6665. memtodest(&sepc, 1, syntax, quotes);
  6666. }
  6667. }
  6668. break;
  6669. } /* case '*' */
  6670. case '0':
  6671. case '1':
  6672. case '2':
  6673. case '3':
  6674. case '4':
  6675. case '5':
  6676. case '6':
  6677. case '7':
  6678. case '8':
  6679. case '9':
  6680. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6681. if (num < 0 || num > shellparam.nparam)
  6682. return -1;
  6683. p = num ? shellparam.p[num - 1] : arg0;
  6684. goto value;
  6685. default:
  6686. /* NB: name has form "VAR=..." */
  6687. p = lookupvar(name);
  6688. value:
  6689. if (!p)
  6690. return -1;
  6691. len = strtodest(p, syntax, quotes);
  6692. #if ENABLE_UNICODE_SUPPORT
  6693. if (subtype == VSLENGTH && len > 0) {
  6694. reinit_unicode_for_ash();
  6695. if (unicode_status == UNICODE_ON) {
  6696. STADJUST(-len, expdest);
  6697. discard = 0;
  6698. len = unicode_strlen(p);
  6699. }
  6700. }
  6701. #endif
  6702. break;
  6703. }
  6704. if (discard)
  6705. STADJUST(-len, expdest);
  6706. return len;
  6707. }
  6708. /*
  6709. * Expand a variable, and return a pointer to the next character in the
  6710. * input string.
  6711. */
  6712. static char *
  6713. evalvar(char *p, int flag)
  6714. {
  6715. char varflags;
  6716. char subtype;
  6717. int quoted;
  6718. char *var;
  6719. int patloc;
  6720. int startloc;
  6721. ssize_t varlen;
  6722. varflags = (unsigned char) *p++;
  6723. subtype = varflags & VSTYPE;
  6724. if (!subtype)
  6725. raise_error_syntax("bad substitution");
  6726. quoted = flag & EXP_QUOTED;
  6727. var = p;
  6728. startloc = expdest - (char *)stackblock();
  6729. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6730. again:
  6731. varlen = varvalue(var, varflags, flag, quoted);
  6732. if (varflags & VSNUL)
  6733. varlen--;
  6734. if (subtype == VSPLUS) {
  6735. varlen = -1 - varlen;
  6736. goto vsplus;
  6737. }
  6738. if (subtype == VSMINUS) {
  6739. vsplus:
  6740. if (varlen < 0) {
  6741. argstr(
  6742. p,
  6743. flag | EXP_TILDE | EXP_WORD
  6744. );
  6745. goto end;
  6746. }
  6747. goto record;
  6748. }
  6749. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6750. if (varlen >= 0)
  6751. goto record;
  6752. subevalvar(p, var, 0, subtype, startloc, varflags,
  6753. flag & ~QUOTES_ESC);
  6754. varflags &= ~VSNUL;
  6755. /*
  6756. * Remove any recorded regions beyond
  6757. * start of variable
  6758. */
  6759. removerecordregions(startloc);
  6760. goto again;
  6761. }
  6762. if (varlen < 0 && uflag)
  6763. varunset(p, var, 0, 0);
  6764. if (subtype == VSLENGTH) {
  6765. cvtnum(varlen > 0 ? varlen : 0);
  6766. goto record;
  6767. }
  6768. if (subtype == VSNORMAL) {
  6769. record:
  6770. if (quoted) {
  6771. quoted = *var == '@' && shellparam.nparam;
  6772. if (!quoted)
  6773. goto end;
  6774. }
  6775. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6776. goto end;
  6777. }
  6778. #if DEBUG
  6779. switch (subtype) {
  6780. case VSTRIMLEFT:
  6781. case VSTRIMLEFTMAX:
  6782. case VSTRIMRIGHT:
  6783. case VSTRIMRIGHTMAX:
  6784. #if BASH_SUBSTR
  6785. case VSSUBSTR:
  6786. #endif
  6787. #if BASH_PATTERN_SUBST
  6788. case VSREPLACE:
  6789. case VSREPLACEALL:
  6790. #endif
  6791. break;
  6792. default:
  6793. abort();
  6794. }
  6795. #endif
  6796. if (varlen >= 0) {
  6797. /*
  6798. * Terminate the string and start recording the pattern
  6799. * right after it
  6800. */
  6801. STPUTC('\0', expdest);
  6802. patloc = expdest - (char *)stackblock();
  6803. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6804. startloc, varflags, flag)) {
  6805. int amount = expdest - (
  6806. (char *)stackblock() + patloc - 1
  6807. );
  6808. STADJUST(-amount, expdest);
  6809. }
  6810. /* Remove any recorded regions beyond start of variable */
  6811. removerecordregions(startloc);
  6812. goto record;
  6813. }
  6814. end:
  6815. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6816. int nesting = 1;
  6817. for (;;) {
  6818. unsigned char c = *p++;
  6819. if (c == CTLESC)
  6820. p++;
  6821. else if (c == CTLBACKQ) {
  6822. if (varlen >= 0)
  6823. argbackq = argbackq->next;
  6824. } else if (c == CTLVAR) {
  6825. if ((*p++ & VSTYPE) != VSNORMAL)
  6826. nesting++;
  6827. } else if (c == CTLENDVAR) {
  6828. if (--nesting == 0)
  6829. break;
  6830. }
  6831. }
  6832. }
  6833. return p;
  6834. }
  6835. /*
  6836. * Add a file name to the list.
  6837. */
  6838. static void
  6839. addfname(const char *name)
  6840. {
  6841. struct strlist *sp;
  6842. sp = stzalloc(sizeof(*sp));
  6843. sp->text = sstrdup(name);
  6844. *exparg.lastp = sp;
  6845. exparg.lastp = &sp->next;
  6846. }
  6847. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6848. static int
  6849. hasmeta(const char *p)
  6850. {
  6851. static const char chars[] ALIGN1 = {
  6852. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6853. };
  6854. for (;;) {
  6855. p = strpbrk(p, chars);
  6856. if (!p)
  6857. break;
  6858. switch ((unsigned char)*p) {
  6859. case CTLQUOTEMARK:
  6860. for (;;) {
  6861. p++;
  6862. if ((unsigned char)*p == CTLQUOTEMARK)
  6863. break;
  6864. if ((unsigned char)*p == CTLESC)
  6865. p++;
  6866. if (*p == '\0') /* huh? */
  6867. return 0;
  6868. }
  6869. break;
  6870. case '\\':
  6871. case CTLESC:
  6872. p++;
  6873. if (*p == '\0')
  6874. return 0;
  6875. break;
  6876. case '[':
  6877. if (!strchr(p + 1, ']')) {
  6878. /* It's not a properly closed [] pattern,
  6879. * but other metas may follow. Continue checking.
  6880. * my[file* _is_ globbed by bash
  6881. * and matches filenames like "my[file1".
  6882. */
  6883. break;
  6884. }
  6885. /* fallthrough */
  6886. default:
  6887. /* case '*': */
  6888. /* case '?': */
  6889. return 1;
  6890. }
  6891. p++;
  6892. }
  6893. return 0;
  6894. }
  6895. /* If we want to use glob() from libc... */
  6896. #if !ENABLE_ASH_INTERNAL_GLOB
  6897. /* Add the result of glob() to the list */
  6898. static void
  6899. addglob(const glob_t *pglob)
  6900. {
  6901. char **p = pglob->gl_pathv;
  6902. do {
  6903. addfname(*p);
  6904. } while (*++p);
  6905. }
  6906. static void
  6907. expandmeta(struct strlist *str /*, int flag*/)
  6908. {
  6909. /* TODO - EXP_REDIR */
  6910. while (str) {
  6911. char *p;
  6912. glob_t pglob;
  6913. int i;
  6914. if (fflag)
  6915. goto nometa;
  6916. if (!hasmeta(str->text))
  6917. goto nometa;
  6918. INT_OFF;
  6919. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6920. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6921. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6922. //
  6923. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6924. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6925. // Which means you need to unescape the string, right? Not so fast:
  6926. // if there _is_ a file named "file\?" (with backslash), it is returned
  6927. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6928. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6929. //
  6930. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6931. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6932. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6933. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6934. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6935. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6936. i = glob(p, 0, NULL, &pglob);
  6937. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6938. if (p != str->text)
  6939. free(p);
  6940. switch (i) {
  6941. case 0:
  6942. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6943. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6944. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6945. goto nometa2;
  6946. #endif
  6947. addglob(&pglob);
  6948. globfree(&pglob);
  6949. INT_ON;
  6950. break;
  6951. case GLOB_NOMATCH:
  6952. //nometa2:
  6953. globfree(&pglob);
  6954. INT_ON;
  6955. nometa:
  6956. *exparg.lastp = str;
  6957. rmescapes(str->text, 0, NULL);
  6958. exparg.lastp = &str->next;
  6959. break;
  6960. default: /* GLOB_NOSPACE */
  6961. globfree(&pglob);
  6962. INT_ON;
  6963. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  6964. }
  6965. str = str->next;
  6966. }
  6967. }
  6968. #else
  6969. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  6970. /*
  6971. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6972. */
  6973. typedef struct exp_t {
  6974. char *dir;
  6975. unsigned dir_max;
  6976. } exp_t;
  6977. static void
  6978. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  6979. {
  6980. #define expdir exp->dir
  6981. #define expdir_max exp->dir_max
  6982. char *enddir = expdir + expdir_len;
  6983. char *p;
  6984. const char *cp;
  6985. char *start;
  6986. char *endname;
  6987. int metaflag;
  6988. struct stat statb;
  6989. DIR *dirp;
  6990. struct dirent *dp;
  6991. int atend;
  6992. int matchdot;
  6993. int esc;
  6994. metaflag = 0;
  6995. start = name;
  6996. for (p = name; esc = 0, *p; p += esc + 1) {
  6997. if (*p == '*' || *p == '?')
  6998. metaflag = 1;
  6999. else if (*p == '[') {
  7000. char *q = p + 1;
  7001. if (*q == '!')
  7002. q++;
  7003. for (;;) {
  7004. if (*q == '\\')
  7005. q++;
  7006. if (*q == '/' || *q == '\0')
  7007. break;
  7008. if (*++q == ']') {
  7009. metaflag = 1;
  7010. break;
  7011. }
  7012. }
  7013. } else {
  7014. if (*p == '\\' && p[1])
  7015. esc++;
  7016. if (p[esc] == '/') {
  7017. if (metaflag)
  7018. break;
  7019. start = p + esc + 1;
  7020. }
  7021. }
  7022. }
  7023. if (metaflag == 0) { /* we've reached the end of the file name */
  7024. if (!expdir_len)
  7025. return;
  7026. p = name;
  7027. do {
  7028. if (*p == '\\' && p[1])
  7029. p++;
  7030. *enddir++ = *p;
  7031. } while (*p++);
  7032. if (lstat(expdir, &statb) == 0)
  7033. addfname(expdir);
  7034. return;
  7035. }
  7036. endname = p;
  7037. if (name < start) {
  7038. p = name;
  7039. do {
  7040. if (*p == '\\' && p[1])
  7041. p++;
  7042. *enddir++ = *p++;
  7043. } while (p < start);
  7044. }
  7045. *enddir = '\0';
  7046. cp = expdir;
  7047. expdir_len = enddir - cp;
  7048. if (!expdir_len)
  7049. cp = ".";
  7050. dirp = opendir(cp);
  7051. if (dirp == NULL)
  7052. return;
  7053. if (*endname == 0) {
  7054. atend = 1;
  7055. } else {
  7056. atend = 0;
  7057. *endname = '\0';
  7058. endname += esc + 1;
  7059. }
  7060. name_len -= endname - name;
  7061. matchdot = 0;
  7062. p = start;
  7063. if (*p == '\\')
  7064. p++;
  7065. if (*p == '.')
  7066. matchdot++;
  7067. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7068. if (dp->d_name[0] == '.' && !matchdot)
  7069. continue;
  7070. if (pmatch(start, dp->d_name)) {
  7071. if (atend) {
  7072. strcpy(enddir, dp->d_name);
  7073. addfname(expdir);
  7074. } else {
  7075. unsigned offset;
  7076. unsigned len;
  7077. p = stpcpy(enddir, dp->d_name);
  7078. *p = '/';
  7079. offset = p - expdir + 1;
  7080. len = offset + name_len + NAME_MAX;
  7081. if (len > expdir_max) {
  7082. len += PATH_MAX;
  7083. expdir = ckrealloc(expdir, len);
  7084. expdir_max = len;
  7085. }
  7086. expmeta(exp, endname, name_len, offset);
  7087. enddir = expdir + expdir_len;
  7088. }
  7089. }
  7090. }
  7091. closedir(dirp);
  7092. if (!atend)
  7093. endname[-esc - 1] = esc ? '\\' : '/';
  7094. #undef expdir
  7095. #undef expdir_max
  7096. }
  7097. static struct strlist *
  7098. msort(struct strlist *list, int len)
  7099. {
  7100. struct strlist *p, *q = NULL;
  7101. struct strlist **lpp;
  7102. int half;
  7103. int n;
  7104. if (len <= 1)
  7105. return list;
  7106. half = len >> 1;
  7107. p = list;
  7108. for (n = half; --n >= 0;) {
  7109. q = p;
  7110. p = p->next;
  7111. }
  7112. q->next = NULL; /* terminate first half of list */
  7113. q = msort(list, half); /* sort first half of list */
  7114. p = msort(p, len - half); /* sort second half */
  7115. lpp = &list;
  7116. for (;;) {
  7117. #if ENABLE_LOCALE_SUPPORT
  7118. if (strcoll(p->text, q->text) < 0)
  7119. #else
  7120. if (strcmp(p->text, q->text) < 0)
  7121. #endif
  7122. {
  7123. *lpp = p;
  7124. lpp = &p->next;
  7125. p = *lpp;
  7126. if (p == NULL) {
  7127. *lpp = q;
  7128. break;
  7129. }
  7130. } else {
  7131. *lpp = q;
  7132. lpp = &q->next;
  7133. q = *lpp;
  7134. if (q == NULL) {
  7135. *lpp = p;
  7136. break;
  7137. }
  7138. }
  7139. }
  7140. return list;
  7141. }
  7142. /*
  7143. * Sort the results of file name expansion. It calculates the number of
  7144. * strings to sort and then calls msort (short for merge sort) to do the
  7145. * work.
  7146. */
  7147. static struct strlist *
  7148. expsort(struct strlist *str)
  7149. {
  7150. int len;
  7151. struct strlist *sp;
  7152. len = 0;
  7153. for (sp = str; sp; sp = sp->next)
  7154. len++;
  7155. return msort(str, len);
  7156. }
  7157. static void
  7158. expandmeta(struct strlist *str /*, int flag*/)
  7159. {
  7160. /* TODO - EXP_REDIR */
  7161. while (str) {
  7162. exp_t exp;
  7163. struct strlist **savelastp;
  7164. struct strlist *sp;
  7165. char *p;
  7166. unsigned len;
  7167. if (fflag)
  7168. goto nometa;
  7169. if (!hasmeta(str->text))
  7170. goto nometa;
  7171. savelastp = exparg.lastp;
  7172. INT_OFF;
  7173. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7174. len = strlen(p);
  7175. exp.dir_max = len + PATH_MAX;
  7176. exp.dir = ckmalloc(exp.dir_max);
  7177. expmeta(&exp, p, len, 0);
  7178. free(exp.dir);
  7179. if (p != str->text)
  7180. free(p);
  7181. INT_ON;
  7182. if (exparg.lastp == savelastp) {
  7183. /*
  7184. * no matches
  7185. */
  7186. nometa:
  7187. *exparg.lastp = str;
  7188. rmescapes(str->text, 0, NULL);
  7189. exparg.lastp = &str->next;
  7190. } else {
  7191. *exparg.lastp = NULL;
  7192. *savelastp = sp = expsort(*savelastp);
  7193. while (sp->next != NULL)
  7194. sp = sp->next;
  7195. exparg.lastp = &sp->next;
  7196. }
  7197. str = str->next;
  7198. }
  7199. }
  7200. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7201. /*
  7202. * Perform variable substitution and command substitution on an argument,
  7203. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7204. * perform splitting and file name expansion. When arglist is NULL, perform
  7205. * here document expansion.
  7206. */
  7207. static void
  7208. expandarg(union node *arg, struct arglist *arglist, int flag)
  7209. {
  7210. struct strlist *sp;
  7211. char *p;
  7212. argbackq = arg->narg.backquote;
  7213. STARTSTACKSTR(expdest);
  7214. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7215. argstr(arg->narg.text, flag);
  7216. p = _STPUTC('\0', expdest);
  7217. expdest = p - 1;
  7218. if (arglist == NULL) {
  7219. /* here document expanded */
  7220. goto out;
  7221. }
  7222. p = grabstackstr(p);
  7223. TRACE(("expandarg: p:'%s'\n", p));
  7224. exparg.lastp = &exparg.list;
  7225. /*
  7226. * TODO - EXP_REDIR
  7227. */
  7228. if (flag & EXP_FULL) {
  7229. ifsbreakup(p, &exparg);
  7230. *exparg.lastp = NULL;
  7231. exparg.lastp = &exparg.list;
  7232. expandmeta(exparg.list /*, flag*/);
  7233. } else {
  7234. sp = stzalloc(sizeof(*sp));
  7235. sp->text = p;
  7236. *exparg.lastp = sp;
  7237. exparg.lastp = &sp->next;
  7238. }
  7239. *exparg.lastp = NULL;
  7240. if (exparg.list) {
  7241. *arglist->lastp = exparg.list;
  7242. arglist->lastp = exparg.lastp;
  7243. }
  7244. out:
  7245. ifsfree();
  7246. }
  7247. /*
  7248. * Expand shell variables and backquotes inside a here document.
  7249. */
  7250. static void
  7251. expandhere(union node *arg, int fd)
  7252. {
  7253. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7254. full_write(fd, stackblock(), expdest - (char *)stackblock());
  7255. }
  7256. /*
  7257. * Returns true if the pattern matches the string.
  7258. */
  7259. static int
  7260. patmatch(char *pattern, const char *string)
  7261. {
  7262. char *p = preglob(pattern, 0);
  7263. int r = pmatch(p, string);
  7264. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7265. return r;
  7266. }
  7267. /*
  7268. * See if a pattern matches in a case statement.
  7269. */
  7270. static int
  7271. casematch(union node *pattern, char *val)
  7272. {
  7273. struct stackmark smark;
  7274. int result;
  7275. setstackmark(&smark);
  7276. argbackq = pattern->narg.backquote;
  7277. STARTSTACKSTR(expdest);
  7278. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7279. STACKSTRNUL(expdest);
  7280. ifsfree();
  7281. result = patmatch(stackblock(), val);
  7282. popstackmark(&smark);
  7283. return result;
  7284. }
  7285. /* ============ find_command */
  7286. struct builtincmd {
  7287. const char *name;
  7288. int (*builtin)(int, char **) FAST_FUNC;
  7289. /* unsigned flags; */
  7290. };
  7291. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7292. /* "regular" builtins always take precedence over commands,
  7293. * regardless of PATH=....%builtin... position */
  7294. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7295. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7296. struct cmdentry {
  7297. smallint cmdtype; /* CMDxxx */
  7298. union param {
  7299. int index;
  7300. /* index >= 0 for commands without path (slashes) */
  7301. /* (TODO: what exactly does the value mean? PATH position?) */
  7302. /* index == -1 for commands with slashes */
  7303. /* index == (-2 - applet_no) for NOFORK applets */
  7304. const struct builtincmd *cmd;
  7305. struct funcnode *func;
  7306. } u;
  7307. };
  7308. /* values of cmdtype */
  7309. #define CMDUNKNOWN -1 /* no entry in table for command */
  7310. #define CMDNORMAL 0 /* command is an executable program */
  7311. #define CMDFUNCTION 1 /* command is a shell function */
  7312. #define CMDBUILTIN 2 /* command is a shell builtin */
  7313. /* action to find_command() */
  7314. #define DO_ERR 0x01 /* prints errors */
  7315. #define DO_ABS 0x02 /* checks absolute paths */
  7316. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7317. #define DO_ALTPATH 0x08 /* using alternate path */
  7318. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  7319. static void find_command(char *, struct cmdentry *, int, const char *);
  7320. /* ============ Hashing commands */
  7321. /*
  7322. * When commands are first encountered, they are entered in a hash table.
  7323. * This ensures that a full path search will not have to be done for them
  7324. * on each invocation.
  7325. *
  7326. * We should investigate converting to a linear search, even though that
  7327. * would make the command name "hash" a misnomer.
  7328. */
  7329. struct tblentry {
  7330. struct tblentry *next; /* next entry in hash chain */
  7331. union param param; /* definition of builtin function */
  7332. smallint cmdtype; /* CMDxxx */
  7333. char rehash; /* if set, cd done since entry created */
  7334. char cmdname[1]; /* name of command */
  7335. };
  7336. static struct tblentry **cmdtable;
  7337. #define INIT_G_cmdtable() do { \
  7338. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7339. } while (0)
  7340. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7341. static void
  7342. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7343. {
  7344. #if ENABLE_FEATURE_SH_STANDALONE
  7345. if (applet_no >= 0) {
  7346. if (APPLET_IS_NOEXEC(applet_no)) {
  7347. clearenv();
  7348. while (*envp)
  7349. putenv(*envp++);
  7350. popredir(/*drop:*/ 1);
  7351. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7352. }
  7353. /* re-exec ourselves with the new arguments */
  7354. execve(bb_busybox_exec_path, argv, envp);
  7355. /* If they called chroot or otherwise made the binary no longer
  7356. * executable, fall through */
  7357. }
  7358. #endif
  7359. repeat:
  7360. #ifdef SYSV
  7361. do {
  7362. execve(cmd, argv, envp);
  7363. } while (errno == EINTR);
  7364. #else
  7365. execve(cmd, argv, envp);
  7366. #endif
  7367. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7368. /* Run "cmd" as a shell script:
  7369. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7370. * "If the execve() function fails with ENOEXEC, the shell
  7371. * shall execute a command equivalent to having a shell invoked
  7372. * with the command name as its first operand,
  7373. * with any remaining arguments passed to the new shell"
  7374. *
  7375. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7376. * just call ourselves.
  7377. *
  7378. * Note that bash reads ~80 chars of the file, and if it sees
  7379. * a zero byte before it sees newline, it doesn't try to
  7380. * interpret it, but fails with "cannot execute binary file"
  7381. * message and exit code 126. For one, this prevents attempts
  7382. * to interpret foreign ELF binaries as shell scripts.
  7383. */
  7384. argv[0] = (char*) cmd;
  7385. cmd = bb_busybox_exec_path;
  7386. /* NB: this is only possible because all callers of shellexec()
  7387. * ensure that the argv[-1] slot exists!
  7388. */
  7389. argv--;
  7390. argv[0] = (char*) "ash";
  7391. goto repeat;
  7392. }
  7393. }
  7394. /*
  7395. * Exec a program. Never returns. If you change this routine, you may
  7396. * have to change the find_command routine as well.
  7397. * argv[-1] must exist and be writable! See tryexec() for why.
  7398. */
  7399. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7400. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7401. {
  7402. char *cmdname;
  7403. int e;
  7404. char **envp;
  7405. int exerrno;
  7406. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7407. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7408. if (strchr(prog, '/') != NULL
  7409. #if ENABLE_FEATURE_SH_STANDALONE
  7410. || (applet_no = find_applet_by_name(prog)) >= 0
  7411. #endif
  7412. ) {
  7413. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7414. if (applet_no >= 0) {
  7415. /* We tried execing ourself, but it didn't work.
  7416. * Maybe /proc/self/exe doesn't exist?
  7417. * Try $PATH search.
  7418. */
  7419. goto try_PATH;
  7420. }
  7421. e = errno;
  7422. } else {
  7423. try_PATH:
  7424. e = ENOENT;
  7425. while ((cmdname = path_advance(&path, prog)) != NULL) {
  7426. if (--idx < 0 && pathopt == NULL) {
  7427. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7428. if (errno != ENOENT && errno != ENOTDIR)
  7429. e = errno;
  7430. }
  7431. stunalloc(cmdname);
  7432. }
  7433. }
  7434. /* Map to POSIX errors */
  7435. switch (e) {
  7436. default:
  7437. exerrno = 126;
  7438. break;
  7439. case ELOOP:
  7440. case ENAMETOOLONG:
  7441. case ENOENT:
  7442. case ENOTDIR:
  7443. exerrno = 127;
  7444. break;
  7445. }
  7446. exitstatus = exerrno;
  7447. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7448. prog, e, suppress_int));
  7449. ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
  7450. /* NOTREACHED */
  7451. }
  7452. static void
  7453. printentry(struct tblentry *cmdp)
  7454. {
  7455. int idx;
  7456. const char *path;
  7457. char *name;
  7458. idx = cmdp->param.index;
  7459. path = pathval();
  7460. do {
  7461. name = path_advance(&path, cmdp->cmdname);
  7462. stunalloc(name);
  7463. } while (--idx >= 0);
  7464. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7465. }
  7466. /*
  7467. * Clear out command entries. The argument specifies the first entry in
  7468. * PATH which has changed.
  7469. */
  7470. static void
  7471. clearcmdentry(int firstchange)
  7472. {
  7473. struct tblentry **tblp;
  7474. struct tblentry **pp;
  7475. struct tblentry *cmdp;
  7476. INT_OFF;
  7477. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7478. pp = tblp;
  7479. while ((cmdp = *pp) != NULL) {
  7480. if ((cmdp->cmdtype == CMDNORMAL &&
  7481. cmdp->param.index >= firstchange)
  7482. || (cmdp->cmdtype == CMDBUILTIN &&
  7483. builtinloc >= firstchange)
  7484. ) {
  7485. *pp = cmdp->next;
  7486. free(cmdp);
  7487. } else {
  7488. pp = &cmdp->next;
  7489. }
  7490. }
  7491. }
  7492. INT_ON;
  7493. }
  7494. /*
  7495. * Locate a command in the command hash table. If "add" is nonzero,
  7496. * add the command to the table if it is not already present. The
  7497. * variable "lastcmdentry" is set to point to the address of the link
  7498. * pointing to the entry, so that delete_cmd_entry can delete the
  7499. * entry.
  7500. *
  7501. * Interrupts must be off if called with add != 0.
  7502. */
  7503. static struct tblentry **lastcmdentry;
  7504. static struct tblentry *
  7505. cmdlookup(const char *name, int add)
  7506. {
  7507. unsigned int hashval;
  7508. const char *p;
  7509. struct tblentry *cmdp;
  7510. struct tblentry **pp;
  7511. p = name;
  7512. hashval = (unsigned char)*p << 4;
  7513. while (*p)
  7514. hashval += (unsigned char)*p++;
  7515. hashval &= 0x7FFF;
  7516. pp = &cmdtable[hashval % CMDTABLESIZE];
  7517. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7518. if (strcmp(cmdp->cmdname, name) == 0)
  7519. break;
  7520. pp = &cmdp->next;
  7521. }
  7522. if (add && cmdp == NULL) {
  7523. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7524. + strlen(name)
  7525. /* + 1 - already done because
  7526. * tblentry::cmdname is char[1] */);
  7527. /*cmdp->next = NULL; - ckzalloc did it */
  7528. cmdp->cmdtype = CMDUNKNOWN;
  7529. strcpy(cmdp->cmdname, name);
  7530. }
  7531. lastcmdentry = pp;
  7532. return cmdp;
  7533. }
  7534. /*
  7535. * Delete the command entry returned on the last lookup.
  7536. */
  7537. static void
  7538. delete_cmd_entry(void)
  7539. {
  7540. struct tblentry *cmdp;
  7541. INT_OFF;
  7542. cmdp = *lastcmdentry;
  7543. *lastcmdentry = cmdp->next;
  7544. if (cmdp->cmdtype == CMDFUNCTION)
  7545. freefunc(cmdp->param.func);
  7546. free(cmdp);
  7547. INT_ON;
  7548. }
  7549. /*
  7550. * Add a new command entry, replacing any existing command entry for
  7551. * the same name - except special builtins.
  7552. */
  7553. static void
  7554. addcmdentry(char *name, struct cmdentry *entry)
  7555. {
  7556. struct tblentry *cmdp;
  7557. cmdp = cmdlookup(name, 1);
  7558. if (cmdp->cmdtype == CMDFUNCTION) {
  7559. freefunc(cmdp->param.func);
  7560. }
  7561. cmdp->cmdtype = entry->cmdtype;
  7562. cmdp->param = entry->u;
  7563. cmdp->rehash = 0;
  7564. }
  7565. static int FAST_FUNC
  7566. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7567. {
  7568. struct tblentry **pp;
  7569. struct tblentry *cmdp;
  7570. int c;
  7571. struct cmdentry entry;
  7572. char *name;
  7573. if (nextopt("r") != '\0') {
  7574. clearcmdentry(0);
  7575. return 0;
  7576. }
  7577. if (*argptr == NULL) {
  7578. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7579. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7580. if (cmdp->cmdtype == CMDNORMAL)
  7581. printentry(cmdp);
  7582. }
  7583. }
  7584. return 0;
  7585. }
  7586. c = 0;
  7587. while ((name = *argptr) != NULL) {
  7588. cmdp = cmdlookup(name, 0);
  7589. if (cmdp != NULL
  7590. && (cmdp->cmdtype == CMDNORMAL
  7591. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  7592. ) {
  7593. delete_cmd_entry();
  7594. }
  7595. find_command(name, &entry, DO_ERR, pathval());
  7596. if (entry.cmdtype == CMDUNKNOWN)
  7597. c = 1;
  7598. argptr++;
  7599. }
  7600. return c;
  7601. }
  7602. /*
  7603. * Called when a cd is done. Marks all commands so the next time they
  7604. * are executed they will be rehashed.
  7605. */
  7606. static void
  7607. hashcd(void)
  7608. {
  7609. struct tblentry **pp;
  7610. struct tblentry *cmdp;
  7611. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7612. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7613. if (cmdp->cmdtype == CMDNORMAL
  7614. || (cmdp->cmdtype == CMDBUILTIN
  7615. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7616. && builtinloc > 0)
  7617. ) {
  7618. cmdp->rehash = 1;
  7619. }
  7620. }
  7621. }
  7622. }
  7623. /*
  7624. * Fix command hash table when PATH changed.
  7625. * Called before PATH is changed. The argument is the new value of PATH;
  7626. * pathval() still returns the old value at this point.
  7627. * Called with interrupts off.
  7628. */
  7629. static void FAST_FUNC
  7630. changepath(const char *new)
  7631. {
  7632. const char *old;
  7633. int firstchange;
  7634. int idx;
  7635. int idx_bltin;
  7636. old = pathval();
  7637. firstchange = 9999; /* assume no change */
  7638. idx = 0;
  7639. idx_bltin = -1;
  7640. for (;;) {
  7641. if (*old != *new) {
  7642. firstchange = idx;
  7643. if ((*old == '\0' && *new == ':')
  7644. || (*old == ':' && *new == '\0')
  7645. ) {
  7646. firstchange++;
  7647. }
  7648. old = new; /* ignore subsequent differences */
  7649. }
  7650. if (*new == '\0')
  7651. break;
  7652. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7653. idx_bltin = idx;
  7654. if (*new == ':')
  7655. idx++;
  7656. new++;
  7657. old++;
  7658. }
  7659. if (builtinloc < 0 && idx_bltin >= 0)
  7660. builtinloc = idx_bltin; /* zap builtins */
  7661. if (builtinloc >= 0 && idx_bltin < 0)
  7662. firstchange = 0;
  7663. clearcmdentry(firstchange);
  7664. builtinloc = idx_bltin;
  7665. }
  7666. enum {
  7667. TEOF,
  7668. TNL,
  7669. TREDIR,
  7670. TWORD,
  7671. TSEMI,
  7672. TBACKGND,
  7673. TAND,
  7674. TOR,
  7675. TPIPE,
  7676. TLP,
  7677. TRP,
  7678. TENDCASE,
  7679. TENDBQUOTE,
  7680. TNOT,
  7681. TCASE,
  7682. TDO,
  7683. TDONE,
  7684. TELIF,
  7685. TELSE,
  7686. TESAC,
  7687. TFI,
  7688. TFOR,
  7689. #if BASH_FUNCTION
  7690. TFUNCTION,
  7691. #endif
  7692. TIF,
  7693. TIN,
  7694. TTHEN,
  7695. TUNTIL,
  7696. TWHILE,
  7697. TBEGIN,
  7698. TEND
  7699. };
  7700. typedef smallint token_id_t;
  7701. /* Nth bit indicates if token marks the end of a list */
  7702. enum {
  7703. tokendlist = 0
  7704. /* 0 */ | (1u << TEOF)
  7705. /* 1 */ | (0u << TNL)
  7706. /* 2 */ | (0u << TREDIR)
  7707. /* 3 */ | (0u << TWORD)
  7708. /* 4 */ | (0u << TSEMI)
  7709. /* 5 */ | (0u << TBACKGND)
  7710. /* 6 */ | (0u << TAND)
  7711. /* 7 */ | (0u << TOR)
  7712. /* 8 */ | (0u << TPIPE)
  7713. /* 9 */ | (0u << TLP)
  7714. /* 10 */ | (1u << TRP)
  7715. /* 11 */ | (1u << TENDCASE)
  7716. /* 12 */ | (1u << TENDBQUOTE)
  7717. /* 13 */ | (0u << TNOT)
  7718. /* 14 */ | (0u << TCASE)
  7719. /* 15 */ | (1u << TDO)
  7720. /* 16 */ | (1u << TDONE)
  7721. /* 17 */ | (1u << TELIF)
  7722. /* 18 */ | (1u << TELSE)
  7723. /* 19 */ | (1u << TESAC)
  7724. /* 20 */ | (1u << TFI)
  7725. /* 21 */ | (0u << TFOR)
  7726. #if BASH_FUNCTION
  7727. /* 22 */ | (0u << TFUNCTION)
  7728. #endif
  7729. /* 23 */ | (0u << TIF)
  7730. /* 24 */ | (0u << TIN)
  7731. /* 25 */ | (1u << TTHEN)
  7732. /* 26 */ | (0u << TUNTIL)
  7733. /* 27 */ | (0u << TWHILE)
  7734. /* 28 */ | (0u << TBEGIN)
  7735. /* 29 */ | (1u << TEND)
  7736. , /* thus far 29 bits used */
  7737. };
  7738. static const char *const tokname_array[] = {
  7739. "end of file",
  7740. "newline",
  7741. "redirection",
  7742. "word",
  7743. ";",
  7744. "&",
  7745. "&&",
  7746. "||",
  7747. "|",
  7748. "(",
  7749. ")",
  7750. ";;",
  7751. "`",
  7752. #define KWDOFFSET 13
  7753. /* the following are keywords */
  7754. "!",
  7755. "case",
  7756. "do",
  7757. "done",
  7758. "elif",
  7759. "else",
  7760. "esac",
  7761. "fi",
  7762. "for",
  7763. #if BASH_FUNCTION
  7764. "function",
  7765. #endif
  7766. "if",
  7767. "in",
  7768. "then",
  7769. "until",
  7770. "while",
  7771. "{",
  7772. "}",
  7773. };
  7774. /* Wrapper around strcmp for qsort/bsearch/... */
  7775. static int
  7776. pstrcmp(const void *a, const void *b)
  7777. {
  7778. return strcmp((char*)a, *(char**)b);
  7779. }
  7780. static const char *const *
  7781. findkwd(const char *s)
  7782. {
  7783. return bsearch(s, tokname_array + KWDOFFSET,
  7784. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7785. sizeof(tokname_array[0]), pstrcmp);
  7786. }
  7787. /*
  7788. * Locate and print what a word is...
  7789. */
  7790. static int
  7791. describe_command(char *command, const char *path, int describe_command_verbose)
  7792. {
  7793. struct cmdentry entry;
  7794. #if ENABLE_ASH_ALIAS
  7795. const struct alias *ap;
  7796. #endif
  7797. path = path ? path : pathval();
  7798. if (describe_command_verbose) {
  7799. out1str(command);
  7800. }
  7801. /* First look at the keywords */
  7802. if (findkwd(command)) {
  7803. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7804. goto out;
  7805. }
  7806. #if ENABLE_ASH_ALIAS
  7807. /* Then look at the aliases */
  7808. ap = lookupalias(command, 0);
  7809. if (ap != NULL) {
  7810. if (!describe_command_verbose) {
  7811. out1str("alias ");
  7812. printalias(ap);
  7813. return 0;
  7814. }
  7815. out1fmt(" is an alias for %s", ap->val);
  7816. goto out;
  7817. }
  7818. #endif
  7819. /* Brute force */
  7820. find_command(command, &entry, DO_ABS, path);
  7821. switch (entry.cmdtype) {
  7822. case CMDNORMAL: {
  7823. int j = entry.u.index;
  7824. char *p;
  7825. if (j < 0) {
  7826. p = command;
  7827. } else {
  7828. do {
  7829. p = path_advance(&path, command);
  7830. stunalloc(p);
  7831. } while (--j >= 0);
  7832. }
  7833. if (describe_command_verbose) {
  7834. out1fmt(" is %s", p);
  7835. } else {
  7836. out1str(p);
  7837. }
  7838. break;
  7839. }
  7840. case CMDFUNCTION:
  7841. if (describe_command_verbose) {
  7842. /*out1str(" is a shell function");*/
  7843. out1str(" is a function"); /* bash says this */
  7844. } else {
  7845. out1str(command);
  7846. }
  7847. break;
  7848. case CMDBUILTIN:
  7849. if (describe_command_verbose) {
  7850. out1fmt(" is a %sshell builtin",
  7851. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7852. "special " : nullstr
  7853. );
  7854. } else {
  7855. out1str(command);
  7856. }
  7857. break;
  7858. default:
  7859. if (describe_command_verbose) {
  7860. out1str(": not found\n");
  7861. }
  7862. return 127;
  7863. }
  7864. out:
  7865. out1str("\n");
  7866. return 0;
  7867. }
  7868. static int FAST_FUNC
  7869. typecmd(int argc UNUSED_PARAM, char **argv)
  7870. {
  7871. int i = 1;
  7872. int err = 0;
  7873. int verbose = 1;
  7874. /* type -p ... ? (we don't bother checking for 'p') */
  7875. if (argv[1] && argv[1][0] == '-') {
  7876. i++;
  7877. verbose = 0;
  7878. }
  7879. while (argv[i]) {
  7880. err |= describe_command(argv[i++], NULL, verbose);
  7881. }
  7882. return err;
  7883. }
  7884. #if ENABLE_ASH_CMDCMD
  7885. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7886. static char **
  7887. parse_command_args(char **argv, const char **path)
  7888. {
  7889. char *cp, c;
  7890. for (;;) {
  7891. cp = *++argv;
  7892. if (!cp)
  7893. return NULL;
  7894. if (*cp++ != '-')
  7895. break;
  7896. c = *cp++;
  7897. if (!c)
  7898. break;
  7899. if (c == '-' && !*cp) {
  7900. if (!*++argv)
  7901. return NULL;
  7902. break;
  7903. }
  7904. do {
  7905. switch (c) {
  7906. case 'p':
  7907. *path = bb_default_path;
  7908. break;
  7909. default:
  7910. /* run 'typecmd' for other options */
  7911. return NULL;
  7912. }
  7913. c = *cp++;
  7914. } while (c);
  7915. }
  7916. return argv;
  7917. }
  7918. static int FAST_FUNC
  7919. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7920. {
  7921. char *cmd;
  7922. int c;
  7923. enum {
  7924. VERIFY_BRIEF = 1,
  7925. VERIFY_VERBOSE = 2,
  7926. } verify = 0;
  7927. const char *path = NULL;
  7928. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7929. * never reaches this function.
  7930. */
  7931. while ((c = nextopt("pvV")) != '\0')
  7932. if (c == 'V')
  7933. verify |= VERIFY_VERBOSE;
  7934. else if (c == 'v')
  7935. /*verify |= VERIFY_BRIEF*/;
  7936. #if DEBUG
  7937. else if (c != 'p')
  7938. abort();
  7939. #endif
  7940. else
  7941. path = bb_default_path;
  7942. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7943. cmd = *argptr;
  7944. if (/*verify && */ cmd)
  7945. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7946. return 0;
  7947. }
  7948. #endif
  7949. /*static int funcblocksize; // size of structures in function */
  7950. /*static int funcstringsize; // size of strings in node */
  7951. static void *funcblock; /* block to allocate function from */
  7952. static char *funcstring_end; /* end of block to allocate strings from */
  7953. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7954. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7955. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7956. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7957. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7958. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7959. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7960. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7961. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7962. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7963. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7964. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7965. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7966. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7967. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7968. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7969. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7970. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7971. #if BASH_REDIR_OUTPUT
  7972. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7973. #endif
  7974. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7975. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7976. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7977. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7978. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7979. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7980. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7981. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7982. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7983. };
  7984. static int calcsize(int funcblocksize, union node *n);
  7985. static int
  7986. sizenodelist(int funcblocksize, struct nodelist *lp)
  7987. {
  7988. while (lp) {
  7989. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7990. funcblocksize = calcsize(funcblocksize, lp->n);
  7991. lp = lp->next;
  7992. }
  7993. return funcblocksize;
  7994. }
  7995. static int
  7996. calcsize(int funcblocksize, union node *n)
  7997. {
  7998. if (n == NULL)
  7999. return funcblocksize;
  8000. funcblocksize += nodesize[n->type];
  8001. switch (n->type) {
  8002. case NCMD:
  8003. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  8004. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  8005. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  8006. break;
  8007. case NPIPE:
  8008. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  8009. break;
  8010. case NREDIR:
  8011. case NBACKGND:
  8012. case NSUBSHELL:
  8013. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  8014. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  8015. break;
  8016. case NAND:
  8017. case NOR:
  8018. case NSEMI:
  8019. case NWHILE:
  8020. case NUNTIL:
  8021. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  8022. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  8023. break;
  8024. case NIF:
  8025. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  8026. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  8027. funcblocksize = calcsize(funcblocksize, n->nif.test);
  8028. break;
  8029. case NFOR:
  8030. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  8031. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  8032. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  8033. break;
  8034. case NCASE:
  8035. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  8036. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  8037. break;
  8038. case NCLIST:
  8039. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  8040. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  8041. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  8042. break;
  8043. case NDEFUN:
  8044. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8045. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8046. break;
  8047. case NARG:
  8048. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8049. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8050. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8051. break;
  8052. case NTO:
  8053. #if BASH_REDIR_OUTPUT
  8054. case NTO2:
  8055. #endif
  8056. case NCLOBBER:
  8057. case NFROM:
  8058. case NFROMTO:
  8059. case NAPPEND:
  8060. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8061. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8062. break;
  8063. case NTOFD:
  8064. case NFROMFD:
  8065. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8066. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8067. break;
  8068. case NHERE:
  8069. case NXHERE:
  8070. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8071. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8072. break;
  8073. case NNOT:
  8074. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8075. break;
  8076. };
  8077. return funcblocksize;
  8078. }
  8079. static char *
  8080. nodeckstrdup(char *s)
  8081. {
  8082. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8083. return strcpy(funcstring_end, s);
  8084. }
  8085. static union node *copynode(union node *);
  8086. static struct nodelist *
  8087. copynodelist(struct nodelist *lp)
  8088. {
  8089. struct nodelist *start;
  8090. struct nodelist **lpp;
  8091. lpp = &start;
  8092. while (lp) {
  8093. *lpp = funcblock;
  8094. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8095. (*lpp)->n = copynode(lp->n);
  8096. lp = lp->next;
  8097. lpp = &(*lpp)->next;
  8098. }
  8099. *lpp = NULL;
  8100. return start;
  8101. }
  8102. static union node *
  8103. copynode(union node *n)
  8104. {
  8105. union node *new;
  8106. if (n == NULL)
  8107. return NULL;
  8108. new = funcblock;
  8109. funcblock = (char *) funcblock + nodesize[n->type];
  8110. switch (n->type) {
  8111. case NCMD:
  8112. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8113. new->ncmd.args = copynode(n->ncmd.args);
  8114. new->ncmd.assign = copynode(n->ncmd.assign);
  8115. new->ncmd.linno = n->ncmd.linno;
  8116. break;
  8117. case NPIPE:
  8118. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8119. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8120. break;
  8121. case NREDIR:
  8122. case NBACKGND:
  8123. case NSUBSHELL:
  8124. new->nredir.redirect = copynode(n->nredir.redirect);
  8125. new->nredir.n = copynode(n->nredir.n);
  8126. new->nredir.linno = n->nredir.linno;
  8127. break;
  8128. case NAND:
  8129. case NOR:
  8130. case NSEMI:
  8131. case NWHILE:
  8132. case NUNTIL:
  8133. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8134. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8135. break;
  8136. case NIF:
  8137. new->nif.elsepart = copynode(n->nif.elsepart);
  8138. new->nif.ifpart = copynode(n->nif.ifpart);
  8139. new->nif.test = copynode(n->nif.test);
  8140. break;
  8141. case NFOR:
  8142. new->nfor.var = nodeckstrdup(n->nfor.var);
  8143. new->nfor.body = copynode(n->nfor.body);
  8144. new->nfor.args = copynode(n->nfor.args);
  8145. new->nfor.linno = n->nfor.linno;
  8146. break;
  8147. case NCASE:
  8148. new->ncase.cases = copynode(n->ncase.cases);
  8149. new->ncase.expr = copynode(n->ncase.expr);
  8150. new->ncase.linno = n->ncase.linno;
  8151. break;
  8152. case NCLIST:
  8153. new->nclist.body = copynode(n->nclist.body);
  8154. new->nclist.pattern = copynode(n->nclist.pattern);
  8155. new->nclist.next = copynode(n->nclist.next);
  8156. break;
  8157. case NDEFUN:
  8158. new->ndefun.body = copynode(n->ndefun.body);
  8159. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8160. new->ndefun.linno = n->ndefun.linno;
  8161. break;
  8162. case NARG:
  8163. new->narg.backquote = copynodelist(n->narg.backquote);
  8164. new->narg.text = nodeckstrdup(n->narg.text);
  8165. new->narg.next = copynode(n->narg.next);
  8166. break;
  8167. case NTO:
  8168. #if BASH_REDIR_OUTPUT
  8169. case NTO2:
  8170. #endif
  8171. case NCLOBBER:
  8172. case NFROM:
  8173. case NFROMTO:
  8174. case NAPPEND:
  8175. new->nfile.fname = copynode(n->nfile.fname);
  8176. new->nfile.fd = n->nfile.fd;
  8177. new->nfile.next = copynode(n->nfile.next);
  8178. break;
  8179. case NTOFD:
  8180. case NFROMFD:
  8181. new->ndup.vname = copynode(n->ndup.vname);
  8182. new->ndup.dupfd = n->ndup.dupfd;
  8183. new->ndup.fd = n->ndup.fd;
  8184. new->ndup.next = copynode(n->ndup.next);
  8185. break;
  8186. case NHERE:
  8187. case NXHERE:
  8188. new->nhere.doc = copynode(n->nhere.doc);
  8189. new->nhere.fd = n->nhere.fd;
  8190. new->nhere.next = copynode(n->nhere.next);
  8191. break;
  8192. case NNOT:
  8193. new->nnot.com = copynode(n->nnot.com);
  8194. break;
  8195. };
  8196. new->type = n->type;
  8197. return new;
  8198. }
  8199. /*
  8200. * Make a copy of a parse tree.
  8201. */
  8202. static struct funcnode *
  8203. copyfunc(union node *n)
  8204. {
  8205. struct funcnode *f;
  8206. size_t blocksize;
  8207. /*funcstringsize = 0;*/
  8208. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8209. f = ckzalloc(blocksize /* + funcstringsize */);
  8210. funcblock = (char *) f + offsetof(struct funcnode, n);
  8211. funcstring_end = (char *) f + blocksize;
  8212. copynode(n);
  8213. /* f->count = 0; - ckzalloc did it */
  8214. return f;
  8215. }
  8216. /*
  8217. * Define a shell function.
  8218. */
  8219. static void
  8220. defun(union node *func)
  8221. {
  8222. struct cmdentry entry;
  8223. INT_OFF;
  8224. entry.cmdtype = CMDFUNCTION;
  8225. entry.u.func = copyfunc(func);
  8226. addcmdentry(func->ndefun.text, &entry);
  8227. INT_ON;
  8228. }
  8229. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8230. #define SKIPBREAK (1 << 0)
  8231. #define SKIPCONT (1 << 1)
  8232. #define SKIPFUNC (1 << 2)
  8233. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8234. static int skipcount; /* number of levels to skip */
  8235. static int loopnest; /* current loop nesting level */
  8236. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8237. /* Forward decl way out to parsing code - dotrap needs it */
  8238. static int evalstring(char *s, int flags);
  8239. /* Called to execute a trap.
  8240. * Single callsite - at the end of evaltree().
  8241. * If we return non-zero, evaltree raises EXEXIT exception.
  8242. *
  8243. * Perhaps we should avoid entering new trap handlers
  8244. * while we are executing a trap handler. [is it a TODO?]
  8245. */
  8246. static void
  8247. dotrap(void)
  8248. {
  8249. uint8_t *g;
  8250. int sig;
  8251. uint8_t last_status;
  8252. if (!pending_sig)
  8253. return;
  8254. last_status = exitstatus;
  8255. pending_sig = 0;
  8256. barrier();
  8257. TRACE(("dotrap entered\n"));
  8258. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8259. char *p;
  8260. if (!*g)
  8261. continue;
  8262. if (evalskip) {
  8263. pending_sig = sig;
  8264. break;
  8265. }
  8266. p = trap[sig];
  8267. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8268. * don't upset it by resetting gotsig[SIGINT-1] */
  8269. if (sig == SIGINT && !p)
  8270. continue;
  8271. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8272. *g = 0;
  8273. if (!p)
  8274. continue;
  8275. evalstring(p, 0);
  8276. }
  8277. exitstatus = last_status;
  8278. TRACE(("dotrap returns\n"));
  8279. }
  8280. /* forward declarations - evaluation is fairly recursive business... */
  8281. static int evalloop(union node *, int);
  8282. static int evalfor(union node *, int);
  8283. static int evalcase(union node *, int);
  8284. static int evalsubshell(union node *, int);
  8285. static void expredir(union node *);
  8286. static int evalpipe(union node *, int);
  8287. static int evalcommand(union node *, int);
  8288. static int evalbltin(const struct builtincmd *, int, char **, int);
  8289. static void prehash(union node *);
  8290. /*
  8291. * Evaluate a parse tree. The value is left in the global variable
  8292. * exitstatus.
  8293. */
  8294. static int
  8295. evaltree(union node *n, int flags)
  8296. {
  8297. int checkexit = 0;
  8298. int (*evalfn)(union node *, int);
  8299. struct stackmark smark;
  8300. int status = 0;
  8301. setstackmark(&smark);
  8302. if (n == NULL) {
  8303. TRACE(("evaltree(NULL) called\n"));
  8304. goto out;
  8305. }
  8306. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8307. dotrap();
  8308. switch (n->type) {
  8309. default:
  8310. #if DEBUG
  8311. out1fmt("Node type = %d\n", n->type);
  8312. fflush_all();
  8313. break;
  8314. #endif
  8315. case NNOT:
  8316. status = !evaltree(n->nnot.com, EV_TESTED);
  8317. goto setstatus;
  8318. case NREDIR:
  8319. errlinno = lineno = n->nredir.linno;
  8320. if (funcline)
  8321. lineno -= funcline - 1;
  8322. expredir(n->nredir.redirect);
  8323. pushredir(n->nredir.redirect);
  8324. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8325. if (!status) {
  8326. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8327. }
  8328. if (n->nredir.redirect)
  8329. popredir(/*drop:*/ 0);
  8330. goto setstatus;
  8331. case NCMD:
  8332. evalfn = evalcommand;
  8333. checkexit:
  8334. if (eflag && !(flags & EV_TESTED))
  8335. checkexit = ~0;
  8336. goto calleval;
  8337. case NFOR:
  8338. evalfn = evalfor;
  8339. goto calleval;
  8340. case NWHILE:
  8341. case NUNTIL:
  8342. evalfn = evalloop;
  8343. goto calleval;
  8344. case NSUBSHELL:
  8345. case NBACKGND:
  8346. evalfn = evalsubshell;
  8347. goto checkexit;
  8348. case NPIPE:
  8349. evalfn = evalpipe;
  8350. goto checkexit;
  8351. case NCASE:
  8352. evalfn = evalcase;
  8353. goto calleval;
  8354. case NAND:
  8355. case NOR:
  8356. case NSEMI: {
  8357. #if NAND + 1 != NOR
  8358. #error NAND + 1 != NOR
  8359. #endif
  8360. #if NOR + 1 != NSEMI
  8361. #error NOR + 1 != NSEMI
  8362. #endif
  8363. unsigned is_or = n->type - NAND;
  8364. status = evaltree(
  8365. n->nbinary.ch1,
  8366. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8367. );
  8368. if ((!status) == is_or || evalskip)
  8369. break;
  8370. n = n->nbinary.ch2;
  8371. evaln:
  8372. evalfn = evaltree;
  8373. calleval:
  8374. status = evalfn(n, flags);
  8375. goto setstatus;
  8376. }
  8377. case NIF:
  8378. status = evaltree(n->nif.test, EV_TESTED);
  8379. if (evalskip)
  8380. break;
  8381. if (!status) {
  8382. n = n->nif.ifpart;
  8383. goto evaln;
  8384. }
  8385. if (n->nif.elsepart) {
  8386. n = n->nif.elsepart;
  8387. goto evaln;
  8388. }
  8389. status = 0;
  8390. goto setstatus;
  8391. case NDEFUN:
  8392. defun(n);
  8393. /* Not necessary. To test it:
  8394. * "false; f() { qwerty; }; echo $?" should print 0.
  8395. */
  8396. /* status = 0; */
  8397. setstatus:
  8398. exitstatus = status;
  8399. break;
  8400. }
  8401. out:
  8402. /* Order of checks below is important:
  8403. * signal handlers trigger before exit caused by "set -e".
  8404. */
  8405. dotrap();
  8406. if (checkexit & status)
  8407. raise_exception(EXEXIT);
  8408. if (flags & EV_EXIT)
  8409. raise_exception(EXEXIT);
  8410. popstackmark(&smark);
  8411. TRACE(("leaving evaltree (no interrupts)\n"));
  8412. return exitstatus;
  8413. }
  8414. static int
  8415. skiploop(void)
  8416. {
  8417. int skip = evalskip;
  8418. switch (skip) {
  8419. case 0:
  8420. break;
  8421. case SKIPBREAK:
  8422. case SKIPCONT:
  8423. if (--skipcount <= 0) {
  8424. evalskip = 0;
  8425. break;
  8426. }
  8427. skip = SKIPBREAK;
  8428. break;
  8429. }
  8430. return skip;
  8431. }
  8432. static int
  8433. evalloop(union node *n, int flags)
  8434. {
  8435. int skip;
  8436. int status;
  8437. loopnest++;
  8438. status = 0;
  8439. flags &= EV_TESTED;
  8440. do {
  8441. int i;
  8442. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8443. skip = skiploop();
  8444. if (skip == SKIPFUNC)
  8445. status = i;
  8446. if (skip)
  8447. continue;
  8448. if (n->type != NWHILE)
  8449. i = !i;
  8450. if (i != 0)
  8451. break;
  8452. status = evaltree(n->nbinary.ch2, flags);
  8453. skip = skiploop();
  8454. } while (!(skip & ~SKIPCONT));
  8455. loopnest--;
  8456. return status;
  8457. }
  8458. static int
  8459. evalfor(union node *n, int flags)
  8460. {
  8461. struct arglist arglist;
  8462. union node *argp;
  8463. struct strlist *sp;
  8464. int status = 0;
  8465. errlinno = lineno = n->ncase.linno;
  8466. if (funcline)
  8467. lineno -= funcline - 1;
  8468. arglist.list = NULL;
  8469. arglist.lastp = &arglist.list;
  8470. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8471. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8472. }
  8473. *arglist.lastp = NULL;
  8474. loopnest++;
  8475. flags &= EV_TESTED;
  8476. for (sp = arglist.list; sp; sp = sp->next) {
  8477. setvar0(n->nfor.var, sp->text);
  8478. status = evaltree(n->nfor.body, flags);
  8479. if (skiploop() & ~SKIPCONT)
  8480. break;
  8481. }
  8482. loopnest--;
  8483. return status;
  8484. }
  8485. static int
  8486. evalcase(union node *n, int flags)
  8487. {
  8488. union node *cp;
  8489. union node *patp;
  8490. struct arglist arglist;
  8491. int status = 0;
  8492. errlinno = lineno = n->ncase.linno;
  8493. if (funcline)
  8494. lineno -= funcline - 1;
  8495. arglist.list = NULL;
  8496. arglist.lastp = &arglist.list;
  8497. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8498. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8499. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8500. if (casematch(patp, arglist.list->text)) {
  8501. /* Ensure body is non-empty as otherwise
  8502. * EV_EXIT may prevent us from setting the
  8503. * exit status.
  8504. */
  8505. if (evalskip == 0 && cp->nclist.body) {
  8506. status = evaltree(cp->nclist.body, flags);
  8507. }
  8508. goto out;
  8509. }
  8510. }
  8511. }
  8512. out:
  8513. return status;
  8514. }
  8515. /*
  8516. * Kick off a subshell to evaluate a tree.
  8517. */
  8518. static int
  8519. evalsubshell(union node *n, int flags)
  8520. {
  8521. struct job *jp;
  8522. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8523. int status;
  8524. errlinno = lineno = n->nredir.linno;
  8525. if (funcline)
  8526. lineno -= funcline - 1;
  8527. expredir(n->nredir.redirect);
  8528. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8529. goto nofork;
  8530. INT_OFF;
  8531. if (backgnd == FORK_FG)
  8532. get_tty_state();
  8533. jp = makejob(/*n,*/ 1);
  8534. if (forkshell(jp, n, backgnd) == 0) {
  8535. /* child */
  8536. INT_ON;
  8537. flags |= EV_EXIT;
  8538. if (backgnd)
  8539. flags &= ~EV_TESTED;
  8540. nofork:
  8541. redirect(n->nredir.redirect, 0);
  8542. evaltreenr(n->nredir.n, flags);
  8543. /* never returns */
  8544. }
  8545. /* parent */
  8546. status = 0;
  8547. if (backgnd == FORK_FG)
  8548. status = waitforjob(jp);
  8549. INT_ON;
  8550. return status;
  8551. }
  8552. /*
  8553. * Compute the names of the files in a redirection list.
  8554. */
  8555. static void fixredir(union node *, const char *, int);
  8556. static void
  8557. expredir(union node *n)
  8558. {
  8559. union node *redir;
  8560. for (redir = n; redir; redir = redir->nfile.next) {
  8561. struct arglist fn;
  8562. fn.list = NULL;
  8563. fn.lastp = &fn.list;
  8564. switch (redir->type) {
  8565. case NFROMTO:
  8566. case NFROM:
  8567. case NTO:
  8568. #if BASH_REDIR_OUTPUT
  8569. case NTO2:
  8570. #endif
  8571. case NCLOBBER:
  8572. case NAPPEND:
  8573. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8574. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8575. #if BASH_REDIR_OUTPUT
  8576. store_expfname:
  8577. #endif
  8578. #if 0
  8579. // By the design of stack allocator, the loop of this kind:
  8580. // while true; do while true; do break; done </dev/null; done
  8581. // will look like a memory leak: ash plans to free expfname's
  8582. // of "/dev/null" as soon as it finishes running the loop
  8583. // (in this case, never).
  8584. // This "fix" is wrong:
  8585. if (redir->nfile.expfname)
  8586. stunalloc(redir->nfile.expfname);
  8587. // It results in corrupted state of stacked allocations.
  8588. #endif
  8589. redir->nfile.expfname = fn.list->text;
  8590. break;
  8591. case NFROMFD:
  8592. case NTOFD: /* >& */
  8593. if (redir->ndup.vname) {
  8594. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  8595. if (fn.list == NULL)
  8596. ash_msg_and_raise_error("redir error");
  8597. #if BASH_REDIR_OUTPUT
  8598. //FIXME: we used expandarg with different args!
  8599. if (!isdigit_str9(fn.list->text)) {
  8600. /* >&file, not >&fd */
  8601. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8602. ash_msg_and_raise_error("redir error");
  8603. redir->type = NTO2;
  8604. goto store_expfname;
  8605. }
  8606. #endif
  8607. fixredir(redir, fn.list->text, 1);
  8608. }
  8609. break;
  8610. }
  8611. }
  8612. }
  8613. /*
  8614. * Evaluate a pipeline. All the processes in the pipeline are children
  8615. * of the process creating the pipeline. (This differs from some versions
  8616. * of the shell, which make the last process in a pipeline the parent
  8617. * of all the rest.)
  8618. */
  8619. static int
  8620. evalpipe(union node *n, int flags)
  8621. {
  8622. struct job *jp;
  8623. struct nodelist *lp;
  8624. int pipelen;
  8625. int prevfd;
  8626. int pip[2];
  8627. int status = 0;
  8628. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8629. pipelen = 0;
  8630. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8631. pipelen++;
  8632. flags |= EV_EXIT;
  8633. INT_OFF;
  8634. if (n->npipe.pipe_backgnd == 0)
  8635. get_tty_state();
  8636. jp = makejob(/*n,*/ pipelen);
  8637. prevfd = -1;
  8638. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8639. prehash(lp->n);
  8640. pip[1] = -1;
  8641. if (lp->next) {
  8642. if (pipe(pip) < 0) {
  8643. close(prevfd);
  8644. ash_msg_and_raise_perror("can't create pipe");
  8645. }
  8646. }
  8647. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8648. /* child */
  8649. INT_ON;
  8650. if (pip[1] >= 0) {
  8651. close(pip[0]);
  8652. }
  8653. if (prevfd > 0) {
  8654. dup2(prevfd, 0);
  8655. close(prevfd);
  8656. }
  8657. if (pip[1] > 1) {
  8658. dup2(pip[1], 1);
  8659. close(pip[1]);
  8660. }
  8661. evaltreenr(lp->n, flags);
  8662. /* never returns */
  8663. }
  8664. /* parent */
  8665. if (prevfd >= 0)
  8666. close(prevfd);
  8667. prevfd = pip[0];
  8668. /* Don't want to trigger debugging */
  8669. if (pip[1] != -1)
  8670. close(pip[1]);
  8671. }
  8672. if (n->npipe.pipe_backgnd == 0) {
  8673. status = waitforjob(jp);
  8674. TRACE(("evalpipe: job done exit status %d\n", status));
  8675. }
  8676. INT_ON;
  8677. return status;
  8678. }
  8679. /*
  8680. * Controls whether the shell is interactive or not.
  8681. */
  8682. static void
  8683. setinteractive(int on)
  8684. {
  8685. static smallint is_interactive;
  8686. if (++on == is_interactive)
  8687. return;
  8688. is_interactive = on;
  8689. setsignal(SIGINT);
  8690. setsignal(SIGQUIT);
  8691. setsignal(SIGTERM);
  8692. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8693. if (is_interactive > 1) {
  8694. /* Looks like they want an interactive shell */
  8695. static smallint did_banner;
  8696. if (!did_banner) {
  8697. /* note: ash and hush share this string */
  8698. out1fmt("\n\n%s %s\n"
  8699. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8700. "\n",
  8701. bb_banner,
  8702. "built-in shell (ash)"
  8703. );
  8704. did_banner = 1;
  8705. }
  8706. }
  8707. #endif
  8708. }
  8709. static void
  8710. optschanged(void)
  8711. {
  8712. #if DEBUG
  8713. opentrace();
  8714. #endif
  8715. setinteractive(iflag);
  8716. setjobctl(mflag);
  8717. #if ENABLE_FEATURE_EDITING_VI
  8718. if (viflag)
  8719. line_input_state->flags |= VI_MODE;
  8720. else
  8721. line_input_state->flags &= ~VI_MODE;
  8722. #else
  8723. viflag = 0; /* forcibly keep the option off */
  8724. #endif
  8725. }
  8726. struct localvar_list {
  8727. struct localvar_list *next;
  8728. struct localvar *lv;
  8729. };
  8730. static struct localvar_list *localvar_stack;
  8731. /*
  8732. * Called after a function returns.
  8733. * Interrupts must be off.
  8734. */
  8735. static void
  8736. poplocalvars(int keep)
  8737. {
  8738. struct localvar_list *ll;
  8739. struct localvar *lvp, *next;
  8740. struct var *vp;
  8741. INT_OFF;
  8742. ll = localvar_stack;
  8743. localvar_stack = ll->next;
  8744. next = ll->lv;
  8745. free(ll);
  8746. while ((lvp = next) != NULL) {
  8747. next = lvp->next;
  8748. vp = lvp->vp;
  8749. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8750. if (keep) {
  8751. int bits = VSTRFIXED;
  8752. if (lvp->flags != VUNSET) {
  8753. if (vp->var_text == lvp->text)
  8754. bits |= VTEXTFIXED;
  8755. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8756. free((char*)lvp->text);
  8757. }
  8758. vp->flags &= ~bits;
  8759. vp->flags |= (lvp->flags & bits);
  8760. if ((vp->flags &
  8761. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8762. unsetvar(vp->var_text);
  8763. } else if (vp == NULL) { /* $- saved */
  8764. memcpy(optlist, lvp->text, sizeof(optlist));
  8765. free((char*)lvp->text);
  8766. optschanged();
  8767. } else if (lvp->flags == VUNSET) {
  8768. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8769. unsetvar(vp->var_text);
  8770. } else {
  8771. if (vp->var_func)
  8772. vp->var_func(var_end(lvp->text));
  8773. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8774. free((char*)vp->var_text);
  8775. vp->flags = lvp->flags;
  8776. vp->var_text = lvp->text;
  8777. }
  8778. free(lvp);
  8779. }
  8780. INT_ON;
  8781. }
  8782. /*
  8783. * Create a new localvar environment.
  8784. */
  8785. static struct localvar_list *
  8786. pushlocalvars(void)
  8787. {
  8788. struct localvar_list *ll;
  8789. INT_OFF;
  8790. ll = ckzalloc(sizeof(*ll));
  8791. /*ll->lv = NULL; - zalloc did it */
  8792. ll->next = localvar_stack;
  8793. localvar_stack = ll;
  8794. INT_ON;
  8795. return ll->next;
  8796. }
  8797. static void
  8798. unwindlocalvars(struct localvar_list *stop)
  8799. {
  8800. while (localvar_stack != stop)
  8801. poplocalvars(0);
  8802. }
  8803. static int
  8804. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8805. {
  8806. volatile struct shparam saveparam;
  8807. struct jmploc *volatile savehandler;
  8808. struct jmploc jmploc;
  8809. int e;
  8810. int savefuncline;
  8811. saveparam = shellparam;
  8812. savefuncline = funcline;
  8813. savehandler = exception_handler;
  8814. e = setjmp(jmploc.loc);
  8815. if (e) {
  8816. goto funcdone;
  8817. }
  8818. INT_OFF;
  8819. exception_handler = &jmploc;
  8820. shellparam.malloced = 0;
  8821. func->count++;
  8822. funcline = func->n.ndefun.linno;
  8823. INT_ON;
  8824. shellparam.nparam = argc - 1;
  8825. shellparam.p = argv + 1;
  8826. #if ENABLE_ASH_GETOPTS
  8827. shellparam.optind = 1;
  8828. shellparam.optoff = -1;
  8829. #endif
  8830. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  8831. funcdone:
  8832. INT_OFF;
  8833. funcline = savefuncline;
  8834. freefunc(func);
  8835. freeparam(&shellparam);
  8836. shellparam = saveparam;
  8837. exception_handler = savehandler;
  8838. INT_ON;
  8839. evalskip &= ~SKIPFUNC;
  8840. return e;
  8841. }
  8842. /*
  8843. * Make a variable a local variable. When a variable is made local, it's
  8844. * value and flags are saved in a localvar structure. The saved values
  8845. * will be restored when the shell function returns. We handle the name
  8846. * "-" as a special case: it makes changes to "set +-options" local
  8847. * (options will be restored on return from the function).
  8848. */
  8849. static void
  8850. mklocal(char *name)
  8851. {
  8852. struct localvar *lvp;
  8853. struct var **vpp;
  8854. struct var *vp;
  8855. char *eq = strchr(name, '=');
  8856. INT_OFF;
  8857. /* Cater for duplicate "local". Examples:
  8858. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8859. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8860. */
  8861. lvp = localvar_stack->lv;
  8862. while (lvp) {
  8863. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8864. if (eq)
  8865. setvareq(name, 0);
  8866. /* else:
  8867. * it's a duplicate "local VAR" declaration, do nothing
  8868. */
  8869. goto ret;
  8870. }
  8871. lvp = lvp->next;
  8872. }
  8873. lvp = ckzalloc(sizeof(*lvp));
  8874. if (LONE_DASH(name)) {
  8875. char *p;
  8876. p = ckmalloc(sizeof(optlist));
  8877. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8878. vp = NULL;
  8879. } else {
  8880. vpp = hashvar(name);
  8881. vp = *findvar(vpp, name);
  8882. if (vp == NULL) {
  8883. /* variable did not exist yet */
  8884. if (eq)
  8885. vp = setvareq(name, VSTRFIXED);
  8886. else
  8887. vp = setvar(name, NULL, VSTRFIXED);
  8888. lvp->flags = VUNSET;
  8889. } else {
  8890. lvp->text = vp->var_text;
  8891. lvp->flags = vp->flags;
  8892. /* make sure neither "struct var" nor string gets freed
  8893. * during (un)setting:
  8894. */
  8895. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8896. if (eq)
  8897. setvareq(name, 0);
  8898. else
  8899. /* "local VAR" unsets VAR: */
  8900. setvar0(name, NULL);
  8901. }
  8902. }
  8903. lvp->vp = vp;
  8904. lvp->next = localvar_stack->lv;
  8905. localvar_stack->lv = lvp;
  8906. ret:
  8907. INT_ON;
  8908. }
  8909. /*
  8910. * The "local" command.
  8911. */
  8912. static int FAST_FUNC
  8913. localcmd(int argc UNUSED_PARAM, char **argv)
  8914. {
  8915. char *name;
  8916. if (!localvar_stack)
  8917. ash_msg_and_raise_error("not in a function");
  8918. argv = argptr;
  8919. while ((name = *argv++) != NULL) {
  8920. mklocal(name);
  8921. }
  8922. return 0;
  8923. }
  8924. static int FAST_FUNC
  8925. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8926. {
  8927. return 1;
  8928. }
  8929. static int FAST_FUNC
  8930. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8931. {
  8932. return 0;
  8933. }
  8934. static int FAST_FUNC
  8935. execcmd(int argc UNUSED_PARAM, char **argv)
  8936. {
  8937. optionarg = NULL;
  8938. while (nextopt("a:") != '\0')
  8939. /* nextopt() sets optionarg to "-a ARGV0" */;
  8940. argv = argptr;
  8941. if (argv[0]) {
  8942. char *prog;
  8943. iflag = 0; /* exit on error */
  8944. mflag = 0;
  8945. optschanged();
  8946. /* We should set up signals for "exec CMD"
  8947. * the same way as for "CMD" without "exec".
  8948. * But optschanged->setinteractive->setsignal
  8949. * still thought we are a root shell. Therefore, for example,
  8950. * SIGQUIT is still set to IGN. Fix it:
  8951. */
  8952. shlvl++;
  8953. setsignal(SIGQUIT);
  8954. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  8955. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  8956. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  8957. prog = argv[0];
  8958. if (optionarg)
  8959. argv[0] = optionarg;
  8960. shellexec(prog, argv, pathval(), 0);
  8961. /* NOTREACHED */
  8962. }
  8963. return 0;
  8964. }
  8965. /*
  8966. * The return command.
  8967. */
  8968. static int FAST_FUNC
  8969. returncmd(int argc UNUSED_PARAM, char **argv)
  8970. {
  8971. /*
  8972. * If called outside a function, do what ksh does;
  8973. * skip the rest of the file.
  8974. */
  8975. evalskip = SKIPFUNC;
  8976. return argv[1] ? number(argv[1]) : exitstatus;
  8977. }
  8978. /* Forward declarations for builtintab[] */
  8979. static int breakcmd(int, char **) FAST_FUNC;
  8980. static int dotcmd(int, char **) FAST_FUNC;
  8981. static int evalcmd(int, char **, int) FAST_FUNC;
  8982. static int exitcmd(int, char **) FAST_FUNC;
  8983. static int exportcmd(int, char **) FAST_FUNC;
  8984. #if ENABLE_ASH_GETOPTS
  8985. static int getoptscmd(int, char **) FAST_FUNC;
  8986. #endif
  8987. #if ENABLE_ASH_HELP
  8988. static int helpcmd(int, char **) FAST_FUNC;
  8989. #endif
  8990. #if MAX_HISTORY
  8991. static int historycmd(int, char **) FAST_FUNC;
  8992. #endif
  8993. #if ENABLE_FEATURE_SH_MATH
  8994. static int letcmd(int, char **) FAST_FUNC;
  8995. #endif
  8996. static int readcmd(int, char **) FAST_FUNC;
  8997. static int setcmd(int, char **) FAST_FUNC;
  8998. static int shiftcmd(int, char **) FAST_FUNC;
  8999. static int timescmd(int, char **) FAST_FUNC;
  9000. static int trapcmd(int, char **) FAST_FUNC;
  9001. static int umaskcmd(int, char **) FAST_FUNC;
  9002. static int unsetcmd(int, char **) FAST_FUNC;
  9003. static int ulimitcmd(int, char **) FAST_FUNC;
  9004. #define BUILTIN_NOSPEC "0"
  9005. #define BUILTIN_SPECIAL "1"
  9006. #define BUILTIN_REGULAR "2"
  9007. #define BUILTIN_SPEC_REG "3"
  9008. #define BUILTIN_ASSIGN "4"
  9009. #define BUILTIN_SPEC_ASSG "5"
  9010. #define BUILTIN_REG_ASSG "6"
  9011. #define BUILTIN_SPEC_REG_ASSG "7"
  9012. /* Stubs for calling non-FAST_FUNC's */
  9013. #if ENABLE_ASH_ECHO
  9014. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  9015. #endif
  9016. #if ENABLE_ASH_PRINTF
  9017. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  9018. #endif
  9019. #if ENABLE_ASH_TEST || BASH_TEST2
  9020. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  9021. #endif
  9022. /* Keep these in proper order since it is searched via bsearch() */
  9023. static const struct builtincmd builtintab[] = {
  9024. { BUILTIN_SPEC_REG "." , dotcmd },
  9025. { BUILTIN_SPEC_REG ":" , truecmd },
  9026. #if ENABLE_ASH_TEST
  9027. { BUILTIN_REGULAR "[" , testcmd },
  9028. #endif
  9029. #if BASH_TEST2
  9030. { BUILTIN_REGULAR "[[" , testcmd },
  9031. #endif
  9032. #if ENABLE_ASH_ALIAS
  9033. { BUILTIN_REG_ASSG "alias" , aliascmd },
  9034. #endif
  9035. #if JOBS
  9036. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  9037. #endif
  9038. { BUILTIN_SPEC_REG "break" , breakcmd },
  9039. { BUILTIN_REGULAR "cd" , cdcmd },
  9040. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9041. #if ENABLE_ASH_CMDCMD
  9042. { BUILTIN_REGULAR "command" , commandcmd },
  9043. #endif
  9044. { BUILTIN_SPEC_REG "continue", breakcmd },
  9045. #if ENABLE_ASH_ECHO
  9046. { BUILTIN_REGULAR "echo" , echocmd },
  9047. #endif
  9048. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9049. { BUILTIN_SPEC_REG "exec" , execcmd },
  9050. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9051. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9052. { BUILTIN_REGULAR "false" , falsecmd },
  9053. #if JOBS
  9054. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9055. #endif
  9056. #if ENABLE_ASH_GETOPTS
  9057. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9058. #endif
  9059. { BUILTIN_NOSPEC "hash" , hashcmd },
  9060. #if ENABLE_ASH_HELP
  9061. { BUILTIN_NOSPEC "help" , helpcmd },
  9062. #endif
  9063. #if MAX_HISTORY
  9064. { BUILTIN_NOSPEC "history" , historycmd },
  9065. #endif
  9066. #if JOBS
  9067. { BUILTIN_REGULAR "jobs" , jobscmd },
  9068. { BUILTIN_REGULAR "kill" , killcmd },
  9069. #endif
  9070. #if ENABLE_FEATURE_SH_MATH
  9071. { BUILTIN_NOSPEC "let" , letcmd },
  9072. #endif
  9073. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9074. #if ENABLE_ASH_PRINTF
  9075. { BUILTIN_REGULAR "printf" , printfcmd },
  9076. #endif
  9077. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  9078. { BUILTIN_REGULAR "read" , readcmd },
  9079. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9080. { BUILTIN_SPEC_REG "return" , returncmd },
  9081. { BUILTIN_SPEC_REG "set" , setcmd },
  9082. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9083. #if BASH_SOURCE
  9084. { BUILTIN_SPEC_REG "source" , dotcmd },
  9085. #endif
  9086. #if ENABLE_ASH_TEST
  9087. { BUILTIN_REGULAR "test" , testcmd },
  9088. #endif
  9089. { BUILTIN_SPEC_REG "times" , timescmd },
  9090. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9091. { BUILTIN_REGULAR "true" , truecmd },
  9092. { BUILTIN_NOSPEC "type" , typecmd },
  9093. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  9094. { BUILTIN_REGULAR "umask" , umaskcmd },
  9095. #if ENABLE_ASH_ALIAS
  9096. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9097. #endif
  9098. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9099. { BUILTIN_REGULAR "wait" , waitcmd },
  9100. };
  9101. /* Should match the above table! */
  9102. #define COMMANDCMD (builtintab + \
  9103. /* . : */ 2 + \
  9104. /* [ */ 1 * ENABLE_ASH_TEST + \
  9105. /* [[ */ 1 * BASH_TEST2 + \
  9106. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9107. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9108. /* break cd cddir */ 3)
  9109. #define EVALCMD (COMMANDCMD + \
  9110. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9111. /* continue */ 1 + \
  9112. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9113. 0)
  9114. #define EXECCMD (EVALCMD + \
  9115. /* eval */ 1)
  9116. /*
  9117. * Search the table of builtin commands.
  9118. */
  9119. static int
  9120. pstrcmp1(const void *a, const void *b)
  9121. {
  9122. return strcmp((char*)a, *(char**)b + 1);
  9123. }
  9124. static struct builtincmd *
  9125. find_builtin(const char *name)
  9126. {
  9127. struct builtincmd *bp;
  9128. bp = bsearch(
  9129. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9130. pstrcmp1
  9131. );
  9132. return bp;
  9133. }
  9134. /*
  9135. * Execute a simple command.
  9136. */
  9137. static void unwindfiles(struct parsefile *stop);
  9138. static int
  9139. isassignment(const char *p)
  9140. {
  9141. const char *q = endofname(p);
  9142. if (p == q)
  9143. return 0;
  9144. return *q == '=';
  9145. }
  9146. static int FAST_FUNC
  9147. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9148. {
  9149. /* Preserve exitstatus of a previous possible redirection
  9150. * as POSIX mandates */
  9151. return back_exitstatus;
  9152. }
  9153. static int
  9154. evalcommand(union node *cmd, int flags)
  9155. {
  9156. static const struct builtincmd null_bltin = {
  9157. "\0\0", bltincmd /* why three NULs? */
  9158. };
  9159. struct localvar_list *localvar_stop;
  9160. struct parsefile *file_stop;
  9161. struct redirtab *redir_stop;
  9162. union node *argp;
  9163. struct arglist arglist;
  9164. struct arglist varlist;
  9165. char **argv;
  9166. int argc;
  9167. const struct strlist *sp;
  9168. struct cmdentry cmdentry;
  9169. struct job *jp;
  9170. char *lastarg;
  9171. const char *path;
  9172. int spclbltin;
  9173. int status;
  9174. char **nargv;
  9175. smallint cmd_is_exec;
  9176. errlinno = lineno = cmd->ncmd.linno;
  9177. if (funcline)
  9178. lineno -= funcline - 1;
  9179. /* First expand the arguments. */
  9180. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9181. localvar_stop = pushlocalvars();
  9182. file_stop = g_parsefile;
  9183. back_exitstatus = 0;
  9184. cmdentry.cmdtype = CMDBUILTIN;
  9185. cmdentry.u.cmd = &null_bltin;
  9186. varlist.lastp = &varlist.list;
  9187. *varlist.lastp = NULL;
  9188. arglist.lastp = &arglist.list;
  9189. *arglist.lastp = NULL;
  9190. argc = 0;
  9191. if (cmd->ncmd.args) {
  9192. struct builtincmd *bcmd;
  9193. smallint pseudovarflag;
  9194. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  9195. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  9196. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  9197. struct strlist **spp;
  9198. spp = arglist.lastp;
  9199. if (pseudovarflag && isassignment(argp->narg.text))
  9200. expandarg(argp, &arglist, EXP_VARTILDE);
  9201. else
  9202. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  9203. for (sp = *spp; sp; sp = sp->next)
  9204. argc++;
  9205. }
  9206. }
  9207. /* Reserve one extra spot at the front for shellexec. */
  9208. nargv = stalloc(sizeof(char *) * (argc + 2));
  9209. argv = ++nargv;
  9210. for (sp = arglist.list; sp; sp = sp->next) {
  9211. TRACE(("evalcommand arg: %s\n", sp->text));
  9212. *nargv++ = sp->text;
  9213. }
  9214. *nargv = NULL;
  9215. lastarg = NULL;
  9216. if (iflag && funcline == 0 && argc > 0)
  9217. lastarg = nargv[-1];
  9218. expredir(cmd->ncmd.redirect);
  9219. redir_stop = pushredir(cmd->ncmd.redirect);
  9220. preverrout_fd = 2;
  9221. if (BASH_XTRACEFD && xflag) {
  9222. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9223. * we do not emulate this. We only use its value.
  9224. */
  9225. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9226. if (xtracefd && is_number(xtracefd))
  9227. preverrout_fd = atoi(xtracefd);
  9228. }
  9229. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9230. path = vpath.var_text;
  9231. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9232. struct strlist **spp;
  9233. char *p;
  9234. spp = varlist.lastp;
  9235. expandarg(argp, &varlist, EXP_VARTILDE);
  9236. mklocal((*spp)->text);
  9237. /*
  9238. * Modify the command lookup path, if a PATH= assignment
  9239. * is present
  9240. */
  9241. p = (*spp)->text;
  9242. if (varcmp(p, path) == 0)
  9243. path = p;
  9244. }
  9245. /* Print the command if xflag is set. */
  9246. if (xflag) {
  9247. const char *pfx = "";
  9248. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9249. sp = varlist.list;
  9250. while (sp) {
  9251. char *varval = sp->text;
  9252. char *eq = strchrnul(varval, '=');
  9253. if (*eq)
  9254. eq++;
  9255. fdprintf(preverrout_fd, "%s%.*s%s",
  9256. pfx,
  9257. (int)(eq - varval), varval,
  9258. maybe_single_quote(eq)
  9259. );
  9260. sp = sp->next;
  9261. pfx = " ";
  9262. }
  9263. sp = arglist.list;
  9264. while (sp) {
  9265. fdprintf(preverrout_fd, "%s%s",
  9266. pfx,
  9267. /* always quote if matches reserved word: */
  9268. findkwd(sp->text)
  9269. ? single_quote(sp->text)
  9270. : maybe_single_quote(sp->text)
  9271. );
  9272. sp = sp->next;
  9273. pfx = " ";
  9274. }
  9275. safe_write(preverrout_fd, "\n", 1);
  9276. }
  9277. cmd_is_exec = 0;
  9278. spclbltin = -1;
  9279. /* Now locate the command. */
  9280. if (argc) {
  9281. int cmd_flag = DO_ERR;
  9282. #if ENABLE_ASH_CMDCMD
  9283. const char *oldpath = path + 5;
  9284. #endif
  9285. path += 5;
  9286. for (;;) {
  9287. find_command(argv[0], &cmdentry, cmd_flag, path);
  9288. if (cmdentry.cmdtype == CMDUNKNOWN) {
  9289. flush_stdout_stderr();
  9290. status = 127;
  9291. goto bail;
  9292. }
  9293. /* implement bltin and command here */
  9294. if (cmdentry.cmdtype != CMDBUILTIN)
  9295. break;
  9296. if (spclbltin < 0)
  9297. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9298. if (cmdentry.u.cmd == EXECCMD)
  9299. cmd_is_exec = 1;
  9300. #if ENABLE_ASH_CMDCMD
  9301. if (cmdentry.u.cmd == COMMANDCMD) {
  9302. path = oldpath;
  9303. nargv = parse_command_args(argv, &path);
  9304. if (!nargv)
  9305. break;
  9306. /* It's "command [-p] PROG ARGS" (that is, no -Vv).
  9307. * nargv => "PROG". path is updated if -p.
  9308. */
  9309. argc -= nargv - argv;
  9310. argv = nargv;
  9311. cmd_flag |= DO_NOFUNC;
  9312. } else
  9313. #endif
  9314. break;
  9315. }
  9316. }
  9317. if (status) {
  9318. bail:
  9319. exitstatus = status;
  9320. /* We have a redirection error. */
  9321. if (spclbltin > 0)
  9322. raise_exception(EXERROR);
  9323. goto out;
  9324. }
  9325. /* Execute the command. */
  9326. switch (cmdentry.cmdtype) {
  9327. default: {
  9328. #if ENABLE_FEATURE_SH_STANDALONE \
  9329. && ENABLE_FEATURE_SH_NOFORK \
  9330. && NUM_APPLETS > 1
  9331. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9332. * around run_nofork_applet() call.
  9333. * (2) Should this check also be done in forkshell()?
  9334. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9335. */
  9336. /* find_command() encodes applet_no as (-2 - applet_no) */
  9337. int applet_no = (- cmdentry.u.index - 2);
  9338. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9339. char **sv_environ;
  9340. INT_OFF;
  9341. sv_environ = environ;
  9342. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9343. /*
  9344. * Run <applet>_main().
  9345. * Signals (^C) can't interrupt here.
  9346. * Otherwise we can mangle stdio or malloc internal state.
  9347. * This makes applets which can run for a long time
  9348. * and/or wait for user input ineligible for NOFORK:
  9349. * for example, "yes" or "rm" (rm -i waits for input).
  9350. */
  9351. status = run_nofork_applet(applet_no, argv);
  9352. environ = sv_environ;
  9353. /*
  9354. * Try enabling NOFORK for "yes" applet.
  9355. * ^C _will_ stop it (write returns EINTR),
  9356. * but this causes stdout FILE to be stuck
  9357. * and needing clearerr(). What if other applets
  9358. * also can get EINTRs? Do we need to switch
  9359. * our signals to SA_RESTART?
  9360. */
  9361. /*clearerr(stdout);*/
  9362. INT_ON;
  9363. break;
  9364. }
  9365. #endif
  9366. /* Can we avoid forking? For example, very last command
  9367. * in a script or a subshell does not need forking,
  9368. * we can just exec it.
  9369. */
  9370. if (!(flags & EV_EXIT) || may_have_traps) {
  9371. /* No, forking off a child is necessary */
  9372. INT_OFF;
  9373. get_tty_state();
  9374. jp = makejob(/*cmd,*/ 1);
  9375. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9376. /* parent */
  9377. status = waitforjob(jp);
  9378. INT_ON;
  9379. TRACE(("forked child exited with %d\n", status));
  9380. break;
  9381. }
  9382. /* child */
  9383. FORCE_INT_ON;
  9384. /* fall through to exec'ing external program */
  9385. }
  9386. listsetvar(varlist.list, VEXPORT|VSTACK);
  9387. shellexec(argv[0], argv, path, cmdentry.u.index);
  9388. /* NOTREACHED */
  9389. } /* default */
  9390. case CMDBUILTIN:
  9391. if (spclbltin > 0 || argc == 0) {
  9392. poplocalvars(1);
  9393. if (cmd_is_exec && argc > 1)
  9394. listsetvar(varlist.list, VEXPORT);
  9395. }
  9396. /* Tight loop with builtins only:
  9397. * "while kill -0 $child; do true; done"
  9398. * will never exit even if $child died, unless we do this
  9399. * to reap the zombie and make kill detect that it's gone: */
  9400. dowait(DOWAIT_NONBLOCK, NULL);
  9401. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
  9402. if (exception_type == EXERROR && spclbltin <= 0) {
  9403. FORCE_INT_ON;
  9404. goto readstatus;
  9405. }
  9406. raise:
  9407. longjmp(exception_handler->loc, 1);
  9408. }
  9409. goto readstatus;
  9410. case CMDFUNCTION:
  9411. /* See above for the rationale */
  9412. dowait(DOWAIT_NONBLOCK, NULL);
  9413. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9414. goto raise;
  9415. readstatus:
  9416. status = exitstatus;
  9417. break;
  9418. } /* switch */
  9419. out:
  9420. if (cmd->ncmd.redirect)
  9421. popredir(/*drop:*/ cmd_is_exec);
  9422. unwindredir(redir_stop);
  9423. unwindfiles(file_stop);
  9424. unwindlocalvars(localvar_stop);
  9425. if (lastarg) {
  9426. /* dsl: I think this is intended to be used to support
  9427. * '_' in 'vi' command mode during line editing...
  9428. * However I implemented that within libedit itself.
  9429. */
  9430. setvar0("_", lastarg);
  9431. }
  9432. return status;
  9433. }
  9434. static int
  9435. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9436. {
  9437. char *volatile savecmdname;
  9438. struct jmploc *volatile savehandler;
  9439. struct jmploc jmploc;
  9440. int status;
  9441. int i;
  9442. savecmdname = commandname;
  9443. savehandler = exception_handler;
  9444. i = setjmp(jmploc.loc);
  9445. if (i)
  9446. goto cmddone;
  9447. exception_handler = &jmploc;
  9448. commandname = argv[0];
  9449. argptr = argv + 1;
  9450. optptr = NULL; /* initialize nextopt */
  9451. if (cmd == EVALCMD)
  9452. status = evalcmd(argc, argv, flags);
  9453. else
  9454. status = (*cmd->builtin)(argc, argv);
  9455. flush_stdout_stderr();
  9456. status |= ferror(stdout);
  9457. exitstatus = status;
  9458. cmddone:
  9459. clearerr(stdout);
  9460. commandname = savecmdname;
  9461. exception_handler = savehandler;
  9462. return i;
  9463. }
  9464. static int
  9465. goodname(const char *p)
  9466. {
  9467. return endofname(p)[0] == '\0';
  9468. }
  9469. /*
  9470. * Search for a command. This is called before we fork so that the
  9471. * location of the command will be available in the parent as well as
  9472. * the child. The check for "goodname" is an overly conservative
  9473. * check that the name will not be subject to expansion.
  9474. */
  9475. static void
  9476. prehash(union node *n)
  9477. {
  9478. struct cmdentry entry;
  9479. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9480. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9481. }
  9482. /* ============ Builtin commands
  9483. *
  9484. * Builtin commands whose functions are closely tied to evaluation
  9485. * are implemented here.
  9486. */
  9487. /*
  9488. * Handle break and continue commands. Break, continue, and return are
  9489. * all handled by setting the evalskip flag. The evaluation routines
  9490. * above all check this flag, and if it is set they start skipping
  9491. * commands rather than executing them. The variable skipcount is
  9492. * the number of loops to break/continue, or the number of function
  9493. * levels to return. (The latter is always 1.) It should probably
  9494. * be an error to break out of more loops than exist, but it isn't
  9495. * in the standard shell so we don't make it one here.
  9496. */
  9497. static int FAST_FUNC
  9498. breakcmd(int argc UNUSED_PARAM, char **argv)
  9499. {
  9500. int n = argv[1] ? number(argv[1]) : 1;
  9501. if (n <= 0)
  9502. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9503. if (n > loopnest)
  9504. n = loopnest;
  9505. if (n > 0) {
  9506. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9507. skipcount = n;
  9508. }
  9509. return 0;
  9510. }
  9511. /*
  9512. * This implements the input routines used by the parser.
  9513. */
  9514. enum {
  9515. INPUT_PUSH_FILE = 1,
  9516. INPUT_NOFILE_OK = 2,
  9517. };
  9518. static smallint checkkwd;
  9519. /* values of checkkwd variable */
  9520. #define CHKALIAS 0x1
  9521. #define CHKKWD 0x2
  9522. #define CHKNL 0x4
  9523. #define CHKEOFMARK 0x8
  9524. /*
  9525. * Push a string back onto the input at this current parsefile level.
  9526. * We handle aliases this way.
  9527. */
  9528. #if !ENABLE_ASH_ALIAS
  9529. #define pushstring(s, ap) pushstring(s)
  9530. #endif
  9531. static void
  9532. pushstring(char *s, struct alias *ap)
  9533. {
  9534. struct strpush *sp;
  9535. int len;
  9536. len = strlen(s);
  9537. INT_OFF;
  9538. if (g_parsefile->strpush) {
  9539. sp = ckzalloc(sizeof(*sp));
  9540. sp->prev = g_parsefile->strpush;
  9541. } else {
  9542. sp = &(g_parsefile->basestrpush);
  9543. }
  9544. g_parsefile->strpush = sp;
  9545. sp->prev_string = g_parsefile->next_to_pgetc;
  9546. sp->prev_left_in_line = g_parsefile->left_in_line;
  9547. sp->unget = g_parsefile->unget;
  9548. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9549. #if ENABLE_ASH_ALIAS
  9550. sp->ap = ap;
  9551. if (ap) {
  9552. ap->flag |= ALIASINUSE;
  9553. sp->string = s;
  9554. }
  9555. #endif
  9556. g_parsefile->next_to_pgetc = s;
  9557. g_parsefile->left_in_line = len;
  9558. g_parsefile->unget = 0;
  9559. INT_ON;
  9560. }
  9561. static void
  9562. popstring(void)
  9563. {
  9564. struct strpush *sp = g_parsefile->strpush;
  9565. INT_OFF;
  9566. #if ENABLE_ASH_ALIAS
  9567. if (sp->ap) {
  9568. if (g_parsefile->next_to_pgetc[-1] == ' '
  9569. || g_parsefile->next_to_pgetc[-1] == '\t'
  9570. ) {
  9571. checkkwd |= CHKALIAS;
  9572. }
  9573. if (sp->string != sp->ap->val) {
  9574. free(sp->string);
  9575. }
  9576. sp->ap->flag &= ~ALIASINUSE;
  9577. if (sp->ap->flag & ALIASDEAD) {
  9578. unalias(sp->ap->name);
  9579. }
  9580. }
  9581. #endif
  9582. g_parsefile->next_to_pgetc = sp->prev_string;
  9583. g_parsefile->left_in_line = sp->prev_left_in_line;
  9584. g_parsefile->unget = sp->unget;
  9585. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9586. g_parsefile->strpush = sp->prev;
  9587. if (sp != &(g_parsefile->basestrpush))
  9588. free(sp);
  9589. INT_ON;
  9590. }
  9591. static int
  9592. preadfd(void)
  9593. {
  9594. int nr;
  9595. char *buf = g_parsefile->buf;
  9596. g_parsefile->next_to_pgetc = buf;
  9597. #if ENABLE_FEATURE_EDITING
  9598. retry:
  9599. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9600. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9601. else {
  9602. # if ENABLE_ASH_IDLE_TIMEOUT
  9603. int timeout = -1;
  9604. if (iflag) {
  9605. const char *tmout_var = lookupvar("TMOUT");
  9606. if (tmout_var) {
  9607. timeout = atoi(tmout_var) * 1000;
  9608. if (timeout <= 0)
  9609. timeout = -1;
  9610. }
  9611. }
  9612. line_input_state->timeout = timeout;
  9613. # endif
  9614. # if ENABLE_FEATURE_TAB_COMPLETION
  9615. line_input_state->path_lookup = pathval();
  9616. # endif
  9617. reinit_unicode_for_ash();
  9618. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9619. if (nr == 0) {
  9620. /* ^C pressed, "convert" to SIGINT */
  9621. write(STDOUT_FILENO, "^C", 2);
  9622. if (trap[SIGINT]) {
  9623. buf[0] = '\n';
  9624. buf[1] = '\0';
  9625. raise(SIGINT);
  9626. return 1;
  9627. }
  9628. exitstatus = 128 + SIGINT;
  9629. bb_putchar('\n');
  9630. goto retry;
  9631. }
  9632. if (nr < 0) {
  9633. if (errno == 0) {
  9634. /* Ctrl+D pressed */
  9635. nr = 0;
  9636. }
  9637. # if ENABLE_ASH_IDLE_TIMEOUT
  9638. else if (errno == EAGAIN && timeout > 0) {
  9639. puts("\007timed out waiting for input: auto-logout");
  9640. exitshell();
  9641. }
  9642. # endif
  9643. }
  9644. }
  9645. #else
  9646. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9647. #endif
  9648. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9649. if (nr < 0) {
  9650. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9651. int flags = fcntl(0, F_GETFL);
  9652. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9653. flags &= ~O_NONBLOCK;
  9654. if (fcntl(0, F_SETFL, flags) >= 0) {
  9655. out2str("sh: turning off NDELAY mode\n");
  9656. goto retry;
  9657. }
  9658. }
  9659. }
  9660. }
  9661. #endif
  9662. return nr;
  9663. }
  9664. /*
  9665. * Refill the input buffer and return the next input character:
  9666. *
  9667. * 1) If a string was pushed back on the input, pop it;
  9668. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9669. * or we are reading from a string so we can't refill the buffer,
  9670. * return EOF.
  9671. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9672. * 4) Process input up to the next newline, deleting nul characters.
  9673. */
  9674. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9675. #define pgetc_debug(...) ((void)0)
  9676. static int pgetc(void);
  9677. static int
  9678. preadbuffer(void)
  9679. {
  9680. char *q;
  9681. int more;
  9682. if (g_parsefile->strpush) {
  9683. #if ENABLE_ASH_ALIAS
  9684. if (g_parsefile->left_in_line == -1
  9685. && g_parsefile->strpush->ap
  9686. && g_parsefile->next_to_pgetc[-1] != ' '
  9687. && g_parsefile->next_to_pgetc[-1] != '\t'
  9688. ) {
  9689. pgetc_debug("preadbuffer PEOA");
  9690. return PEOA;
  9691. }
  9692. #endif
  9693. popstring();
  9694. return pgetc();
  9695. }
  9696. /* on both branches above g_parsefile->left_in_line < 0.
  9697. * "pgetc" needs refilling.
  9698. */
  9699. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9700. * pungetc() may increment it a few times.
  9701. * Assuming it won't increment it to less than -90.
  9702. */
  9703. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9704. pgetc_debug("preadbuffer PEOF1");
  9705. /* even in failure keep left_in_line and next_to_pgetc
  9706. * in lock step, for correct multi-layer pungetc.
  9707. * left_in_line was decremented before preadbuffer(),
  9708. * must inc next_to_pgetc: */
  9709. g_parsefile->next_to_pgetc++;
  9710. return PEOF;
  9711. }
  9712. more = g_parsefile->left_in_buffer;
  9713. if (more <= 0) {
  9714. flush_stdout_stderr();
  9715. again:
  9716. more = preadfd();
  9717. if (more <= 0) {
  9718. /* don't try reading again */
  9719. g_parsefile->left_in_line = -99;
  9720. pgetc_debug("preadbuffer PEOF2");
  9721. g_parsefile->next_to_pgetc++;
  9722. return PEOF;
  9723. }
  9724. }
  9725. /* Find out where's the end of line.
  9726. * Set g_parsefile->left_in_line
  9727. * and g_parsefile->left_in_buffer acordingly.
  9728. * NUL chars are deleted.
  9729. */
  9730. q = g_parsefile->next_to_pgetc;
  9731. for (;;) {
  9732. char c;
  9733. more--;
  9734. c = *q;
  9735. if (c == '\0') {
  9736. memmove(q, q + 1, more);
  9737. } else {
  9738. q++;
  9739. if (c == '\n') {
  9740. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9741. break;
  9742. }
  9743. }
  9744. if (more <= 0) {
  9745. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9746. if (g_parsefile->left_in_line < 0)
  9747. goto again;
  9748. break;
  9749. }
  9750. }
  9751. g_parsefile->left_in_buffer = more;
  9752. if (vflag) {
  9753. char save = *q;
  9754. *q = '\0';
  9755. out2str(g_parsefile->next_to_pgetc);
  9756. *q = save;
  9757. }
  9758. pgetc_debug("preadbuffer at %d:%p'%s'",
  9759. g_parsefile->left_in_line,
  9760. g_parsefile->next_to_pgetc,
  9761. g_parsefile->next_to_pgetc);
  9762. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9763. }
  9764. static void
  9765. nlprompt(void)
  9766. {
  9767. g_parsefile->linno++;
  9768. setprompt_if(doprompt, 2);
  9769. }
  9770. static void
  9771. nlnoprompt(void)
  9772. {
  9773. g_parsefile->linno++;
  9774. needprompt = doprompt;
  9775. }
  9776. static int
  9777. pgetc(void)
  9778. {
  9779. int c;
  9780. pgetc_debug("pgetc at %d:%p'%s'",
  9781. g_parsefile->left_in_line,
  9782. g_parsefile->next_to_pgetc,
  9783. g_parsefile->next_to_pgetc);
  9784. if (g_parsefile->unget)
  9785. return g_parsefile->lastc[--g_parsefile->unget];
  9786. if (--g_parsefile->left_in_line >= 0)
  9787. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9788. else
  9789. c = preadbuffer();
  9790. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9791. g_parsefile->lastc[0] = c;
  9792. return c;
  9793. }
  9794. #if ENABLE_ASH_ALIAS
  9795. static int
  9796. pgetc_without_PEOA(void)
  9797. {
  9798. int c;
  9799. do {
  9800. pgetc_debug("pgetc at %d:%p'%s'",
  9801. g_parsefile->left_in_line,
  9802. g_parsefile->next_to_pgetc,
  9803. g_parsefile->next_to_pgetc);
  9804. c = pgetc();
  9805. } while (c == PEOA);
  9806. return c;
  9807. }
  9808. #else
  9809. # define pgetc_without_PEOA() pgetc()
  9810. #endif
  9811. /*
  9812. * Undo a call to pgetc. Only two characters may be pushed back.
  9813. * PEOF may be pushed back.
  9814. */
  9815. static void
  9816. pungetc(void)
  9817. {
  9818. g_parsefile->unget++;
  9819. }
  9820. /* This one eats backslash+newline */
  9821. static int
  9822. pgetc_eatbnl(void)
  9823. {
  9824. int c;
  9825. while ((c = pgetc()) == '\\') {
  9826. if (pgetc() != '\n') {
  9827. pungetc();
  9828. break;
  9829. }
  9830. nlprompt();
  9831. }
  9832. return c;
  9833. }
  9834. struct synstack {
  9835. smalluint syntax;
  9836. uint8_t innerdq :1;
  9837. uint8_t varpushed :1;
  9838. uint8_t dblquote :1;
  9839. int varnest; /* levels of variables expansion */
  9840. int dqvarnest; /* levels of variables expansion within double quotes */
  9841. int parenlevel; /* levels of parens in arithmetic */
  9842. struct synstack *prev;
  9843. struct synstack *next;
  9844. };
  9845. static void
  9846. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  9847. {
  9848. memset(next, 0, sizeof(*next));
  9849. next->syntax = syntax;
  9850. next->next = *stack;
  9851. (*stack)->prev = next;
  9852. *stack = next;
  9853. }
  9854. static ALWAYS_INLINE void
  9855. synstack_pop(struct synstack **stack)
  9856. {
  9857. *stack = (*stack)->next;
  9858. }
  9859. /*
  9860. * To handle the "." command, a stack of input files is used. Pushfile
  9861. * adds a new entry to the stack and popfile restores the previous level.
  9862. */
  9863. static void
  9864. pushfile(void)
  9865. {
  9866. struct parsefile *pf;
  9867. pf = ckzalloc(sizeof(*pf));
  9868. pf->prev = g_parsefile;
  9869. pf->pf_fd = -1;
  9870. /*pf->strpush = NULL; - ckzalloc did it */
  9871. /*pf->basestrpush.prev = NULL;*/
  9872. /*pf->unget = 0;*/
  9873. g_parsefile = pf;
  9874. }
  9875. static void
  9876. popfile(void)
  9877. {
  9878. struct parsefile *pf = g_parsefile;
  9879. if (pf == &basepf)
  9880. return;
  9881. INT_OFF;
  9882. if (pf->pf_fd >= 0)
  9883. close(pf->pf_fd);
  9884. free(pf->buf);
  9885. while (pf->strpush)
  9886. popstring();
  9887. g_parsefile = pf->prev;
  9888. free(pf);
  9889. INT_ON;
  9890. }
  9891. static void
  9892. unwindfiles(struct parsefile *stop)
  9893. {
  9894. while (g_parsefile != stop)
  9895. popfile();
  9896. }
  9897. /*
  9898. * Return to top level.
  9899. */
  9900. static void
  9901. popallfiles(void)
  9902. {
  9903. unwindfiles(&basepf);
  9904. }
  9905. /*
  9906. * Close the file(s) that the shell is reading commands from. Called
  9907. * after a fork is done.
  9908. */
  9909. static void
  9910. closescript(void)
  9911. {
  9912. popallfiles();
  9913. if (g_parsefile->pf_fd > 0) {
  9914. close(g_parsefile->pf_fd);
  9915. g_parsefile->pf_fd = 0;
  9916. }
  9917. }
  9918. /*
  9919. * Like setinputfile, but takes an open file descriptor. Call this with
  9920. * interrupts off.
  9921. */
  9922. static void
  9923. setinputfd(int fd, int push)
  9924. {
  9925. if (push) {
  9926. pushfile();
  9927. g_parsefile->buf = NULL;
  9928. }
  9929. g_parsefile->pf_fd = fd;
  9930. if (g_parsefile->buf == NULL)
  9931. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9932. g_parsefile->left_in_buffer = 0;
  9933. g_parsefile->left_in_line = 0;
  9934. g_parsefile->linno = 1;
  9935. }
  9936. /*
  9937. * Set the input to take input from a file. If push is set, push the
  9938. * old input onto the stack first.
  9939. */
  9940. static int
  9941. setinputfile(const char *fname, int flags)
  9942. {
  9943. int fd;
  9944. INT_OFF;
  9945. fd = open(fname, O_RDONLY | O_CLOEXEC);
  9946. if (fd < 0) {
  9947. if (flags & INPUT_NOFILE_OK)
  9948. goto out;
  9949. exitstatus = 127;
  9950. ash_msg_and_raise_perror("can't open '%s'", fname);
  9951. }
  9952. if (fd < 10)
  9953. fd = savefd(fd);
  9954. else if (O_CLOEXEC == 0) /* old libc */
  9955. close_on_exec_on(fd);
  9956. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9957. out:
  9958. INT_ON;
  9959. return fd;
  9960. }
  9961. /*
  9962. * Like setinputfile, but takes input from a string.
  9963. */
  9964. static void
  9965. setinputstring(char *string)
  9966. {
  9967. INT_OFF;
  9968. pushfile();
  9969. g_parsefile->next_to_pgetc = string;
  9970. g_parsefile->left_in_line = strlen(string);
  9971. g_parsefile->buf = NULL;
  9972. g_parsefile->linno = 1;
  9973. INT_ON;
  9974. }
  9975. /*
  9976. * Routines to check for mail.
  9977. */
  9978. #if ENABLE_ASH_MAIL
  9979. /* Hash of mtimes of mailboxes */
  9980. static unsigned mailtime_hash;
  9981. /* Set if MAIL or MAILPATH is changed. */
  9982. static smallint mail_var_path_changed;
  9983. /*
  9984. * Print appropriate message(s) if mail has arrived.
  9985. * If mail_var_path_changed is set,
  9986. * then the value of MAIL has mail_var_path_changed,
  9987. * so we just update the values.
  9988. */
  9989. static void
  9990. chkmail(void)
  9991. {
  9992. const char *mpath;
  9993. char *p;
  9994. char *q;
  9995. unsigned new_hash;
  9996. struct stackmark smark;
  9997. struct stat statb;
  9998. setstackmark(&smark);
  9999. mpath = mpathset() ? mpathval() : mailval();
  10000. new_hash = 0;
  10001. for (;;) {
  10002. p = path_advance(&mpath, nullstr);
  10003. if (p == NULL)
  10004. break;
  10005. if (*p == '\0')
  10006. continue;
  10007. for (q = p; *q; q++)
  10008. continue;
  10009. #if DEBUG
  10010. if (q[-1] != '/')
  10011. abort();
  10012. #endif
  10013. q[-1] = '\0'; /* delete trailing '/' */
  10014. if (stat(p, &statb) < 0) {
  10015. continue;
  10016. }
  10017. /* Very simplistic "hash": just a sum of all mtimes */
  10018. new_hash += (unsigned)statb.st_mtime;
  10019. }
  10020. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  10021. if (mailtime_hash != 0)
  10022. out2str("you have mail\n");
  10023. mailtime_hash = new_hash;
  10024. }
  10025. mail_var_path_changed = 0;
  10026. popstackmark(&smark);
  10027. }
  10028. static void FAST_FUNC
  10029. changemail(const char *val UNUSED_PARAM)
  10030. {
  10031. mail_var_path_changed = 1;
  10032. }
  10033. #endif /* ASH_MAIL */
  10034. /* ============ ??? */
  10035. /*
  10036. * Set the shell parameters.
  10037. */
  10038. static void
  10039. setparam(char **argv)
  10040. {
  10041. char **newparam;
  10042. char **ap;
  10043. int nparam;
  10044. for (nparam = 0; argv[nparam]; nparam++)
  10045. continue;
  10046. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10047. while (*argv) {
  10048. *ap++ = ckstrdup(*argv++);
  10049. }
  10050. *ap = NULL;
  10051. freeparam(&shellparam);
  10052. shellparam.malloced = 1;
  10053. shellparam.nparam = nparam;
  10054. shellparam.p = newparam;
  10055. #if ENABLE_ASH_GETOPTS
  10056. shellparam.optind = 1;
  10057. shellparam.optoff = -1;
  10058. #endif
  10059. }
  10060. /*
  10061. * Process shell options. The global variable argptr contains a pointer
  10062. * to the argument list; we advance it past the options.
  10063. *
  10064. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10065. * For a non-interactive shell, an error condition encountered
  10066. * by a special built-in ... shall cause the shell to write a diagnostic message
  10067. * to standard error and exit as shown in the following table:
  10068. * Error Special Built-In
  10069. * ...
  10070. * Utility syntax error (option or operand error) Shall exit
  10071. * ...
  10072. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10073. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10074. * and shell continues), and people rely on this behavior!
  10075. * Testcase:
  10076. * set -o barfoo 2>/dev/null
  10077. * echo $?
  10078. *
  10079. * Oh well. Let's mimic that.
  10080. */
  10081. static int
  10082. plus_minus_o(char *name, int val)
  10083. {
  10084. int i;
  10085. if (name) {
  10086. for (i = 0; i < NOPTS; i++) {
  10087. if (strcmp(name, optnames(i)) == 0) {
  10088. optlist[i] = val;
  10089. return 0;
  10090. }
  10091. }
  10092. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10093. return 1;
  10094. }
  10095. for (i = 0; i < NOPTS; i++) {
  10096. if (val) {
  10097. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10098. } else {
  10099. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10100. }
  10101. }
  10102. return 0;
  10103. }
  10104. static void
  10105. setoption(int flag, int val)
  10106. {
  10107. int i;
  10108. for (i = 0; i < NOPTS; i++) {
  10109. if (optletters(i) == flag) {
  10110. optlist[i] = val;
  10111. return;
  10112. }
  10113. }
  10114. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10115. /* NOTREACHED */
  10116. }
  10117. static int
  10118. options(int cmdline, int *login_sh)
  10119. {
  10120. char *p;
  10121. int val;
  10122. int c;
  10123. if (cmdline)
  10124. minusc = NULL;
  10125. while ((p = *argptr) != NULL) {
  10126. c = *p++;
  10127. if (c != '-' && c != '+')
  10128. break;
  10129. argptr++;
  10130. val = 0; /* val = 0 if c == '+' */
  10131. if (c == '-') {
  10132. val = 1;
  10133. if (p[0] == '\0' || LONE_DASH(p)) {
  10134. if (!cmdline) {
  10135. /* "-" means turn off -x and -v */
  10136. if (p[0] == '\0')
  10137. xflag = vflag = 0;
  10138. /* "--" means reset params */
  10139. else if (*argptr == NULL)
  10140. setparam(argptr);
  10141. }
  10142. break; /* "-" or "--" terminates options */
  10143. }
  10144. }
  10145. /* first char was + or - */
  10146. while ((c = *p++) != '\0') {
  10147. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10148. if (c == 'c' && cmdline) {
  10149. minusc = p; /* command is after shell args */
  10150. } else if (c == 'o') {
  10151. if (plus_minus_o(*argptr, val)) {
  10152. /* it already printed err message */
  10153. return 1; /* error */
  10154. }
  10155. if (*argptr)
  10156. argptr++;
  10157. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  10158. if (login_sh)
  10159. *login_sh = 1;
  10160. /* bash does not accept +-login, we also won't */
  10161. } else if (cmdline && val && (c == '-')) { /* long options */
  10162. if (strcmp(p, "login") == 0) {
  10163. if (login_sh)
  10164. *login_sh = 1;
  10165. }
  10166. break;
  10167. } else {
  10168. setoption(c, val);
  10169. }
  10170. }
  10171. }
  10172. return 0;
  10173. }
  10174. /*
  10175. * The shift builtin command.
  10176. */
  10177. static int FAST_FUNC
  10178. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10179. {
  10180. int n;
  10181. char **ap1, **ap2;
  10182. n = 1;
  10183. if (argv[1])
  10184. n = number(argv[1]);
  10185. if (n > shellparam.nparam)
  10186. return 1;
  10187. INT_OFF;
  10188. shellparam.nparam -= n;
  10189. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10190. if (shellparam.malloced)
  10191. free(*ap1);
  10192. }
  10193. ap2 = shellparam.p;
  10194. while ((*ap2++ = *ap1++) != NULL)
  10195. continue;
  10196. #if ENABLE_ASH_GETOPTS
  10197. shellparam.optind = 1;
  10198. shellparam.optoff = -1;
  10199. #endif
  10200. INT_ON;
  10201. return 0;
  10202. }
  10203. /*
  10204. * POSIX requires that 'set' (but not export or readonly) output the
  10205. * variables in lexicographic order - by the locale's collating order (sigh).
  10206. * Maybe we could keep them in an ordered balanced binary tree
  10207. * instead of hashed lists.
  10208. * For now just roll 'em through qsort for printing...
  10209. */
  10210. static int
  10211. showvars(const char *sep_prefix, int on, int off)
  10212. {
  10213. const char *sep;
  10214. char **ep, **epend;
  10215. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10216. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10217. sep = *sep_prefix ? " " : sep_prefix;
  10218. for (; ep < epend; ep++) {
  10219. const char *p;
  10220. const char *q;
  10221. p = endofname(*ep);
  10222. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10223. * makes "export -p" to have output not suitable for "eval":
  10224. * import os
  10225. * os.environ["test-test"]="test"
  10226. * if os.fork() == 0:
  10227. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10228. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10229. */
  10230. q = nullstr;
  10231. if (*p == '=')
  10232. q = single_quote(++p);
  10233. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10234. }
  10235. return 0;
  10236. }
  10237. /*
  10238. * The set command builtin.
  10239. */
  10240. static int FAST_FUNC
  10241. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10242. {
  10243. int retval;
  10244. if (!argv[1])
  10245. return showvars(nullstr, 0, VUNSET);
  10246. INT_OFF;
  10247. retval = options(/*cmdline:*/ 0, NULL);
  10248. if (retval == 0) { /* if no parse error... */
  10249. optschanged();
  10250. if (*argptr != NULL) {
  10251. setparam(argptr);
  10252. }
  10253. }
  10254. INT_ON;
  10255. return retval;
  10256. }
  10257. #if ENABLE_ASH_RANDOM_SUPPORT
  10258. static void FAST_FUNC
  10259. change_random(const char *value)
  10260. {
  10261. uint32_t t;
  10262. if (value == NULL) {
  10263. /* "get", generate */
  10264. t = next_random(&random_gen);
  10265. /* set without recursion */
  10266. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10267. vrandom.flags &= ~VNOFUNC;
  10268. } else {
  10269. /* set/reset */
  10270. t = strtoul(value, NULL, 10);
  10271. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10272. }
  10273. }
  10274. #endif
  10275. #if ENABLE_ASH_GETOPTS
  10276. static int
  10277. getopts(char *optstr, char *optvar, char **optfirst)
  10278. {
  10279. char *p, *q;
  10280. char c = '?';
  10281. int done = 0;
  10282. char sbuf[2];
  10283. char **optnext;
  10284. int ind = shellparam.optind;
  10285. int off = shellparam.optoff;
  10286. sbuf[1] = '\0';
  10287. shellparam.optind = -1;
  10288. optnext = optfirst + ind - 1;
  10289. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10290. p = NULL;
  10291. else
  10292. p = optnext[-1] + off;
  10293. if (p == NULL || *p == '\0') {
  10294. /* Current word is done, advance */
  10295. p = *optnext;
  10296. if (p == NULL || *p != '-' || *++p == '\0') {
  10297. atend:
  10298. unsetvar("OPTARG");
  10299. p = NULL;
  10300. done = 1;
  10301. goto out;
  10302. }
  10303. optnext++;
  10304. if (LONE_DASH(p)) /* check for "--" */
  10305. goto atend;
  10306. }
  10307. c = *p++;
  10308. for (q = optstr; *q != c;) {
  10309. if (*q == '\0') {
  10310. /* OPTERR is a bashism */
  10311. const char *cp = lookupvar("OPTERR");
  10312. if ((cp && LONE_CHAR(cp, '0'))
  10313. || (optstr[0] == ':')
  10314. ) {
  10315. sbuf[0] = c;
  10316. /*sbuf[1] = '\0'; - already is */
  10317. setvar0("OPTARG", sbuf);
  10318. } else {
  10319. fprintf(stderr, "Illegal option -%c\n", c);
  10320. unsetvar("OPTARG");
  10321. }
  10322. c = '?';
  10323. goto out;
  10324. }
  10325. if (*++q == ':')
  10326. q++;
  10327. }
  10328. if (*++q == ':') {
  10329. if (*p == '\0' && (p = *optnext) == NULL) {
  10330. /* OPTERR is a bashism */
  10331. const char *cp = lookupvar("OPTERR");
  10332. if ((cp && LONE_CHAR(cp, '0'))
  10333. || (optstr[0] == ':')
  10334. ) {
  10335. sbuf[0] = c;
  10336. /*sbuf[1] = '\0'; - already is */
  10337. setvar0("OPTARG", sbuf);
  10338. c = ':';
  10339. } else {
  10340. fprintf(stderr, "No arg for -%c option\n", c);
  10341. unsetvar("OPTARG");
  10342. c = '?';
  10343. }
  10344. goto out;
  10345. }
  10346. if (p == *optnext)
  10347. optnext++;
  10348. setvar0("OPTARG", p);
  10349. p = NULL;
  10350. } else
  10351. setvar0("OPTARG", nullstr);
  10352. out:
  10353. ind = optnext - optfirst + 1;
  10354. setvar("OPTIND", itoa(ind), VNOFUNC);
  10355. sbuf[0] = c;
  10356. /*sbuf[1] = '\0'; - already is */
  10357. setvar0(optvar, sbuf);
  10358. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10359. shellparam.optind = ind;
  10360. return done;
  10361. }
  10362. /*
  10363. * The getopts builtin. Shellparam.optnext points to the next argument
  10364. * to be processed. Shellparam.optptr points to the next character to
  10365. * be processed in the current argument. If shellparam.optnext is NULL,
  10366. * then it's the first time getopts has been called.
  10367. */
  10368. static int FAST_FUNC
  10369. getoptscmd(int argc, char **argv)
  10370. {
  10371. char **optbase;
  10372. if (argc < 3)
  10373. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10374. if (argc == 3) {
  10375. optbase = shellparam.p;
  10376. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10377. shellparam.optind = 1;
  10378. shellparam.optoff = -1;
  10379. }
  10380. } else {
  10381. optbase = &argv[3];
  10382. if ((unsigned)shellparam.optind > argc - 2) {
  10383. shellparam.optind = 1;
  10384. shellparam.optoff = -1;
  10385. }
  10386. }
  10387. return getopts(argv[1], argv[2], optbase);
  10388. }
  10389. #endif /* ASH_GETOPTS */
  10390. /* ============ Shell parser */
  10391. struct heredoc {
  10392. struct heredoc *next; /* next here document in list */
  10393. union node *here; /* redirection node */
  10394. char *eofmark; /* string indicating end of input */
  10395. smallint striptabs; /* if set, strip leading tabs */
  10396. };
  10397. static smallint tokpushback; /* last token pushed back */
  10398. static smallint quoteflag; /* set if (part of) last token was quoted */
  10399. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10400. static struct heredoc *heredoclist; /* list of here documents to read */
  10401. static char *wordtext; /* text of last word returned by readtoken */
  10402. static struct nodelist *backquotelist;
  10403. static union node *redirnode;
  10404. static struct heredoc *heredoc;
  10405. static const char *
  10406. tokname(char *buf, int tok)
  10407. {
  10408. if (tok < TSEMI)
  10409. return tokname_array[tok];
  10410. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10411. return buf;
  10412. }
  10413. /* raise_error_unexpected_syntax:
  10414. * Called when an unexpected token is read during the parse. The argument
  10415. * is the token that is expected, or -1 if more than one type of token can
  10416. * occur at this point.
  10417. */
  10418. static void raise_error_unexpected_syntax(int) NORETURN;
  10419. static void
  10420. raise_error_unexpected_syntax(int token)
  10421. {
  10422. char msg[64];
  10423. char buf[16];
  10424. int l;
  10425. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10426. if (token >= 0)
  10427. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10428. raise_error_syntax(msg);
  10429. /* NOTREACHED */
  10430. }
  10431. /* parsing is heavily cross-recursive, need these forward decls */
  10432. static union node *andor(void);
  10433. static union node *pipeline(void);
  10434. static union node *parse_command(void);
  10435. static void parseheredoc(void);
  10436. static int peektoken(void);
  10437. static int readtoken(void);
  10438. static union node *
  10439. list(int nlflag)
  10440. {
  10441. union node *n1, *n2, *n3;
  10442. int tok;
  10443. n1 = NULL;
  10444. for (;;) {
  10445. switch (peektoken()) {
  10446. case TNL:
  10447. if (!(nlflag & 1))
  10448. break;
  10449. parseheredoc();
  10450. return n1;
  10451. case TEOF:
  10452. if (!n1 && (nlflag & 1))
  10453. n1 = NODE_EOF;
  10454. parseheredoc();
  10455. return n1;
  10456. }
  10457. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10458. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10459. return n1;
  10460. nlflag |= 2;
  10461. n2 = andor();
  10462. tok = readtoken();
  10463. if (tok == TBACKGND) {
  10464. if (n2->type == NPIPE) {
  10465. n2->npipe.pipe_backgnd = 1;
  10466. } else {
  10467. if (n2->type != NREDIR) {
  10468. n3 = stzalloc(sizeof(struct nredir));
  10469. n3->nredir.n = n2;
  10470. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10471. n2 = n3;
  10472. }
  10473. n2->type = NBACKGND;
  10474. }
  10475. }
  10476. if (n1 == NULL) {
  10477. n1 = n2;
  10478. } else {
  10479. n3 = stzalloc(sizeof(struct nbinary));
  10480. n3->type = NSEMI;
  10481. n3->nbinary.ch1 = n1;
  10482. n3->nbinary.ch2 = n2;
  10483. n1 = n3;
  10484. }
  10485. switch (tok) {
  10486. case TNL:
  10487. case TEOF:
  10488. tokpushback = 1;
  10489. /* fall through */
  10490. case TBACKGND:
  10491. case TSEMI:
  10492. break;
  10493. default:
  10494. if ((nlflag & 1))
  10495. raise_error_unexpected_syntax(-1);
  10496. tokpushback = 1;
  10497. return n1;
  10498. }
  10499. }
  10500. }
  10501. static union node *
  10502. andor(void)
  10503. {
  10504. union node *n1, *n2, *n3;
  10505. int t;
  10506. n1 = pipeline();
  10507. for (;;) {
  10508. t = readtoken();
  10509. if (t == TAND) {
  10510. t = NAND;
  10511. } else if (t == TOR) {
  10512. t = NOR;
  10513. } else {
  10514. tokpushback = 1;
  10515. return n1;
  10516. }
  10517. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10518. n2 = pipeline();
  10519. n3 = stzalloc(sizeof(struct nbinary));
  10520. n3->type = t;
  10521. n3->nbinary.ch1 = n1;
  10522. n3->nbinary.ch2 = n2;
  10523. n1 = n3;
  10524. }
  10525. }
  10526. static union node *
  10527. pipeline(void)
  10528. {
  10529. union node *n1, *n2, *pipenode;
  10530. struct nodelist *lp, *prev;
  10531. int negate;
  10532. negate = 0;
  10533. TRACE(("pipeline: entered\n"));
  10534. if (readtoken() == TNOT) {
  10535. negate = !negate;
  10536. checkkwd = CHKKWD | CHKALIAS;
  10537. } else
  10538. tokpushback = 1;
  10539. n1 = parse_command();
  10540. if (readtoken() == TPIPE) {
  10541. pipenode = stzalloc(sizeof(struct npipe));
  10542. pipenode->type = NPIPE;
  10543. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10544. lp = stzalloc(sizeof(struct nodelist));
  10545. pipenode->npipe.cmdlist = lp;
  10546. lp->n = n1;
  10547. do {
  10548. prev = lp;
  10549. lp = stzalloc(sizeof(struct nodelist));
  10550. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10551. lp->n = parse_command();
  10552. prev->next = lp;
  10553. } while (readtoken() == TPIPE);
  10554. lp->next = NULL;
  10555. n1 = pipenode;
  10556. }
  10557. tokpushback = 1;
  10558. if (negate) {
  10559. n2 = stzalloc(sizeof(struct nnot));
  10560. n2->type = NNOT;
  10561. n2->nnot.com = n1;
  10562. return n2;
  10563. }
  10564. return n1;
  10565. }
  10566. static union node *
  10567. makename(void)
  10568. {
  10569. union node *n;
  10570. n = stzalloc(sizeof(struct narg));
  10571. n->type = NARG;
  10572. /*n->narg.next = NULL; - stzalloc did it */
  10573. n->narg.text = wordtext;
  10574. n->narg.backquote = backquotelist;
  10575. return n;
  10576. }
  10577. static void
  10578. fixredir(union node *n, const char *text, int err)
  10579. {
  10580. int fd;
  10581. TRACE(("Fix redir %s %d\n", text, err));
  10582. if (!err)
  10583. n->ndup.vname = NULL;
  10584. fd = bb_strtou(text, NULL, 10);
  10585. if (!errno && fd >= 0)
  10586. n->ndup.dupfd = fd;
  10587. else if (LONE_DASH(text))
  10588. n->ndup.dupfd = -1;
  10589. else {
  10590. if (err)
  10591. raise_error_syntax("bad fd number");
  10592. n->ndup.vname = makename();
  10593. }
  10594. }
  10595. static void
  10596. parsefname(void)
  10597. {
  10598. union node *n = redirnode;
  10599. if (n->type == NHERE)
  10600. checkkwd = CHKEOFMARK;
  10601. if (readtoken() != TWORD)
  10602. raise_error_unexpected_syntax(-1);
  10603. if (n->type == NHERE) {
  10604. struct heredoc *here = heredoc;
  10605. struct heredoc *p;
  10606. if (quoteflag == 0)
  10607. n->type = NXHERE;
  10608. TRACE(("Here document %d\n", n->type));
  10609. rmescapes(wordtext, 0, NULL);
  10610. here->eofmark = wordtext;
  10611. here->next = NULL;
  10612. if (heredoclist == NULL)
  10613. heredoclist = here;
  10614. else {
  10615. for (p = heredoclist; p->next; p = p->next)
  10616. continue;
  10617. p->next = here;
  10618. }
  10619. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10620. fixredir(n, wordtext, 0);
  10621. } else {
  10622. n->nfile.fname = makename();
  10623. }
  10624. }
  10625. static union node *
  10626. simplecmd(void)
  10627. {
  10628. union node *args, **app;
  10629. union node *n = NULL;
  10630. union node *vars, **vpp;
  10631. union node **rpp, *redir;
  10632. int savecheckkwd;
  10633. int savelinno;
  10634. #if BASH_TEST2
  10635. smallint double_brackets_flag = 0;
  10636. #endif
  10637. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10638. args = NULL;
  10639. app = &args;
  10640. vars = NULL;
  10641. vpp = &vars;
  10642. redir = NULL;
  10643. rpp = &redir;
  10644. savecheckkwd = CHKALIAS;
  10645. savelinno = g_parsefile->linno;
  10646. for (;;) {
  10647. int t;
  10648. checkkwd = savecheckkwd;
  10649. t = readtoken();
  10650. switch (t) {
  10651. #if BASH_FUNCTION
  10652. case TFUNCTION:
  10653. if (peektoken() != TWORD)
  10654. raise_error_unexpected_syntax(TWORD);
  10655. function_flag = 1;
  10656. break;
  10657. #endif
  10658. #if BASH_TEST2
  10659. case TAND: /* "&&" */
  10660. case TOR: /* "||" */
  10661. if (!double_brackets_flag) {
  10662. tokpushback = 1;
  10663. goto out;
  10664. }
  10665. wordtext = (char *) (t == TAND ? "-a" : "-o");
  10666. #endif
  10667. case TWORD:
  10668. n = stzalloc(sizeof(struct narg));
  10669. n->type = NARG;
  10670. /*n->narg.next = NULL; - stzalloc did it */
  10671. n->narg.text = wordtext;
  10672. #if BASH_TEST2
  10673. if (strcmp("[[", wordtext) == 0)
  10674. double_brackets_flag = 1;
  10675. else if (strcmp("]]", wordtext) == 0)
  10676. double_brackets_flag = 0;
  10677. #endif
  10678. n->narg.backquote = backquotelist;
  10679. if (savecheckkwd && isassignment(wordtext)) {
  10680. *vpp = n;
  10681. vpp = &n->narg.next;
  10682. } else {
  10683. *app = n;
  10684. app = &n->narg.next;
  10685. savecheckkwd = 0;
  10686. }
  10687. #if BASH_FUNCTION
  10688. if (function_flag) {
  10689. checkkwd = CHKNL | CHKKWD;
  10690. switch (peektoken()) {
  10691. case TBEGIN:
  10692. case TIF:
  10693. case TCASE:
  10694. case TUNTIL:
  10695. case TWHILE:
  10696. case TFOR:
  10697. goto do_func;
  10698. case TLP:
  10699. function_flag = 0;
  10700. break;
  10701. # if BASH_TEST2
  10702. case TWORD:
  10703. if (strcmp("[[", wordtext) == 0)
  10704. goto do_func;
  10705. /* fall through */
  10706. # endif
  10707. default:
  10708. raise_error_unexpected_syntax(-1);
  10709. }
  10710. }
  10711. #endif
  10712. break;
  10713. case TREDIR:
  10714. *rpp = n = redirnode;
  10715. rpp = &n->nfile.next;
  10716. parsefname(); /* read name of redirection file */
  10717. break;
  10718. case TLP:
  10719. IF_BASH_FUNCTION(do_func:)
  10720. if (args && app == &args->narg.next
  10721. && !vars && !redir
  10722. ) {
  10723. struct builtincmd *bcmd;
  10724. const char *name;
  10725. /* We have a function */
  10726. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10727. raise_error_unexpected_syntax(TRP);
  10728. name = n->narg.text;
  10729. if (!goodname(name)
  10730. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10731. ) {
  10732. raise_error_syntax("bad function name");
  10733. }
  10734. n->type = NDEFUN;
  10735. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10736. n->ndefun.text = n->narg.text;
  10737. n->ndefun.linno = g_parsefile->linno;
  10738. n->ndefun.body = parse_command();
  10739. return n;
  10740. }
  10741. IF_BASH_FUNCTION(function_flag = 0;)
  10742. /* fall through */
  10743. default:
  10744. tokpushback = 1;
  10745. goto out;
  10746. }
  10747. }
  10748. out:
  10749. *app = NULL;
  10750. *vpp = NULL;
  10751. *rpp = NULL;
  10752. n = stzalloc(sizeof(struct ncmd));
  10753. if (NCMD != 0)
  10754. n->type = NCMD;
  10755. n->ncmd.linno = savelinno;
  10756. n->ncmd.args = args;
  10757. n->ncmd.assign = vars;
  10758. n->ncmd.redirect = redir;
  10759. return n;
  10760. }
  10761. static union node *
  10762. parse_command(void)
  10763. {
  10764. union node *n1, *n2;
  10765. union node *ap, **app;
  10766. union node *cp, **cpp;
  10767. union node *redir, **rpp;
  10768. union node **rpp2;
  10769. int t;
  10770. int savelinno;
  10771. redir = NULL;
  10772. rpp2 = &redir;
  10773. savelinno = g_parsefile->linno;
  10774. switch (readtoken()) {
  10775. default:
  10776. raise_error_unexpected_syntax(-1);
  10777. /* NOTREACHED */
  10778. case TIF:
  10779. n1 = stzalloc(sizeof(struct nif));
  10780. n1->type = NIF;
  10781. n1->nif.test = list(0);
  10782. if (readtoken() != TTHEN)
  10783. raise_error_unexpected_syntax(TTHEN);
  10784. n1->nif.ifpart = list(0);
  10785. n2 = n1;
  10786. while (readtoken() == TELIF) {
  10787. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10788. n2 = n2->nif.elsepart;
  10789. n2->type = NIF;
  10790. n2->nif.test = list(0);
  10791. if (readtoken() != TTHEN)
  10792. raise_error_unexpected_syntax(TTHEN);
  10793. n2->nif.ifpart = list(0);
  10794. }
  10795. if (lasttoken == TELSE)
  10796. n2->nif.elsepart = list(0);
  10797. else {
  10798. n2->nif.elsepart = NULL;
  10799. tokpushback = 1;
  10800. }
  10801. t = TFI;
  10802. break;
  10803. case TWHILE:
  10804. case TUNTIL: {
  10805. int got;
  10806. n1 = stzalloc(sizeof(struct nbinary));
  10807. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10808. n1->nbinary.ch1 = list(0);
  10809. got = readtoken();
  10810. if (got != TDO) {
  10811. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10812. got == TWORD ? wordtext : ""));
  10813. raise_error_unexpected_syntax(TDO);
  10814. }
  10815. n1->nbinary.ch2 = list(0);
  10816. t = TDONE;
  10817. break;
  10818. }
  10819. case TFOR:
  10820. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10821. raise_error_syntax("bad for loop variable");
  10822. n1 = stzalloc(sizeof(struct nfor));
  10823. n1->type = NFOR;
  10824. n1->nfor.linno = savelinno;
  10825. n1->nfor.var = wordtext;
  10826. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10827. if (readtoken() == TIN) {
  10828. app = &ap;
  10829. while (readtoken() == TWORD) {
  10830. n2 = stzalloc(sizeof(struct narg));
  10831. n2->type = NARG;
  10832. /*n2->narg.next = NULL; - stzalloc did it */
  10833. n2->narg.text = wordtext;
  10834. n2->narg.backquote = backquotelist;
  10835. *app = n2;
  10836. app = &n2->narg.next;
  10837. }
  10838. *app = NULL;
  10839. n1->nfor.args = ap;
  10840. if (lasttoken != TNL && lasttoken != TSEMI)
  10841. raise_error_unexpected_syntax(-1);
  10842. } else {
  10843. n2 = stzalloc(sizeof(struct narg));
  10844. n2->type = NARG;
  10845. /*n2->narg.next = NULL; - stzalloc did it */
  10846. n2->narg.text = (char *)dolatstr;
  10847. /*n2->narg.backquote = NULL;*/
  10848. n1->nfor.args = n2;
  10849. /*
  10850. * Newline or semicolon here is optional (but note
  10851. * that the original Bourne shell only allowed NL).
  10852. */
  10853. if (lasttoken != TSEMI)
  10854. tokpushback = 1;
  10855. }
  10856. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10857. if (readtoken() != TDO)
  10858. raise_error_unexpected_syntax(TDO);
  10859. n1->nfor.body = list(0);
  10860. t = TDONE;
  10861. break;
  10862. case TCASE:
  10863. n1 = stzalloc(sizeof(struct ncase));
  10864. n1->type = NCASE;
  10865. n1->ncase.linno = savelinno;
  10866. if (readtoken() != TWORD)
  10867. raise_error_unexpected_syntax(TWORD);
  10868. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10869. n2->type = NARG;
  10870. /*n2->narg.next = NULL; - stzalloc did it */
  10871. n2->narg.text = wordtext;
  10872. n2->narg.backquote = backquotelist;
  10873. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10874. if (readtoken() != TIN)
  10875. raise_error_unexpected_syntax(TIN);
  10876. cpp = &n1->ncase.cases;
  10877. next_case:
  10878. checkkwd = CHKNL | CHKKWD;
  10879. t = readtoken();
  10880. while (t != TESAC) {
  10881. if (lasttoken == TLP)
  10882. readtoken();
  10883. *cpp = cp = stzalloc(sizeof(struct nclist));
  10884. cp->type = NCLIST;
  10885. app = &cp->nclist.pattern;
  10886. for (;;) {
  10887. *app = ap = stzalloc(sizeof(struct narg));
  10888. ap->type = NARG;
  10889. /*ap->narg.next = NULL; - stzalloc did it */
  10890. ap->narg.text = wordtext;
  10891. ap->narg.backquote = backquotelist;
  10892. if (readtoken() != TPIPE)
  10893. break;
  10894. app = &ap->narg.next;
  10895. readtoken();
  10896. }
  10897. //ap->narg.next = NULL;
  10898. if (lasttoken != TRP)
  10899. raise_error_unexpected_syntax(TRP);
  10900. cp->nclist.body = list(2);
  10901. cpp = &cp->nclist.next;
  10902. checkkwd = CHKNL | CHKKWD;
  10903. t = readtoken();
  10904. if (t != TESAC) {
  10905. if (t != TENDCASE)
  10906. raise_error_unexpected_syntax(TENDCASE);
  10907. goto next_case;
  10908. }
  10909. }
  10910. *cpp = NULL;
  10911. goto redir;
  10912. case TLP:
  10913. n1 = stzalloc(sizeof(struct nredir));
  10914. n1->type = NSUBSHELL;
  10915. n1->nredir.linno = savelinno;
  10916. n1->nredir.n = list(0);
  10917. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10918. t = TRP;
  10919. break;
  10920. case TBEGIN:
  10921. n1 = list(0);
  10922. t = TEND;
  10923. break;
  10924. IF_BASH_FUNCTION(case TFUNCTION:)
  10925. case TWORD:
  10926. case TREDIR:
  10927. tokpushback = 1;
  10928. return simplecmd();
  10929. }
  10930. if (readtoken() != t)
  10931. raise_error_unexpected_syntax(t);
  10932. redir:
  10933. /* Now check for redirection which may follow command */
  10934. checkkwd = CHKKWD | CHKALIAS;
  10935. rpp = rpp2;
  10936. while (readtoken() == TREDIR) {
  10937. *rpp = n2 = redirnode;
  10938. rpp = &n2->nfile.next;
  10939. parsefname();
  10940. }
  10941. tokpushback = 1;
  10942. *rpp = NULL;
  10943. if (redir) {
  10944. if (n1->type != NSUBSHELL) {
  10945. n2 = stzalloc(sizeof(struct nredir));
  10946. n2->type = NREDIR;
  10947. n2->nredir.linno = savelinno;
  10948. n2->nredir.n = n1;
  10949. n1 = n2;
  10950. }
  10951. n1->nredir.redirect = redir;
  10952. }
  10953. return n1;
  10954. }
  10955. #if BASH_DOLLAR_SQUOTE
  10956. static int
  10957. decode_dollar_squote(void)
  10958. {
  10959. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  10960. int c, cnt;
  10961. char *p;
  10962. char buf[4];
  10963. c = pgetc();
  10964. p = strchr(C_escapes, c);
  10965. if (p) {
  10966. buf[0] = c;
  10967. p = buf;
  10968. cnt = 3;
  10969. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  10970. do {
  10971. c = pgetc();
  10972. *++p = c;
  10973. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  10974. pungetc();
  10975. } else if (c == 'x') { /* \xHH */
  10976. do {
  10977. c = pgetc();
  10978. *++p = c;
  10979. } while (isxdigit(c) && --cnt);
  10980. pungetc();
  10981. if (cnt == 3) { /* \x but next char is "bad" */
  10982. c = 'x';
  10983. goto unrecognized;
  10984. }
  10985. } else { /* simple seq like \\ or \t */
  10986. p++;
  10987. }
  10988. *p = '\0';
  10989. p = buf;
  10990. c = bb_process_escape_sequence((void*)&p);
  10991. } else { /* unrecognized "\z": print both chars unless ' or " */
  10992. if (c != '\'' && c != '"') {
  10993. unrecognized:
  10994. c |= 0x100; /* "please encode \, then me" */
  10995. }
  10996. }
  10997. return c;
  10998. }
  10999. #endif
  11000. /* Used by expandstr to get here-doc like behaviour. */
  11001. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  11002. static ALWAYS_INLINE int
  11003. realeofmark(const char *eofmark)
  11004. {
  11005. return eofmark && eofmark != FAKEEOFMARK;
  11006. }
  11007. /*
  11008. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  11009. * is not NULL, read a here document. In the latter case, eofmark is the
  11010. * word which marks the end of the document and striptabs is true if
  11011. * leading tabs should be stripped from the document. The argument c
  11012. * is the first character of the input token or document.
  11013. *
  11014. * Because C does not have internal subroutines, I have simulated them
  11015. * using goto's to implement the subroutine linkage. The following macros
  11016. * will run code that appears at the end of readtoken1.
  11017. */
  11018. #define CHECKEND() {goto checkend; checkend_return:;}
  11019. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  11020. #define PARSESUB() {goto parsesub; parsesub_return:;}
  11021. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  11022. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  11023. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  11024. static int
  11025. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  11026. {
  11027. /* NB: syntax parameter fits into smallint */
  11028. /* c parameter is an unsigned char or PEOF or PEOA */
  11029. char *out;
  11030. size_t len;
  11031. struct nodelist *bqlist;
  11032. smallint quotef;
  11033. smallint oldstyle;
  11034. smallint pssyntax; /* we are expanding a prompt string */
  11035. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  11036. /* syntax stack */
  11037. struct synstack synbase = { };
  11038. struct synstack *synstack = &synbase;
  11039. #if ENABLE_ASH_EXPAND_PRMT
  11040. pssyntax = (syntax == PSSYNTAX);
  11041. if (pssyntax)
  11042. syntax = DQSYNTAX;
  11043. #else
  11044. pssyntax = 0; /* constant */
  11045. #endif
  11046. synstack->syntax = syntax;
  11047. if (syntax == DQSYNTAX)
  11048. synstack->dblquote = 1;
  11049. quotef = 0;
  11050. bqlist = NULL;
  11051. STARTSTACKSTR(out);
  11052. loop:
  11053. /* For each line, until end of word */
  11054. CHECKEND(); /* set c to PEOF if at end of here document */
  11055. for (;;) { /* until end of line or end of word */
  11056. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11057. switch (SIT(c, synstack->syntax)) {
  11058. case CNL: /* '\n' */
  11059. if (synstack->syntax == BASESYNTAX
  11060. && !synstack->varnest
  11061. ) {
  11062. goto endword; /* exit outer loop */
  11063. }
  11064. USTPUTC(c, out);
  11065. nlprompt();
  11066. c = pgetc();
  11067. goto loop; /* continue outer loop */
  11068. case CWORD:
  11069. USTPUTC(c, out);
  11070. break;
  11071. case CCTL:
  11072. #if BASH_DOLLAR_SQUOTE
  11073. if (c == '\\' && bash_dollar_squote) {
  11074. c = decode_dollar_squote();
  11075. if (c == '\0') {
  11076. /* skip $'\000', $'\x00' (like bash) */
  11077. break;
  11078. }
  11079. if (c & 0x100) {
  11080. /* Unknown escape. Encode as '\z' */
  11081. c = (unsigned char)c;
  11082. if (eofmark == NULL || synstack->dblquote)
  11083. USTPUTC(CTLESC, out);
  11084. USTPUTC('\\', out);
  11085. }
  11086. }
  11087. #endif
  11088. if (!eofmark || synstack->dblquote || synstack->varnest)
  11089. USTPUTC(CTLESC, out);
  11090. USTPUTC(c, out);
  11091. break;
  11092. case CBACK: /* backslash */
  11093. c = pgetc_without_PEOA();
  11094. if (c == PEOF) {
  11095. USTPUTC(CTLESC, out);
  11096. USTPUTC('\\', out);
  11097. pungetc();
  11098. } else if (c == '\n') {
  11099. nlprompt();
  11100. } else {
  11101. if (pssyntax && c == '$') {
  11102. USTPUTC(CTLESC, out);
  11103. USTPUTC('\\', out);
  11104. }
  11105. /* Backslash is retained if we are in "str"
  11106. * and next char isn't dquote-special.
  11107. */
  11108. if (synstack->dblquote
  11109. && c != '\\'
  11110. && c != '`'
  11111. && c != '$'
  11112. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11113. && (c != '}' || !synstack->varnest)
  11114. ) {
  11115. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11116. USTPUTC('\\', out);
  11117. }
  11118. USTPUTC(CTLESC, out);
  11119. USTPUTC(c, out);
  11120. quotef = 1;
  11121. }
  11122. break;
  11123. case CSQUOTE:
  11124. synstack->syntax = SQSYNTAX;
  11125. quotemark:
  11126. if (eofmark == NULL) {
  11127. USTPUTC(CTLQUOTEMARK, out);
  11128. }
  11129. break;
  11130. case CDQUOTE:
  11131. synstack->syntax = DQSYNTAX;
  11132. synstack->dblquote = 1;
  11133. toggledq:
  11134. if (synstack->varnest)
  11135. synstack->innerdq ^= 1;
  11136. goto quotemark;
  11137. case CENDQUOTE:
  11138. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11139. if (eofmark != NULL && synstack->varnest == 0) {
  11140. USTPUTC(c, out);
  11141. break;
  11142. }
  11143. if (synstack->dqvarnest == 0) {
  11144. synstack->syntax = BASESYNTAX;
  11145. synstack->dblquote = 0;
  11146. }
  11147. quotef = 1;
  11148. if (c == '"')
  11149. goto toggledq;
  11150. goto quotemark;
  11151. case CVAR: /* '$' */
  11152. PARSESUB(); /* parse substitution */
  11153. break;
  11154. case CENDVAR: /* '}' */
  11155. if (!synstack->innerdq && synstack->varnest > 0) {
  11156. if (!--synstack->varnest && synstack->varpushed)
  11157. synstack_pop(&synstack);
  11158. else if (synstack->dqvarnest > 0)
  11159. synstack->dqvarnest--;
  11160. c = CTLENDVAR;
  11161. }
  11162. USTPUTC(c, out);
  11163. break;
  11164. #if ENABLE_FEATURE_SH_MATH
  11165. case CLP: /* '(' in arithmetic */
  11166. synstack->parenlevel++;
  11167. USTPUTC(c, out);
  11168. break;
  11169. case CRP: /* ')' in arithmetic */
  11170. if (synstack->parenlevel > 0) {
  11171. synstack->parenlevel--;
  11172. } else {
  11173. if (pgetc_eatbnl() == ')') {
  11174. c = CTLENDARI;
  11175. synstack_pop(&synstack);
  11176. } else {
  11177. /*
  11178. * unbalanced parens
  11179. * (don't 2nd guess - no error)
  11180. */
  11181. pungetc();
  11182. }
  11183. }
  11184. USTPUTC(c, out);
  11185. break;
  11186. #endif
  11187. case CBQUOTE: /* '`' */
  11188. if (checkkwd & CHKEOFMARK) {
  11189. quotef = 1;
  11190. USTPUTC('`', out);
  11191. break;
  11192. }
  11193. PARSEBACKQOLD();
  11194. break;
  11195. case CENDFILE:
  11196. goto endword; /* exit outer loop */
  11197. case CIGN:
  11198. break;
  11199. default:
  11200. if (synstack->varnest == 0) {
  11201. #if BASH_REDIR_OUTPUT
  11202. if (c == '&') {
  11203. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11204. if (pgetc() == '>')
  11205. c = 0x100 + '>'; /* flag &> */
  11206. pungetc();
  11207. }
  11208. #endif
  11209. goto endword; /* exit outer loop */
  11210. }
  11211. IF_ASH_ALIAS(if (c != PEOA))
  11212. USTPUTC(c, out);
  11213. }
  11214. c = pgetc();
  11215. } /* for (;;) */
  11216. endword:
  11217. #if ENABLE_FEATURE_SH_MATH
  11218. if (synstack->syntax == ARISYNTAX)
  11219. raise_error_syntax("missing '))'");
  11220. #endif
  11221. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11222. raise_error_syntax("unterminated quoted string");
  11223. if (synstack->varnest != 0) {
  11224. /* { */
  11225. raise_error_syntax("missing '}'");
  11226. }
  11227. USTPUTC('\0', out);
  11228. len = out - (char *)stackblock();
  11229. out = stackblock();
  11230. if (eofmark == NULL) {
  11231. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11232. && quotef == 0
  11233. ) {
  11234. if (isdigit_str9(out)) {
  11235. PARSEREDIR(); /* passed as params: out, c */
  11236. lasttoken = TREDIR;
  11237. return lasttoken;
  11238. }
  11239. /* else: non-number X seen, interpret it
  11240. * as "NNNX>file" = "NNNX >file" */
  11241. }
  11242. pungetc();
  11243. }
  11244. quoteflag = quotef;
  11245. backquotelist = bqlist;
  11246. grabstackblock(len);
  11247. wordtext = out;
  11248. lasttoken = TWORD;
  11249. return lasttoken;
  11250. /* end of readtoken routine */
  11251. /*
  11252. * Check to see whether we are at the end of the here document. When this
  11253. * is called, c is set to the first character of the next input line. If
  11254. * we are at the end of the here document, this routine sets the c to PEOF.
  11255. */
  11256. checkend: {
  11257. if (realeofmark(eofmark)) {
  11258. int markloc;
  11259. char *p;
  11260. #if ENABLE_ASH_ALIAS
  11261. if (c == PEOA)
  11262. c = pgetc_without_PEOA();
  11263. #endif
  11264. if (striptabs) {
  11265. while (c == '\t') {
  11266. c = pgetc_without_PEOA();
  11267. }
  11268. }
  11269. markloc = out - (char *)stackblock();
  11270. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11271. if (c != *p)
  11272. goto more_heredoc;
  11273. c = pgetc_without_PEOA();
  11274. }
  11275. if (c == '\n' || c == PEOF) {
  11276. c = PEOF;
  11277. g_parsefile->linno++;
  11278. needprompt = doprompt;
  11279. } else {
  11280. int len_here;
  11281. more_heredoc:
  11282. p = (char *)stackblock() + markloc + 1;
  11283. len_here = out - p;
  11284. if (len_here) {
  11285. len_here -= (c >= PEOF);
  11286. c = p[-1];
  11287. if (len_here) {
  11288. char *str;
  11289. str = alloca(len_here + 1);
  11290. *(char *)mempcpy(str, p, len_here) = '\0';
  11291. pushstring(str, NULL);
  11292. }
  11293. }
  11294. }
  11295. STADJUST((char *)stackblock() + markloc - out, out);
  11296. }
  11297. goto checkend_return;
  11298. }
  11299. /*
  11300. * Parse a redirection operator. The variable "out" points to a string
  11301. * specifying the fd to be redirected. The variable "c" contains the
  11302. * first character of the redirection operator.
  11303. */
  11304. parseredir: {
  11305. /* out is already checked to be a valid number or "" */
  11306. int fd = (*out == '\0' ? -1 : atoi(out));
  11307. union node *np;
  11308. np = stzalloc(sizeof(struct nfile));
  11309. if (c == '>') {
  11310. np->nfile.fd = 1;
  11311. c = pgetc_eatbnl();
  11312. if (c == '>')
  11313. np->type = NAPPEND;
  11314. else if (c == '|')
  11315. np->type = NCLOBBER;
  11316. else if (c == '&')
  11317. np->type = NTOFD;
  11318. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11319. else {
  11320. np->type = NTO;
  11321. pungetc();
  11322. }
  11323. }
  11324. #if BASH_REDIR_OUTPUT
  11325. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11326. np->nfile.fd = 1;
  11327. pgetc(); /* this is '>', no need to check */
  11328. np->type = NTO2;
  11329. }
  11330. #endif
  11331. else { /* c == '<' */
  11332. /*np->nfile.fd = 0; - stzalloc did it */
  11333. c = pgetc_eatbnl();
  11334. switch (c) {
  11335. case '<':
  11336. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11337. np = stzalloc(sizeof(struct nhere));
  11338. /*np->nfile.fd = 0; - stzalloc did it */
  11339. }
  11340. np->type = NHERE;
  11341. heredoc = stzalloc(sizeof(struct heredoc));
  11342. heredoc->here = np;
  11343. c = pgetc_eatbnl();
  11344. if (c == '-') {
  11345. heredoc->striptabs = 1;
  11346. } else {
  11347. /*heredoc->striptabs = 0; - stzalloc did it */
  11348. pungetc();
  11349. }
  11350. break;
  11351. case '&':
  11352. np->type = NFROMFD;
  11353. break;
  11354. case '>':
  11355. np->type = NFROMTO;
  11356. break;
  11357. default:
  11358. np->type = NFROM;
  11359. pungetc();
  11360. break;
  11361. }
  11362. }
  11363. if (fd >= 0)
  11364. np->nfile.fd = fd;
  11365. redirnode = np;
  11366. goto parseredir_return;
  11367. }
  11368. /*
  11369. * Parse a substitution. At this point, we have read the dollar sign
  11370. * and nothing else.
  11371. */
  11372. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11373. * (assuming ascii char codes, as the original implementation did) */
  11374. #define is_special(c) \
  11375. (((unsigned)(c) - 33 < 32) \
  11376. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11377. parsesub: {
  11378. unsigned char subtype;
  11379. int typeloc;
  11380. c = pgetc_eatbnl();
  11381. if ((checkkwd & CHKEOFMARK)
  11382. || c > 255 /* PEOA or PEOF */
  11383. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11384. ) {
  11385. #if BASH_DOLLAR_SQUOTE
  11386. if (synstack->syntax != DQSYNTAX && c == '\'')
  11387. bash_dollar_squote = 1;
  11388. else
  11389. #endif
  11390. USTPUTC('$', out);
  11391. pungetc();
  11392. } else if (c == '(') {
  11393. /* $(command) or $((arith)) */
  11394. if (pgetc_eatbnl() == '(') {
  11395. #if ENABLE_FEATURE_SH_MATH
  11396. PARSEARITH();
  11397. #else
  11398. raise_error_syntax("support for $((arith)) is disabled");
  11399. #endif
  11400. } else {
  11401. pungetc();
  11402. PARSEBACKQNEW();
  11403. }
  11404. } else {
  11405. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11406. smalluint newsyn = synstack->syntax;
  11407. USTPUTC(CTLVAR, out);
  11408. typeloc = out - (char *)stackblock();
  11409. STADJUST(1, out);
  11410. subtype = VSNORMAL;
  11411. if (c == '{') {
  11412. c = pgetc_eatbnl();
  11413. subtype = 0;
  11414. }
  11415. varname:
  11416. if (is_name(c)) {
  11417. /* $[{[#]]NAME[}] */
  11418. do {
  11419. STPUTC(c, out);
  11420. c = pgetc_eatbnl();
  11421. } while (is_in_name(c));
  11422. } else if (isdigit(c)) {
  11423. /* $[{[#]]NUM[}] */
  11424. do {
  11425. STPUTC(c, out);
  11426. c = pgetc_eatbnl();
  11427. } while (isdigit(c));
  11428. } else if (c != '}') {
  11429. /* $[{[#]]<specialchar>[}] */
  11430. int cc = c;
  11431. c = pgetc_eatbnl();
  11432. if (!subtype && cc == '#') {
  11433. subtype = VSLENGTH;
  11434. if (c == '_' || isalnum(c))
  11435. goto varname;
  11436. cc = c;
  11437. c = pgetc_eatbnl();
  11438. if (cc == '}' || c != '}') {
  11439. pungetc();
  11440. subtype = 0;
  11441. c = cc;
  11442. cc = '#';
  11443. }
  11444. }
  11445. if (!is_special(cc)) {
  11446. if (subtype == VSLENGTH)
  11447. subtype = 0;
  11448. goto badsub;
  11449. }
  11450. USTPUTC(cc, out);
  11451. } else
  11452. goto badsub;
  11453. if (c != '}' && subtype == VSLENGTH) {
  11454. /* ${#VAR didn't end with } */
  11455. goto badsub;
  11456. }
  11457. if (subtype == 0) {
  11458. static const char types[] ALIGN1 = "}-+?=";
  11459. /* ${VAR...} but not $VAR or ${#VAR} */
  11460. /* c == first char after VAR */
  11461. int cc = c;
  11462. switch (c) {
  11463. case ':':
  11464. c = pgetc_eatbnl();
  11465. #if BASH_SUBSTR
  11466. /* This check is only needed to not misinterpret
  11467. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11468. * constructs.
  11469. */
  11470. if (!strchr(types, c)) {
  11471. subtype = VSSUBSTR;
  11472. pungetc();
  11473. break; /* "goto badsub" is bigger (!) */
  11474. }
  11475. #endif
  11476. subtype = VSNUL;
  11477. /*FALLTHROUGH*/
  11478. default: {
  11479. const char *p = strchr(types, c);
  11480. if (p == NULL)
  11481. break;
  11482. subtype |= p - types + VSNORMAL;
  11483. break;
  11484. }
  11485. case '%':
  11486. case '#':
  11487. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11488. c = pgetc_eatbnl();
  11489. if (c == cc)
  11490. subtype++;
  11491. else
  11492. pungetc();
  11493. newsyn = BASESYNTAX;
  11494. break;
  11495. #if BASH_PATTERN_SUBST
  11496. case '/':
  11497. /* ${v/[/]pattern/repl} */
  11498. //TODO: encode pattern and repl separately.
  11499. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11500. // are broken (should print "ONE")
  11501. subtype = VSREPLACE;
  11502. newsyn = BASESYNTAX;
  11503. c = pgetc_eatbnl();
  11504. if (c != '/')
  11505. goto badsub;
  11506. subtype++; /* VSREPLACEALL */
  11507. break;
  11508. #endif
  11509. }
  11510. } else {
  11511. badsub:
  11512. pungetc();
  11513. }
  11514. if (newsyn == ARISYNTAX)
  11515. newsyn = DQSYNTAX;
  11516. if ((newsyn != synstack->syntax || synstack->innerdq)
  11517. && subtype != VSNORMAL
  11518. ) {
  11519. synstack_push(&synstack,
  11520. synstack->prev ?: alloca(sizeof(*synstack)),
  11521. newsyn);
  11522. synstack->varpushed = 1;
  11523. synstack->dblquote = newsyn != BASESYNTAX;
  11524. }
  11525. ((unsigned char *)stackblock())[typeloc] = subtype;
  11526. if (subtype != VSNORMAL) {
  11527. synstack->varnest++;
  11528. if (synstack->dblquote)
  11529. synstack->dqvarnest++;
  11530. }
  11531. STPUTC('=', out);
  11532. }
  11533. goto parsesub_return;
  11534. }
  11535. /*
  11536. * Called to parse command substitutions. Newstyle is set if the command
  11537. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11538. * list of commands (passed by reference), and savelen is the number of
  11539. * characters on the top of the stack which must be preserved.
  11540. */
  11541. parsebackq: {
  11542. struct nodelist **nlpp;
  11543. union node *n;
  11544. char *str;
  11545. size_t savelen;
  11546. smallint saveprompt = 0;
  11547. str = NULL;
  11548. savelen = out - (char *)stackblock();
  11549. if (savelen > 0) {
  11550. /*
  11551. * FIXME: this can allocate very large block on stack and SEGV.
  11552. * Example:
  11553. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11554. * allocates 100kb for every command subst. With about
  11555. * a hundred command substitutions stack overflows.
  11556. * With larger prepended string, SEGV happens sooner.
  11557. */
  11558. str = alloca(savelen);
  11559. memcpy(str, stackblock(), savelen);
  11560. }
  11561. if (oldstyle) {
  11562. /* We must read until the closing backquote, giving special
  11563. * treatment to some slashes, and then push the string and
  11564. * reread it as input, interpreting it normally.
  11565. */
  11566. char *pout;
  11567. size_t psavelen;
  11568. char *pstr;
  11569. STARTSTACKSTR(pout);
  11570. for (;;) {
  11571. int pc;
  11572. setprompt_if(needprompt, 2);
  11573. pc = pgetc_eatbnl();
  11574. switch (pc) {
  11575. case '`':
  11576. goto done;
  11577. case '\\':
  11578. pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
  11579. if (pc != '\\' && pc != '`' && pc != '$'
  11580. && (!synstack->dblquote || pc != '"')
  11581. ) {
  11582. STPUTC('\\', pout);
  11583. }
  11584. if (pc <= 255 /* not PEOA or PEOF */) {
  11585. break;
  11586. }
  11587. /* fall through */
  11588. case PEOF:
  11589. IF_ASH_ALIAS(case PEOA:)
  11590. raise_error_syntax("EOF in backquote substitution");
  11591. case '\n':
  11592. nlnoprompt();
  11593. break;
  11594. default:
  11595. break;
  11596. }
  11597. STPUTC(pc, pout);
  11598. }
  11599. done:
  11600. STPUTC('\0', pout);
  11601. psavelen = pout - (char *)stackblock();
  11602. if (psavelen > 0) {
  11603. pstr = grabstackstr(pout);
  11604. setinputstring(pstr);
  11605. }
  11606. }
  11607. nlpp = &bqlist;
  11608. while (*nlpp)
  11609. nlpp = &(*nlpp)->next;
  11610. *nlpp = stzalloc(sizeof(**nlpp));
  11611. /* (*nlpp)->next = NULL; - stzalloc did it */
  11612. if (oldstyle) {
  11613. saveprompt = doprompt;
  11614. doprompt = 0;
  11615. }
  11616. n = list(2);
  11617. if (oldstyle)
  11618. doprompt = saveprompt;
  11619. else if (readtoken() != TRP)
  11620. raise_error_unexpected_syntax(TRP);
  11621. (*nlpp)->n = n;
  11622. if (oldstyle) {
  11623. /*
  11624. * Start reading from old file again, ignoring any pushed back
  11625. * tokens left from the backquote parsing
  11626. */
  11627. popfile();
  11628. tokpushback = 0;
  11629. }
  11630. while (stackblocksize() <= savelen)
  11631. growstackblock();
  11632. STARTSTACKSTR(out);
  11633. if (str) {
  11634. memcpy(out, str, savelen);
  11635. STADJUST(savelen, out);
  11636. }
  11637. USTPUTC(CTLBACKQ, out);
  11638. if (oldstyle)
  11639. goto parsebackq_oldreturn;
  11640. goto parsebackq_newreturn;
  11641. }
  11642. #if ENABLE_FEATURE_SH_MATH
  11643. /*
  11644. * Parse an arithmetic expansion (indicate start of one and set state)
  11645. */
  11646. parsearith: {
  11647. synstack_push(&synstack,
  11648. synstack->prev ?: alloca(sizeof(*synstack)),
  11649. ARISYNTAX);
  11650. synstack->dblquote = 1;
  11651. USTPUTC(CTLARI, out);
  11652. goto parsearith_return;
  11653. }
  11654. #endif
  11655. } /* end of readtoken */
  11656. /*
  11657. * Read the next input token.
  11658. * If the token is a word, we set backquotelist to the list of cmds in
  11659. * backquotes. We set quoteflag to true if any part of the word was
  11660. * quoted.
  11661. * If the token is TREDIR, then we set redirnode to a structure containing
  11662. * the redirection.
  11663. *
  11664. * [Change comment: here documents and internal procedures]
  11665. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11666. * word parsing code into a separate routine. In this case, readtoken
  11667. * doesn't need to have any internal procedures, but parseword does.
  11668. * We could also make parseoperator in essence the main routine, and
  11669. * have parseword (readtoken1?) handle both words and redirection.]
  11670. */
  11671. #define NEW_xxreadtoken
  11672. #ifdef NEW_xxreadtoken
  11673. /* singles must be first! */
  11674. static const char xxreadtoken_chars[7] ALIGN1 = {
  11675. '\n', '(', ')', /* singles */
  11676. '&', '|', ';', /* doubles */
  11677. 0
  11678. };
  11679. #define xxreadtoken_singles 3
  11680. #define xxreadtoken_doubles 3
  11681. static const char xxreadtoken_tokens[] ALIGN1 = {
  11682. TNL, TLP, TRP, /* only single occurrence allowed */
  11683. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11684. TEOF, /* corresponds to trailing nul */
  11685. TAND, TOR, TENDCASE /* if double occurrence */
  11686. };
  11687. static int
  11688. xxreadtoken(void)
  11689. {
  11690. int c;
  11691. if (tokpushback) {
  11692. tokpushback = 0;
  11693. return lasttoken;
  11694. }
  11695. setprompt_if(needprompt, 2);
  11696. for (;;) { /* until token or start of word found */
  11697. c = pgetc_eatbnl();
  11698. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11699. continue;
  11700. if (c == '#') {
  11701. while ((c = pgetc()) != '\n' && c != PEOF)
  11702. continue;
  11703. pungetc();
  11704. } else if (c == '\\') {
  11705. break; /* return readtoken1(...) */
  11706. } else {
  11707. const char *p;
  11708. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11709. if (c != PEOF) {
  11710. if (c == '\n') {
  11711. nlnoprompt();
  11712. }
  11713. p = strchr(xxreadtoken_chars, c);
  11714. if (p == NULL)
  11715. break; /* return readtoken1(...) */
  11716. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11717. int cc = pgetc_eatbnl();
  11718. if (cc == c) { /* double occurrence? */
  11719. p += xxreadtoken_doubles + 1;
  11720. } else {
  11721. pungetc();
  11722. #if BASH_REDIR_OUTPUT
  11723. if (c == '&' && cc == '>') /* &> */
  11724. break; /* return readtoken1(...) */
  11725. #endif
  11726. }
  11727. }
  11728. }
  11729. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11730. return lasttoken;
  11731. }
  11732. } /* for (;;) */
  11733. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11734. }
  11735. #else /* old xxreadtoken */
  11736. #define RETURN(token) return lasttoken = token
  11737. static int
  11738. xxreadtoken(void)
  11739. {
  11740. int c;
  11741. if (tokpushback) {
  11742. tokpushback = 0;
  11743. return lasttoken;
  11744. }
  11745. setprompt_if(needprompt, 2);
  11746. for (;;) { /* until token or start of word found */
  11747. c = pgetc_eatbnl();
  11748. switch (c) {
  11749. case ' ': case '\t':
  11750. IF_ASH_ALIAS(case PEOA:)
  11751. continue;
  11752. case '#':
  11753. while ((c = pgetc()) != '\n' && c != PEOF)
  11754. continue;
  11755. pungetc();
  11756. continue;
  11757. case '\n':
  11758. nlnoprompt();
  11759. RETURN(TNL);
  11760. case PEOF:
  11761. RETURN(TEOF);
  11762. case '&':
  11763. if (pgetc_eatbnl() == '&')
  11764. RETURN(TAND);
  11765. pungetc();
  11766. RETURN(TBACKGND);
  11767. case '|':
  11768. if (pgetc_eatbnl() == '|')
  11769. RETURN(TOR);
  11770. pungetc();
  11771. RETURN(TPIPE);
  11772. case ';':
  11773. if (pgetc_eatbnl() == ';')
  11774. RETURN(TENDCASE);
  11775. pungetc();
  11776. RETURN(TSEMI);
  11777. case '(':
  11778. RETURN(TLP);
  11779. case ')':
  11780. RETURN(TRP);
  11781. }
  11782. break;
  11783. }
  11784. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11785. #undef RETURN
  11786. }
  11787. #endif /* old xxreadtoken */
  11788. static int
  11789. readtoken(void)
  11790. {
  11791. int t;
  11792. int kwd = checkkwd;
  11793. #if DEBUG
  11794. smallint alreadyseen = tokpushback;
  11795. #endif
  11796. #if ENABLE_ASH_ALIAS
  11797. top:
  11798. #endif
  11799. t = xxreadtoken();
  11800. /*
  11801. * eat newlines
  11802. */
  11803. if (kwd & CHKNL) {
  11804. while (t == TNL) {
  11805. parseheredoc();
  11806. t = xxreadtoken();
  11807. }
  11808. }
  11809. if (t != TWORD || quoteflag) {
  11810. goto out;
  11811. }
  11812. /*
  11813. * check for keywords
  11814. */
  11815. if (kwd & CHKKWD) {
  11816. const char *const *pp;
  11817. pp = findkwd(wordtext);
  11818. if (pp) {
  11819. lasttoken = t = pp - tokname_array;
  11820. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11821. goto out;
  11822. }
  11823. }
  11824. if (checkkwd & CHKALIAS) {
  11825. #if ENABLE_ASH_ALIAS
  11826. struct alias *ap;
  11827. ap = lookupalias(wordtext, 1);
  11828. if (ap != NULL) {
  11829. if (*ap->val) {
  11830. pushstring(ap->val, ap);
  11831. }
  11832. goto top;
  11833. }
  11834. #endif
  11835. }
  11836. out:
  11837. checkkwd = 0;
  11838. #if DEBUG
  11839. if (!alreadyseen)
  11840. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11841. else
  11842. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11843. #endif
  11844. return t;
  11845. }
  11846. static int
  11847. peektoken(void)
  11848. {
  11849. int t;
  11850. t = readtoken();
  11851. tokpushback = 1;
  11852. return t;
  11853. }
  11854. /*
  11855. * Read and parse a command. Returns NODE_EOF on end of file.
  11856. * (NULL is a valid parse tree indicating a blank line.)
  11857. */
  11858. static union node *
  11859. parsecmd(int interact)
  11860. {
  11861. tokpushback = 0;
  11862. checkkwd = 0;
  11863. heredoclist = 0;
  11864. doprompt = interact;
  11865. setprompt_if(doprompt, doprompt);
  11866. needprompt = 0;
  11867. return list(1);
  11868. }
  11869. /*
  11870. * Input any here documents.
  11871. */
  11872. static void
  11873. parseheredoc(void)
  11874. {
  11875. struct heredoc *here;
  11876. union node *n;
  11877. here = heredoclist;
  11878. heredoclist = NULL;
  11879. while (here) {
  11880. tokpushback = 0;
  11881. setprompt_if(needprompt, 2);
  11882. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11883. here->eofmark, here->striptabs);
  11884. n = stzalloc(sizeof(struct narg));
  11885. n->narg.type = NARG;
  11886. /*n->narg.next = NULL; - stzalloc did it */
  11887. n->narg.text = wordtext;
  11888. n->narg.backquote = backquotelist;
  11889. here->here->nhere.doc = n;
  11890. here = here->next;
  11891. }
  11892. }
  11893. static const char *
  11894. expandstr(const char *ps, int syntax_type)
  11895. {
  11896. union node n;
  11897. int saveprompt;
  11898. /* XXX Fix (char *) cast. */
  11899. setinputstring((char *)ps);
  11900. saveprompt = doprompt;
  11901. doprompt = 0;
  11902. /* readtoken1() might die horribly.
  11903. * Try a prompt with syntactically wrong command:
  11904. * PS1='$(date "+%H:%M:%S) > '
  11905. */
  11906. {
  11907. volatile int saveint;
  11908. struct jmploc *volatile savehandler = exception_handler;
  11909. struct jmploc jmploc;
  11910. SAVE_INT(saveint);
  11911. if (setjmp(jmploc.loc) == 0) {
  11912. exception_handler = &jmploc;
  11913. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  11914. }
  11915. exception_handler = savehandler;
  11916. RESTORE_INT(saveint);
  11917. }
  11918. doprompt = saveprompt;
  11919. popfile();
  11920. n.narg.type = NARG;
  11921. n.narg.next = NULL;
  11922. n.narg.text = wordtext;
  11923. n.narg.backquote = backquotelist;
  11924. expandarg(&n, NULL, EXP_QUOTED);
  11925. return stackblock();
  11926. }
  11927. static inline int
  11928. parser_eof(void)
  11929. {
  11930. return tokpushback && lasttoken == TEOF;
  11931. }
  11932. /*
  11933. * Execute a command or commands contained in a string.
  11934. */
  11935. static int
  11936. evalstring(char *s, int flags)
  11937. {
  11938. struct jmploc *volatile savehandler;
  11939. struct jmploc jmploc;
  11940. int ex;
  11941. union node *n;
  11942. struct stackmark smark;
  11943. int status;
  11944. s = sstrdup(s);
  11945. setinputstring(s);
  11946. setstackmark(&smark);
  11947. status = 0;
  11948. /* On exception inside execution loop, we must popfile().
  11949. * Try interactively:
  11950. * readonly a=a
  11951. * command eval "a=b" # throws "is read only" error
  11952. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  11953. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  11954. */
  11955. savehandler = exception_handler;
  11956. ex = setjmp(jmploc.loc);
  11957. if (ex)
  11958. goto out;
  11959. exception_handler = &jmploc;
  11960. while ((n = parsecmd(0)) != NODE_EOF) {
  11961. int i;
  11962. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  11963. if (n)
  11964. status = i;
  11965. popstackmark(&smark);
  11966. if (evalskip)
  11967. break;
  11968. }
  11969. out:
  11970. popstackmark(&smark);
  11971. popfile();
  11972. stunalloc(s);
  11973. exception_handler = savehandler;
  11974. if (ex)
  11975. longjmp(exception_handler->loc, ex);
  11976. return status;
  11977. }
  11978. /*
  11979. * The eval command.
  11980. */
  11981. static int FAST_FUNC
  11982. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  11983. {
  11984. char *p;
  11985. char *concat;
  11986. if (argv[1]) {
  11987. p = argv[1];
  11988. argv += 2;
  11989. if (argv[0]) {
  11990. STARTSTACKSTR(concat);
  11991. for (;;) {
  11992. concat = stack_putstr(p, concat);
  11993. p = *argv++;
  11994. if (p == NULL)
  11995. break;
  11996. STPUTC(' ', concat);
  11997. }
  11998. STPUTC('\0', concat);
  11999. p = grabstackstr(concat);
  12000. }
  12001. return evalstring(p, flags & EV_TESTED);
  12002. }
  12003. return 0;
  12004. }
  12005. /*
  12006. * Read and execute commands.
  12007. * "Top" is nonzero for the top level command loop;
  12008. * it turns on prompting if the shell is interactive.
  12009. */
  12010. static int
  12011. cmdloop(int top)
  12012. {
  12013. union node *n;
  12014. struct stackmark smark;
  12015. int inter;
  12016. int status = 0;
  12017. int numeof = 0;
  12018. TRACE(("cmdloop(%d) called\n", top));
  12019. for (;;) {
  12020. int skip;
  12021. setstackmark(&smark);
  12022. #if JOBS
  12023. if (doing_jobctl)
  12024. showjobs(SHOW_CHANGED|SHOW_STDERR);
  12025. #endif
  12026. inter = 0;
  12027. if (iflag && top) {
  12028. inter++;
  12029. chkmail();
  12030. }
  12031. n = parsecmd(inter);
  12032. #if DEBUG
  12033. if (DEBUG > 2 && debug && (n != NODE_EOF))
  12034. showtree(n);
  12035. #endif
  12036. if (n == NODE_EOF) {
  12037. if (!top || numeof >= 50)
  12038. break;
  12039. if (!stoppedjobs()) {
  12040. if (!Iflag)
  12041. break;
  12042. out2str("\nUse \"exit\" to leave shell.\n");
  12043. }
  12044. numeof++;
  12045. } else if (nflag == 0) {
  12046. int i;
  12047. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12048. job_warning >>= 1;
  12049. numeof = 0;
  12050. i = evaltree(n, 0);
  12051. if (n)
  12052. status = i;
  12053. }
  12054. popstackmark(&smark);
  12055. skip = evalskip;
  12056. if (skip) {
  12057. evalskip &= ~SKIPFUNC;
  12058. break;
  12059. }
  12060. }
  12061. return status;
  12062. }
  12063. /*
  12064. * Take commands from a file. To be compatible we should do a path
  12065. * search for the file, which is necessary to find sub-commands.
  12066. */
  12067. static char *
  12068. find_dot_file(char *name)
  12069. {
  12070. char *fullname;
  12071. const char *path = pathval();
  12072. struct stat statb;
  12073. /* don't try this for absolute or relative paths */
  12074. if (strchr(name, '/'))
  12075. return name;
  12076. while ((fullname = path_advance(&path, name)) != NULL) {
  12077. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  12078. /*
  12079. * Don't bother freeing here, since it will
  12080. * be freed by the caller.
  12081. */
  12082. return fullname;
  12083. }
  12084. if (fullname != name)
  12085. stunalloc(fullname);
  12086. }
  12087. /* not found in PATH */
  12088. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12089. return name;
  12090. #else
  12091. ash_msg_and_raise_error("%s: not found", name);
  12092. /* NOTREACHED */
  12093. #endif
  12094. }
  12095. static int FAST_FUNC
  12096. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12097. {
  12098. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12099. int status = 0;
  12100. char *fullname;
  12101. char **argv;
  12102. char *args_need_save;
  12103. volatile struct shparam saveparam;
  12104. //???
  12105. // struct strlist *sp;
  12106. // for (sp = cmdenviron; sp; sp = sp->next)
  12107. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12108. nextopt(nullstr); /* handle possible "--" */
  12109. argv = argptr;
  12110. if (!argv[0]) {
  12111. /* bash says: "bash: .: filename argument required" */
  12112. return 2; /* bash compat */
  12113. }
  12114. /* This aborts if file isn't found, which is POSIXly correct.
  12115. * bash returns exitcode 1 instead.
  12116. */
  12117. fullname = find_dot_file(argv[0]);
  12118. argv++;
  12119. args_need_save = argv[0];
  12120. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12121. int argc;
  12122. saveparam = shellparam;
  12123. shellparam.malloced = 0;
  12124. argc = 1;
  12125. while (argv[argc])
  12126. argc++;
  12127. shellparam.nparam = argc;
  12128. shellparam.p = argv;
  12129. };
  12130. /* This aborts if file can't be opened, which is POSIXly correct.
  12131. * bash returns exitcode 1 instead.
  12132. */
  12133. setinputfile(fullname, INPUT_PUSH_FILE);
  12134. commandname = fullname;
  12135. status = cmdloop(0);
  12136. popfile();
  12137. if (args_need_save) {
  12138. freeparam(&shellparam);
  12139. shellparam = saveparam;
  12140. };
  12141. return status;
  12142. }
  12143. static int FAST_FUNC
  12144. exitcmd(int argc UNUSED_PARAM, char **argv)
  12145. {
  12146. if (stoppedjobs())
  12147. return 0;
  12148. if (argv[1])
  12149. exitstatus = number(argv[1]);
  12150. raise_exception(EXEXIT);
  12151. /* NOTREACHED */
  12152. }
  12153. /*
  12154. * Read a file containing shell functions.
  12155. */
  12156. static void
  12157. readcmdfile(char *name)
  12158. {
  12159. setinputfile(name, INPUT_PUSH_FILE);
  12160. cmdloop(0);
  12161. popfile();
  12162. }
  12163. /* ============ find_command inplementation */
  12164. /*
  12165. * Resolve a command name. If you change this routine, you may have to
  12166. * change the shellexec routine as well.
  12167. */
  12168. static void
  12169. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12170. {
  12171. struct tblentry *cmdp;
  12172. int idx;
  12173. int prev;
  12174. char *fullname;
  12175. struct stat statb;
  12176. int e;
  12177. int updatetbl;
  12178. struct builtincmd *bcmd;
  12179. /* If name contains a slash, don't use PATH or hash table */
  12180. if (strchr(name, '/') != NULL) {
  12181. entry->u.index = -1;
  12182. if (act & DO_ABS) {
  12183. while (stat(name, &statb) < 0) {
  12184. #ifdef SYSV
  12185. if (errno == EINTR)
  12186. continue;
  12187. #endif
  12188. entry->cmdtype = CMDUNKNOWN;
  12189. return;
  12190. }
  12191. }
  12192. entry->cmdtype = CMDNORMAL;
  12193. return;
  12194. }
  12195. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12196. updatetbl = (path == pathval());
  12197. if (!updatetbl) {
  12198. act |= DO_ALTPATH;
  12199. if (strstr(path, "%builtin") != NULL)
  12200. act |= DO_ALTBLTIN;
  12201. }
  12202. /* If name is in the table, check answer will be ok */
  12203. cmdp = cmdlookup(name, 0);
  12204. if (cmdp != NULL) {
  12205. int bit;
  12206. switch (cmdp->cmdtype) {
  12207. default:
  12208. #if DEBUG
  12209. abort();
  12210. #endif
  12211. case CMDNORMAL:
  12212. bit = DO_ALTPATH;
  12213. break;
  12214. case CMDFUNCTION:
  12215. bit = DO_NOFUNC;
  12216. break;
  12217. case CMDBUILTIN:
  12218. bit = DO_ALTBLTIN;
  12219. break;
  12220. }
  12221. if (act & bit) {
  12222. updatetbl = 0;
  12223. cmdp = NULL;
  12224. } else if (cmdp->rehash == 0)
  12225. /* if not invalidated by cd, we're done */
  12226. goto success;
  12227. }
  12228. /* If %builtin not in path, check for builtin next */
  12229. bcmd = find_builtin(name);
  12230. if (bcmd) {
  12231. if (IS_BUILTIN_REGULAR(bcmd))
  12232. goto builtin_success;
  12233. if (act & DO_ALTPATH) {
  12234. if (!(act & DO_ALTBLTIN))
  12235. goto builtin_success;
  12236. } else if (builtinloc <= 0) {
  12237. goto builtin_success;
  12238. }
  12239. }
  12240. #if ENABLE_FEATURE_SH_STANDALONE
  12241. {
  12242. int applet_no = find_applet_by_name(name);
  12243. if (applet_no >= 0) {
  12244. entry->cmdtype = CMDNORMAL;
  12245. entry->u.index = -2 - applet_no;
  12246. return;
  12247. }
  12248. }
  12249. #endif
  12250. /* We have to search path. */
  12251. prev = -1; /* where to start */
  12252. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12253. if (cmdp->cmdtype == CMDBUILTIN)
  12254. prev = builtinloc;
  12255. else
  12256. prev = cmdp->param.index;
  12257. }
  12258. e = ENOENT;
  12259. idx = -1;
  12260. loop:
  12261. while ((fullname = path_advance(&path, name)) != NULL) {
  12262. stunalloc(fullname);
  12263. /* NB: code below will still use fullname
  12264. * despite it being "unallocated" */
  12265. idx++;
  12266. if (pathopt) {
  12267. if (prefix(pathopt, "builtin")) {
  12268. if (bcmd)
  12269. goto builtin_success;
  12270. continue;
  12271. }
  12272. if ((act & DO_NOFUNC)
  12273. || !prefix(pathopt, "func")
  12274. ) { /* ignore unimplemented options */
  12275. continue;
  12276. }
  12277. }
  12278. /* if rehash, don't redo absolute path names */
  12279. if (fullname[0] == '/' && idx <= prev) {
  12280. if (idx < prev)
  12281. continue;
  12282. TRACE(("searchexec \"%s\": no change\n", name));
  12283. goto success;
  12284. }
  12285. while (stat(fullname, &statb) < 0) {
  12286. #ifdef SYSV
  12287. if (errno == EINTR)
  12288. continue;
  12289. #endif
  12290. if (errno != ENOENT && errno != ENOTDIR)
  12291. e = errno;
  12292. goto loop;
  12293. }
  12294. e = EACCES; /* if we fail, this will be the error */
  12295. if (!S_ISREG(statb.st_mode))
  12296. continue;
  12297. if (pathopt) { /* this is a %func directory */
  12298. stalloc(strlen(fullname) + 1);
  12299. /* NB: stalloc will return space pointed by fullname
  12300. * (because we don't have any intervening allocations
  12301. * between stunalloc above and this stalloc) */
  12302. readcmdfile(fullname);
  12303. cmdp = cmdlookup(name, 0);
  12304. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12305. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12306. stunalloc(fullname);
  12307. goto success;
  12308. }
  12309. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12310. if (!updatetbl) {
  12311. entry->cmdtype = CMDNORMAL;
  12312. entry->u.index = idx;
  12313. return;
  12314. }
  12315. INT_OFF;
  12316. cmdp = cmdlookup(name, 1);
  12317. cmdp->cmdtype = CMDNORMAL;
  12318. cmdp->param.index = idx;
  12319. INT_ON;
  12320. goto success;
  12321. }
  12322. /* We failed. If there was an entry for this command, delete it */
  12323. if (cmdp && updatetbl)
  12324. delete_cmd_entry();
  12325. if (act & DO_ERR) {
  12326. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12327. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12328. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12329. char *argv[3];
  12330. argv[0] = (char*) "command_not_found_handle";
  12331. argv[1] = name;
  12332. argv[2] = NULL;
  12333. evalfun(hookp->param.func, 2, argv, 0);
  12334. entry->cmdtype = CMDUNKNOWN;
  12335. return;
  12336. }
  12337. #endif
  12338. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12339. }
  12340. entry->cmdtype = CMDUNKNOWN;
  12341. return;
  12342. builtin_success:
  12343. if (!updatetbl) {
  12344. entry->cmdtype = CMDBUILTIN;
  12345. entry->u.cmd = bcmd;
  12346. return;
  12347. }
  12348. INT_OFF;
  12349. cmdp = cmdlookup(name, 1);
  12350. cmdp->cmdtype = CMDBUILTIN;
  12351. cmdp->param.cmd = bcmd;
  12352. INT_ON;
  12353. success:
  12354. cmdp->rehash = 0;
  12355. entry->cmdtype = cmdp->cmdtype;
  12356. entry->u = cmdp->param;
  12357. }
  12358. /*
  12359. * The trap builtin.
  12360. */
  12361. static int FAST_FUNC
  12362. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12363. {
  12364. char *action;
  12365. char **ap;
  12366. int signo, exitcode;
  12367. nextopt(nullstr);
  12368. ap = argptr;
  12369. if (!*ap) {
  12370. for (signo = 0; signo < NSIG; signo++) {
  12371. char *tr = trap_ptr[signo];
  12372. if (tr) {
  12373. /* note: bash adds "SIG", but only if invoked
  12374. * as "bash". If called as "sh", or if set -o posix,
  12375. * then it prints short signal names.
  12376. * We are printing short names: */
  12377. out1fmt("trap -- %s %s\n",
  12378. single_quote(tr),
  12379. get_signame(signo));
  12380. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12381. * In this case, we will exit very soon, no need to free(). */
  12382. /* if (trap_ptr != trap && tp[0]) */
  12383. /* free(tr); */
  12384. }
  12385. }
  12386. /*
  12387. if (trap_ptr != trap) {
  12388. free(trap_ptr);
  12389. trap_ptr = trap;
  12390. }
  12391. */
  12392. return 0;
  12393. }
  12394. /* Why the second check?
  12395. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12396. * In this case, NUM is signal no, not an action.
  12397. */
  12398. action = NULL;
  12399. if (ap[1] && !is_number(ap[0]))
  12400. action = *ap++;
  12401. exitcode = 0;
  12402. while (*ap) {
  12403. signo = get_signum(*ap);
  12404. if (signo < 0) {
  12405. /* Mimic bash message exactly */
  12406. ash_msg("%s: invalid signal specification", *ap);
  12407. exitcode = 1;
  12408. goto next;
  12409. }
  12410. INT_OFF;
  12411. if (action) {
  12412. if (LONE_DASH(action))
  12413. action = NULL;
  12414. else {
  12415. if (action[0]) /* not NULL and not "" and not "-" */
  12416. may_have_traps = 1;
  12417. action = ckstrdup(action);
  12418. }
  12419. }
  12420. free(trap[signo]);
  12421. trap[signo] = action;
  12422. if (signo != 0)
  12423. setsignal(signo);
  12424. INT_ON;
  12425. next:
  12426. ap++;
  12427. }
  12428. return exitcode;
  12429. }
  12430. /* ============ Builtins */
  12431. #if ENABLE_ASH_HELP
  12432. static int FAST_FUNC
  12433. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12434. {
  12435. unsigned col;
  12436. unsigned i;
  12437. out1fmt(
  12438. "Built-in commands:\n"
  12439. "------------------\n");
  12440. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12441. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12442. builtintab[i].name + 1);
  12443. if (col > 60) {
  12444. out1fmt("\n");
  12445. col = 0;
  12446. }
  12447. }
  12448. # if ENABLE_FEATURE_SH_STANDALONE
  12449. {
  12450. const char *a = applet_names;
  12451. while (*a) {
  12452. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12453. if (col > 60) {
  12454. out1fmt("\n");
  12455. col = 0;
  12456. }
  12457. while (*a++ != '\0')
  12458. continue;
  12459. }
  12460. }
  12461. # endif
  12462. newline_and_flush(stdout);
  12463. return EXIT_SUCCESS;
  12464. }
  12465. #endif
  12466. #if MAX_HISTORY
  12467. static int FAST_FUNC
  12468. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12469. {
  12470. show_history(line_input_state);
  12471. return EXIT_SUCCESS;
  12472. }
  12473. #endif
  12474. /*
  12475. * The export and readonly commands.
  12476. */
  12477. static int FAST_FUNC
  12478. exportcmd(int argc UNUSED_PARAM, char **argv)
  12479. {
  12480. struct var *vp;
  12481. char *name;
  12482. const char *p;
  12483. char **aptr;
  12484. char opt;
  12485. int flag;
  12486. int flag_off;
  12487. /* "readonly" in bash accepts, but ignores -n.
  12488. * We do the same: it saves a conditional in nextopt's param.
  12489. */
  12490. flag_off = 0;
  12491. while ((opt = nextopt("np")) != '\0') {
  12492. if (opt == 'n')
  12493. flag_off = VEXPORT;
  12494. }
  12495. flag = VEXPORT;
  12496. if (argv[0][0] == 'r') {
  12497. flag = VREADONLY;
  12498. flag_off = 0; /* readonly ignores -n */
  12499. }
  12500. flag_off = ~flag_off;
  12501. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12502. {
  12503. aptr = argptr;
  12504. name = *aptr;
  12505. if (name) {
  12506. do {
  12507. p = strchr(name, '=');
  12508. if (p != NULL) {
  12509. p++;
  12510. } else {
  12511. vp = *findvar(hashvar(name), name);
  12512. if (vp) {
  12513. vp->flags = ((vp->flags | flag) & flag_off);
  12514. continue;
  12515. }
  12516. }
  12517. setvar(name, p, (flag & flag_off));
  12518. } while ((name = *++aptr) != NULL);
  12519. return 0;
  12520. }
  12521. }
  12522. /* No arguments. Show the list of exported or readonly vars.
  12523. * -n is ignored.
  12524. */
  12525. showvars(argv[0], flag, 0);
  12526. return 0;
  12527. }
  12528. /*
  12529. * Delete a function if it exists.
  12530. */
  12531. static void
  12532. unsetfunc(const char *name)
  12533. {
  12534. struct tblentry *cmdp;
  12535. cmdp = cmdlookup(name, 0);
  12536. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12537. delete_cmd_entry();
  12538. }
  12539. /*
  12540. * The unset builtin command. We unset the function before we unset the
  12541. * variable to allow a function to be unset when there is a readonly variable
  12542. * with the same name.
  12543. */
  12544. static int FAST_FUNC
  12545. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12546. {
  12547. char **ap;
  12548. int i;
  12549. int flag = 0;
  12550. while ((i = nextopt("vf")) != 0) {
  12551. flag = i;
  12552. }
  12553. for (ap = argptr; *ap; ap++) {
  12554. if (flag != 'f') {
  12555. unsetvar(*ap);
  12556. continue;
  12557. }
  12558. if (flag != 'v')
  12559. unsetfunc(*ap);
  12560. }
  12561. return 0;
  12562. }
  12563. static const unsigned char timescmd_str[] ALIGN1 = {
  12564. ' ', offsetof(struct tms, tms_utime),
  12565. '\n', offsetof(struct tms, tms_stime),
  12566. ' ', offsetof(struct tms, tms_cutime),
  12567. '\n', offsetof(struct tms, tms_cstime),
  12568. 0
  12569. };
  12570. static int FAST_FUNC
  12571. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12572. {
  12573. unsigned clk_tck;
  12574. const unsigned char *p;
  12575. struct tms buf;
  12576. clk_tck = bb_clk_tck();
  12577. times(&buf);
  12578. p = timescmd_str;
  12579. do {
  12580. unsigned sec, frac;
  12581. unsigned long t;
  12582. t = *(clock_t *)(((char *) &buf) + p[1]);
  12583. sec = t / clk_tck;
  12584. frac = t % clk_tck;
  12585. out1fmt("%um%u.%03us%c",
  12586. sec / 60, sec % 60,
  12587. (frac * 1000) / clk_tck,
  12588. p[0]);
  12589. p += 2;
  12590. } while (*p);
  12591. return 0;
  12592. }
  12593. #if ENABLE_FEATURE_SH_MATH
  12594. /*
  12595. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12596. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12597. *
  12598. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12599. */
  12600. static int FAST_FUNC
  12601. letcmd(int argc UNUSED_PARAM, char **argv)
  12602. {
  12603. arith_t i;
  12604. argv++;
  12605. if (!*argv)
  12606. ash_msg_and_raise_error("expression expected");
  12607. do {
  12608. i = ash_arith(*argv);
  12609. } while (*++argv);
  12610. return !i;
  12611. }
  12612. #endif
  12613. /*
  12614. * The read builtin. Options:
  12615. * -r Do not interpret '\' specially
  12616. * -s Turn off echo (tty only)
  12617. * -n NCHARS Read NCHARS max
  12618. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12619. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12620. * -u FD Read from given FD instead of fd 0
  12621. * -d DELIM End on DELIM char, not newline
  12622. * This uses unbuffered input, which may be avoidable in some cases.
  12623. * TODO: bash also has:
  12624. * -a ARRAY Read into array[0],[1],etc
  12625. * -e Use line editing (tty only)
  12626. */
  12627. static int FAST_FUNC
  12628. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12629. {
  12630. struct builtin_read_params params;
  12631. const char *r;
  12632. int i;
  12633. memset(&params, 0, sizeof(params));
  12634. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12635. switch (i) {
  12636. case 'p':
  12637. params.opt_p = optionarg;
  12638. break;
  12639. case 'n':
  12640. params.opt_n = optionarg;
  12641. break;
  12642. case 's':
  12643. params.read_flags |= BUILTIN_READ_SILENT;
  12644. break;
  12645. case 't':
  12646. params.opt_t = optionarg;
  12647. break;
  12648. case 'r':
  12649. params.read_flags |= BUILTIN_READ_RAW;
  12650. break;
  12651. case 'u':
  12652. params.opt_u = optionarg;
  12653. break;
  12654. #if BASH_READ_D
  12655. case 'd':
  12656. params.opt_d = optionarg;
  12657. break;
  12658. #endif
  12659. default:
  12660. break;
  12661. }
  12662. }
  12663. params.argv = argptr;
  12664. params.setvar = setvar0;
  12665. params.ifs = bltinlookup("IFS"); /* can be NULL */
  12666. /* "read -s" needs to save/restore termios, can't allow ^C
  12667. * to jump out of it.
  12668. */
  12669. again:
  12670. INT_OFF;
  12671. r = shell_builtin_read(&params);
  12672. INT_ON;
  12673. if ((uintptr_t)r == 1 && errno == EINTR) {
  12674. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12675. * Correct behavior is to not exit "read"
  12676. */
  12677. if (pending_sig == 0)
  12678. goto again;
  12679. }
  12680. if ((uintptr_t)r > 1)
  12681. ash_msg_and_raise_error(r);
  12682. return (uintptr_t)r;
  12683. }
  12684. static int FAST_FUNC
  12685. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12686. {
  12687. static const char permuser[3] ALIGN1 = "ogu";
  12688. mode_t mask;
  12689. int symbolic_mode = 0;
  12690. while (nextopt("S") != '\0') {
  12691. symbolic_mode = 1;
  12692. }
  12693. INT_OFF;
  12694. mask = umask(0);
  12695. umask(mask);
  12696. INT_ON;
  12697. if (*argptr == NULL) {
  12698. if (symbolic_mode) {
  12699. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12700. char *p = buf;
  12701. int i;
  12702. i = 2;
  12703. for (;;) {
  12704. *p++ = ',';
  12705. *p++ = permuser[i];
  12706. *p++ = '=';
  12707. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12708. if (!(mask & 0400)) *p++ = 'r';
  12709. if (!(mask & 0200)) *p++ = 'w';
  12710. if (!(mask & 0100)) *p++ = 'x';
  12711. mask <<= 3;
  12712. if (--i < 0)
  12713. break;
  12714. }
  12715. *p = '\0';
  12716. puts(buf + 1);
  12717. } else {
  12718. out1fmt("%04o\n", mask);
  12719. }
  12720. } else {
  12721. char *modestr = *argptr;
  12722. /* numeric umasks are taken as-is */
  12723. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12724. if (!isdigit(modestr[0]))
  12725. mask ^= 0777;
  12726. mask = bb_parse_mode(modestr, mask);
  12727. if ((unsigned)mask > 0777) {
  12728. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12729. }
  12730. if (!isdigit(modestr[0]))
  12731. mask ^= 0777;
  12732. umask(mask);
  12733. }
  12734. return 0;
  12735. }
  12736. static int FAST_FUNC
  12737. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12738. {
  12739. return shell_builtin_ulimit(argv);
  12740. }
  12741. /* ============ main() and helpers */
  12742. /*
  12743. * Called to exit the shell.
  12744. */
  12745. static void
  12746. exitshell(void)
  12747. {
  12748. struct jmploc loc;
  12749. char *p;
  12750. int status;
  12751. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12752. save_history(line_input_state);
  12753. #endif
  12754. status = exitstatus;
  12755. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  12756. if (setjmp(loc.loc)) {
  12757. if (exception_type == EXEXIT)
  12758. status = exitstatus;
  12759. goto out;
  12760. }
  12761. exception_handler = &loc;
  12762. p = trap[0];
  12763. if (p) {
  12764. trap[0] = NULL;
  12765. evalskip = 0;
  12766. evalstring(p, 0);
  12767. /*free(p); - we'll exit soon */
  12768. }
  12769. out:
  12770. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12771. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12772. */
  12773. setjobctl(0);
  12774. flush_stdout_stderr();
  12775. _exit(status);
  12776. /* NOTREACHED */
  12777. }
  12778. /* Don't inline: conserve stack of caller from having our locals too */
  12779. static NOINLINE void
  12780. init(void)
  12781. {
  12782. /* we will never free this */
  12783. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12784. basepf.linno = 1;
  12785. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  12786. setsignal(SIGCHLD);
  12787. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  12788. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  12789. */
  12790. signal(SIGHUP, SIG_DFL);
  12791. {
  12792. char **envp;
  12793. const char *p;
  12794. initvar();
  12795. for (envp = environ; envp && *envp; envp++) {
  12796. /* Used to have
  12797. * p = endofname(*envp);
  12798. * if (p != *envp && *p == '=') {
  12799. * here to weed out badly-named variables, but this breaks
  12800. * scenarios where people do want them passed to children:
  12801. * import os
  12802. * os.environ["test-test"]="test"
  12803. * if os.fork() == 0:
  12804. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  12805. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  12806. */
  12807. if (strchr(*envp, '=')) {
  12808. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12809. }
  12810. }
  12811. setvareq((char*)defifsvar, VTEXTFIXED);
  12812. setvareq((char*)defoptindvar, VTEXTFIXED);
  12813. setvar0("PPID", utoa(getppid()));
  12814. #if BASH_SHLVL_VAR
  12815. p = lookupvar("SHLVL");
  12816. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12817. #endif
  12818. #if BASH_HOSTNAME_VAR
  12819. if (!lookupvar("HOSTNAME")) {
  12820. struct utsname uts;
  12821. uname(&uts);
  12822. setvar0("HOSTNAME", uts.nodename);
  12823. }
  12824. #endif
  12825. p = lookupvar("PWD");
  12826. if (p) {
  12827. struct stat st1, st2;
  12828. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12829. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12830. ) {
  12831. p = NULL;
  12832. }
  12833. }
  12834. setpwd(p, 0);
  12835. }
  12836. }
  12837. //usage:#define ash_trivial_usage
  12838. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  12839. //usage:#define ash_full_usage "\n\n"
  12840. //usage: "Unix shell interpreter"
  12841. /*
  12842. * Process the shell command line arguments.
  12843. */
  12844. static int
  12845. procargs(char **argv)
  12846. {
  12847. int i;
  12848. const char *xminusc;
  12849. char **xargv;
  12850. int login_sh;
  12851. xargv = argv;
  12852. login_sh = xargv[0] && xargv[0][0] == '-';
  12853. #if NUM_SCRIPTS > 0
  12854. if (minusc)
  12855. goto setarg0;
  12856. #endif
  12857. arg0 = xargv[0];
  12858. /* if (xargv[0]) - mmm, this is always true! */
  12859. xargv++;
  12860. argptr = xargv;
  12861. for (i = 0; i < NOPTS; i++)
  12862. optlist[i] = 2;
  12863. if (options(/*cmdline:*/ 1, &login_sh)) {
  12864. /* it already printed err message */
  12865. raise_exception(EXERROR);
  12866. }
  12867. xargv = argptr;
  12868. xminusc = minusc;
  12869. if (*xargv == NULL) {
  12870. if (xminusc)
  12871. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  12872. sflag = 1;
  12873. }
  12874. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  12875. iflag = 1;
  12876. if (mflag == 2)
  12877. mflag = iflag;
  12878. for (i = 0; i < NOPTS; i++)
  12879. if (optlist[i] == 2)
  12880. optlist[i] = 0;
  12881. #if DEBUG == 2
  12882. debug = 1;
  12883. #endif
  12884. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  12885. if (xminusc) {
  12886. minusc = *xargv++;
  12887. if (*xargv)
  12888. goto setarg0;
  12889. } else if (!sflag) {
  12890. setinputfile(*xargv, 0);
  12891. setarg0:
  12892. arg0 = *xargv++;
  12893. commandname = arg0;
  12894. }
  12895. shellparam.p = xargv;
  12896. #if ENABLE_ASH_GETOPTS
  12897. shellparam.optind = 1;
  12898. shellparam.optoff = -1;
  12899. #endif
  12900. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  12901. while (*xargv) {
  12902. shellparam.nparam++;
  12903. xargv++;
  12904. }
  12905. optschanged();
  12906. return login_sh;
  12907. }
  12908. /*
  12909. * Read /etc/profile, ~/.profile, $ENV.
  12910. */
  12911. static void
  12912. read_profile(const char *name)
  12913. {
  12914. name = expandstr(name, DQSYNTAX);
  12915. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  12916. return;
  12917. cmdloop(0);
  12918. popfile();
  12919. }
  12920. /*
  12921. * This routine is called when an error or an interrupt occurs in an
  12922. * interactive shell and control is returned to the main command loop.
  12923. * (In dash, this function is auto-generated by build machinery).
  12924. */
  12925. static void
  12926. reset(void)
  12927. {
  12928. /* from eval.c: */
  12929. evalskip = 0;
  12930. loopnest = 0;
  12931. /* from expand.c: */
  12932. ifsfree();
  12933. /* from input.c: */
  12934. g_parsefile->left_in_buffer = 0;
  12935. g_parsefile->left_in_line = 0; /* clear input buffer */
  12936. popallfiles();
  12937. /* from redir.c: */
  12938. unwindredir(NULL);
  12939. /* from var.c: */
  12940. unwindlocalvars(NULL);
  12941. }
  12942. #if PROFILE
  12943. static short profile_buf[16384];
  12944. extern int etext();
  12945. #endif
  12946. /*
  12947. * Main routine. We initialize things, parse the arguments, execute
  12948. * profiles if we're a login shell, and then call cmdloop to execute
  12949. * commands. The setjmp call sets up the location to jump to when an
  12950. * exception occurs. When an exception occurs the variable "state"
  12951. * is used to figure out how far we had gotten.
  12952. */
  12953. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12954. #if NUM_SCRIPTS > 0
  12955. int ash_main(int argc, char **argv)
  12956. #else
  12957. int ash_main(int argc UNUSED_PARAM, char **argv)
  12958. #endif
  12959. /* note: 'argc' is used only if embedded scripts are enabled */
  12960. {
  12961. volatile smallint state;
  12962. struct jmploc jmploc;
  12963. struct stackmark smark;
  12964. int login_sh;
  12965. /* Initialize global data */
  12966. INIT_G_misc();
  12967. INIT_G_memstack();
  12968. INIT_G_var();
  12969. #if ENABLE_ASH_ALIAS
  12970. INIT_G_alias();
  12971. #endif
  12972. INIT_G_cmdtable();
  12973. #if PROFILE
  12974. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12975. #endif
  12976. #if ENABLE_FEATURE_EDITING
  12977. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12978. #endif
  12979. state = 0;
  12980. if (setjmp(jmploc.loc)) {
  12981. smallint e;
  12982. smallint s;
  12983. reset();
  12984. e = exception_type;
  12985. s = state;
  12986. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  12987. exitshell();
  12988. }
  12989. if (e == EXINT) {
  12990. newline_and_flush(stderr);
  12991. }
  12992. popstackmark(&smark);
  12993. FORCE_INT_ON; /* enable interrupts */
  12994. if (s == 1)
  12995. goto state1;
  12996. if (s == 2)
  12997. goto state2;
  12998. if (s == 3)
  12999. goto state3;
  13000. goto state4;
  13001. }
  13002. exception_handler = &jmploc;
  13003. rootpid = getpid();
  13004. init();
  13005. setstackmark(&smark);
  13006. #if NUM_SCRIPTS > 0
  13007. if (argc < 0)
  13008. /* Non-NULL minusc tells procargs that an embedded script is being run */
  13009. minusc = get_script_content(-argc - 1);
  13010. #endif
  13011. login_sh = procargs(argv);
  13012. #if DEBUG
  13013. TRACE(("Shell args: "));
  13014. trace_puts_args(argv);
  13015. #endif
  13016. if (login_sh) {
  13017. const char *hp;
  13018. state = 1;
  13019. read_profile("/etc/profile");
  13020. state1:
  13021. state = 2;
  13022. hp = lookupvar("HOME");
  13023. if (hp)
  13024. read_profile("$HOME/.profile");
  13025. }
  13026. state2:
  13027. state = 3;
  13028. if (
  13029. #ifndef linux
  13030. getuid() == geteuid() && getgid() == getegid() &&
  13031. #endif
  13032. iflag
  13033. ) {
  13034. const char *shinit = lookupvar("ENV");
  13035. if (shinit != NULL && *shinit != '\0')
  13036. read_profile(shinit);
  13037. }
  13038. popstackmark(&smark);
  13039. state3:
  13040. state = 4;
  13041. if (minusc) {
  13042. /* evalstring pushes parsefile stack.
  13043. * Ensure we don't falsely claim that 0 (stdin)
  13044. * is one of stacked source fds.
  13045. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13046. // if (!sflag) g_parsefile->pf_fd = -1;
  13047. // ^^ not necessary since now we special-case fd 0
  13048. // in save_fd_on_redirect()
  13049. evalstring(minusc, sflag ? 0 : EV_EXIT);
  13050. }
  13051. if (sflag || minusc == NULL) {
  13052. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13053. if (iflag) {
  13054. const char *hp = lookupvar("HISTFILE");
  13055. if (!hp) {
  13056. hp = lookupvar("HOME");
  13057. if (hp) {
  13058. INT_OFF;
  13059. hp = concat_path_file(hp, ".ash_history");
  13060. setvar0("HISTFILE", hp);
  13061. free((char*)hp);
  13062. INT_ON;
  13063. hp = lookupvar("HISTFILE");
  13064. }
  13065. }
  13066. if (hp)
  13067. line_input_state->hist_file = hp;
  13068. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13069. hp = lookupvar("HISTFILESIZE");
  13070. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13071. # endif
  13072. }
  13073. #endif
  13074. state4: /* XXX ??? - why isn't this before the "if" statement */
  13075. cmdloop(1);
  13076. }
  13077. #if PROFILE
  13078. monitor(0);
  13079. #endif
  13080. #ifdef GPROF
  13081. {
  13082. extern void _mcleanup(void);
  13083. _mcleanup();
  13084. }
  13085. #endif
  13086. TRACE(("End of main reached\n"));
  13087. exitshell();
  13088. /* NOTREACHED */
  13089. }
  13090. /*-
  13091. * Copyright (c) 1989, 1991, 1993, 1994
  13092. * The Regents of the University of California. All rights reserved.
  13093. *
  13094. * This code is derived from software contributed to Berkeley by
  13095. * Kenneth Almquist.
  13096. *
  13097. * Redistribution and use in source and binary forms, with or without
  13098. * modification, are permitted provided that the following conditions
  13099. * are met:
  13100. * 1. Redistributions of source code must retain the above copyright
  13101. * notice, this list of conditions and the following disclaimer.
  13102. * 2. Redistributions in binary form must reproduce the above copyright
  13103. * notice, this list of conditions and the following disclaimer in the
  13104. * documentation and/or other materials provided with the distribution.
  13105. * 3. Neither the name of the University nor the names of its contributors
  13106. * may be used to endorse or promote products derived from this software
  13107. * without specific prior written permission.
  13108. *
  13109. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13110. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13111. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13112. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13113. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13114. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13115. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13116. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13117. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13118. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13119. * SUCH DAMAGE.
  13120. */