ash.c 282 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034
  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 the GPL v2 or later, see the file LICENSE in this tarball.
  17. */
  18. /*
  19. * The following should be set to reflect the type of system you have:
  20. * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  21. * define SYSV if you are running under System V.
  22. * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
  23. * define DEBUG=2 to compile in and turn on debugging.
  24. *
  25. * When debugging is on, debugging info will be written to ./trace and
  26. * a quit signal will generate a core dump.
  27. */
  28. #define DEBUG 0
  29. /* Tweak debug output verbosity here */
  30. #define DEBUG_TIME 0
  31. #define DEBUG_PID 1
  32. #define DEBUG_SIG 1
  33. #define PROFILE 0
  34. #define JOBS ENABLE_ASH_JOB_CONTROL
  35. #if DEBUG
  36. # ifndef _GNU_SOURCE
  37. # define _GNU_SOURCE
  38. # endif
  39. #endif
  40. #include "busybox.h" /* for applet_names */
  41. #include <paths.h>
  42. #include <setjmp.h>
  43. #include <fnmatch.h>
  44. #include "shell_common.h"
  45. #include "builtin_read.h"
  46. #include "builtin_ulimit.h"
  47. #include "math.h"
  48. #if ENABLE_ASH_RANDOM_SUPPORT
  49. # include "random.h"
  50. #else
  51. # define CLEAR_RANDOM_T(rnd) ((void)0)
  52. #endif
  53. #define SKIP_definitions 1
  54. #include "applet_tables.h"
  55. #undef SKIP_definitions
  56. #if NUM_APPLETS == 1
  57. /* STANDALONE does not make sense, and won't compile */
  58. # undef CONFIG_FEATURE_SH_STANDALONE
  59. # undef ENABLE_FEATURE_SH_STANDALONE
  60. # undef IF_FEATURE_SH_STANDALONE
  61. # undef IF_NOT_FEATURE_SH_STANDALONE
  62. # define ENABLE_FEATURE_SH_STANDALONE 0
  63. # define IF_FEATURE_SH_STANDALONE(...)
  64. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  65. #endif
  66. #ifndef PIPE_BUF
  67. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  68. #endif
  69. #if !BB_MMU
  70. # error "Do not even bother, ash will not run on NOMMU machine"
  71. #endif
  72. /* ============ Hash table sizes. Configurable. */
  73. #define VTABSIZE 39
  74. #define ATABSIZE 39
  75. #define CMDTABLESIZE 31 /* should be prime */
  76. /* ============ Shell options */
  77. static const char *const optletters_optnames[] = {
  78. "e" "errexit",
  79. "f" "noglob",
  80. "I" "ignoreeof",
  81. "i" "interactive",
  82. "m" "monitor",
  83. "n" "noexec",
  84. "s" "stdin",
  85. "x" "xtrace",
  86. "v" "verbose",
  87. "C" "noclobber",
  88. "a" "allexport",
  89. "b" "notify",
  90. "u" "nounset",
  91. "\0" "vi"
  92. #if ENABLE_ASH_BASH_COMPAT
  93. ,"\0" "pipefail"
  94. #endif
  95. #if DEBUG
  96. ,"\0" "nolog"
  97. ,"\0" "debug"
  98. #endif
  99. };
  100. #define optletters(n) optletters_optnames[n][0]
  101. #define optnames(n) (optletters_optnames[n] + 1)
  102. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  103. /* ============ Misc data */
  104. static const char homestr[] ALIGN1 = "HOME";
  105. static const char snlfmt[] ALIGN1 = "%s\n";
  106. static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
  107. /*
  108. * We enclose jmp_buf in a structure so that we can declare pointers to
  109. * jump locations. The global variable handler contains the location to
  110. * jump to when an exception occurs, and the global variable exception_type
  111. * contains a code identifying the exception. To implement nested
  112. * exception handlers, the user should save the value of handler on entry
  113. * to an inner scope, set handler to point to a jmploc structure for the
  114. * inner scope, and restore handler on exit from the scope.
  115. */
  116. struct jmploc {
  117. jmp_buf loc;
  118. };
  119. struct globals_misc {
  120. /* pid of main shell */
  121. int rootpid;
  122. /* shell level: 0 for the main shell, 1 for its children, and so on */
  123. int shlvl;
  124. #define rootshell (!shlvl)
  125. char *minusc; /* argument to -c option */
  126. char *curdir; // = nullstr; /* current working directory */
  127. char *physdir; // = nullstr; /* physical working directory */
  128. char *arg0; /* value of $0 */
  129. struct jmploc *exception_handler;
  130. volatile int suppress_int; /* counter */
  131. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  132. /* last pending signal */
  133. volatile /*sig_atomic_t*/ smallint pending_sig;
  134. smallint exception_type; /* kind of exception (0..5) */
  135. /* exceptions */
  136. #define EXINT 0 /* SIGINT received */
  137. #define EXERROR 1 /* a generic error */
  138. #define EXSHELLPROC 2 /* execute a shell procedure */
  139. #define EXEXEC 3 /* command execution failed */
  140. #define EXEXIT 4 /* exit the shell */
  141. #define EXSIG 5 /* trapped signal in wait(1) */
  142. smallint isloginsh;
  143. char nullstr[1]; /* zero length string */
  144. char optlist[NOPTS];
  145. #define eflag optlist[0]
  146. #define fflag optlist[1]
  147. #define Iflag optlist[2]
  148. #define iflag optlist[3]
  149. #define mflag optlist[4]
  150. #define nflag optlist[5]
  151. #define sflag optlist[6]
  152. #define xflag optlist[7]
  153. #define vflag optlist[8]
  154. #define Cflag optlist[9]
  155. #define aflag optlist[10]
  156. #define bflag optlist[11]
  157. #define uflag optlist[12]
  158. #define viflag optlist[13]
  159. #if ENABLE_ASH_BASH_COMPAT
  160. # define pipefail optlist[14]
  161. #else
  162. # define pipefail 0
  163. #endif
  164. #if DEBUG
  165. # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
  166. # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
  167. #endif
  168. /* trap handler commands */
  169. /*
  170. * Sigmode records the current value of the signal handlers for the various
  171. * modes. A value of zero means that the current handler is not known.
  172. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  173. */
  174. char sigmode[NSIG - 1];
  175. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  176. #define S_CATCH 2 /* signal is caught */
  177. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  178. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  179. /* indicates specified signal received */
  180. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  181. char *trap[NSIG];
  182. char **trap_ptr; /* used only by "trap hack" */
  183. /* Rarely referenced stuff */
  184. #if ENABLE_ASH_RANDOM_SUPPORT
  185. random_t random_gen;
  186. #endif
  187. pid_t backgndpid; /* pid of last background process */
  188. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  189. };
  190. extern struct globals_misc *const ash_ptr_to_globals_misc;
  191. #define G_misc (*ash_ptr_to_globals_misc)
  192. #define rootpid (G_misc.rootpid )
  193. #define shlvl (G_misc.shlvl )
  194. #define minusc (G_misc.minusc )
  195. #define curdir (G_misc.curdir )
  196. #define physdir (G_misc.physdir )
  197. #define arg0 (G_misc.arg0 )
  198. #define exception_handler (G_misc.exception_handler)
  199. #define exception_type (G_misc.exception_type )
  200. #define suppress_int (G_misc.suppress_int )
  201. #define pending_int (G_misc.pending_int )
  202. #define pending_sig (G_misc.pending_sig )
  203. #define isloginsh (G_misc.isloginsh )
  204. #define nullstr (G_misc.nullstr )
  205. #define optlist (G_misc.optlist )
  206. #define sigmode (G_misc.sigmode )
  207. #define gotsig (G_misc.gotsig )
  208. #define trap (G_misc.trap )
  209. #define trap_ptr (G_misc.trap_ptr )
  210. #define random_gen (G_misc.random_gen )
  211. #define backgndpid (G_misc.backgndpid )
  212. #define job_warning (G_misc.job_warning)
  213. #define INIT_G_misc() do { \
  214. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  215. barrier(); \
  216. curdir = nullstr; \
  217. physdir = nullstr; \
  218. trap_ptr = trap; \
  219. } while (0)
  220. /* ============ DEBUG */
  221. #if DEBUG
  222. static void trace_printf(const char *fmt, ...);
  223. static void trace_vprintf(const char *fmt, va_list va);
  224. # define TRACE(param) trace_printf param
  225. # define TRACEV(param) trace_vprintf param
  226. # define close(fd) do { \
  227. int dfd = (fd); \
  228. if (close(dfd) < 0) \
  229. bb_error_msg("bug on %d: closing %d(0x%x)", \
  230. __LINE__, dfd, dfd); \
  231. } while (0)
  232. #else
  233. # define TRACE(param)
  234. # define TRACEV(param)
  235. #endif
  236. /* ============ Utility functions */
  237. #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
  238. static int isdigit_str9(const char *str)
  239. {
  240. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  241. while (--maxlen && isdigit(*str))
  242. str++;
  243. return (*str == '\0');
  244. }
  245. /* ============ Interrupts / exceptions */
  246. /*
  247. * These macros allow the user to suspend the handling of interrupt signals
  248. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  249. * much more efficient and portable. (But hacking the kernel is so much
  250. * more fun than worrying about efficiency and portability. :-))
  251. */
  252. #define INT_OFF do { \
  253. suppress_int++; \
  254. xbarrier(); \
  255. } while (0)
  256. /*
  257. * Called to raise an exception. Since C doesn't include exceptions, we
  258. * just do a longjmp to the exception handler. The type of exception is
  259. * stored in the global variable "exception_type".
  260. */
  261. static void raise_exception(int) NORETURN;
  262. static void
  263. raise_exception(int e)
  264. {
  265. #if DEBUG
  266. if (exception_handler == NULL)
  267. abort();
  268. #endif
  269. INT_OFF;
  270. exception_type = e;
  271. longjmp(exception_handler->loc, 1);
  272. }
  273. #if DEBUG
  274. #define raise_exception(e) do { \
  275. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  276. raise_exception(e); \
  277. } while (0)
  278. #endif
  279. /*
  280. * Called from trap.c when a SIGINT is received. (If the user specifies
  281. * that SIGINT is to be trapped or ignored using the trap builtin, then
  282. * this routine is not called.) Suppressint is nonzero when interrupts
  283. * are held using the INT_OFF macro. (The test for iflag is just
  284. * defensive programming.)
  285. */
  286. static void raise_interrupt(void) NORETURN;
  287. static void
  288. raise_interrupt(void)
  289. {
  290. int ex_type;
  291. pending_int = 0;
  292. /* Signal is not automatically unmasked after it is raised,
  293. * do it ourself - unmask all signals */
  294. sigprocmask_allsigs(SIG_UNBLOCK);
  295. /* pending_sig = 0; - now done in onsig() */
  296. ex_type = EXSIG;
  297. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  298. if (!(rootshell && iflag)) {
  299. /* Kill ourself with SIGINT */
  300. signal(SIGINT, SIG_DFL);
  301. raise(SIGINT);
  302. }
  303. ex_type = EXINT;
  304. }
  305. raise_exception(ex_type);
  306. /* NOTREACHED */
  307. }
  308. #if DEBUG
  309. #define raise_interrupt() do { \
  310. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  311. raise_interrupt(); \
  312. } while (0)
  313. #endif
  314. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  315. int_on(void)
  316. {
  317. xbarrier();
  318. if (--suppress_int == 0 && pending_int) {
  319. raise_interrupt();
  320. }
  321. }
  322. #define INT_ON int_on()
  323. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  324. force_int_on(void)
  325. {
  326. xbarrier();
  327. suppress_int = 0;
  328. if (pending_int)
  329. raise_interrupt();
  330. }
  331. #define FORCE_INT_ON force_int_on()
  332. #define SAVE_INT(v) ((v) = suppress_int)
  333. #define RESTORE_INT(v) do { \
  334. xbarrier(); \
  335. suppress_int = (v); \
  336. if (suppress_int == 0 && pending_int) \
  337. raise_interrupt(); \
  338. } while (0)
  339. /* ============ Stdout/stderr output */
  340. static void
  341. outstr(const char *p, FILE *file)
  342. {
  343. INT_OFF;
  344. fputs(p, file);
  345. INT_ON;
  346. }
  347. static void
  348. flush_stdout_stderr(void)
  349. {
  350. INT_OFF;
  351. fflush_all();
  352. INT_ON;
  353. }
  354. static void
  355. outcslow(int c, FILE *dest)
  356. {
  357. INT_OFF;
  358. putc(c, dest);
  359. fflush(dest);
  360. INT_ON;
  361. }
  362. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  363. static int
  364. out1fmt(const char *fmt, ...)
  365. {
  366. va_list ap;
  367. int r;
  368. INT_OFF;
  369. va_start(ap, fmt);
  370. r = vprintf(fmt, ap);
  371. va_end(ap);
  372. INT_ON;
  373. return r;
  374. }
  375. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  376. static int
  377. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  378. {
  379. va_list ap;
  380. int ret;
  381. va_start(ap, fmt);
  382. INT_OFF;
  383. ret = vsnprintf(outbuf, length, fmt, ap);
  384. va_end(ap);
  385. INT_ON;
  386. return ret;
  387. }
  388. static void
  389. out1str(const char *p)
  390. {
  391. outstr(p, stdout);
  392. }
  393. static void
  394. out2str(const char *p)
  395. {
  396. outstr(p, stderr);
  397. flush_stdout_stderr();
  398. }
  399. /* ============ Parser structures */
  400. /* control characters in argument strings */
  401. #define CTL_FIRST CTLESC
  402. #define CTLESC ((unsigned char)'\201') /* escape next character */
  403. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  404. #define CTLENDVAR ((unsigned char)'\203')
  405. #define CTLBACKQ ((unsigned char)'\204')
  406. #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
  407. /* CTLBACKQ | CTLQUOTE == '\205' */
  408. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  409. #define CTLENDARI ((unsigned char)'\207')
  410. #define CTLQUOTEMARK ((unsigned char)'\210')
  411. #define CTL_LAST CTLQUOTEMARK
  412. /* variable substitution byte (follows CTLVAR) */
  413. #define VSTYPE 0x0f /* type of variable substitution */
  414. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  415. #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
  416. /* values of VSTYPE field */
  417. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  418. #define VSMINUS 0x2 /* ${var-text} */
  419. #define VSPLUS 0x3 /* ${var+text} */
  420. #define VSQUESTION 0x4 /* ${var?message} */
  421. #define VSASSIGN 0x5 /* ${var=text} */
  422. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  423. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  424. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  425. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  426. #define VSLENGTH 0xa /* ${#var} */
  427. #if ENABLE_ASH_BASH_COMPAT
  428. #define VSSUBSTR 0xc /* ${var:position:length} */
  429. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  430. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  431. #endif
  432. static const char dolatstr[] ALIGN1 = {
  433. CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
  434. };
  435. #define NCMD 0
  436. #define NPIPE 1
  437. #define NREDIR 2
  438. #define NBACKGND 3
  439. #define NSUBSHELL 4
  440. #define NAND 5
  441. #define NOR 6
  442. #define NSEMI 7
  443. #define NIF 8
  444. #define NWHILE 9
  445. #define NUNTIL 10
  446. #define NFOR 11
  447. #define NCASE 12
  448. #define NCLIST 13
  449. #define NDEFUN 14
  450. #define NARG 15
  451. #define NTO 16
  452. #if ENABLE_ASH_BASH_COMPAT
  453. #define NTO2 17
  454. #endif
  455. #define NCLOBBER 18
  456. #define NFROM 19
  457. #define NFROMTO 20
  458. #define NAPPEND 21
  459. #define NTOFD 22
  460. #define NFROMFD 23
  461. #define NHERE 24
  462. #define NXHERE 25
  463. #define NNOT 26
  464. #define N_NUMBER 27
  465. union node;
  466. struct ncmd {
  467. smallint type; /* Nxxxx */
  468. union node *assign;
  469. union node *args;
  470. union node *redirect;
  471. };
  472. struct npipe {
  473. smallint type;
  474. smallint pipe_backgnd;
  475. struct nodelist *cmdlist;
  476. };
  477. struct nredir {
  478. smallint type;
  479. union node *n;
  480. union node *redirect;
  481. };
  482. struct nbinary {
  483. smallint type;
  484. union node *ch1;
  485. union node *ch2;
  486. };
  487. struct nif {
  488. smallint type;
  489. union node *test;
  490. union node *ifpart;
  491. union node *elsepart;
  492. };
  493. struct nfor {
  494. smallint type;
  495. union node *args;
  496. union node *body;
  497. char *var;
  498. };
  499. struct ncase {
  500. smallint type;
  501. union node *expr;
  502. union node *cases;
  503. };
  504. struct nclist {
  505. smallint type;
  506. union node *next;
  507. union node *pattern;
  508. union node *body;
  509. };
  510. struct narg {
  511. smallint type;
  512. union node *next;
  513. char *text;
  514. struct nodelist *backquote;
  515. };
  516. /* nfile and ndup layout must match!
  517. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  518. * that it is actually NTO2 (>&file), and change its type.
  519. */
  520. struct nfile {
  521. smallint type;
  522. union node *next;
  523. int fd;
  524. int _unused_dupfd;
  525. union node *fname;
  526. char *expfname;
  527. };
  528. struct ndup {
  529. smallint type;
  530. union node *next;
  531. int fd;
  532. int dupfd;
  533. union node *vname;
  534. char *_unused_expfname;
  535. };
  536. struct nhere {
  537. smallint type;
  538. union node *next;
  539. int fd;
  540. union node *doc;
  541. };
  542. struct nnot {
  543. smallint type;
  544. union node *com;
  545. };
  546. union node {
  547. smallint type;
  548. struct ncmd ncmd;
  549. struct npipe npipe;
  550. struct nredir nredir;
  551. struct nbinary nbinary;
  552. struct nif nif;
  553. struct nfor nfor;
  554. struct ncase ncase;
  555. struct nclist nclist;
  556. struct narg narg;
  557. struct nfile nfile;
  558. struct ndup ndup;
  559. struct nhere nhere;
  560. struct nnot nnot;
  561. };
  562. /*
  563. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  564. * It must be distinct from NULL.
  565. */
  566. #define NODE_EOF ((union node *) -1L)
  567. struct nodelist {
  568. struct nodelist *next;
  569. union node *n;
  570. };
  571. struct funcnode {
  572. int count;
  573. union node n;
  574. };
  575. /*
  576. * Free a parse tree.
  577. */
  578. static void
  579. freefunc(struct funcnode *f)
  580. {
  581. if (f && --f->count < 0)
  582. free(f);
  583. }
  584. /* ============ Debugging output */
  585. #if DEBUG
  586. static FILE *tracefile;
  587. static void
  588. trace_printf(const char *fmt, ...)
  589. {
  590. va_list va;
  591. if (debug != 1)
  592. return;
  593. if (DEBUG_TIME)
  594. fprintf(tracefile, "%u ", (int) time(NULL));
  595. if (DEBUG_PID)
  596. fprintf(tracefile, "[%u] ", (int) getpid());
  597. if (DEBUG_SIG)
  598. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  599. va_start(va, fmt);
  600. vfprintf(tracefile, fmt, va);
  601. va_end(va);
  602. }
  603. static void
  604. trace_vprintf(const char *fmt, va_list va)
  605. {
  606. if (debug != 1)
  607. return;
  608. if (DEBUG_TIME)
  609. fprintf(tracefile, "%u ", (int) time(NULL));
  610. if (DEBUG_PID)
  611. fprintf(tracefile, "[%u] ", (int) getpid());
  612. if (DEBUG_SIG)
  613. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  614. vfprintf(tracefile, fmt, va);
  615. }
  616. static void
  617. trace_puts(const char *s)
  618. {
  619. if (debug != 1)
  620. return;
  621. fputs(s, tracefile);
  622. }
  623. static void
  624. trace_puts_quoted(char *s)
  625. {
  626. char *p;
  627. char c;
  628. if (debug != 1)
  629. return;
  630. putc('"', tracefile);
  631. for (p = s; *p; p++) {
  632. switch ((unsigned char)*p) {
  633. case '\n': c = 'n'; goto backslash;
  634. case '\t': c = 't'; goto backslash;
  635. case '\r': c = 'r'; goto backslash;
  636. case '\"': c = '\"'; goto backslash;
  637. case '\\': c = '\\'; goto backslash;
  638. case CTLESC: c = 'e'; goto backslash;
  639. case CTLVAR: c = 'v'; goto backslash;
  640. case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
  641. case CTLBACKQ: c = 'q'; goto backslash;
  642. case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
  643. backslash:
  644. putc('\\', tracefile);
  645. putc(c, tracefile);
  646. break;
  647. default:
  648. if (*p >= ' ' && *p <= '~')
  649. putc(*p, tracefile);
  650. else {
  651. putc('\\', tracefile);
  652. putc((*p >> 6) & 03, tracefile);
  653. putc((*p >> 3) & 07, tracefile);
  654. putc(*p & 07, tracefile);
  655. }
  656. break;
  657. }
  658. }
  659. putc('"', tracefile);
  660. }
  661. static void
  662. trace_puts_args(char **ap)
  663. {
  664. if (debug != 1)
  665. return;
  666. if (!*ap)
  667. return;
  668. while (1) {
  669. trace_puts_quoted(*ap);
  670. if (!*++ap) {
  671. putc('\n', tracefile);
  672. break;
  673. }
  674. putc(' ', tracefile);
  675. }
  676. }
  677. static void
  678. opentrace(void)
  679. {
  680. char s[100];
  681. #ifdef O_APPEND
  682. int flags;
  683. #endif
  684. if (debug != 1) {
  685. if (tracefile)
  686. fflush(tracefile);
  687. /* leave open because libedit might be using it */
  688. return;
  689. }
  690. strcpy(s, "./trace");
  691. if (tracefile) {
  692. if (!freopen(s, "a", tracefile)) {
  693. fprintf(stderr, "Can't re-open %s\n", s);
  694. debug = 0;
  695. return;
  696. }
  697. } else {
  698. tracefile = fopen(s, "a");
  699. if (tracefile == NULL) {
  700. fprintf(stderr, "Can't open %s\n", s);
  701. debug = 0;
  702. return;
  703. }
  704. }
  705. #ifdef O_APPEND
  706. flags = fcntl(fileno(tracefile), F_GETFL);
  707. if (flags >= 0)
  708. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  709. #endif
  710. setlinebuf(tracefile);
  711. fputs("\nTracing started.\n", tracefile);
  712. }
  713. static void
  714. indent(int amount, char *pfx, FILE *fp)
  715. {
  716. int i;
  717. for (i = 0; i < amount; i++) {
  718. if (pfx && i == amount - 1)
  719. fputs(pfx, fp);
  720. putc('\t', fp);
  721. }
  722. }
  723. /* little circular references here... */
  724. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  725. static void
  726. sharg(union node *arg, FILE *fp)
  727. {
  728. char *p;
  729. struct nodelist *bqlist;
  730. unsigned char subtype;
  731. if (arg->type != NARG) {
  732. out1fmt("<node type %d>\n", arg->type);
  733. abort();
  734. }
  735. bqlist = arg->narg.backquote;
  736. for (p = arg->narg.text; *p; p++) {
  737. switch ((unsigned char)*p) {
  738. case CTLESC:
  739. putc(*++p, fp);
  740. break;
  741. case CTLVAR:
  742. putc('$', fp);
  743. putc('{', fp);
  744. subtype = *++p;
  745. if (subtype == VSLENGTH)
  746. putc('#', fp);
  747. while (*p != '=')
  748. putc(*p++, fp);
  749. if (subtype & VSNUL)
  750. putc(':', fp);
  751. switch (subtype & VSTYPE) {
  752. case VSNORMAL:
  753. putc('}', fp);
  754. break;
  755. case VSMINUS:
  756. putc('-', fp);
  757. break;
  758. case VSPLUS:
  759. putc('+', fp);
  760. break;
  761. case VSQUESTION:
  762. putc('?', fp);
  763. break;
  764. case VSASSIGN:
  765. putc('=', fp);
  766. break;
  767. case VSTRIMLEFT:
  768. putc('#', fp);
  769. break;
  770. case VSTRIMLEFTMAX:
  771. putc('#', fp);
  772. putc('#', fp);
  773. break;
  774. case VSTRIMRIGHT:
  775. putc('%', fp);
  776. break;
  777. case VSTRIMRIGHTMAX:
  778. putc('%', fp);
  779. putc('%', fp);
  780. break;
  781. case VSLENGTH:
  782. break;
  783. default:
  784. out1fmt("<subtype %d>", subtype);
  785. }
  786. break;
  787. case CTLENDVAR:
  788. putc('}', fp);
  789. break;
  790. case CTLBACKQ:
  791. case CTLBACKQ|CTLQUOTE:
  792. putc('$', fp);
  793. putc('(', fp);
  794. shtree(bqlist->n, -1, NULL, fp);
  795. putc(')', fp);
  796. break;
  797. default:
  798. putc(*p, fp);
  799. break;
  800. }
  801. }
  802. }
  803. static void
  804. shcmd(union node *cmd, FILE *fp)
  805. {
  806. union node *np;
  807. int first;
  808. const char *s;
  809. int dftfd;
  810. first = 1;
  811. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  812. if (!first)
  813. putc(' ', fp);
  814. sharg(np, fp);
  815. first = 0;
  816. }
  817. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  818. if (!first)
  819. putc(' ', fp);
  820. dftfd = 0;
  821. switch (np->nfile.type) {
  822. case NTO: s = ">>"+1; dftfd = 1; break;
  823. case NCLOBBER: s = ">|"; dftfd = 1; break;
  824. case NAPPEND: s = ">>"; dftfd = 1; break;
  825. #if ENABLE_ASH_BASH_COMPAT
  826. case NTO2:
  827. #endif
  828. case NTOFD: s = ">&"; dftfd = 1; break;
  829. case NFROM: s = "<"; break;
  830. case NFROMFD: s = "<&"; break;
  831. case NFROMTO: s = "<>"; break;
  832. default: s = "*error*"; break;
  833. }
  834. if (np->nfile.fd != dftfd)
  835. fprintf(fp, "%d", np->nfile.fd);
  836. fputs(s, fp);
  837. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  838. fprintf(fp, "%d", np->ndup.dupfd);
  839. } else {
  840. sharg(np->nfile.fname, fp);
  841. }
  842. first = 0;
  843. }
  844. }
  845. static void
  846. shtree(union node *n, int ind, char *pfx, FILE *fp)
  847. {
  848. struct nodelist *lp;
  849. const char *s;
  850. if (n == NULL)
  851. return;
  852. indent(ind, pfx, fp);
  853. if (n == NODE_EOF) {
  854. fputs("<EOF>", fp);
  855. return;
  856. }
  857. switch (n->type) {
  858. case NSEMI:
  859. s = "; ";
  860. goto binop;
  861. case NAND:
  862. s = " && ";
  863. goto binop;
  864. case NOR:
  865. s = " || ";
  866. binop:
  867. shtree(n->nbinary.ch1, ind, NULL, fp);
  868. /* if (ind < 0) */
  869. fputs(s, fp);
  870. shtree(n->nbinary.ch2, ind, NULL, fp);
  871. break;
  872. case NCMD:
  873. shcmd(n, fp);
  874. if (ind >= 0)
  875. putc('\n', fp);
  876. break;
  877. case NPIPE:
  878. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  879. shtree(lp->n, 0, NULL, fp);
  880. if (lp->next)
  881. fputs(" | ", fp);
  882. }
  883. if (n->npipe.pipe_backgnd)
  884. fputs(" &", fp);
  885. if (ind >= 0)
  886. putc('\n', fp);
  887. break;
  888. default:
  889. fprintf(fp, "<node type %d>", n->type);
  890. if (ind >= 0)
  891. putc('\n', fp);
  892. break;
  893. }
  894. }
  895. static void
  896. showtree(union node *n)
  897. {
  898. trace_puts("showtree called\n");
  899. shtree(n, 1, NULL, stderr);
  900. }
  901. #endif /* DEBUG */
  902. /* ============ Parser data */
  903. /*
  904. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  905. */
  906. struct strlist {
  907. struct strlist *next;
  908. char *text;
  909. };
  910. struct alias;
  911. struct strpush {
  912. struct strpush *prev; /* preceding string on stack */
  913. char *prev_string;
  914. int prev_left_in_line;
  915. #if ENABLE_ASH_ALIAS
  916. struct alias *ap; /* if push was associated with an alias */
  917. #endif
  918. char *string; /* remember the string since it may change */
  919. };
  920. struct parsefile {
  921. struct parsefile *prev; /* preceding file on stack */
  922. int linno; /* current line */
  923. int fd; /* file descriptor (or -1 if string) */
  924. int left_in_line; /* number of chars left in this line */
  925. int left_in_buffer; /* number of chars left in this buffer past the line */
  926. char *next_to_pgetc; /* next char in buffer */
  927. char *buf; /* input buffer */
  928. struct strpush *strpush; /* for pushing strings at this level */
  929. struct strpush basestrpush; /* so pushing one is fast */
  930. };
  931. static struct parsefile basepf; /* top level input file */
  932. static struct parsefile *g_parsefile = &basepf; /* current input file */
  933. static int startlinno; /* line # where last token started */
  934. static char *commandname; /* currently executing command */
  935. static struct strlist *cmdenviron; /* environment for builtin command */
  936. static uint8_t exitstatus; /* exit status of last command */
  937. /* ============ Message printing */
  938. static void
  939. ash_vmsg(const char *msg, va_list ap)
  940. {
  941. fprintf(stderr, "%s: ", arg0);
  942. if (commandname) {
  943. if (strcmp(arg0, commandname))
  944. fprintf(stderr, "%s: ", commandname);
  945. if (!iflag || g_parsefile->fd)
  946. fprintf(stderr, "line %d: ", startlinno);
  947. }
  948. vfprintf(stderr, msg, ap);
  949. outcslow('\n', stderr);
  950. }
  951. /*
  952. * Exverror is called to raise the error exception. If the second argument
  953. * is not NULL then error prints an error message using printf style
  954. * formatting. It then raises the error exception.
  955. */
  956. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  957. static void
  958. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  959. {
  960. #if DEBUG
  961. if (msg) {
  962. TRACE(("ash_vmsg_and_raise(%d, \"", cond));
  963. TRACEV((msg, ap));
  964. TRACE(("\") pid=%d\n", getpid()));
  965. } else
  966. TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
  967. if (msg)
  968. #endif
  969. ash_vmsg(msg, ap);
  970. flush_stdout_stderr();
  971. raise_exception(cond);
  972. /* NOTREACHED */
  973. }
  974. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  975. static void
  976. ash_msg_and_raise_error(const char *msg, ...)
  977. {
  978. va_list ap;
  979. va_start(ap, msg);
  980. ash_vmsg_and_raise(EXERROR, msg, ap);
  981. /* NOTREACHED */
  982. va_end(ap);
  983. }
  984. static void raise_error_syntax(const char *) NORETURN;
  985. static void
  986. raise_error_syntax(const char *msg)
  987. {
  988. ash_msg_and_raise_error("syntax error: %s", msg);
  989. /* NOTREACHED */
  990. }
  991. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  992. static void
  993. ash_msg_and_raise(int cond, const char *msg, ...)
  994. {
  995. va_list ap;
  996. va_start(ap, msg);
  997. ash_vmsg_and_raise(cond, msg, ap);
  998. /* NOTREACHED */
  999. va_end(ap);
  1000. }
  1001. /*
  1002. * error/warning routines for external builtins
  1003. */
  1004. static void
  1005. ash_msg(const char *fmt, ...)
  1006. {
  1007. va_list ap;
  1008. va_start(ap, fmt);
  1009. ash_vmsg(fmt, ap);
  1010. va_end(ap);
  1011. }
  1012. /*
  1013. * Return a string describing an error. The returned string may be a
  1014. * pointer to a static buffer that will be overwritten on the next call.
  1015. * Action describes the operation that got the error.
  1016. */
  1017. static const char *
  1018. errmsg(int e, const char *em)
  1019. {
  1020. if (e == ENOENT || e == ENOTDIR) {
  1021. return em;
  1022. }
  1023. return strerror(e);
  1024. }
  1025. /* ============ Memory allocation */
  1026. #if 0
  1027. /* I consider these wrappers nearly useless:
  1028. * ok, they return you to nearest exception handler, but
  1029. * how much memory do you leak in the process, making
  1030. * memory starvation worse?
  1031. */
  1032. static void *
  1033. ckrealloc(void * p, size_t nbytes)
  1034. {
  1035. p = realloc(p, nbytes);
  1036. if (!p)
  1037. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1038. return p;
  1039. }
  1040. static void *
  1041. ckmalloc(size_t nbytes)
  1042. {
  1043. return ckrealloc(NULL, nbytes);
  1044. }
  1045. static void *
  1046. ckzalloc(size_t nbytes)
  1047. {
  1048. return memset(ckmalloc(nbytes), 0, nbytes);
  1049. }
  1050. static char *
  1051. ckstrdup(const char *s)
  1052. {
  1053. char *p = strdup(s);
  1054. if (!p)
  1055. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1056. return p;
  1057. }
  1058. #else
  1059. /* Using bbox equivalents. They exit if out of memory */
  1060. # define ckrealloc xrealloc
  1061. # define ckmalloc xmalloc
  1062. # define ckzalloc xzalloc
  1063. # define ckstrdup xstrdup
  1064. #endif
  1065. /*
  1066. * It appears that grabstackstr() will barf with such alignments
  1067. * because stalloc() will return a string allocated in a new stackblock.
  1068. */
  1069. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1070. enum {
  1071. /* Most machines require the value returned from malloc to be aligned
  1072. * in some way. The following macro will get this right
  1073. * on many machines. */
  1074. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1075. /* Minimum size of a block */
  1076. MINSIZE = SHELL_ALIGN(504),
  1077. };
  1078. struct stack_block {
  1079. struct stack_block *prev;
  1080. char space[MINSIZE];
  1081. };
  1082. struct stackmark {
  1083. struct stack_block *stackp;
  1084. char *stacknxt;
  1085. size_t stacknleft;
  1086. struct stackmark *marknext;
  1087. };
  1088. struct globals_memstack {
  1089. struct stack_block *g_stackp; // = &stackbase;
  1090. struct stackmark *markp;
  1091. char *g_stacknxt; // = stackbase.space;
  1092. char *sstrend; // = stackbase.space + MINSIZE;
  1093. size_t g_stacknleft; // = MINSIZE;
  1094. int herefd; // = -1;
  1095. struct stack_block stackbase;
  1096. };
  1097. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1098. #define G_memstack (*ash_ptr_to_globals_memstack)
  1099. #define g_stackp (G_memstack.g_stackp )
  1100. #define markp (G_memstack.markp )
  1101. #define g_stacknxt (G_memstack.g_stacknxt )
  1102. #define sstrend (G_memstack.sstrend )
  1103. #define g_stacknleft (G_memstack.g_stacknleft)
  1104. #define herefd (G_memstack.herefd )
  1105. #define stackbase (G_memstack.stackbase )
  1106. #define INIT_G_memstack() do { \
  1107. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1108. barrier(); \
  1109. g_stackp = &stackbase; \
  1110. g_stacknxt = stackbase.space; \
  1111. g_stacknleft = MINSIZE; \
  1112. sstrend = stackbase.space + MINSIZE; \
  1113. herefd = -1; \
  1114. } while (0)
  1115. #define stackblock() ((void *)g_stacknxt)
  1116. #define stackblocksize() g_stacknleft
  1117. /*
  1118. * Parse trees for commands are allocated in lifo order, so we use a stack
  1119. * to make this more efficient, and also to avoid all sorts of exception
  1120. * handling code to handle interrupts in the middle of a parse.
  1121. *
  1122. * The size 504 was chosen because the Ultrix malloc handles that size
  1123. * well.
  1124. */
  1125. static void *
  1126. stalloc(size_t nbytes)
  1127. {
  1128. char *p;
  1129. size_t aligned;
  1130. aligned = SHELL_ALIGN(nbytes);
  1131. if (aligned > g_stacknleft) {
  1132. size_t len;
  1133. size_t blocksize;
  1134. struct stack_block *sp;
  1135. blocksize = aligned;
  1136. if (blocksize < MINSIZE)
  1137. blocksize = MINSIZE;
  1138. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1139. if (len < blocksize)
  1140. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1141. INT_OFF;
  1142. sp = ckmalloc(len);
  1143. sp->prev = g_stackp;
  1144. g_stacknxt = sp->space;
  1145. g_stacknleft = blocksize;
  1146. sstrend = g_stacknxt + blocksize;
  1147. g_stackp = sp;
  1148. INT_ON;
  1149. }
  1150. p = g_stacknxt;
  1151. g_stacknxt += aligned;
  1152. g_stacknleft -= aligned;
  1153. return p;
  1154. }
  1155. static void *
  1156. stzalloc(size_t nbytes)
  1157. {
  1158. return memset(stalloc(nbytes), 0, nbytes);
  1159. }
  1160. static void
  1161. stunalloc(void *p)
  1162. {
  1163. #if DEBUG
  1164. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1165. write(STDERR_FILENO, "stunalloc\n", 10);
  1166. abort();
  1167. }
  1168. #endif
  1169. g_stacknleft += g_stacknxt - (char *)p;
  1170. g_stacknxt = p;
  1171. }
  1172. /*
  1173. * Like strdup but works with the ash stack.
  1174. */
  1175. static char *
  1176. ststrdup(const char *p)
  1177. {
  1178. size_t len = strlen(p) + 1;
  1179. return memcpy(stalloc(len), p, len);
  1180. }
  1181. static void
  1182. setstackmark(struct stackmark *mark)
  1183. {
  1184. mark->stackp = g_stackp;
  1185. mark->stacknxt = g_stacknxt;
  1186. mark->stacknleft = g_stacknleft;
  1187. mark->marknext = markp;
  1188. markp = mark;
  1189. }
  1190. static void
  1191. popstackmark(struct stackmark *mark)
  1192. {
  1193. struct stack_block *sp;
  1194. if (!mark->stackp)
  1195. return;
  1196. INT_OFF;
  1197. markp = mark->marknext;
  1198. while (g_stackp != mark->stackp) {
  1199. sp = g_stackp;
  1200. g_stackp = sp->prev;
  1201. free(sp);
  1202. }
  1203. g_stacknxt = mark->stacknxt;
  1204. g_stacknleft = mark->stacknleft;
  1205. sstrend = mark->stacknxt + mark->stacknleft;
  1206. INT_ON;
  1207. }
  1208. /*
  1209. * When the parser reads in a string, it wants to stick the string on the
  1210. * stack and only adjust the stack pointer when it knows how big the
  1211. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1212. * of space on top of the stack and stackblocklen returns the length of
  1213. * this block. Growstackblock will grow this space by at least one byte,
  1214. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1215. * part of the block that has been used.
  1216. */
  1217. static void
  1218. growstackblock(void)
  1219. {
  1220. size_t newlen;
  1221. newlen = g_stacknleft * 2;
  1222. if (newlen < g_stacknleft)
  1223. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1224. if (newlen < 128)
  1225. newlen += 128;
  1226. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1227. struct stack_block *oldstackp;
  1228. struct stackmark *xmark;
  1229. struct stack_block *sp;
  1230. struct stack_block *prevstackp;
  1231. size_t grosslen;
  1232. INT_OFF;
  1233. oldstackp = g_stackp;
  1234. sp = g_stackp;
  1235. prevstackp = sp->prev;
  1236. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1237. sp = ckrealloc(sp, grosslen);
  1238. sp->prev = prevstackp;
  1239. g_stackp = sp;
  1240. g_stacknxt = sp->space;
  1241. g_stacknleft = newlen;
  1242. sstrend = sp->space + newlen;
  1243. /*
  1244. * Stack marks pointing to the start of the old block
  1245. * must be relocated to point to the new block
  1246. */
  1247. xmark = markp;
  1248. while (xmark != NULL && xmark->stackp == oldstackp) {
  1249. xmark->stackp = g_stackp;
  1250. xmark->stacknxt = g_stacknxt;
  1251. xmark->stacknleft = g_stacknleft;
  1252. xmark = xmark->marknext;
  1253. }
  1254. INT_ON;
  1255. } else {
  1256. char *oldspace = g_stacknxt;
  1257. size_t oldlen = g_stacknleft;
  1258. char *p = stalloc(newlen);
  1259. /* free the space we just allocated */
  1260. g_stacknxt = memcpy(p, oldspace, oldlen);
  1261. g_stacknleft += newlen;
  1262. }
  1263. }
  1264. static void
  1265. grabstackblock(size_t len)
  1266. {
  1267. len = SHELL_ALIGN(len);
  1268. g_stacknxt += len;
  1269. g_stacknleft -= len;
  1270. }
  1271. /*
  1272. * The following routines are somewhat easier to use than the above.
  1273. * The user declares a variable of type STACKSTR, which may be declared
  1274. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1275. * the user uses the macro STPUTC to add characters to the string. In
  1276. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1277. * grown as necessary. When the user is done, she can just leave the
  1278. * string there and refer to it using stackblock(). Or she can allocate
  1279. * the space for it using grabstackstr(). If it is necessary to allow
  1280. * someone else to use the stack temporarily and then continue to grow
  1281. * the string, the user should use grabstack to allocate the space, and
  1282. * then call ungrabstr(p) to return to the previous mode of operation.
  1283. *
  1284. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1285. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1286. * is space for at least one character.
  1287. */
  1288. static void *
  1289. growstackstr(void)
  1290. {
  1291. size_t len = stackblocksize();
  1292. if (herefd >= 0 && len >= 1024) {
  1293. full_write(herefd, stackblock(), len);
  1294. return stackblock();
  1295. }
  1296. growstackblock();
  1297. return (char *)stackblock() + len;
  1298. }
  1299. /*
  1300. * Called from CHECKSTRSPACE.
  1301. */
  1302. static char *
  1303. makestrspace(size_t newlen, char *p)
  1304. {
  1305. size_t len = p - g_stacknxt;
  1306. size_t size = stackblocksize();
  1307. for (;;) {
  1308. size_t nleft;
  1309. size = stackblocksize();
  1310. nleft = size - len;
  1311. if (nleft >= newlen)
  1312. break;
  1313. growstackblock();
  1314. }
  1315. return (char *)stackblock() + len;
  1316. }
  1317. static char *
  1318. stack_nputstr(const char *s, size_t n, char *p)
  1319. {
  1320. p = makestrspace(n, p);
  1321. p = (char *)memcpy(p, s, n) + n;
  1322. return p;
  1323. }
  1324. static char *
  1325. stack_putstr(const char *s, char *p)
  1326. {
  1327. return stack_nputstr(s, strlen(s), p);
  1328. }
  1329. static char *
  1330. _STPUTC(int c, char *p)
  1331. {
  1332. if (p == sstrend)
  1333. p = growstackstr();
  1334. *p++ = c;
  1335. return p;
  1336. }
  1337. #define STARTSTACKSTR(p) ((p) = stackblock())
  1338. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1339. #define CHECKSTRSPACE(n, p) do { \
  1340. char *q = (p); \
  1341. size_t l = (n); \
  1342. size_t m = sstrend - q; \
  1343. if (l > m) \
  1344. (p) = makestrspace(l, q); \
  1345. } while (0)
  1346. #define USTPUTC(c, p) (*(p)++ = (c))
  1347. #define STACKSTRNUL(p) do { \
  1348. if ((p) == sstrend) \
  1349. (p) = growstackstr(); \
  1350. *(p) = '\0'; \
  1351. } while (0)
  1352. #define STUNPUTC(p) (--(p))
  1353. #define STTOPC(p) ((p)[-1])
  1354. #define STADJUST(amount, p) ((p) += (amount))
  1355. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1356. #define ungrabstackstr(s, p) stunalloc(s)
  1357. #define stackstrend() ((void *)sstrend)
  1358. /* ============ String helpers */
  1359. /*
  1360. * prefix -- see if pfx is a prefix of string.
  1361. */
  1362. static char *
  1363. prefix(const char *string, const char *pfx)
  1364. {
  1365. while (*pfx) {
  1366. if (*pfx++ != *string++)
  1367. return NULL;
  1368. }
  1369. return (char *) string;
  1370. }
  1371. /*
  1372. * Check for a valid number. This should be elsewhere.
  1373. */
  1374. static int
  1375. is_number(const char *p)
  1376. {
  1377. do {
  1378. if (!isdigit(*p))
  1379. return 0;
  1380. } while (*++p != '\0');
  1381. return 1;
  1382. }
  1383. /*
  1384. * Convert a string of digits to an integer, printing an error message on
  1385. * failure.
  1386. */
  1387. static int
  1388. number(const char *s)
  1389. {
  1390. if (!is_number(s))
  1391. ash_msg_and_raise_error(msg_illnum, s);
  1392. return atoi(s);
  1393. }
  1394. /*
  1395. * Produce a possibly single quoted string suitable as input to the shell.
  1396. * The return string is allocated on the stack.
  1397. */
  1398. static char *
  1399. single_quote(const char *s)
  1400. {
  1401. char *p;
  1402. STARTSTACKSTR(p);
  1403. do {
  1404. char *q;
  1405. size_t len;
  1406. len = strchrnul(s, '\'') - s;
  1407. q = p = makestrspace(len + 3, p);
  1408. *q++ = '\'';
  1409. q = (char *)memcpy(q, s, len) + len;
  1410. *q++ = '\'';
  1411. s += len;
  1412. STADJUST(q - p, p);
  1413. if (*s != '\'')
  1414. break;
  1415. len = 0;
  1416. do len++; while (*++s == '\'');
  1417. q = p = makestrspace(len + 3, p);
  1418. *q++ = '"';
  1419. q = (char *)memcpy(q, s - len, len) + len;
  1420. *q++ = '"';
  1421. STADJUST(q - p, p);
  1422. } while (*s);
  1423. USTPUTC('\0', p);
  1424. return stackblock();
  1425. }
  1426. /* ============ nextopt */
  1427. static char **argptr; /* argument list for builtin commands */
  1428. static char *optionarg; /* set by nextopt (like getopt) */
  1429. static char *optptr; /* used by nextopt */
  1430. /*
  1431. * XXX - should get rid of. Have all builtins use getopt(3).
  1432. * The library getopt must have the BSD extension static variable
  1433. * "optreset", otherwise it can't be used within the shell safely.
  1434. *
  1435. * Standard option processing (a la getopt) for builtin routines.
  1436. * The only argument that is passed to nextopt is the option string;
  1437. * the other arguments are unnecessary. It returns the character,
  1438. * or '\0' on end of input.
  1439. */
  1440. static int
  1441. nextopt(const char *optstring)
  1442. {
  1443. char *p;
  1444. const char *q;
  1445. char c;
  1446. p = optptr;
  1447. if (p == NULL || *p == '\0') {
  1448. /* We ate entire "-param", take next one */
  1449. p = *argptr;
  1450. if (p == NULL)
  1451. return '\0';
  1452. if (*p != '-')
  1453. return '\0';
  1454. if (*++p == '\0') /* just "-" ? */
  1455. return '\0';
  1456. argptr++;
  1457. if (LONE_DASH(p)) /* "--" ? */
  1458. return '\0';
  1459. /* p => next "-param" */
  1460. }
  1461. /* p => some option char in the middle of a "-param" */
  1462. c = *p++;
  1463. for (q = optstring; *q != c;) {
  1464. if (*q == '\0')
  1465. ash_msg_and_raise_error("illegal option -%c", c);
  1466. if (*++q == ':')
  1467. q++;
  1468. }
  1469. if (*++q == ':') {
  1470. if (*p == '\0') {
  1471. p = *argptr++;
  1472. if (p == NULL)
  1473. ash_msg_and_raise_error("no arg for -%c option", c);
  1474. }
  1475. optionarg = p;
  1476. p = NULL;
  1477. }
  1478. optptr = p;
  1479. return c;
  1480. }
  1481. /* ============ Shell variables */
  1482. /*
  1483. * The parsefile structure pointed to by the global variable parsefile
  1484. * contains information about the current file being read.
  1485. */
  1486. struct shparam {
  1487. int nparam; /* # of positional parameters (without $0) */
  1488. #if ENABLE_ASH_GETOPTS
  1489. int optind; /* next parameter to be processed by getopts */
  1490. int optoff; /* used by getopts */
  1491. #endif
  1492. unsigned char malloced; /* if parameter list dynamically allocated */
  1493. char **p; /* parameter list */
  1494. };
  1495. /*
  1496. * Free the list of positional parameters.
  1497. */
  1498. static void
  1499. freeparam(volatile struct shparam *param)
  1500. {
  1501. if (param->malloced) {
  1502. char **ap, **ap1;
  1503. ap = ap1 = param->p;
  1504. while (*ap)
  1505. free(*ap++);
  1506. free(ap1);
  1507. }
  1508. }
  1509. #if ENABLE_ASH_GETOPTS
  1510. static void FAST_FUNC getoptsreset(const char *value);
  1511. #endif
  1512. struct var {
  1513. struct var *next; /* next entry in hash list */
  1514. int flags; /* flags are defined above */
  1515. const char *text; /* name=value */
  1516. void (*func)(const char *) FAST_FUNC; /* function to be called when */
  1517. /* the variable gets set/unset */
  1518. };
  1519. struct localvar {
  1520. struct localvar *next; /* next local variable in list */
  1521. struct var *vp; /* the variable that was made local */
  1522. int flags; /* saved flags */
  1523. const char *text; /* saved text */
  1524. };
  1525. /* flags */
  1526. #define VEXPORT 0x01 /* variable is exported */
  1527. #define VREADONLY 0x02 /* variable cannot be modified */
  1528. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1529. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1530. #define VSTACK 0x10 /* text is allocated on the stack */
  1531. #define VUNSET 0x20 /* the variable is not set */
  1532. #define VNOFUNC 0x40 /* don't call the callback function */
  1533. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1534. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1535. #if ENABLE_ASH_RANDOM_SUPPORT
  1536. # define VDYNAMIC 0x200 /* dynamic variable */
  1537. #else
  1538. # define VDYNAMIC 0
  1539. #endif
  1540. /* Need to be before varinit_data[] */
  1541. #if ENABLE_LOCALE_SUPPORT
  1542. static void FAST_FUNC
  1543. change_lc_all(const char *value)
  1544. {
  1545. if (value && *value != '\0')
  1546. setlocale(LC_ALL, value);
  1547. }
  1548. static void FAST_FUNC
  1549. change_lc_ctype(const char *value)
  1550. {
  1551. if (value && *value != '\0')
  1552. setlocale(LC_CTYPE, value);
  1553. }
  1554. #endif
  1555. #if ENABLE_ASH_MAIL
  1556. static void chkmail(void);
  1557. static void changemail(const char *) FAST_FUNC;
  1558. #endif
  1559. static void changepath(const char *) FAST_FUNC;
  1560. #if ENABLE_ASH_RANDOM_SUPPORT
  1561. static void change_random(const char *) FAST_FUNC;
  1562. #endif
  1563. static const struct {
  1564. int flags;
  1565. const char *text;
  1566. void (*func)(const char *) FAST_FUNC;
  1567. } varinit_data[] = {
  1568. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1569. #if ENABLE_ASH_MAIL
  1570. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
  1571. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
  1572. #endif
  1573. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1574. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1575. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1576. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1577. #if ENABLE_ASH_GETOPTS
  1578. { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
  1579. #endif
  1580. #if ENABLE_ASH_RANDOM_SUPPORT
  1581. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
  1582. #endif
  1583. #if ENABLE_LOCALE_SUPPORT
  1584. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
  1585. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
  1586. #endif
  1587. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1588. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
  1589. #endif
  1590. };
  1591. struct redirtab;
  1592. struct globals_var {
  1593. struct shparam shellparam; /* $@ current positional parameters */
  1594. struct redirtab *redirlist;
  1595. int g_nullredirs;
  1596. int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1597. struct var *vartab[VTABSIZE];
  1598. struct var varinit[ARRAY_SIZE(varinit_data)];
  1599. };
  1600. extern struct globals_var *const ash_ptr_to_globals_var;
  1601. #define G_var (*ash_ptr_to_globals_var)
  1602. #define shellparam (G_var.shellparam )
  1603. //#define redirlist (G_var.redirlist )
  1604. #define g_nullredirs (G_var.g_nullredirs )
  1605. #define preverrout_fd (G_var.preverrout_fd)
  1606. #define vartab (G_var.vartab )
  1607. #define varinit (G_var.varinit )
  1608. #define INIT_G_var() do { \
  1609. unsigned i; \
  1610. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1611. barrier(); \
  1612. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1613. varinit[i].flags = varinit_data[i].flags; \
  1614. varinit[i].text = varinit_data[i].text; \
  1615. varinit[i].func = varinit_data[i].func; \
  1616. } \
  1617. } while (0)
  1618. #define vifs varinit[0]
  1619. #if ENABLE_ASH_MAIL
  1620. # define vmail (&vifs)[1]
  1621. # define vmpath (&vmail)[1]
  1622. # define vpath (&vmpath)[1]
  1623. #else
  1624. # define vpath (&vifs)[1]
  1625. #endif
  1626. #define vps1 (&vpath)[1]
  1627. #define vps2 (&vps1)[1]
  1628. #define vps4 (&vps2)[1]
  1629. #if ENABLE_ASH_GETOPTS
  1630. # define voptind (&vps4)[1]
  1631. # if ENABLE_ASH_RANDOM_SUPPORT
  1632. # define vrandom (&voptind)[1]
  1633. # endif
  1634. #else
  1635. # if ENABLE_ASH_RANDOM_SUPPORT
  1636. # define vrandom (&vps4)[1]
  1637. # endif
  1638. #endif
  1639. /*
  1640. * The following macros access the values of the above variables.
  1641. * They have to skip over the name. They return the null string
  1642. * for unset variables.
  1643. */
  1644. #define ifsval() (vifs.text + 4)
  1645. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1646. #if ENABLE_ASH_MAIL
  1647. # define mailval() (vmail.text + 5)
  1648. # define mpathval() (vmpath.text + 9)
  1649. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1650. #endif
  1651. #define pathval() (vpath.text + 5)
  1652. #define ps1val() (vps1.text + 4)
  1653. #define ps2val() (vps2.text + 4)
  1654. #define ps4val() (vps4.text + 4)
  1655. #if ENABLE_ASH_GETOPTS
  1656. # define optindval() (voptind.text + 7)
  1657. #endif
  1658. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  1659. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  1660. #if ENABLE_ASH_GETOPTS
  1661. static void FAST_FUNC
  1662. getoptsreset(const char *value)
  1663. {
  1664. shellparam.optind = number(value);
  1665. shellparam.optoff = -1;
  1666. }
  1667. #endif
  1668. /*
  1669. * Return of a legal variable name (a letter or underscore followed by zero or
  1670. * more letters, underscores, and digits).
  1671. */
  1672. static char* FAST_FUNC
  1673. endofname(const char *name)
  1674. {
  1675. char *p;
  1676. p = (char *) name;
  1677. if (!is_name(*p))
  1678. return p;
  1679. while (*++p) {
  1680. if (!is_in_name(*p))
  1681. break;
  1682. }
  1683. return p;
  1684. }
  1685. /*
  1686. * Compares two strings up to the first = or '\0'. The first
  1687. * string must be terminated by '='; the second may be terminated by
  1688. * either '=' or '\0'.
  1689. */
  1690. static int
  1691. varcmp(const char *p, const char *q)
  1692. {
  1693. int c, d;
  1694. while ((c = *p) == (d = *q)) {
  1695. if (!c || c == '=')
  1696. goto out;
  1697. p++;
  1698. q++;
  1699. }
  1700. if (c == '=')
  1701. c = '\0';
  1702. if (d == '=')
  1703. d = '\0';
  1704. out:
  1705. return c - d;
  1706. }
  1707. static int
  1708. varequal(const char *a, const char *b)
  1709. {
  1710. return !varcmp(a, b);
  1711. }
  1712. /*
  1713. * Find the appropriate entry in the hash table from the name.
  1714. */
  1715. static struct var **
  1716. hashvar(const char *p)
  1717. {
  1718. unsigned hashval;
  1719. hashval = ((unsigned char) *p) << 4;
  1720. while (*p && *p != '=')
  1721. hashval += (unsigned char) *p++;
  1722. return &vartab[hashval % VTABSIZE];
  1723. }
  1724. static int
  1725. vpcmp(const void *a, const void *b)
  1726. {
  1727. return varcmp(*(const char **)a, *(const char **)b);
  1728. }
  1729. /*
  1730. * This routine initializes the builtin variables.
  1731. */
  1732. static void
  1733. initvar(void)
  1734. {
  1735. struct var *vp;
  1736. struct var *end;
  1737. struct var **vpp;
  1738. /*
  1739. * PS1 depends on uid
  1740. */
  1741. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1742. vps1.text = "PS1=\\w \\$ ";
  1743. #else
  1744. if (!geteuid())
  1745. vps1.text = "PS1=# ";
  1746. #endif
  1747. vp = varinit;
  1748. end = vp + ARRAY_SIZE(varinit);
  1749. do {
  1750. vpp = hashvar(vp->text);
  1751. vp->next = *vpp;
  1752. *vpp = vp;
  1753. } while (++vp < end);
  1754. }
  1755. static struct var **
  1756. findvar(struct var **vpp, const char *name)
  1757. {
  1758. for (; *vpp; vpp = &(*vpp)->next) {
  1759. if (varequal((*vpp)->text, name)) {
  1760. break;
  1761. }
  1762. }
  1763. return vpp;
  1764. }
  1765. /*
  1766. * Find the value of a variable. Returns NULL if not set.
  1767. */
  1768. static const char* FAST_FUNC
  1769. lookupvar(const char *name)
  1770. {
  1771. struct var *v;
  1772. v = *findvar(hashvar(name), name);
  1773. if (v) {
  1774. #if ENABLE_ASH_RANDOM_SUPPORT
  1775. /*
  1776. * Dynamic variables are implemented roughly the same way they are
  1777. * in bash. Namely, they're "special" so long as they aren't unset.
  1778. * As soon as they're unset, they're no longer dynamic, and dynamic
  1779. * lookup will no longer happen at that point. -- PFM.
  1780. */
  1781. if ((v->flags & VDYNAMIC))
  1782. (*v->func)(NULL);
  1783. #endif
  1784. if (!(v->flags & VUNSET))
  1785. return strchrnul(v->text, '=') + 1;
  1786. }
  1787. return NULL;
  1788. }
  1789. /*
  1790. * Search the environment of a builtin command.
  1791. */
  1792. static const char *
  1793. bltinlookup(const char *name)
  1794. {
  1795. struct strlist *sp;
  1796. for (sp = cmdenviron; sp; sp = sp->next) {
  1797. if (varequal(sp->text, name))
  1798. return strchrnul(sp->text, '=') + 1;
  1799. }
  1800. return lookupvar(name);
  1801. }
  1802. /*
  1803. * Same as setvar except that the variable and value are passed in
  1804. * the first argument as name=value. Since the first argument will
  1805. * be actually stored in the table, it should not be a string that
  1806. * will go away.
  1807. * Called with interrupts off.
  1808. */
  1809. static void
  1810. setvareq(char *s, int flags)
  1811. {
  1812. struct var *vp, **vpp;
  1813. vpp = hashvar(s);
  1814. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  1815. vp = *findvar(vpp, s);
  1816. if (vp) {
  1817. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  1818. const char *n;
  1819. if (flags & VNOSAVE)
  1820. free(s);
  1821. n = vp->text;
  1822. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  1823. }
  1824. if (flags & VNOSET)
  1825. return;
  1826. if (vp->func && (flags & VNOFUNC) == 0)
  1827. (*vp->func)(strchrnul(s, '=') + 1);
  1828. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  1829. free((char*)vp->text);
  1830. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  1831. } else {
  1832. if (flags & VNOSET)
  1833. return;
  1834. /* not found */
  1835. vp = ckzalloc(sizeof(*vp));
  1836. vp->next = *vpp;
  1837. /*vp->func = NULL; - ckzalloc did it */
  1838. *vpp = vp;
  1839. }
  1840. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  1841. s = ckstrdup(s);
  1842. vp->text = s;
  1843. vp->flags = flags;
  1844. }
  1845. /*
  1846. * Set the value of a variable. The flags argument is ored with the
  1847. * flags of the variable. If val is NULL, the variable is unset.
  1848. */
  1849. static void
  1850. setvar(const char *name, const char *val, int flags)
  1851. {
  1852. char *p, *q;
  1853. size_t namelen;
  1854. char *nameeq;
  1855. size_t vallen;
  1856. q = endofname(name);
  1857. p = strchrnul(q, '=');
  1858. namelen = p - name;
  1859. if (!namelen || p != q)
  1860. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  1861. vallen = 0;
  1862. if (val == NULL) {
  1863. flags |= VUNSET;
  1864. } else {
  1865. vallen = strlen(val);
  1866. }
  1867. INT_OFF;
  1868. nameeq = ckmalloc(namelen + vallen + 2);
  1869. p = (char *)memcpy(nameeq, name, namelen) + namelen;
  1870. if (val) {
  1871. *p++ = '=';
  1872. p = (char *)memcpy(p, val, vallen) + vallen;
  1873. }
  1874. *p = '\0';
  1875. setvareq(nameeq, flags | VNOSAVE);
  1876. INT_ON;
  1877. }
  1878. static void FAST_FUNC
  1879. setvar2(const char *name, const char *val)
  1880. {
  1881. setvar(name, val, 0);
  1882. }
  1883. #if ENABLE_ASH_GETOPTS
  1884. /*
  1885. * Safe version of setvar, returns 1 on success 0 on failure.
  1886. */
  1887. static int
  1888. setvarsafe(const char *name, const char *val, int flags)
  1889. {
  1890. int err;
  1891. volatile int saveint;
  1892. struct jmploc *volatile savehandler = exception_handler;
  1893. struct jmploc jmploc;
  1894. SAVE_INT(saveint);
  1895. if (setjmp(jmploc.loc))
  1896. err = 1;
  1897. else {
  1898. exception_handler = &jmploc;
  1899. setvar(name, val, flags);
  1900. err = 0;
  1901. }
  1902. exception_handler = savehandler;
  1903. RESTORE_INT(saveint);
  1904. return err;
  1905. }
  1906. #endif
  1907. /*
  1908. * Unset the specified variable.
  1909. */
  1910. static int
  1911. unsetvar(const char *s)
  1912. {
  1913. struct var **vpp;
  1914. struct var *vp;
  1915. int retval;
  1916. vpp = findvar(hashvar(s), s);
  1917. vp = *vpp;
  1918. retval = 2;
  1919. if (vp) {
  1920. int flags = vp->flags;
  1921. retval = 1;
  1922. if (flags & VREADONLY)
  1923. goto out;
  1924. #if ENABLE_ASH_RANDOM_SUPPORT
  1925. vp->flags &= ~VDYNAMIC;
  1926. #endif
  1927. if (flags & VUNSET)
  1928. goto ok;
  1929. if ((flags & VSTRFIXED) == 0) {
  1930. INT_OFF;
  1931. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  1932. free((char*)vp->text);
  1933. *vpp = vp->next;
  1934. free(vp);
  1935. INT_ON;
  1936. } else {
  1937. setvar(s, 0, 0);
  1938. vp->flags &= ~VEXPORT;
  1939. }
  1940. ok:
  1941. retval = 0;
  1942. }
  1943. out:
  1944. return retval;
  1945. }
  1946. /*
  1947. * Process a linked list of variable assignments.
  1948. */
  1949. static void
  1950. listsetvar(struct strlist *list_set_var, int flags)
  1951. {
  1952. struct strlist *lp = list_set_var;
  1953. if (!lp)
  1954. return;
  1955. INT_OFF;
  1956. do {
  1957. setvareq(lp->text, flags);
  1958. lp = lp->next;
  1959. } while (lp);
  1960. INT_ON;
  1961. }
  1962. /*
  1963. * Generate a list of variables satisfying the given conditions.
  1964. */
  1965. static char **
  1966. listvars(int on, int off, char ***end)
  1967. {
  1968. struct var **vpp;
  1969. struct var *vp;
  1970. char **ep;
  1971. int mask;
  1972. STARTSTACKSTR(ep);
  1973. vpp = vartab;
  1974. mask = on | off;
  1975. do {
  1976. for (vp = *vpp; vp; vp = vp->next) {
  1977. if ((vp->flags & mask) == on) {
  1978. if (ep == stackstrend())
  1979. ep = growstackstr();
  1980. *ep++ = (char *) vp->text;
  1981. }
  1982. }
  1983. } while (++vpp < vartab + VTABSIZE);
  1984. if (ep == stackstrend())
  1985. ep = growstackstr();
  1986. if (end)
  1987. *end = ep;
  1988. *ep++ = NULL;
  1989. return grabstackstr(ep);
  1990. }
  1991. /* ============ Path search helper
  1992. *
  1993. * The variable path (passed by reference) should be set to the start
  1994. * of the path before the first call; path_advance will update
  1995. * this value as it proceeds. Successive calls to path_advance will return
  1996. * the possible path expansions in sequence. If an option (indicated by
  1997. * a percent sign) appears in the path entry then the global variable
  1998. * pathopt will be set to point to it; otherwise pathopt will be set to
  1999. * NULL.
  2000. */
  2001. static const char *pathopt; /* set by path_advance */
  2002. static char *
  2003. path_advance(const char **path, const char *name)
  2004. {
  2005. const char *p;
  2006. char *q;
  2007. const char *start;
  2008. size_t len;
  2009. if (*path == NULL)
  2010. return NULL;
  2011. start = *path;
  2012. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2013. continue;
  2014. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2015. while (stackblocksize() < len)
  2016. growstackblock();
  2017. q = stackblock();
  2018. if (p != start) {
  2019. memcpy(q, start, p - start);
  2020. q += p - start;
  2021. *q++ = '/';
  2022. }
  2023. strcpy(q, name);
  2024. pathopt = NULL;
  2025. if (*p == '%') {
  2026. pathopt = ++p;
  2027. while (*p && *p != ':')
  2028. p++;
  2029. }
  2030. if (*p == ':')
  2031. *path = p + 1;
  2032. else
  2033. *path = NULL;
  2034. return stalloc(len);
  2035. }
  2036. /* ============ Prompt */
  2037. static smallint doprompt; /* if set, prompt the user */
  2038. static smallint needprompt; /* true if interactive and at start of line */
  2039. #if ENABLE_FEATURE_EDITING
  2040. static line_input_t *line_input_state;
  2041. static const char *cmdedit_prompt;
  2042. static void
  2043. putprompt(const char *s)
  2044. {
  2045. if (ENABLE_ASH_EXPAND_PRMT) {
  2046. free((char*)cmdedit_prompt);
  2047. cmdedit_prompt = ckstrdup(s);
  2048. return;
  2049. }
  2050. cmdedit_prompt = s;
  2051. }
  2052. #else
  2053. static void
  2054. putprompt(const char *s)
  2055. {
  2056. out2str(s);
  2057. }
  2058. #endif
  2059. #if ENABLE_ASH_EXPAND_PRMT
  2060. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2061. static const char *expandstr(const char *ps);
  2062. #else
  2063. #define expandstr(s) s
  2064. #endif
  2065. static void
  2066. setprompt(int whichprompt)
  2067. {
  2068. const char *prompt;
  2069. #if ENABLE_ASH_EXPAND_PRMT
  2070. struct stackmark smark;
  2071. #endif
  2072. needprompt = 0;
  2073. switch (whichprompt) {
  2074. case 1:
  2075. prompt = ps1val();
  2076. break;
  2077. case 2:
  2078. prompt = ps2val();
  2079. break;
  2080. default: /* 0 */
  2081. prompt = nullstr;
  2082. }
  2083. #if ENABLE_ASH_EXPAND_PRMT
  2084. setstackmark(&smark);
  2085. stalloc(stackblocksize());
  2086. #endif
  2087. putprompt(expandstr(prompt));
  2088. #if ENABLE_ASH_EXPAND_PRMT
  2089. popstackmark(&smark);
  2090. #endif
  2091. }
  2092. /* ============ The cd and pwd commands */
  2093. #define CD_PHYSICAL 1
  2094. #define CD_PRINT 2
  2095. static int
  2096. cdopt(void)
  2097. {
  2098. int flags = 0;
  2099. int i, j;
  2100. j = 'L';
  2101. while ((i = nextopt("LP")) != '\0') {
  2102. if (i != j) {
  2103. flags ^= CD_PHYSICAL;
  2104. j = i;
  2105. }
  2106. }
  2107. return flags;
  2108. }
  2109. /*
  2110. * Update curdir (the name of the current directory) in response to a
  2111. * cd command.
  2112. */
  2113. static const char *
  2114. updatepwd(const char *dir)
  2115. {
  2116. char *new;
  2117. char *p;
  2118. char *cdcomppath;
  2119. const char *lim;
  2120. cdcomppath = ststrdup(dir);
  2121. STARTSTACKSTR(new);
  2122. if (*dir != '/') {
  2123. if (curdir == nullstr)
  2124. return 0;
  2125. new = stack_putstr(curdir, new);
  2126. }
  2127. new = makestrspace(strlen(dir) + 2, new);
  2128. lim = (char *)stackblock() + 1;
  2129. if (*dir != '/') {
  2130. if (new[-1] != '/')
  2131. USTPUTC('/', new);
  2132. if (new > lim && *lim == '/')
  2133. lim++;
  2134. } else {
  2135. USTPUTC('/', new);
  2136. cdcomppath++;
  2137. if (dir[1] == '/' && dir[2] != '/') {
  2138. USTPUTC('/', new);
  2139. cdcomppath++;
  2140. lim++;
  2141. }
  2142. }
  2143. p = strtok(cdcomppath, "/");
  2144. while (p) {
  2145. switch (*p) {
  2146. case '.':
  2147. if (p[1] == '.' && p[2] == '\0') {
  2148. while (new > lim) {
  2149. STUNPUTC(new);
  2150. if (new[-1] == '/')
  2151. break;
  2152. }
  2153. break;
  2154. }
  2155. if (p[1] == '\0')
  2156. break;
  2157. /* fall through */
  2158. default:
  2159. new = stack_putstr(p, new);
  2160. USTPUTC('/', new);
  2161. }
  2162. p = strtok(0, "/");
  2163. }
  2164. if (new > lim)
  2165. STUNPUTC(new);
  2166. *new = 0;
  2167. return stackblock();
  2168. }
  2169. /*
  2170. * Find out what the current directory is. If we already know the current
  2171. * directory, this routine returns immediately.
  2172. */
  2173. static char *
  2174. getpwd(void)
  2175. {
  2176. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2177. return dir ? dir : nullstr;
  2178. }
  2179. static void
  2180. setpwd(const char *val, int setold)
  2181. {
  2182. char *oldcur, *dir;
  2183. oldcur = dir = curdir;
  2184. if (setold) {
  2185. setvar("OLDPWD", oldcur, VEXPORT);
  2186. }
  2187. INT_OFF;
  2188. if (physdir != nullstr) {
  2189. if (physdir != oldcur)
  2190. free(physdir);
  2191. physdir = nullstr;
  2192. }
  2193. if (oldcur == val || !val) {
  2194. char *s = getpwd();
  2195. physdir = s;
  2196. if (!val)
  2197. dir = s;
  2198. } else
  2199. dir = ckstrdup(val);
  2200. if (oldcur != dir && oldcur != nullstr) {
  2201. free(oldcur);
  2202. }
  2203. curdir = dir;
  2204. INT_ON;
  2205. setvar("PWD", dir, VEXPORT);
  2206. }
  2207. static void hashcd(void);
  2208. /*
  2209. * Actually do the chdir. We also call hashcd to let the routines in exec.c
  2210. * know that the current directory has changed.
  2211. */
  2212. static int
  2213. docd(const char *dest, int flags)
  2214. {
  2215. const char *dir = NULL;
  2216. int err;
  2217. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2218. INT_OFF;
  2219. if (!(flags & CD_PHYSICAL)) {
  2220. dir = updatepwd(dest);
  2221. if (dir)
  2222. dest = dir;
  2223. }
  2224. err = chdir(dest);
  2225. if (err)
  2226. goto out;
  2227. setpwd(dir, 1);
  2228. hashcd();
  2229. out:
  2230. INT_ON;
  2231. return err;
  2232. }
  2233. static int FAST_FUNC
  2234. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2235. {
  2236. const char *dest;
  2237. const char *path;
  2238. const char *p;
  2239. char c;
  2240. struct stat statb;
  2241. int flags;
  2242. flags = cdopt();
  2243. dest = *argptr;
  2244. if (!dest)
  2245. dest = bltinlookup(homestr);
  2246. else if (LONE_DASH(dest)) {
  2247. dest = bltinlookup("OLDPWD");
  2248. flags |= CD_PRINT;
  2249. }
  2250. if (!dest)
  2251. dest = nullstr;
  2252. if (*dest == '/')
  2253. goto step7;
  2254. if (*dest == '.') {
  2255. c = dest[1];
  2256. dotdot:
  2257. switch (c) {
  2258. case '\0':
  2259. case '/':
  2260. goto step6;
  2261. case '.':
  2262. c = dest[2];
  2263. if (c != '.')
  2264. goto dotdot;
  2265. }
  2266. }
  2267. if (!*dest)
  2268. dest = ".";
  2269. path = bltinlookup("CDPATH");
  2270. if (!path) {
  2271. step6:
  2272. step7:
  2273. p = dest;
  2274. goto docd;
  2275. }
  2276. do {
  2277. c = *path;
  2278. p = path_advance(&path, dest);
  2279. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2280. if (c && c != ':')
  2281. flags |= CD_PRINT;
  2282. docd:
  2283. if (!docd(p, flags))
  2284. goto out;
  2285. break;
  2286. }
  2287. } while (path);
  2288. ash_msg_and_raise_error("can't cd to %s", dest);
  2289. /* NOTREACHED */
  2290. out:
  2291. if (flags & CD_PRINT)
  2292. out1fmt(snlfmt, curdir);
  2293. return 0;
  2294. }
  2295. static int FAST_FUNC
  2296. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2297. {
  2298. int flags;
  2299. const char *dir = curdir;
  2300. flags = cdopt();
  2301. if (flags) {
  2302. if (physdir == nullstr)
  2303. setpwd(dir, 0);
  2304. dir = physdir;
  2305. }
  2306. out1fmt(snlfmt, dir);
  2307. return 0;
  2308. }
  2309. /* ============ ... */
  2310. #define IBUFSIZ COMMON_BUFSIZE
  2311. /* buffer for top level input file */
  2312. #define basebuf bb_common_bufsiz1
  2313. /* Syntax classes */
  2314. #define CWORD 0 /* character is nothing special */
  2315. #define CNL 1 /* newline character */
  2316. #define CBACK 2 /* a backslash character */
  2317. #define CSQUOTE 3 /* single quote */
  2318. #define CDQUOTE 4 /* double quote */
  2319. #define CENDQUOTE 5 /* a terminating quote */
  2320. #define CBQUOTE 6 /* backwards single quote */
  2321. #define CVAR 7 /* a dollar sign */
  2322. #define CENDVAR 8 /* a '}' character */
  2323. #define CLP 9 /* a left paren in arithmetic */
  2324. #define CRP 10 /* a right paren in arithmetic */
  2325. #define CENDFILE 11 /* end of file */
  2326. #define CCTL 12 /* like CWORD, except it must be escaped */
  2327. #define CSPCL 13 /* these terminate a word */
  2328. #define CIGN 14 /* character should be ignored */
  2329. #define PEOF 256
  2330. #if ENABLE_ASH_ALIAS
  2331. # define PEOA 257
  2332. #endif
  2333. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2334. #if ENABLE_SH_MATH_SUPPORT
  2335. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2336. #else
  2337. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2338. #endif
  2339. static const uint16_t S_I_T[] = {
  2340. #if ENABLE_ASH_ALIAS
  2341. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2342. #endif
  2343. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2344. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2345. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2346. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2347. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2348. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2349. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2350. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2351. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2352. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2353. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2354. #if !USE_SIT_FUNCTION
  2355. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2356. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2357. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2358. #endif
  2359. #undef SIT_ITEM
  2360. };
  2361. /* Constants below must match table above */
  2362. enum {
  2363. #if ENABLE_ASH_ALIAS
  2364. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2365. #endif
  2366. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2367. CNL_CNL_CNL_CNL , /* 2 */
  2368. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2369. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2370. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2371. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2372. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2373. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2374. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2375. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2376. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2377. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2378. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2379. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2380. };
  2381. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2382. * caller must ensure proper cast on it if c is *char_ptr!
  2383. */
  2384. /* Values for syntax param */
  2385. #define BASESYNTAX 0 /* not in quotes */
  2386. #define DQSYNTAX 1 /* in double quotes */
  2387. #define SQSYNTAX 2 /* in single quotes */
  2388. #define ARISYNTAX 3 /* in arithmetic */
  2389. #define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2390. #if USE_SIT_FUNCTION
  2391. static int
  2392. SIT(int c, int syntax)
  2393. {
  2394. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
  2395. # if ENABLE_ASH_ALIAS
  2396. static const uint8_t syntax_index_table[] ALIGN1 = {
  2397. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2398. 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
  2399. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2400. 11, 3 /* "}~" */
  2401. };
  2402. # else
  2403. static const uint8_t syntax_index_table[] ALIGN1 = {
  2404. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2405. 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
  2406. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2407. 10, 2 /* "}~" */
  2408. };
  2409. # endif
  2410. const char *s;
  2411. int indx;
  2412. if (c == PEOF)
  2413. return CENDFILE;
  2414. # if ENABLE_ASH_ALIAS
  2415. if (c == PEOA)
  2416. indx = 0;
  2417. else
  2418. # endif
  2419. {
  2420. /* Cast is purely for paranoia here,
  2421. * just in case someone passed signed char to us */
  2422. if ((unsigned char)c >= CTL_FIRST
  2423. && (unsigned char)c <= CTL_LAST
  2424. ) {
  2425. return CCTL;
  2426. }
  2427. s = strchrnul(spec_symbls, c);
  2428. if (*s == '\0')
  2429. return CWORD;
  2430. indx = syntax_index_table[s - spec_symbls];
  2431. }
  2432. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2433. }
  2434. #else /* !USE_SIT_FUNCTION */
  2435. static const uint8_t syntax_index_table[] = {
  2436. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2437. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2438. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2439. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2440. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2441. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2442. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2443. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2444. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2445. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2446. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2447. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2448. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2449. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2450. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2451. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2452. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2453. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2454. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2455. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2456. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2457. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2458. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2459. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2460. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2461. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2462. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2463. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2464. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2465. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2466. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2467. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2468. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2469. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2470. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2471. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2472. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2473. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2474. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2475. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2476. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2477. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2478. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2479. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2480. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2481. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2482. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2483. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2484. /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
  2485. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2486. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2487. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2488. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2489. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2490. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2491. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2492. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2493. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2494. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2495. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2496. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2497. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2498. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2499. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2500. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2501. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2502. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2503. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2504. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2505. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2506. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2507. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2508. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2509. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2510. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2511. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2512. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2513. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2514. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2515. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2516. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2517. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2518. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2519. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2520. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2521. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2522. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2523. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2524. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2525. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2526. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2527. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2528. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2529. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2530. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2531. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2532. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2533. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2534. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2535. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2536. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2537. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2538. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2539. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2540. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2541. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2542. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2543. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2544. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2545. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2546. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2547. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2548. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2549. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2550. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2551. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2552. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2553. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2554. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2555. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2556. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2557. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2558. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2559. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2560. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2561. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2562. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2563. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2564. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2565. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2566. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2567. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2568. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2569. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2570. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2571. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2572. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2573. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2574. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2575. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2576. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2577. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2578. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2579. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2580. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2581. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2582. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2583. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2584. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2585. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2586. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2587. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2588. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2589. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2590. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2591. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2592. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2593. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2594. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2595. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2596. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2597. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2598. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2599. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2600. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2601. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2602. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2603. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2604. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2605. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2606. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2607. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2608. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2609. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2610. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2611. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2612. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2613. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2614. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2615. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2616. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2617. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2618. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2619. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2620. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2621. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2622. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2623. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2624. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2625. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2626. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2627. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2628. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2629. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2630. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2631. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2632. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2633. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2634. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2635. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2636. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2637. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2638. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2639. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2640. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2641. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2642. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2643. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2644. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2645. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2646. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2647. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2648. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2649. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2650. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2651. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2652. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2653. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2654. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2655. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2656. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2657. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2658. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2659. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2660. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2661. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2662. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2663. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2664. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2665. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2666. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2667. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2668. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2669. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2670. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2671. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2672. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2673. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2674. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2675. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2676. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2677. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2678. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2679. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2680. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2681. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2682. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2683. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2684. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2685. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2686. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2687. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2688. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2689. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2690. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2691. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2692. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2693. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2694. # if ENABLE_ASH_ALIAS
  2695. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2696. # endif
  2697. };
  2698. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2699. #endif /* !USE_SIT_FUNCTION */
  2700. /* ============ Alias handling */
  2701. #if ENABLE_ASH_ALIAS
  2702. #define ALIASINUSE 1
  2703. #define ALIASDEAD 2
  2704. struct alias {
  2705. struct alias *next;
  2706. char *name;
  2707. char *val;
  2708. int flag;
  2709. };
  2710. static struct alias **atab; // [ATABSIZE];
  2711. #define INIT_G_alias() do { \
  2712. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2713. } while (0)
  2714. static struct alias **
  2715. __lookupalias(const char *name) {
  2716. unsigned int hashval;
  2717. struct alias **app;
  2718. const char *p;
  2719. unsigned int ch;
  2720. p = name;
  2721. ch = (unsigned char)*p;
  2722. hashval = ch << 4;
  2723. while (ch) {
  2724. hashval += ch;
  2725. ch = (unsigned char)*++p;
  2726. }
  2727. app = &atab[hashval % ATABSIZE];
  2728. for (; *app; app = &(*app)->next) {
  2729. if (strcmp(name, (*app)->name) == 0) {
  2730. break;
  2731. }
  2732. }
  2733. return app;
  2734. }
  2735. static struct alias *
  2736. lookupalias(const char *name, int check)
  2737. {
  2738. struct alias *ap = *__lookupalias(name);
  2739. if (check && ap && (ap->flag & ALIASINUSE))
  2740. return NULL;
  2741. return ap;
  2742. }
  2743. static struct alias *
  2744. freealias(struct alias *ap)
  2745. {
  2746. struct alias *next;
  2747. if (ap->flag & ALIASINUSE) {
  2748. ap->flag |= ALIASDEAD;
  2749. return ap;
  2750. }
  2751. next = ap->next;
  2752. free(ap->name);
  2753. free(ap->val);
  2754. free(ap);
  2755. return next;
  2756. }
  2757. static void
  2758. setalias(const char *name, const char *val)
  2759. {
  2760. struct alias *ap, **app;
  2761. app = __lookupalias(name);
  2762. ap = *app;
  2763. INT_OFF;
  2764. if (ap) {
  2765. if (!(ap->flag & ALIASINUSE)) {
  2766. free(ap->val);
  2767. }
  2768. ap->val = ckstrdup(val);
  2769. ap->flag &= ~ALIASDEAD;
  2770. } else {
  2771. /* not found */
  2772. ap = ckzalloc(sizeof(struct alias));
  2773. ap->name = ckstrdup(name);
  2774. ap->val = ckstrdup(val);
  2775. /*ap->flag = 0; - ckzalloc did it */
  2776. /*ap->next = NULL;*/
  2777. *app = ap;
  2778. }
  2779. INT_ON;
  2780. }
  2781. static int
  2782. unalias(const char *name)
  2783. {
  2784. struct alias **app;
  2785. app = __lookupalias(name);
  2786. if (*app) {
  2787. INT_OFF;
  2788. *app = freealias(*app);
  2789. INT_ON;
  2790. return 0;
  2791. }
  2792. return 1;
  2793. }
  2794. static void
  2795. rmaliases(void)
  2796. {
  2797. struct alias *ap, **app;
  2798. int i;
  2799. INT_OFF;
  2800. for (i = 0; i < ATABSIZE; i++) {
  2801. app = &atab[i];
  2802. for (ap = *app; ap; ap = *app) {
  2803. *app = freealias(*app);
  2804. if (ap == *app) {
  2805. app = &ap->next;
  2806. }
  2807. }
  2808. }
  2809. INT_ON;
  2810. }
  2811. static void
  2812. printalias(const struct alias *ap)
  2813. {
  2814. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  2815. }
  2816. /*
  2817. * TODO - sort output
  2818. */
  2819. static int FAST_FUNC
  2820. aliascmd(int argc UNUSED_PARAM, char **argv)
  2821. {
  2822. char *n, *v;
  2823. int ret = 0;
  2824. struct alias *ap;
  2825. if (!argv[1]) {
  2826. int i;
  2827. for (i = 0; i < ATABSIZE; i++) {
  2828. for (ap = atab[i]; ap; ap = ap->next) {
  2829. printalias(ap);
  2830. }
  2831. }
  2832. return 0;
  2833. }
  2834. while ((n = *++argv) != NULL) {
  2835. v = strchr(n+1, '=');
  2836. if (v == NULL) { /* n+1: funny ksh stuff */
  2837. ap = *__lookupalias(n);
  2838. if (ap == NULL) {
  2839. fprintf(stderr, "%s: %s not found\n", "alias", n);
  2840. ret = 1;
  2841. } else
  2842. printalias(ap);
  2843. } else {
  2844. *v++ = '\0';
  2845. setalias(n, v);
  2846. }
  2847. }
  2848. return ret;
  2849. }
  2850. static int FAST_FUNC
  2851. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2852. {
  2853. int i;
  2854. while ((i = nextopt("a")) != '\0') {
  2855. if (i == 'a') {
  2856. rmaliases();
  2857. return 0;
  2858. }
  2859. }
  2860. for (i = 0; *argptr; argptr++) {
  2861. if (unalias(*argptr)) {
  2862. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  2863. i = 1;
  2864. }
  2865. }
  2866. return i;
  2867. }
  2868. #endif /* ASH_ALIAS */
  2869. /* ============ jobs.c */
  2870. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  2871. #define FORK_FG 0
  2872. #define FORK_BG 1
  2873. #define FORK_NOJOB 2
  2874. /* mode flags for showjob(s) */
  2875. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  2876. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  2877. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  2878. /*
  2879. * A job structure contains information about a job. A job is either a
  2880. * single process or a set of processes contained in a pipeline. In the
  2881. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  2882. * array of pids.
  2883. */
  2884. struct procstat {
  2885. pid_t ps_pid; /* process id */
  2886. int ps_status; /* last process status from wait() */
  2887. char *ps_cmd; /* text of command being run */
  2888. };
  2889. struct job {
  2890. struct procstat ps0; /* status of process */
  2891. struct procstat *ps; /* status or processes when more than one */
  2892. #if JOBS
  2893. int stopstatus; /* status of a stopped job */
  2894. #endif
  2895. uint32_t
  2896. nprocs: 16, /* number of processes */
  2897. state: 8,
  2898. #define JOBRUNNING 0 /* at least one proc running */
  2899. #define JOBSTOPPED 1 /* all procs are stopped */
  2900. #define JOBDONE 2 /* all procs are completed */
  2901. #if JOBS
  2902. sigint: 1, /* job was killed by SIGINT */
  2903. jobctl: 1, /* job running under job control */
  2904. #endif
  2905. waited: 1, /* true if this entry has been waited for */
  2906. used: 1, /* true if this entry is in used */
  2907. changed: 1; /* true if status has changed */
  2908. struct job *prev_job; /* previous job */
  2909. };
  2910. static struct job *makejob(/*union node *,*/ int);
  2911. static int forkshell(struct job *, union node *, int);
  2912. static int waitforjob(struct job *);
  2913. #if !JOBS
  2914. enum { doing_jobctl = 0 };
  2915. #define setjobctl(on) do {} while (0)
  2916. #else
  2917. static smallint doing_jobctl; //references:8
  2918. static void setjobctl(int);
  2919. #endif
  2920. /*
  2921. * Ignore a signal.
  2922. */
  2923. static void
  2924. ignoresig(int signo)
  2925. {
  2926. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  2927. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  2928. /* No, need to do it */
  2929. signal(signo, SIG_IGN);
  2930. }
  2931. sigmode[signo - 1] = S_HARD_IGN;
  2932. }
  2933. /*
  2934. * Signal handler. Only one usage site - in setsignal()
  2935. */
  2936. static void
  2937. onsig(int signo)
  2938. {
  2939. gotsig[signo - 1] = 1;
  2940. if (signo == SIGINT && !trap[SIGINT]) {
  2941. if (!suppress_int) {
  2942. pending_sig = 0;
  2943. raise_interrupt(); /* does not return */
  2944. }
  2945. pending_int = 1;
  2946. } else {
  2947. pending_sig = signo;
  2948. }
  2949. }
  2950. /*
  2951. * Set the signal handler for the specified signal. The routine figures
  2952. * out what it should be set to.
  2953. */
  2954. static void
  2955. setsignal(int signo)
  2956. {
  2957. char *t;
  2958. char cur_act, new_act;
  2959. struct sigaction act;
  2960. t = trap[signo];
  2961. new_act = S_DFL;
  2962. if (t != NULL) { /* trap for this sig is set */
  2963. new_act = S_CATCH;
  2964. if (t[0] == '\0') /* trap is "": ignore this sig */
  2965. new_act = S_IGN;
  2966. }
  2967. if (rootshell && new_act == S_DFL) {
  2968. switch (signo) {
  2969. case SIGINT:
  2970. if (iflag || minusc || sflag == 0)
  2971. new_act = S_CATCH;
  2972. break;
  2973. case SIGQUIT:
  2974. #if DEBUG
  2975. if (debug)
  2976. break;
  2977. #endif
  2978. /* man bash:
  2979. * "In all cases, bash ignores SIGQUIT. Non-builtin
  2980. * commands run by bash have signal handlers
  2981. * set to the values inherited by the shell
  2982. * from its parent". */
  2983. new_act = S_IGN;
  2984. break;
  2985. case SIGTERM:
  2986. if (iflag)
  2987. new_act = S_IGN;
  2988. break;
  2989. #if JOBS
  2990. case SIGTSTP:
  2991. case SIGTTOU:
  2992. if (mflag)
  2993. new_act = S_IGN;
  2994. break;
  2995. #endif
  2996. }
  2997. }
  2998. //TODO: if !rootshell, we reset SIGQUIT to DFL,
  2999. //whereas we have to restore it to what shell got on entry
  3000. //from the parent. See comment above
  3001. t = &sigmode[signo - 1];
  3002. cur_act = *t;
  3003. if (cur_act == 0) {
  3004. /* current setting is not yet known */
  3005. if (sigaction(signo, NULL, &act)) {
  3006. /* pretend it worked; maybe we should give a warning,
  3007. * but other shells don't. We don't alter sigmode,
  3008. * so we retry every time.
  3009. * btw, in Linux it never fails. --vda */
  3010. return;
  3011. }
  3012. if (act.sa_handler == SIG_IGN) {
  3013. cur_act = S_HARD_IGN;
  3014. if (mflag
  3015. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3016. ) {
  3017. cur_act = S_IGN; /* don't hard ignore these */
  3018. }
  3019. }
  3020. }
  3021. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3022. return;
  3023. act.sa_handler = SIG_DFL;
  3024. switch (new_act) {
  3025. case S_CATCH:
  3026. act.sa_handler = onsig;
  3027. act.sa_flags = 0; /* matters only if !DFL and !IGN */
  3028. sigfillset(&act.sa_mask); /* ditto */
  3029. break;
  3030. case S_IGN:
  3031. act.sa_handler = SIG_IGN;
  3032. break;
  3033. }
  3034. sigaction_set(signo, &act);
  3035. *t = new_act;
  3036. }
  3037. /* mode flags for set_curjob */
  3038. #define CUR_DELETE 2
  3039. #define CUR_RUNNING 1
  3040. #define CUR_STOPPED 0
  3041. /* mode flags for dowait */
  3042. #define DOWAIT_NONBLOCK WNOHANG
  3043. #define DOWAIT_BLOCK 0
  3044. #if JOBS
  3045. /* pgrp of shell on invocation */
  3046. static int initialpgrp; //references:2
  3047. static int ttyfd = -1; //5
  3048. #endif
  3049. /* array of jobs */
  3050. static struct job *jobtab; //5
  3051. /* size of array */
  3052. static unsigned njobs; //4
  3053. /* current job */
  3054. static struct job *curjob; //lots
  3055. /* number of presumed living untracked jobs */
  3056. static int jobless; //4
  3057. static void
  3058. set_curjob(struct job *jp, unsigned mode)
  3059. {
  3060. struct job *jp1;
  3061. struct job **jpp, **curp;
  3062. /* first remove from list */
  3063. jpp = curp = &curjob;
  3064. do {
  3065. jp1 = *jpp;
  3066. if (jp1 == jp)
  3067. break;
  3068. jpp = &jp1->prev_job;
  3069. } while (1);
  3070. *jpp = jp1->prev_job;
  3071. /* Then re-insert in correct position */
  3072. jpp = curp;
  3073. switch (mode) {
  3074. default:
  3075. #if DEBUG
  3076. abort();
  3077. #endif
  3078. case CUR_DELETE:
  3079. /* job being deleted */
  3080. break;
  3081. case CUR_RUNNING:
  3082. /* newly created job or backgrounded job,
  3083. put after all stopped jobs. */
  3084. do {
  3085. jp1 = *jpp;
  3086. #if JOBS
  3087. if (!jp1 || jp1->state != JOBSTOPPED)
  3088. #endif
  3089. break;
  3090. jpp = &jp1->prev_job;
  3091. } while (1);
  3092. /* FALLTHROUGH */
  3093. #if JOBS
  3094. case CUR_STOPPED:
  3095. #endif
  3096. /* newly stopped job - becomes curjob */
  3097. jp->prev_job = *jpp;
  3098. *jpp = jp;
  3099. break;
  3100. }
  3101. }
  3102. #if JOBS || DEBUG
  3103. static int
  3104. jobno(const struct job *jp)
  3105. {
  3106. return jp - jobtab + 1;
  3107. }
  3108. #endif
  3109. /*
  3110. * Convert a job name to a job structure.
  3111. */
  3112. #if !JOBS
  3113. #define getjob(name, getctl) getjob(name)
  3114. #endif
  3115. static struct job *
  3116. getjob(const char *name, int getctl)
  3117. {
  3118. struct job *jp;
  3119. struct job *found;
  3120. const char *err_msg = "%s: no such job";
  3121. unsigned num;
  3122. int c;
  3123. const char *p;
  3124. char *(*match)(const char *, const char *);
  3125. jp = curjob;
  3126. p = name;
  3127. if (!p)
  3128. goto currentjob;
  3129. if (*p != '%')
  3130. goto err;
  3131. c = *++p;
  3132. if (!c)
  3133. goto currentjob;
  3134. if (!p[1]) {
  3135. if (c == '+' || c == '%') {
  3136. currentjob:
  3137. err_msg = "No current job";
  3138. goto check;
  3139. }
  3140. if (c == '-') {
  3141. if (jp)
  3142. jp = jp->prev_job;
  3143. err_msg = "No previous job";
  3144. check:
  3145. if (!jp)
  3146. goto err;
  3147. goto gotit;
  3148. }
  3149. }
  3150. if (is_number(p)) {
  3151. num = atoi(p);
  3152. if (num < njobs) {
  3153. jp = jobtab + num - 1;
  3154. if (jp->used)
  3155. goto gotit;
  3156. goto err;
  3157. }
  3158. }
  3159. match = prefix;
  3160. if (*p == '?') {
  3161. match = strstr;
  3162. p++;
  3163. }
  3164. found = NULL;
  3165. while (jp) {
  3166. if (match(jp->ps[0].ps_cmd, p)) {
  3167. if (found)
  3168. goto err;
  3169. found = jp;
  3170. err_msg = "%s: ambiguous";
  3171. }
  3172. jp = jp->prev_job;
  3173. }
  3174. if (!found)
  3175. goto err;
  3176. jp = found;
  3177. gotit:
  3178. #if JOBS
  3179. err_msg = "job %s not created under job control";
  3180. if (getctl && jp->jobctl == 0)
  3181. goto err;
  3182. #endif
  3183. return jp;
  3184. err:
  3185. ash_msg_and_raise_error(err_msg, name);
  3186. }
  3187. /*
  3188. * Mark a job structure as unused.
  3189. */
  3190. static void
  3191. freejob(struct job *jp)
  3192. {
  3193. struct procstat *ps;
  3194. int i;
  3195. INT_OFF;
  3196. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3197. if (ps->ps_cmd != nullstr)
  3198. free(ps->ps_cmd);
  3199. }
  3200. if (jp->ps != &jp->ps0)
  3201. free(jp->ps);
  3202. jp->used = 0;
  3203. set_curjob(jp, CUR_DELETE);
  3204. INT_ON;
  3205. }
  3206. #if JOBS
  3207. static void
  3208. xtcsetpgrp(int fd, pid_t pgrp)
  3209. {
  3210. if (tcsetpgrp(fd, pgrp))
  3211. ash_msg_and_raise_error("can't set tty process group (%m)");
  3212. }
  3213. /*
  3214. * Turn job control on and off.
  3215. *
  3216. * Note: This code assumes that the third arg to ioctl is a character
  3217. * pointer, which is true on Berkeley systems but not System V. Since
  3218. * System V doesn't have job control yet, this isn't a problem now.
  3219. *
  3220. * Called with interrupts off.
  3221. */
  3222. static void
  3223. setjobctl(int on)
  3224. {
  3225. int fd;
  3226. int pgrp;
  3227. if (on == doing_jobctl || rootshell == 0)
  3228. return;
  3229. if (on) {
  3230. int ofd;
  3231. ofd = fd = open(_PATH_TTY, O_RDWR);
  3232. if (fd < 0) {
  3233. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3234. * That sometimes helps to acquire controlling tty.
  3235. * Obviously, a workaround for bugs when someone
  3236. * failed to provide a controlling tty to bash! :) */
  3237. fd = 2;
  3238. while (!isatty(fd))
  3239. if (--fd < 0)
  3240. goto out;
  3241. }
  3242. fd = fcntl(fd, F_DUPFD, 10);
  3243. if (ofd >= 0)
  3244. close(ofd);
  3245. if (fd < 0)
  3246. goto out;
  3247. /* fd is a tty at this point */
  3248. close_on_exec_on(fd);
  3249. do { /* while we are in the background */
  3250. pgrp = tcgetpgrp(fd);
  3251. if (pgrp < 0) {
  3252. out:
  3253. ash_msg("can't access tty; job control turned off");
  3254. mflag = on = 0;
  3255. goto close;
  3256. }
  3257. if (pgrp == getpgrp())
  3258. break;
  3259. killpg(0, SIGTTIN);
  3260. } while (1);
  3261. initialpgrp = pgrp;
  3262. setsignal(SIGTSTP);
  3263. setsignal(SIGTTOU);
  3264. setsignal(SIGTTIN);
  3265. pgrp = rootpid;
  3266. setpgid(0, pgrp);
  3267. xtcsetpgrp(fd, pgrp);
  3268. } else {
  3269. /* turning job control off */
  3270. fd = ttyfd;
  3271. pgrp = initialpgrp;
  3272. /* was xtcsetpgrp, but this can make exiting ash
  3273. * loop forever if pty is already deleted */
  3274. tcsetpgrp(fd, pgrp);
  3275. setpgid(0, pgrp);
  3276. setsignal(SIGTSTP);
  3277. setsignal(SIGTTOU);
  3278. setsignal(SIGTTIN);
  3279. close:
  3280. if (fd >= 0)
  3281. close(fd);
  3282. fd = -1;
  3283. }
  3284. ttyfd = fd;
  3285. doing_jobctl = on;
  3286. }
  3287. static int FAST_FUNC
  3288. killcmd(int argc, char **argv)
  3289. {
  3290. int i = 1;
  3291. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3292. do {
  3293. if (argv[i][0] == '%') {
  3294. struct job *jp = getjob(argv[i], 0);
  3295. unsigned pid = jp->ps[0].ps_pid;
  3296. /* Enough space for ' -NNN<nul>' */
  3297. argv[i] = alloca(sizeof(int)*3 + 3);
  3298. /* kill_main has matching code to expect
  3299. * leading space. Needed to not confuse
  3300. * negative pids with "kill -SIGNAL_NO" syntax */
  3301. sprintf(argv[i], " -%u", pid);
  3302. }
  3303. } while (argv[++i]);
  3304. }
  3305. return kill_main(argc, argv);
  3306. }
  3307. static void
  3308. showpipe(struct job *jp /*, FILE *out*/)
  3309. {
  3310. struct procstat *ps;
  3311. struct procstat *psend;
  3312. psend = jp->ps + jp->nprocs;
  3313. for (ps = jp->ps + 1; ps < psend; ps++)
  3314. printf(" | %s", ps->ps_cmd);
  3315. outcslow('\n', stdout);
  3316. flush_stdout_stderr();
  3317. }
  3318. static int
  3319. restartjob(struct job *jp, int mode)
  3320. {
  3321. struct procstat *ps;
  3322. int i;
  3323. int status;
  3324. pid_t pgid;
  3325. INT_OFF;
  3326. if (jp->state == JOBDONE)
  3327. goto out;
  3328. jp->state = JOBRUNNING;
  3329. pgid = jp->ps[0].ps_pid;
  3330. if (mode == FORK_FG)
  3331. xtcsetpgrp(ttyfd, pgid);
  3332. killpg(pgid, SIGCONT);
  3333. ps = jp->ps;
  3334. i = jp->nprocs;
  3335. do {
  3336. if (WIFSTOPPED(ps->ps_status)) {
  3337. ps->ps_status = -1;
  3338. }
  3339. ps++;
  3340. } while (--i);
  3341. out:
  3342. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3343. INT_ON;
  3344. return status;
  3345. }
  3346. static int FAST_FUNC
  3347. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3348. {
  3349. struct job *jp;
  3350. int mode;
  3351. int retval;
  3352. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3353. nextopt(nullstr);
  3354. argv = argptr;
  3355. do {
  3356. jp = getjob(*argv, 1);
  3357. if (mode == FORK_BG) {
  3358. set_curjob(jp, CUR_RUNNING);
  3359. printf("[%d] ", jobno(jp));
  3360. }
  3361. out1str(jp->ps[0].ps_cmd);
  3362. showpipe(jp /*, stdout*/);
  3363. retval = restartjob(jp, mode);
  3364. } while (*argv && *++argv);
  3365. return retval;
  3366. }
  3367. #endif
  3368. static int
  3369. sprint_status(char *s, int status, int sigonly)
  3370. {
  3371. int col;
  3372. int st;
  3373. col = 0;
  3374. if (!WIFEXITED(status)) {
  3375. #if JOBS
  3376. if (WIFSTOPPED(status))
  3377. st = WSTOPSIG(status);
  3378. else
  3379. #endif
  3380. st = WTERMSIG(status);
  3381. if (sigonly) {
  3382. if (st == SIGINT || st == SIGPIPE)
  3383. goto out;
  3384. #if JOBS
  3385. if (WIFSTOPPED(status))
  3386. goto out;
  3387. #endif
  3388. }
  3389. st &= 0x7f;
  3390. col = fmtstr(s, 32, strsignal(st));
  3391. if (WCOREDUMP(status)) {
  3392. col += fmtstr(s + col, 16, " (core dumped)");
  3393. }
  3394. } else if (!sigonly) {
  3395. st = WEXITSTATUS(status);
  3396. if (st)
  3397. col = fmtstr(s, 16, "Done(%d)", st);
  3398. else
  3399. col = fmtstr(s, 16, "Done");
  3400. }
  3401. out:
  3402. return col;
  3403. }
  3404. static int
  3405. dowait(int wait_flags, struct job *job)
  3406. {
  3407. int pid;
  3408. int status;
  3409. struct job *jp;
  3410. struct job *thisjob;
  3411. int state;
  3412. TRACE(("dowait(0x%x) called\n", wait_flags));
  3413. /* Do a wait system call. If job control is compiled in, we accept
  3414. * stopped processes. wait_flags may have WNOHANG, preventing blocking.
  3415. * NB: _not_ safe_waitpid, we need to detect EINTR */
  3416. if (doing_jobctl)
  3417. wait_flags |= WUNTRACED;
  3418. pid = waitpid(-1, &status, wait_flags);
  3419. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3420. pid, status, errno, strerror(errno)));
  3421. if (pid <= 0)
  3422. return pid;
  3423. INT_OFF;
  3424. thisjob = NULL;
  3425. for (jp = curjob; jp; jp = jp->prev_job) {
  3426. struct procstat *ps;
  3427. struct procstat *psend;
  3428. if (jp->state == JOBDONE)
  3429. continue;
  3430. state = JOBDONE;
  3431. ps = jp->ps;
  3432. psend = ps + jp->nprocs;
  3433. do {
  3434. if (ps->ps_pid == pid) {
  3435. TRACE(("Job %d: changing status of proc %d "
  3436. "from 0x%x to 0x%x\n",
  3437. jobno(jp), pid, ps->ps_status, status));
  3438. ps->ps_status = status;
  3439. thisjob = jp;
  3440. }
  3441. if (ps->ps_status == -1)
  3442. state = JOBRUNNING;
  3443. #if JOBS
  3444. if (state == JOBRUNNING)
  3445. continue;
  3446. if (WIFSTOPPED(ps->ps_status)) {
  3447. jp->stopstatus = ps->ps_status;
  3448. state = JOBSTOPPED;
  3449. }
  3450. #endif
  3451. } while (++ps < psend);
  3452. if (thisjob)
  3453. goto gotjob;
  3454. }
  3455. #if JOBS
  3456. if (!WIFSTOPPED(status))
  3457. #endif
  3458. jobless--;
  3459. goto out;
  3460. gotjob:
  3461. if (state != JOBRUNNING) {
  3462. thisjob->changed = 1;
  3463. if (thisjob->state != state) {
  3464. TRACE(("Job %d: changing state from %d to %d\n",
  3465. jobno(thisjob), thisjob->state, state));
  3466. thisjob->state = state;
  3467. #if JOBS
  3468. if (state == JOBSTOPPED) {
  3469. set_curjob(thisjob, CUR_STOPPED);
  3470. }
  3471. #endif
  3472. }
  3473. }
  3474. out:
  3475. INT_ON;
  3476. if (thisjob && thisjob == job) {
  3477. char s[48 + 1];
  3478. int len;
  3479. len = sprint_status(s, status, 1);
  3480. if (len) {
  3481. s[len] = '\n';
  3482. s[len + 1] = '\0';
  3483. out2str(s);
  3484. }
  3485. }
  3486. return pid;
  3487. }
  3488. static int
  3489. blocking_wait_with_raise_on_sig(struct job *job)
  3490. {
  3491. pid_t pid = dowait(DOWAIT_BLOCK, job);
  3492. if (pid <= 0 && pending_sig)
  3493. raise_exception(EXSIG);
  3494. return pid;
  3495. }
  3496. #if JOBS
  3497. static void
  3498. showjob(FILE *out, struct job *jp, int mode)
  3499. {
  3500. struct procstat *ps;
  3501. struct procstat *psend;
  3502. int col;
  3503. int indent_col;
  3504. char s[80];
  3505. ps = jp->ps;
  3506. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3507. /* just output process (group) id of pipeline */
  3508. fprintf(out, "%d\n", ps->ps_pid);
  3509. return;
  3510. }
  3511. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3512. indent_col = col;
  3513. if (jp == curjob)
  3514. s[col - 3] = '+';
  3515. else if (curjob && jp == curjob->prev_job)
  3516. s[col - 3] = '-';
  3517. if (mode & SHOW_PIDS)
  3518. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3519. psend = ps + jp->nprocs;
  3520. if (jp->state == JOBRUNNING) {
  3521. strcpy(s + col, "Running");
  3522. col += sizeof("Running") - 1;
  3523. } else {
  3524. int status = psend[-1].ps_status;
  3525. if (jp->state == JOBSTOPPED)
  3526. status = jp->stopstatus;
  3527. col += sprint_status(s + col, status, 0);
  3528. }
  3529. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3530. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3531. * or prints several "PID | <cmdN>" lines,
  3532. * depending on SHOW_PIDS bit.
  3533. * We do not print status of individual processes
  3534. * between PID and <cmdN>. bash does it, but not very well:
  3535. * first line shows overall job status, not process status,
  3536. * making it impossible to know 1st process status.
  3537. */
  3538. goto start;
  3539. do {
  3540. /* for each process */
  3541. s[0] = '\0';
  3542. col = 33;
  3543. if (mode & SHOW_PIDS)
  3544. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3545. start:
  3546. fprintf(out, "%s%*c%s%s",
  3547. s,
  3548. 33 - col >= 0 ? 33 - col : 0, ' ',
  3549. ps == jp->ps ? "" : "| ",
  3550. ps->ps_cmd
  3551. );
  3552. } while (++ps != psend);
  3553. outcslow('\n', out);
  3554. jp->changed = 0;
  3555. if (jp->state == JOBDONE) {
  3556. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3557. freejob(jp);
  3558. }
  3559. }
  3560. /*
  3561. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3562. * statuses have changed since the last call to showjobs.
  3563. */
  3564. static void
  3565. showjobs(FILE *out, int mode)
  3566. {
  3567. struct job *jp;
  3568. TRACE(("showjobs(0x%x) called\n", mode));
  3569. /* Handle all finished jobs */
  3570. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3571. continue;
  3572. for (jp = curjob; jp; jp = jp->prev_job) {
  3573. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3574. showjob(out, jp, mode);
  3575. }
  3576. }
  3577. }
  3578. static int FAST_FUNC
  3579. jobscmd(int argc UNUSED_PARAM, char **argv)
  3580. {
  3581. int mode, m;
  3582. mode = 0;
  3583. while ((m = nextopt("lp")) != '\0') {
  3584. if (m == 'l')
  3585. mode |= SHOW_PIDS;
  3586. else
  3587. mode |= SHOW_ONLY_PGID;
  3588. }
  3589. argv = argptr;
  3590. if (*argv) {
  3591. do
  3592. showjob(stdout, getjob(*argv, 0), mode);
  3593. while (*++argv);
  3594. } else {
  3595. showjobs(stdout, mode);
  3596. }
  3597. return 0;
  3598. }
  3599. #endif /* JOBS */
  3600. /* Called only on finished or stopped jobs (no members are running) */
  3601. static int
  3602. getstatus(struct job *job)
  3603. {
  3604. int status;
  3605. int retval;
  3606. struct procstat *ps;
  3607. /* Fetch last member's status */
  3608. ps = job->ps + job->nprocs - 1;
  3609. status = ps->ps_status;
  3610. if (pipefail) {
  3611. /* "set -o pipefail" mode: use last _nonzero_ status */
  3612. while (status == 0 && --ps >= job->ps)
  3613. status = ps->ps_status;
  3614. }
  3615. retval = WEXITSTATUS(status);
  3616. if (!WIFEXITED(status)) {
  3617. #if JOBS
  3618. retval = WSTOPSIG(status);
  3619. if (!WIFSTOPPED(status))
  3620. #endif
  3621. {
  3622. /* XXX: limits number of signals */
  3623. retval = WTERMSIG(status);
  3624. #if JOBS
  3625. if (retval == SIGINT)
  3626. job->sigint = 1;
  3627. #endif
  3628. }
  3629. retval += 128;
  3630. }
  3631. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  3632. jobno(job), job->nprocs, status, retval));
  3633. return retval;
  3634. }
  3635. static int FAST_FUNC
  3636. waitcmd(int argc UNUSED_PARAM, char **argv)
  3637. {
  3638. struct job *job;
  3639. int retval;
  3640. struct job *jp;
  3641. if (pending_sig)
  3642. raise_exception(EXSIG);
  3643. nextopt(nullstr);
  3644. retval = 0;
  3645. argv = argptr;
  3646. if (!*argv) {
  3647. /* wait for all jobs */
  3648. for (;;) {
  3649. jp = curjob;
  3650. while (1) {
  3651. if (!jp) /* no running procs */
  3652. goto ret;
  3653. if (jp->state == JOBRUNNING)
  3654. break;
  3655. jp->waited = 1;
  3656. jp = jp->prev_job;
  3657. }
  3658. /* man bash:
  3659. * "When bash is waiting for an asynchronous command via
  3660. * the wait builtin, the reception of a signal for which a trap
  3661. * has been set will cause the wait builtin to return immediately
  3662. * with an exit status greater than 128, immediately after which
  3663. * the trap is executed."
  3664. * Do we do it that way? */
  3665. blocking_wait_with_raise_on_sig(NULL);
  3666. }
  3667. }
  3668. retval = 127;
  3669. do {
  3670. if (**argv != '%') {
  3671. pid_t pid = number(*argv);
  3672. job = curjob;
  3673. while (1) {
  3674. if (!job)
  3675. goto repeat;
  3676. if (job->ps[job->nprocs - 1].ps_pid == pid)
  3677. break;
  3678. job = job->prev_job;
  3679. }
  3680. } else
  3681. job = getjob(*argv, 0);
  3682. /* loop until process terminated or stopped */
  3683. while (job->state == JOBRUNNING)
  3684. blocking_wait_with_raise_on_sig(NULL);
  3685. job->waited = 1;
  3686. retval = getstatus(job);
  3687. repeat: ;
  3688. } while (*++argv);
  3689. ret:
  3690. return retval;
  3691. }
  3692. static struct job *
  3693. growjobtab(void)
  3694. {
  3695. size_t len;
  3696. ptrdiff_t offset;
  3697. struct job *jp, *jq;
  3698. len = njobs * sizeof(*jp);
  3699. jq = jobtab;
  3700. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  3701. offset = (char *)jp - (char *)jq;
  3702. if (offset) {
  3703. /* Relocate pointers */
  3704. size_t l = len;
  3705. jq = (struct job *)((char *)jq + l);
  3706. while (l) {
  3707. l -= sizeof(*jp);
  3708. jq--;
  3709. #define joff(p) ((struct job *)((char *)(p) + l))
  3710. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  3711. if (joff(jp)->ps == &jq->ps0)
  3712. jmove(joff(jp)->ps);
  3713. if (joff(jp)->prev_job)
  3714. jmove(joff(jp)->prev_job);
  3715. }
  3716. if (curjob)
  3717. jmove(curjob);
  3718. #undef joff
  3719. #undef jmove
  3720. }
  3721. njobs += 4;
  3722. jobtab = jp;
  3723. jp = (struct job *)((char *)jp + len);
  3724. jq = jp + 3;
  3725. do {
  3726. jq->used = 0;
  3727. } while (--jq >= jp);
  3728. return jp;
  3729. }
  3730. /*
  3731. * Return a new job structure.
  3732. * Called with interrupts off.
  3733. */
  3734. static struct job *
  3735. makejob(/*union node *node,*/ int nprocs)
  3736. {
  3737. int i;
  3738. struct job *jp;
  3739. for (i = njobs, jp = jobtab; ; jp++) {
  3740. if (--i < 0) {
  3741. jp = growjobtab();
  3742. break;
  3743. }
  3744. if (jp->used == 0)
  3745. break;
  3746. if (jp->state != JOBDONE || !jp->waited)
  3747. continue;
  3748. #if JOBS
  3749. if (doing_jobctl)
  3750. continue;
  3751. #endif
  3752. freejob(jp);
  3753. break;
  3754. }
  3755. memset(jp, 0, sizeof(*jp));
  3756. #if JOBS
  3757. /* jp->jobctl is a bitfield.
  3758. * "jp->jobctl |= jobctl" likely to give awful code */
  3759. if (doing_jobctl)
  3760. jp->jobctl = 1;
  3761. #endif
  3762. jp->prev_job = curjob;
  3763. curjob = jp;
  3764. jp->used = 1;
  3765. jp->ps = &jp->ps0;
  3766. if (nprocs > 1) {
  3767. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  3768. }
  3769. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  3770. jobno(jp)));
  3771. return jp;
  3772. }
  3773. #if JOBS
  3774. /*
  3775. * Return a string identifying a command (to be printed by the
  3776. * jobs command).
  3777. */
  3778. static char *cmdnextc;
  3779. static void
  3780. cmdputs(const char *s)
  3781. {
  3782. static const char vstype[VSTYPE + 1][3] = {
  3783. "", "}", "-", "+", "?", "=",
  3784. "%", "%%", "#", "##"
  3785. IF_ASH_BASH_COMPAT(, ":", "/", "//")
  3786. };
  3787. const char *p, *str;
  3788. char cc[2];
  3789. char *nextc;
  3790. unsigned char c;
  3791. unsigned char subtype = 0;
  3792. int quoted = 0;
  3793. cc[1] = '\0';
  3794. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  3795. p = s;
  3796. while ((c = *p++) != '\0') {
  3797. str = NULL;
  3798. switch (c) {
  3799. case CTLESC:
  3800. c = *p++;
  3801. break;
  3802. case CTLVAR:
  3803. subtype = *p++;
  3804. if ((subtype & VSTYPE) == VSLENGTH)
  3805. str = "${#";
  3806. else
  3807. str = "${";
  3808. if (!(subtype & VSQUOTE) == !(quoted & 1))
  3809. goto dostr;
  3810. quoted ^= 1;
  3811. c = '"';
  3812. break;
  3813. case CTLENDVAR:
  3814. str = "\"}" + !(quoted & 1);
  3815. quoted >>= 1;
  3816. subtype = 0;
  3817. goto dostr;
  3818. case CTLBACKQ:
  3819. str = "$(...)";
  3820. goto dostr;
  3821. case CTLBACKQ+CTLQUOTE:
  3822. str = "\"$(...)\"";
  3823. goto dostr;
  3824. #if ENABLE_SH_MATH_SUPPORT
  3825. case CTLARI:
  3826. str = "$((";
  3827. goto dostr;
  3828. case CTLENDARI:
  3829. str = "))";
  3830. goto dostr;
  3831. #endif
  3832. case CTLQUOTEMARK:
  3833. quoted ^= 1;
  3834. c = '"';
  3835. break;
  3836. case '=':
  3837. if (subtype == 0)
  3838. break;
  3839. if ((subtype & VSTYPE) != VSNORMAL)
  3840. quoted <<= 1;
  3841. str = vstype[subtype & VSTYPE];
  3842. if (subtype & VSNUL)
  3843. c = ':';
  3844. else
  3845. goto checkstr;
  3846. break;
  3847. case '\'':
  3848. case '\\':
  3849. case '"':
  3850. case '$':
  3851. /* These can only happen inside quotes */
  3852. cc[0] = c;
  3853. str = cc;
  3854. c = '\\';
  3855. break;
  3856. default:
  3857. break;
  3858. }
  3859. USTPUTC(c, nextc);
  3860. checkstr:
  3861. if (!str)
  3862. continue;
  3863. dostr:
  3864. while ((c = *str++) != '\0') {
  3865. USTPUTC(c, nextc);
  3866. }
  3867. } /* while *p++ not NUL */
  3868. if (quoted & 1) {
  3869. USTPUTC('"', nextc);
  3870. }
  3871. *nextc = 0;
  3872. cmdnextc = nextc;
  3873. }
  3874. /* cmdtxt() and cmdlist() call each other */
  3875. static void cmdtxt(union node *n);
  3876. static void
  3877. cmdlist(union node *np, int sep)
  3878. {
  3879. for (; np; np = np->narg.next) {
  3880. if (!sep)
  3881. cmdputs(" ");
  3882. cmdtxt(np);
  3883. if (sep && np->narg.next)
  3884. cmdputs(" ");
  3885. }
  3886. }
  3887. static void
  3888. cmdtxt(union node *n)
  3889. {
  3890. union node *np;
  3891. struct nodelist *lp;
  3892. const char *p;
  3893. if (!n)
  3894. return;
  3895. switch (n->type) {
  3896. default:
  3897. #if DEBUG
  3898. abort();
  3899. #endif
  3900. case NPIPE:
  3901. lp = n->npipe.cmdlist;
  3902. for (;;) {
  3903. cmdtxt(lp->n);
  3904. lp = lp->next;
  3905. if (!lp)
  3906. break;
  3907. cmdputs(" | ");
  3908. }
  3909. break;
  3910. case NSEMI:
  3911. p = "; ";
  3912. goto binop;
  3913. case NAND:
  3914. p = " && ";
  3915. goto binop;
  3916. case NOR:
  3917. p = " || ";
  3918. binop:
  3919. cmdtxt(n->nbinary.ch1);
  3920. cmdputs(p);
  3921. n = n->nbinary.ch2;
  3922. goto donode;
  3923. case NREDIR:
  3924. case NBACKGND:
  3925. n = n->nredir.n;
  3926. goto donode;
  3927. case NNOT:
  3928. cmdputs("!");
  3929. n = n->nnot.com;
  3930. donode:
  3931. cmdtxt(n);
  3932. break;
  3933. case NIF:
  3934. cmdputs("if ");
  3935. cmdtxt(n->nif.test);
  3936. cmdputs("; then ");
  3937. if (n->nif.elsepart) {
  3938. cmdtxt(n->nif.ifpart);
  3939. cmdputs("; else ");
  3940. n = n->nif.elsepart;
  3941. } else {
  3942. n = n->nif.ifpart;
  3943. }
  3944. p = "; fi";
  3945. goto dotail;
  3946. case NSUBSHELL:
  3947. cmdputs("(");
  3948. n = n->nredir.n;
  3949. p = ")";
  3950. goto dotail;
  3951. case NWHILE:
  3952. p = "while ";
  3953. goto until;
  3954. case NUNTIL:
  3955. p = "until ";
  3956. until:
  3957. cmdputs(p);
  3958. cmdtxt(n->nbinary.ch1);
  3959. n = n->nbinary.ch2;
  3960. p = "; done";
  3961. dodo:
  3962. cmdputs("; do ");
  3963. dotail:
  3964. cmdtxt(n);
  3965. goto dotail2;
  3966. case NFOR:
  3967. cmdputs("for ");
  3968. cmdputs(n->nfor.var);
  3969. cmdputs(" in ");
  3970. cmdlist(n->nfor.args, 1);
  3971. n = n->nfor.body;
  3972. p = "; done";
  3973. goto dodo;
  3974. case NDEFUN:
  3975. cmdputs(n->narg.text);
  3976. p = "() { ... }";
  3977. goto dotail2;
  3978. case NCMD:
  3979. cmdlist(n->ncmd.args, 1);
  3980. cmdlist(n->ncmd.redirect, 0);
  3981. break;
  3982. case NARG:
  3983. p = n->narg.text;
  3984. dotail2:
  3985. cmdputs(p);
  3986. break;
  3987. case NHERE:
  3988. case NXHERE:
  3989. p = "<<...";
  3990. goto dotail2;
  3991. case NCASE:
  3992. cmdputs("case ");
  3993. cmdputs(n->ncase.expr->narg.text);
  3994. cmdputs(" in ");
  3995. for (np = n->ncase.cases; np; np = np->nclist.next) {
  3996. cmdtxt(np->nclist.pattern);
  3997. cmdputs(") ");
  3998. cmdtxt(np->nclist.body);
  3999. cmdputs(";; ");
  4000. }
  4001. p = "esac";
  4002. goto dotail2;
  4003. case NTO:
  4004. p = ">";
  4005. goto redir;
  4006. case NCLOBBER:
  4007. p = ">|";
  4008. goto redir;
  4009. case NAPPEND:
  4010. p = ">>";
  4011. goto redir;
  4012. #if ENABLE_ASH_BASH_COMPAT
  4013. case NTO2:
  4014. #endif
  4015. case NTOFD:
  4016. p = ">&";
  4017. goto redir;
  4018. case NFROM:
  4019. p = "<";
  4020. goto redir;
  4021. case NFROMFD:
  4022. p = "<&";
  4023. goto redir;
  4024. case NFROMTO:
  4025. p = "<>";
  4026. redir:
  4027. cmdputs(utoa(n->nfile.fd));
  4028. cmdputs(p);
  4029. if (n->type == NTOFD || n->type == NFROMFD) {
  4030. cmdputs(utoa(n->ndup.dupfd));
  4031. break;
  4032. }
  4033. n = n->nfile.fname;
  4034. goto donode;
  4035. }
  4036. }
  4037. static char *
  4038. commandtext(union node *n)
  4039. {
  4040. char *name;
  4041. STARTSTACKSTR(cmdnextc);
  4042. cmdtxt(n);
  4043. name = stackblock();
  4044. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  4045. name, cmdnextc, cmdnextc));
  4046. return ckstrdup(name);
  4047. }
  4048. #endif /* JOBS */
  4049. /*
  4050. * Fork off a subshell. If we are doing job control, give the subshell its
  4051. * own process group. Jp is a job structure that the job is to be added to.
  4052. * N is the command that will be evaluated by the child. Both jp and n may
  4053. * be NULL. The mode parameter can be one of the following:
  4054. * FORK_FG - Fork off a foreground process.
  4055. * FORK_BG - Fork off a background process.
  4056. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4057. * process group even if job control is on.
  4058. *
  4059. * When job control is turned off, background processes have their standard
  4060. * input redirected to /dev/null (except for the second and later processes
  4061. * in a pipeline).
  4062. *
  4063. * Called with interrupts off.
  4064. */
  4065. /*
  4066. * Clear traps on a fork.
  4067. */
  4068. static void
  4069. clear_traps(void)
  4070. {
  4071. char **tp;
  4072. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4073. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4074. INT_OFF;
  4075. if (trap_ptr == trap)
  4076. free(*tp);
  4077. /* else: it "belongs" to trap_ptr vector, don't free */
  4078. *tp = NULL;
  4079. if ((tp - trap) != 0)
  4080. setsignal(tp - trap);
  4081. INT_ON;
  4082. }
  4083. }
  4084. }
  4085. /* Lives far away from here, needed for forkchild */
  4086. static void closescript(void);
  4087. /* Called after fork(), in child */
  4088. static NOINLINE void
  4089. forkchild(struct job *jp, union node *n, int mode)
  4090. {
  4091. int oldlvl;
  4092. TRACE(("Child shell %d\n", getpid()));
  4093. oldlvl = shlvl;
  4094. shlvl++;
  4095. /* man bash: "Non-builtin commands run by bash have signal handlers
  4096. * set to the values inherited by the shell from its parent".
  4097. * Do we do it correctly? */
  4098. closescript();
  4099. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4100. && n && n->type == NCMD /* is it single cmd? */
  4101. /* && n->ncmd.args->type == NARG - always true? */
  4102. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4103. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4104. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4105. ) {
  4106. TRACE(("Trap hack\n"));
  4107. /* Awful hack for `trap` or $(trap).
  4108. *
  4109. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4110. * contains an example where "trap" is executed in a subshell:
  4111. *
  4112. * save_traps=$(trap)
  4113. * ...
  4114. * eval "$save_traps"
  4115. *
  4116. * Standard does not say that "trap" in subshell shall print
  4117. * parent shell's traps. It only says that its output
  4118. * must have suitable form, but then, in the above example
  4119. * (which is not supposed to be normative), it implies that.
  4120. *
  4121. * bash (and probably other shell) does implement it
  4122. * (traps are reset to defaults, but "trap" still shows them),
  4123. * but as a result, "trap" logic is hopelessly messed up:
  4124. *
  4125. * # trap
  4126. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4127. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4128. * # true | trap <--- trap is in subshell - no output (ditto)
  4129. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4130. * trap -- 'echo Ho' SIGWINCH
  4131. * # echo `(trap)` <--- in subshell in subshell - output
  4132. * trap -- 'echo Ho' SIGWINCH
  4133. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4134. * trap -- 'echo Ho' SIGWINCH
  4135. *
  4136. * The rules when to forget and when to not forget traps
  4137. * get really complex and nonsensical.
  4138. *
  4139. * Our solution: ONLY bare $(trap) or `trap` is special.
  4140. */
  4141. /* Save trap handler strings for trap builtin to print */
  4142. trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
  4143. /* Fall through into clearing traps */
  4144. }
  4145. clear_traps();
  4146. #if JOBS
  4147. /* do job control only in root shell */
  4148. doing_jobctl = 0;
  4149. if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
  4150. pid_t pgrp;
  4151. if (jp->nprocs == 0)
  4152. pgrp = getpid();
  4153. else
  4154. pgrp = jp->ps[0].ps_pid;
  4155. /* this can fail because we are doing it in the parent also */
  4156. setpgid(0, pgrp);
  4157. if (mode == FORK_FG)
  4158. xtcsetpgrp(ttyfd, pgrp);
  4159. setsignal(SIGTSTP);
  4160. setsignal(SIGTTOU);
  4161. } else
  4162. #endif
  4163. if (mode == FORK_BG) {
  4164. /* man bash: "When job control is not in effect,
  4165. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4166. ignoresig(SIGINT);
  4167. ignoresig(SIGQUIT);
  4168. if (jp->nprocs == 0) {
  4169. close(0);
  4170. if (open(bb_dev_null, O_RDONLY) != 0)
  4171. ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
  4172. }
  4173. }
  4174. if (!oldlvl) {
  4175. if (iflag) { /* why if iflag only? */
  4176. setsignal(SIGINT);
  4177. setsignal(SIGTERM);
  4178. }
  4179. /* man bash:
  4180. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4181. * commands run by bash have signal handlers
  4182. * set to the values inherited by the shell
  4183. * from its parent".
  4184. * Take care of the second rule: */
  4185. setsignal(SIGQUIT);
  4186. }
  4187. #if JOBS
  4188. if (n && n->type == NCMD
  4189. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4190. ) {
  4191. TRACE(("Job hack\n"));
  4192. /* "jobs": we do not want to clear job list for it,
  4193. * instead we remove only _its_ own_ job from job list.
  4194. * This makes "jobs .... | cat" more useful.
  4195. */
  4196. freejob(curjob);
  4197. return;
  4198. }
  4199. #endif
  4200. for (jp = curjob; jp; jp = jp->prev_job)
  4201. freejob(jp);
  4202. jobless = 0;
  4203. }
  4204. /* Called after fork(), in parent */
  4205. #if !JOBS
  4206. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4207. #endif
  4208. static void
  4209. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4210. {
  4211. TRACE(("In parent shell: child = %d\n", pid));
  4212. if (!jp) {
  4213. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4214. continue;
  4215. jobless++;
  4216. return;
  4217. }
  4218. #if JOBS
  4219. if (mode != FORK_NOJOB && jp->jobctl) {
  4220. int pgrp;
  4221. if (jp->nprocs == 0)
  4222. pgrp = pid;
  4223. else
  4224. pgrp = jp->ps[0].ps_pid;
  4225. /* This can fail because we are doing it in the child also */
  4226. setpgid(pid, pgrp);
  4227. }
  4228. #endif
  4229. if (mode == FORK_BG) {
  4230. backgndpid = pid; /* set $! */
  4231. set_curjob(jp, CUR_RUNNING);
  4232. }
  4233. if (jp) {
  4234. struct procstat *ps = &jp->ps[jp->nprocs++];
  4235. ps->ps_pid = pid;
  4236. ps->ps_status = -1;
  4237. ps->ps_cmd = nullstr;
  4238. #if JOBS
  4239. if (doing_jobctl && n)
  4240. ps->ps_cmd = commandtext(n);
  4241. #endif
  4242. }
  4243. }
  4244. static int
  4245. forkshell(struct job *jp, union node *n, int mode)
  4246. {
  4247. int pid;
  4248. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4249. pid = fork();
  4250. if (pid < 0) {
  4251. TRACE(("Fork failed, errno=%d", errno));
  4252. if (jp)
  4253. freejob(jp);
  4254. ash_msg_and_raise_error("can't fork");
  4255. }
  4256. if (pid == 0) {
  4257. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4258. forkchild(jp, n, mode);
  4259. } else {
  4260. forkparent(jp, n, mode, pid);
  4261. }
  4262. return pid;
  4263. }
  4264. /*
  4265. * Wait for job to finish.
  4266. *
  4267. * Under job control we have the problem that while a child process
  4268. * is running interrupts generated by the user are sent to the child
  4269. * but not to the shell. This means that an infinite loop started by
  4270. * an interactive user may be hard to kill. With job control turned off,
  4271. * an interactive user may place an interactive program inside a loop.
  4272. * If the interactive program catches interrupts, the user doesn't want
  4273. * these interrupts to also abort the loop. The approach we take here
  4274. * is to have the shell ignore interrupt signals while waiting for a
  4275. * foreground process to terminate, and then send itself an interrupt
  4276. * signal if the child process was terminated by an interrupt signal.
  4277. * Unfortunately, some programs want to do a bit of cleanup and then
  4278. * exit on interrupt; unless these processes terminate themselves by
  4279. * sending a signal to themselves (instead of calling exit) they will
  4280. * confuse this approach.
  4281. *
  4282. * Called with interrupts off.
  4283. */
  4284. static int
  4285. waitforjob(struct job *jp)
  4286. {
  4287. int st;
  4288. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4289. INT_OFF;
  4290. while (jp->state == JOBRUNNING) {
  4291. /* In non-interactive shells, we _can_ get
  4292. * a keyboard signal here and be EINTRed,
  4293. * but we just loop back, waiting for command to complete.
  4294. *
  4295. * man bash:
  4296. * "If bash is waiting for a command to complete and receives
  4297. * a signal for which a trap has been set, the trap
  4298. * will not be executed until the command completes."
  4299. *
  4300. * Reality is that even if trap is not set, bash
  4301. * will not act on the signal until command completes.
  4302. * Try this. sleep5intoff.c:
  4303. * #include <signal.h>
  4304. * #include <unistd.h>
  4305. * int main() {
  4306. * sigset_t set;
  4307. * sigemptyset(&set);
  4308. * sigaddset(&set, SIGINT);
  4309. * sigaddset(&set, SIGQUIT);
  4310. * sigprocmask(SIG_BLOCK, &set, NULL);
  4311. * sleep(5);
  4312. * return 0;
  4313. * }
  4314. * $ bash -c './sleep5intoff; echo hi'
  4315. * ^C^C^C^C <--- pressing ^C once a second
  4316. * $ _
  4317. * $ bash -c './sleep5intoff; echo hi'
  4318. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4319. * $ _
  4320. */
  4321. dowait(DOWAIT_BLOCK, jp);
  4322. }
  4323. INT_ON;
  4324. st = getstatus(jp);
  4325. #if JOBS
  4326. if (jp->jobctl) {
  4327. xtcsetpgrp(ttyfd, rootpid);
  4328. /*
  4329. * This is truly gross.
  4330. * If we're doing job control, then we did a TIOCSPGRP which
  4331. * caused us (the shell) to no longer be in the controlling
  4332. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4333. * intuit from the subprocess exit status whether a SIGINT
  4334. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4335. */
  4336. if (jp->sigint) /* TODO: do the same with all signals */
  4337. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4338. }
  4339. if (jp->state == JOBDONE)
  4340. #endif
  4341. freejob(jp);
  4342. return st;
  4343. }
  4344. /*
  4345. * return 1 if there are stopped jobs, otherwise 0
  4346. */
  4347. static int
  4348. stoppedjobs(void)
  4349. {
  4350. struct job *jp;
  4351. int retval;
  4352. retval = 0;
  4353. if (job_warning)
  4354. goto out;
  4355. jp = curjob;
  4356. if (jp && jp->state == JOBSTOPPED) {
  4357. out2str("You have stopped jobs.\n");
  4358. job_warning = 2;
  4359. retval++;
  4360. }
  4361. out:
  4362. return retval;
  4363. }
  4364. /* ============ redir.c
  4365. *
  4366. * Code for dealing with input/output redirection.
  4367. */
  4368. #define EMPTY -2 /* marks an unused slot in redirtab */
  4369. #define CLOSED -3 /* marks a slot of previously-closed fd */
  4370. /*
  4371. * Open a file in noclobber mode.
  4372. * The code was copied from bash.
  4373. */
  4374. static int
  4375. noclobberopen(const char *fname)
  4376. {
  4377. int r, fd;
  4378. struct stat finfo, finfo2;
  4379. /*
  4380. * If the file exists and is a regular file, return an error
  4381. * immediately.
  4382. */
  4383. r = stat(fname, &finfo);
  4384. if (r == 0 && S_ISREG(finfo.st_mode)) {
  4385. errno = EEXIST;
  4386. return -1;
  4387. }
  4388. /*
  4389. * If the file was not present (r != 0), make sure we open it
  4390. * exclusively so that if it is created before we open it, our open
  4391. * will fail. Make sure that we do not truncate an existing file.
  4392. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  4393. * file was not a regular file, we leave O_EXCL off.
  4394. */
  4395. if (r != 0)
  4396. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4397. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  4398. /* If the open failed, return the file descriptor right away. */
  4399. if (fd < 0)
  4400. return fd;
  4401. /*
  4402. * OK, the open succeeded, but the file may have been changed from a
  4403. * non-regular file to a regular file between the stat and the open.
  4404. * We are assuming that the O_EXCL open handles the case where FILENAME
  4405. * did not exist and is symlinked to an existing file between the stat
  4406. * and open.
  4407. */
  4408. /*
  4409. * If we can open it and fstat the file descriptor, and neither check
  4410. * revealed that it was a regular file, and the file has not been
  4411. * replaced, return the file descriptor.
  4412. */
  4413. if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
  4414. && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
  4415. return fd;
  4416. /* The file has been replaced. badness. */
  4417. close(fd);
  4418. errno = EEXIST;
  4419. return -1;
  4420. }
  4421. /*
  4422. * Handle here documents. Normally we fork off a process to write the
  4423. * data to a pipe. If the document is short, we can stuff the data in
  4424. * the pipe without forking.
  4425. */
  4426. /* openhere needs this forward reference */
  4427. static void expandhere(union node *arg, int fd);
  4428. static int
  4429. openhere(union node *redir)
  4430. {
  4431. int pip[2];
  4432. size_t len = 0;
  4433. if (pipe(pip) < 0)
  4434. ash_msg_and_raise_error("pipe call failed");
  4435. if (redir->type == NHERE) {
  4436. len = strlen(redir->nhere.doc->narg.text);
  4437. if (len <= PIPE_BUF) {
  4438. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4439. goto out;
  4440. }
  4441. }
  4442. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4443. /* child */
  4444. close(pip[0]);
  4445. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4446. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4447. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4448. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4449. signal(SIGPIPE, SIG_DFL);
  4450. if (redir->type == NHERE)
  4451. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4452. else /* NXHERE */
  4453. expandhere(redir->nhere.doc, pip[1]);
  4454. _exit(EXIT_SUCCESS);
  4455. }
  4456. out:
  4457. close(pip[1]);
  4458. return pip[0];
  4459. }
  4460. static int
  4461. openredirect(union node *redir)
  4462. {
  4463. char *fname;
  4464. int f;
  4465. switch (redir->nfile.type) {
  4466. case NFROM:
  4467. fname = redir->nfile.expfname;
  4468. f = open(fname, O_RDONLY);
  4469. if (f < 0)
  4470. goto eopen;
  4471. break;
  4472. case NFROMTO:
  4473. fname = redir->nfile.expfname;
  4474. f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
  4475. if (f < 0)
  4476. goto ecreate;
  4477. break;
  4478. case NTO:
  4479. #if ENABLE_ASH_BASH_COMPAT
  4480. case NTO2:
  4481. #endif
  4482. /* Take care of noclobber mode. */
  4483. if (Cflag) {
  4484. fname = redir->nfile.expfname;
  4485. f = noclobberopen(fname);
  4486. if (f < 0)
  4487. goto ecreate;
  4488. break;
  4489. }
  4490. /* FALLTHROUGH */
  4491. case NCLOBBER:
  4492. fname = redir->nfile.expfname;
  4493. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4494. if (f < 0)
  4495. goto ecreate;
  4496. break;
  4497. case NAPPEND:
  4498. fname = redir->nfile.expfname;
  4499. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4500. if (f < 0)
  4501. goto ecreate;
  4502. break;
  4503. default:
  4504. #if DEBUG
  4505. abort();
  4506. #endif
  4507. /* Fall through to eliminate warning. */
  4508. /* Our single caller does this itself */
  4509. // case NTOFD:
  4510. // case NFROMFD:
  4511. // f = -1;
  4512. // break;
  4513. case NHERE:
  4514. case NXHERE:
  4515. f = openhere(redir);
  4516. break;
  4517. }
  4518. return f;
  4519. ecreate:
  4520. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4521. eopen:
  4522. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4523. }
  4524. /*
  4525. * Copy a file descriptor to be >= to. Returns -1
  4526. * if the source file descriptor is closed, EMPTY if there are no unused
  4527. * file descriptors left.
  4528. */
  4529. /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
  4530. * old code was doing close(to) prior to copyfd() to achieve the same */
  4531. enum {
  4532. COPYFD_EXACT = (int)~(INT_MAX),
  4533. COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
  4534. };
  4535. static int
  4536. copyfd(int from, int to)
  4537. {
  4538. int newfd;
  4539. if (to & COPYFD_EXACT) {
  4540. to &= ~COPYFD_EXACT;
  4541. /*if (from != to)*/
  4542. newfd = dup2(from, to);
  4543. } else {
  4544. newfd = fcntl(from, F_DUPFD, to);
  4545. }
  4546. if (newfd < 0) {
  4547. if (errno == EMFILE)
  4548. return EMPTY;
  4549. /* Happens when source fd is not open: try "echo >&99" */
  4550. ash_msg_and_raise_error("%d: %m", from);
  4551. }
  4552. return newfd;
  4553. }
  4554. /* Struct def and variable are moved down to the first usage site */
  4555. struct two_fd_t {
  4556. int orig, copy;
  4557. };
  4558. struct redirtab {
  4559. struct redirtab *next;
  4560. int nullredirs;
  4561. int pair_count;
  4562. struct two_fd_t two_fd[];
  4563. };
  4564. #define redirlist (G_var.redirlist)
  4565. static int need_to_remember(struct redirtab *rp, int fd)
  4566. {
  4567. int i;
  4568. if (!rp) /* remembering was not requested */
  4569. return 0;
  4570. for (i = 0; i < rp->pair_count; i++) {
  4571. if (rp->two_fd[i].orig == fd) {
  4572. /* already remembered */
  4573. return 0;
  4574. }
  4575. }
  4576. return 1;
  4577. }
  4578. /* "hidden" fd is a fd used to read scripts, or a copy of such */
  4579. static int is_hidden_fd(struct redirtab *rp, int fd)
  4580. {
  4581. int i;
  4582. struct parsefile *pf;
  4583. if (fd == -1)
  4584. return 0;
  4585. pf = g_parsefile;
  4586. while (pf) {
  4587. if (fd == pf->fd) {
  4588. return 1;
  4589. }
  4590. pf = pf->prev;
  4591. }
  4592. if (!rp)
  4593. return 0;
  4594. fd |= COPYFD_RESTORE;
  4595. for (i = 0; i < rp->pair_count; i++) {
  4596. if (rp->two_fd[i].copy == fd) {
  4597. return 1;
  4598. }
  4599. }
  4600. return 0;
  4601. }
  4602. /*
  4603. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  4604. * old file descriptors are stashed away so that the redirection can be
  4605. * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
  4606. * standard output, and the standard error if it becomes a duplicate of
  4607. * stdout, is saved in memory.
  4608. */
  4609. /* flags passed to redirect */
  4610. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  4611. #define REDIR_SAVEFD2 03 /* set preverrout */
  4612. static void
  4613. redirect(union node *redir, int flags)
  4614. {
  4615. struct redirtab *sv;
  4616. int sv_pos;
  4617. int i;
  4618. int fd;
  4619. int newfd;
  4620. int copied_fd2 = -1;
  4621. g_nullredirs++;
  4622. if (!redir) {
  4623. return;
  4624. }
  4625. sv = NULL;
  4626. sv_pos = 0;
  4627. INT_OFF;
  4628. if (flags & REDIR_PUSH) {
  4629. union node *tmp = redir;
  4630. do {
  4631. sv_pos++;
  4632. #if ENABLE_ASH_BASH_COMPAT
  4633. if (tmp->nfile.type == NTO2)
  4634. sv_pos++;
  4635. #endif
  4636. tmp = tmp->nfile.next;
  4637. } while (tmp);
  4638. sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
  4639. sv->next = redirlist;
  4640. sv->pair_count = sv_pos;
  4641. redirlist = sv;
  4642. sv->nullredirs = g_nullredirs - 1;
  4643. g_nullredirs = 0;
  4644. while (sv_pos > 0) {
  4645. sv_pos--;
  4646. sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
  4647. }
  4648. }
  4649. do {
  4650. fd = redir->nfile.fd;
  4651. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  4652. int right_fd = redir->ndup.dupfd;
  4653. /* redirect from/to same file descriptor? */
  4654. if (right_fd == fd)
  4655. continue;
  4656. /* echo >&10 and 10 is a fd opened to the sh script? */
  4657. if (is_hidden_fd(sv, right_fd)) {
  4658. errno = EBADF; /* as if it is closed */
  4659. ash_msg_and_raise_error("%d: %m", right_fd);
  4660. }
  4661. newfd = -1;
  4662. } else {
  4663. newfd = openredirect(redir); /* always >= 0 */
  4664. if (fd == newfd) {
  4665. /* Descriptor wasn't open before redirect.
  4666. * Mark it for close in the future */
  4667. if (need_to_remember(sv, fd)) {
  4668. goto remember_to_close;
  4669. }
  4670. continue;
  4671. }
  4672. }
  4673. #if ENABLE_ASH_BASH_COMPAT
  4674. redirect_more:
  4675. #endif
  4676. if (need_to_remember(sv, fd)) {
  4677. /* Copy old descriptor */
  4678. i = fcntl(fd, F_DUPFD, 10);
  4679. /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
  4680. * are closed in popredir() in the child, preventing them from leaking
  4681. * into child. (popredir() also cleans up the mess in case of failures)
  4682. */
  4683. if (i == -1) {
  4684. i = errno;
  4685. if (i != EBADF) {
  4686. /* Strange error (e.g. "too many files" EMFILE?) */
  4687. if (newfd >= 0)
  4688. close(newfd);
  4689. errno = i;
  4690. ash_msg_and_raise_error("%d: %m", fd);
  4691. /* NOTREACHED */
  4692. }
  4693. /* EBADF: it is not open - good, remember to close it */
  4694. remember_to_close:
  4695. i = CLOSED;
  4696. } else { /* fd is open, save its copy */
  4697. /* "exec fd>&-" should not close fds
  4698. * which point to script file(s).
  4699. * Force them to be restored afterwards */
  4700. if (is_hidden_fd(sv, fd))
  4701. i |= COPYFD_RESTORE;
  4702. }
  4703. if (fd == 2)
  4704. copied_fd2 = i;
  4705. sv->two_fd[sv_pos].orig = fd;
  4706. sv->two_fd[sv_pos].copy = i;
  4707. sv_pos++;
  4708. }
  4709. if (newfd < 0) {
  4710. /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
  4711. if (redir->ndup.dupfd < 0) { /* "fd>&-" */
  4712. /* Don't want to trigger debugging */
  4713. if (fd != -1)
  4714. close(fd);
  4715. } else {
  4716. copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
  4717. }
  4718. } else if (fd != newfd) { /* move newfd to fd */
  4719. copyfd(newfd, fd | COPYFD_EXACT);
  4720. #if ENABLE_ASH_BASH_COMPAT
  4721. if (!(redir->nfile.type == NTO2 && fd == 2))
  4722. #endif
  4723. close(newfd);
  4724. }
  4725. #if ENABLE_ASH_BASH_COMPAT
  4726. if (redir->nfile.type == NTO2 && fd == 1) {
  4727. /* We already redirected it to fd 1, now copy it to 2 */
  4728. newfd = 1;
  4729. fd = 2;
  4730. goto redirect_more;
  4731. }
  4732. #endif
  4733. } while ((redir = redir->nfile.next) != NULL);
  4734. INT_ON;
  4735. if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  4736. preverrout_fd = copied_fd2;
  4737. }
  4738. /*
  4739. * Undo the effects of the last redirection.
  4740. */
  4741. static void
  4742. popredir(int drop, int restore)
  4743. {
  4744. struct redirtab *rp;
  4745. int i;
  4746. if (--g_nullredirs >= 0)
  4747. return;
  4748. INT_OFF;
  4749. rp = redirlist;
  4750. for (i = 0; i < rp->pair_count; i++) {
  4751. int fd = rp->two_fd[i].orig;
  4752. int copy = rp->two_fd[i].copy;
  4753. if (copy == CLOSED) {
  4754. if (!drop)
  4755. close(fd);
  4756. continue;
  4757. }
  4758. if (copy != EMPTY) {
  4759. if (!drop || (restore && (copy & COPYFD_RESTORE))) {
  4760. copy &= ~COPYFD_RESTORE;
  4761. /*close(fd);*/
  4762. copyfd(copy, fd | COPYFD_EXACT);
  4763. }
  4764. close(copy & ~COPYFD_RESTORE);
  4765. }
  4766. }
  4767. redirlist = rp->next;
  4768. g_nullredirs = rp->nullredirs;
  4769. free(rp);
  4770. INT_ON;
  4771. }
  4772. /*
  4773. * Undo all redirections. Called on error or interrupt.
  4774. */
  4775. /*
  4776. * Discard all saved file descriptors.
  4777. */
  4778. static void
  4779. clearredir(int drop)
  4780. {
  4781. for (;;) {
  4782. g_nullredirs = 0;
  4783. if (!redirlist)
  4784. break;
  4785. popredir(drop, /*restore:*/ 0);
  4786. }
  4787. }
  4788. static int
  4789. redirectsafe(union node *redir, int flags)
  4790. {
  4791. int err;
  4792. volatile int saveint;
  4793. struct jmploc *volatile savehandler = exception_handler;
  4794. struct jmploc jmploc;
  4795. SAVE_INT(saveint);
  4796. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  4797. err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
  4798. if (!err) {
  4799. exception_handler = &jmploc;
  4800. redirect(redir, flags);
  4801. }
  4802. exception_handler = savehandler;
  4803. if (err && exception_type != EXERROR)
  4804. longjmp(exception_handler->loc, 1);
  4805. RESTORE_INT(saveint);
  4806. return err;
  4807. }
  4808. /* ============ Routines to expand arguments to commands
  4809. *
  4810. * We have to deal with backquotes, shell variables, and file metacharacters.
  4811. */
  4812. #if ENABLE_SH_MATH_SUPPORT
  4813. static arith_t
  4814. ash_arith(const char *s)
  4815. {
  4816. arith_eval_hooks_t math_hooks;
  4817. arith_t result;
  4818. int errcode = 0;
  4819. math_hooks.lookupvar = lookupvar;
  4820. math_hooks.setvar = setvar2;
  4821. math_hooks.endofname = endofname;
  4822. INT_OFF;
  4823. result = arith(s, &errcode, &math_hooks);
  4824. if (errcode < 0) {
  4825. if (errcode == -3)
  4826. ash_msg_and_raise_error("exponent less than 0");
  4827. if (errcode == -2)
  4828. ash_msg_and_raise_error("divide by zero");
  4829. if (errcode == -5)
  4830. ash_msg_and_raise_error("expression recursion loop detected");
  4831. raise_error_syntax(s);
  4832. }
  4833. INT_ON;
  4834. return result;
  4835. }
  4836. #endif
  4837. /*
  4838. * expandarg flags
  4839. */
  4840. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  4841. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  4842. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  4843. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  4844. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  4845. #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
  4846. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  4847. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  4848. #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
  4849. /*
  4850. * rmescape() flags
  4851. */
  4852. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  4853. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  4854. #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
  4855. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  4856. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  4857. /*
  4858. * Structure specifying which parts of the string should be searched
  4859. * for IFS characters.
  4860. */
  4861. struct ifsregion {
  4862. struct ifsregion *next; /* next region in list */
  4863. int begoff; /* offset of start of region */
  4864. int endoff; /* offset of end of region */
  4865. int nulonly; /* search for nul bytes only */
  4866. };
  4867. struct arglist {
  4868. struct strlist *list;
  4869. struct strlist **lastp;
  4870. };
  4871. /* output of current string */
  4872. static char *expdest;
  4873. /* list of back quote expressions */
  4874. static struct nodelist *argbackq;
  4875. /* first struct in list of ifs regions */
  4876. static struct ifsregion ifsfirst;
  4877. /* last struct in list */
  4878. static struct ifsregion *ifslastp;
  4879. /* holds expanded arg list */
  4880. static struct arglist exparg;
  4881. /*
  4882. * Our own itoa().
  4883. */
  4884. static int
  4885. cvtnum(arith_t num)
  4886. {
  4887. int len;
  4888. expdest = makestrspace(32, expdest);
  4889. len = fmtstr(expdest, 32, arith_t_fmt, num);
  4890. STADJUST(len, expdest);
  4891. return len;
  4892. }
  4893. static size_t
  4894. esclen(const char *start, const char *p)
  4895. {
  4896. size_t esc = 0;
  4897. while (p > start && (unsigned char)*--p == CTLESC) {
  4898. esc++;
  4899. }
  4900. return esc;
  4901. }
  4902. /*
  4903. * Remove any CTLESC characters from a string.
  4904. */
  4905. static char *
  4906. rmescapes(char *str, int flag)
  4907. {
  4908. static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
  4909. char *p, *q, *r;
  4910. unsigned inquotes;
  4911. unsigned protect_against_glob;
  4912. unsigned globbing;
  4913. p = strpbrk(str, qchars);
  4914. if (!p)
  4915. return str;
  4916. q = p;
  4917. r = str;
  4918. if (flag & RMESCAPE_ALLOC) {
  4919. size_t len = p - str;
  4920. size_t fulllen = len + strlen(p) + 1;
  4921. if (flag & RMESCAPE_GROW) {
  4922. int strloc = str - (char *)stackblock();
  4923. r = makestrspace(fulllen, expdest);
  4924. /* p and str may be invalidated by makestrspace */
  4925. str = (char *)stackblock() + strloc;
  4926. p = str + len;
  4927. } else if (flag & RMESCAPE_HEAP) {
  4928. r = ckmalloc(fulllen);
  4929. } else {
  4930. r = stalloc(fulllen);
  4931. }
  4932. q = r;
  4933. if (len > 0) {
  4934. q = (char *)memcpy(q, str, len) + len;
  4935. }
  4936. }
  4937. inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
  4938. globbing = flag & RMESCAPE_GLOB;
  4939. protect_against_glob = globbing;
  4940. while (*p) {
  4941. if ((unsigned char)*p == CTLQUOTEMARK) {
  4942. // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
  4943. // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
  4944. // Note: both inquotes and protect_against_glob only affect whether
  4945. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  4946. inquotes = ~inquotes;
  4947. p++;
  4948. protect_against_glob = globbing;
  4949. continue;
  4950. }
  4951. if (*p == '\\') {
  4952. /* naked back slash */
  4953. protect_against_glob = 0;
  4954. goto copy;
  4955. }
  4956. if ((unsigned char)*p == CTLESC) {
  4957. p++;
  4958. if (protect_against_glob && inquotes && *p != '/') {
  4959. *q++ = '\\';
  4960. }
  4961. }
  4962. protect_against_glob = globbing;
  4963. copy:
  4964. *q++ = *p++;
  4965. }
  4966. *q = '\0';
  4967. if (flag & RMESCAPE_GROW) {
  4968. expdest = r;
  4969. STADJUST(q - r + 1, expdest);
  4970. }
  4971. return r;
  4972. }
  4973. #define pmatch(a, b) !fnmatch((a), (b), 0)
  4974. /*
  4975. * Prepare a pattern for a expmeta (internal glob(3)) call.
  4976. *
  4977. * Returns an stalloced string.
  4978. */
  4979. static char *
  4980. preglob(const char *pattern, int quoted, int flag)
  4981. {
  4982. flag |= RMESCAPE_GLOB;
  4983. if (quoted) {
  4984. flag |= RMESCAPE_QUOTED;
  4985. }
  4986. return rmescapes((char *)pattern, flag);
  4987. }
  4988. /*
  4989. * Put a string on the stack.
  4990. */
  4991. static void
  4992. memtodest(const char *p, size_t len, int syntax, int quotes)
  4993. {
  4994. char *q = expdest;
  4995. q = makestrspace(quotes ? len * 2 : len, q);
  4996. while (len--) {
  4997. unsigned char c = *p++;
  4998. if (c == '\0')
  4999. continue;
  5000. if (quotes) {
  5001. int n = SIT(c, syntax);
  5002. if (n == CCTL || n == CBACK)
  5003. USTPUTC(CTLESC, q);
  5004. }
  5005. USTPUTC(c, q);
  5006. }
  5007. expdest = q;
  5008. }
  5009. static void
  5010. strtodest(const char *p, int syntax, int quotes)
  5011. {
  5012. memtodest(p, strlen(p), syntax, quotes);
  5013. }
  5014. /*
  5015. * Record the fact that we have to scan this region of the
  5016. * string for IFS characters.
  5017. */
  5018. static void
  5019. recordregion(int start, int end, int nulonly)
  5020. {
  5021. struct ifsregion *ifsp;
  5022. if (ifslastp == NULL) {
  5023. ifsp = &ifsfirst;
  5024. } else {
  5025. INT_OFF;
  5026. ifsp = ckzalloc(sizeof(*ifsp));
  5027. /*ifsp->next = NULL; - ckzalloc did it */
  5028. ifslastp->next = ifsp;
  5029. INT_ON;
  5030. }
  5031. ifslastp = ifsp;
  5032. ifslastp->begoff = start;
  5033. ifslastp->endoff = end;
  5034. ifslastp->nulonly = nulonly;
  5035. }
  5036. static void
  5037. removerecordregions(int endoff)
  5038. {
  5039. if (ifslastp == NULL)
  5040. return;
  5041. if (ifsfirst.endoff > endoff) {
  5042. while (ifsfirst.next != NULL) {
  5043. struct ifsregion *ifsp;
  5044. INT_OFF;
  5045. ifsp = ifsfirst.next->next;
  5046. free(ifsfirst.next);
  5047. ifsfirst.next = ifsp;
  5048. INT_ON;
  5049. }
  5050. if (ifsfirst.begoff > endoff)
  5051. ifslastp = NULL;
  5052. else {
  5053. ifslastp = &ifsfirst;
  5054. ifsfirst.endoff = endoff;
  5055. }
  5056. return;
  5057. }
  5058. ifslastp = &ifsfirst;
  5059. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5060. ifslastp=ifslastp->next;
  5061. while (ifslastp->next != NULL) {
  5062. struct ifsregion *ifsp;
  5063. INT_OFF;
  5064. ifsp = ifslastp->next->next;
  5065. free(ifslastp->next);
  5066. ifslastp->next = ifsp;
  5067. INT_ON;
  5068. }
  5069. if (ifslastp->endoff > endoff)
  5070. ifslastp->endoff = endoff;
  5071. }
  5072. static char *
  5073. exptilde(char *startp, char *p, int flags)
  5074. {
  5075. unsigned char c;
  5076. char *name;
  5077. struct passwd *pw;
  5078. const char *home;
  5079. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
  5080. int startloc;
  5081. name = p + 1;
  5082. while ((c = *++p) != '\0') {
  5083. switch (c) {
  5084. case CTLESC:
  5085. return startp;
  5086. case CTLQUOTEMARK:
  5087. return startp;
  5088. case ':':
  5089. if (flags & EXP_VARTILDE)
  5090. goto done;
  5091. break;
  5092. case '/':
  5093. case CTLENDVAR:
  5094. goto done;
  5095. }
  5096. }
  5097. done:
  5098. *p = '\0';
  5099. if (*name == '\0') {
  5100. home = lookupvar(homestr);
  5101. } else {
  5102. pw = getpwnam(name);
  5103. if (pw == NULL)
  5104. goto lose;
  5105. home = pw->pw_dir;
  5106. }
  5107. if (!home || !*home)
  5108. goto lose;
  5109. *p = c;
  5110. startloc = expdest - (char *)stackblock();
  5111. strtodest(home, SQSYNTAX, quotes);
  5112. recordregion(startloc, expdest - (char *)stackblock(), 0);
  5113. return p;
  5114. lose:
  5115. *p = c;
  5116. return startp;
  5117. }
  5118. /*
  5119. * Execute a command inside back quotes. If it's a builtin command, we
  5120. * want to save its output in a block obtained from malloc. Otherwise
  5121. * we fork off a subprocess and get the output of the command via a pipe.
  5122. * Should be called with interrupts off.
  5123. */
  5124. struct backcmd { /* result of evalbackcmd */
  5125. int fd; /* file descriptor to read from */
  5126. int nleft; /* number of chars in buffer */
  5127. char *buf; /* buffer */
  5128. struct job *jp; /* job structure for command */
  5129. };
  5130. /* These forward decls are needed to use "eval" code for backticks handling: */
  5131. static uint8_t back_exitstatus; /* exit status of backquoted command */
  5132. #define EV_EXIT 01 /* exit after evaluating tree */
  5133. static void evaltree(union node *, int);
  5134. static void FAST_FUNC
  5135. evalbackcmd(union node *n, struct backcmd *result)
  5136. {
  5137. int saveherefd;
  5138. result->fd = -1;
  5139. result->buf = NULL;
  5140. result->nleft = 0;
  5141. result->jp = NULL;
  5142. if (n == NULL)
  5143. goto out;
  5144. saveherefd = herefd;
  5145. herefd = -1;
  5146. {
  5147. int pip[2];
  5148. struct job *jp;
  5149. if (pipe(pip) < 0)
  5150. ash_msg_and_raise_error("pipe call failed");
  5151. jp = makejob(/*n,*/ 1);
  5152. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5153. FORCE_INT_ON;
  5154. close(pip[0]);
  5155. if (pip[1] != 1) {
  5156. /*close(1);*/
  5157. copyfd(pip[1], 1 | COPYFD_EXACT);
  5158. close(pip[1]);
  5159. }
  5160. eflag = 0;
  5161. evaltree(n, EV_EXIT); /* actually evaltreenr... */
  5162. /* NOTREACHED */
  5163. }
  5164. close(pip[1]);
  5165. result->fd = pip[0];
  5166. result->jp = jp;
  5167. }
  5168. herefd = saveherefd;
  5169. out:
  5170. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5171. result->fd, result->buf, result->nleft, result->jp));
  5172. }
  5173. /*
  5174. * Expand stuff in backwards quotes.
  5175. */
  5176. static void
  5177. expbackq(union node *cmd, int quoted, int quotes)
  5178. {
  5179. struct backcmd in;
  5180. int i;
  5181. char buf[128];
  5182. char *p;
  5183. char *dest;
  5184. int startloc;
  5185. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5186. struct stackmark smark;
  5187. INT_OFF;
  5188. setstackmark(&smark);
  5189. dest = expdest;
  5190. startloc = dest - (char *)stackblock();
  5191. grabstackstr(dest);
  5192. evalbackcmd(cmd, &in);
  5193. popstackmark(&smark);
  5194. p = in.buf;
  5195. i = in.nleft;
  5196. if (i == 0)
  5197. goto read;
  5198. for (;;) {
  5199. memtodest(p, i, syntax, quotes);
  5200. read:
  5201. if (in.fd < 0)
  5202. break;
  5203. i = nonblock_safe_read(in.fd, buf, sizeof(buf));
  5204. TRACE(("expbackq: read returns %d\n", i));
  5205. if (i <= 0)
  5206. break;
  5207. p = buf;
  5208. }
  5209. free(in.buf);
  5210. if (in.fd >= 0) {
  5211. close(in.fd);
  5212. back_exitstatus = waitforjob(in.jp);
  5213. }
  5214. INT_ON;
  5215. /* Eat all trailing newlines */
  5216. dest = expdest;
  5217. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5218. STUNPUTC(dest);
  5219. expdest = dest;
  5220. if (quoted == 0)
  5221. recordregion(startloc, dest - (char *)stackblock(), 0);
  5222. TRACE(("evalbackq: size=%d: \"%.*s\"\n",
  5223. (dest - (char *)stackblock()) - startloc,
  5224. (dest - (char *)stackblock()) - startloc,
  5225. stackblock() + startloc));
  5226. }
  5227. #if ENABLE_SH_MATH_SUPPORT
  5228. /*
  5229. * Expand arithmetic expression. Backup to start of expression,
  5230. * evaluate, place result in (backed up) result, adjust string position.
  5231. */
  5232. static void
  5233. expari(int quotes)
  5234. {
  5235. char *p, *start;
  5236. int begoff;
  5237. int flag;
  5238. int len;
  5239. /* ifsfree(); */
  5240. /*
  5241. * This routine is slightly over-complicated for
  5242. * efficiency. Next we scan backwards looking for the
  5243. * start of arithmetic.
  5244. */
  5245. start = stackblock();
  5246. p = expdest - 1;
  5247. *p = '\0';
  5248. p--;
  5249. do {
  5250. int esc;
  5251. while ((unsigned char)*p != CTLARI) {
  5252. p--;
  5253. #if DEBUG
  5254. if (p < start) {
  5255. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5256. }
  5257. #endif
  5258. }
  5259. esc = esclen(start, p);
  5260. if (!(esc % 2)) {
  5261. break;
  5262. }
  5263. p -= esc + 1;
  5264. } while (1);
  5265. begoff = p - start;
  5266. removerecordregions(begoff);
  5267. flag = p[1];
  5268. expdest = p;
  5269. if (quotes)
  5270. rmescapes(p + 2, 0);
  5271. len = cvtnum(ash_arith(p + 2));
  5272. if (flag != '"')
  5273. recordregion(begoff, begoff + len, 0);
  5274. }
  5275. #endif
  5276. /* argstr needs it */
  5277. static char *evalvar(char *p, int flags, struct strlist *var_str_list);
  5278. /*
  5279. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5280. * characters to allow for further processing. Otherwise treat
  5281. * $@ like $* since no splitting will be performed.
  5282. *
  5283. * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
  5284. * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
  5285. * for correct expansion of "B=$A" word.
  5286. */
  5287. static void
  5288. argstr(char *p, int flags, struct strlist *var_str_list)
  5289. {
  5290. static const char spclchars[] ALIGN1 = {
  5291. '=',
  5292. ':',
  5293. CTLQUOTEMARK,
  5294. CTLENDVAR,
  5295. CTLESC,
  5296. CTLVAR,
  5297. CTLBACKQ,
  5298. CTLBACKQ | CTLQUOTE,
  5299. #if ENABLE_SH_MATH_SUPPORT
  5300. CTLENDARI,
  5301. #endif
  5302. '\0'
  5303. };
  5304. const char *reject = spclchars;
  5305. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
  5306. int breakall = flags & EXP_WORD;
  5307. int inquotes;
  5308. size_t length;
  5309. int startloc;
  5310. if (!(flags & EXP_VARTILDE)) {
  5311. reject += 2;
  5312. } else if (flags & EXP_VARTILDE2) {
  5313. reject++;
  5314. }
  5315. inquotes = 0;
  5316. length = 0;
  5317. if (flags & EXP_TILDE) {
  5318. char *q;
  5319. flags &= ~EXP_TILDE;
  5320. tilde:
  5321. q = p;
  5322. if (*q == CTLESC && (flags & EXP_QWORD))
  5323. q++;
  5324. if (*q == '~')
  5325. p = exptilde(p, q, flags);
  5326. }
  5327. start:
  5328. startloc = expdest - (char *)stackblock();
  5329. for (;;) {
  5330. unsigned char c;
  5331. length += strcspn(p + length, reject);
  5332. c = p[length];
  5333. if (c) {
  5334. if (!(c & 0x80)
  5335. #if ENABLE_SH_MATH_SUPPORT
  5336. || c == CTLENDARI
  5337. #endif
  5338. ) {
  5339. /* c == '=' || c == ':' || c == CTLENDARI */
  5340. length++;
  5341. }
  5342. }
  5343. if (length > 0) {
  5344. int newloc;
  5345. expdest = stack_nputstr(p, length, expdest);
  5346. newloc = expdest - (char *)stackblock();
  5347. if (breakall && !inquotes && newloc > startloc) {
  5348. recordregion(startloc, newloc, 0);
  5349. }
  5350. startloc = newloc;
  5351. }
  5352. p += length + 1;
  5353. length = 0;
  5354. switch (c) {
  5355. case '\0':
  5356. goto breakloop;
  5357. case '=':
  5358. if (flags & EXP_VARTILDE2) {
  5359. p--;
  5360. continue;
  5361. }
  5362. flags |= EXP_VARTILDE2;
  5363. reject++;
  5364. /* fall through */
  5365. case ':':
  5366. /*
  5367. * sort of a hack - expand tildes in variable
  5368. * assignments (after the first '=' and after ':'s).
  5369. */
  5370. if (*--p == '~') {
  5371. goto tilde;
  5372. }
  5373. continue;
  5374. }
  5375. switch (c) {
  5376. case CTLENDVAR: /* ??? */
  5377. goto breakloop;
  5378. case CTLQUOTEMARK:
  5379. /* "$@" syntax adherence hack */
  5380. if (!inquotes
  5381. && memcmp(p, dolatstr, 4) == 0
  5382. && ( p[4] == CTLQUOTEMARK
  5383. || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
  5384. )
  5385. ) {
  5386. p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
  5387. goto start;
  5388. }
  5389. inquotes = !inquotes;
  5390. addquote:
  5391. if (quotes) {
  5392. p--;
  5393. length++;
  5394. startloc++;
  5395. }
  5396. break;
  5397. case CTLESC:
  5398. startloc++;
  5399. length++;
  5400. goto addquote;
  5401. case CTLVAR:
  5402. p = evalvar(p, flags, var_str_list);
  5403. goto start;
  5404. case CTLBACKQ:
  5405. c = '\0';
  5406. case CTLBACKQ|CTLQUOTE:
  5407. expbackq(argbackq->n, c, quotes);
  5408. argbackq = argbackq->next;
  5409. goto start;
  5410. #if ENABLE_SH_MATH_SUPPORT
  5411. case CTLENDARI:
  5412. p--;
  5413. expari(quotes);
  5414. goto start;
  5415. #endif
  5416. }
  5417. }
  5418. breakloop:
  5419. ;
  5420. }
  5421. static char *
  5422. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
  5423. int zero)
  5424. {
  5425. // This commented out code was added by James Simmons <jsimmons@infradead.org>
  5426. // as part of a larger change when he added support for ${var/a/b}.
  5427. // However, it broke # and % operators:
  5428. //
  5429. //var=ababcdcd
  5430. // ok bad
  5431. //echo ${var#ab} abcdcd abcdcd
  5432. //echo ${var##ab} abcdcd abcdcd
  5433. //echo ${var#a*b} abcdcd ababcdcd (!)
  5434. //echo ${var##a*b} cdcd cdcd
  5435. //echo ${var#?} babcdcd ababcdcd (!)
  5436. //echo ${var##?} babcdcd babcdcd
  5437. //echo ${var#*} ababcdcd babcdcd (!)
  5438. //echo ${var##*}
  5439. //echo ${var%cd} ababcd ababcd
  5440. //echo ${var%%cd} ababcd abab (!)
  5441. //echo ${var%c*d} ababcd ababcd
  5442. //echo ${var%%c*d} abab ababcdcd (!)
  5443. //echo ${var%?} ababcdc ababcdc
  5444. //echo ${var%%?} ababcdc ababcdcd (!)
  5445. //echo ${var%*} ababcdcd ababcdcd
  5446. //echo ${var%%*}
  5447. //
  5448. // Commenting it back out helped. Remove it completely if it really
  5449. // is not needed.
  5450. char *loc, *loc2; //, *full;
  5451. char c;
  5452. loc = startp;
  5453. loc2 = rmesc;
  5454. do {
  5455. int match; // = strlen(str);
  5456. const char *s = loc2;
  5457. c = *loc2;
  5458. if (zero) {
  5459. *loc2 = '\0';
  5460. s = rmesc;
  5461. }
  5462. match = pmatch(str, s); // this line was deleted
  5463. // // chop off end if its '*'
  5464. // full = strrchr(str, '*');
  5465. // if (full && full != str)
  5466. // match--;
  5467. //
  5468. // // If str starts with '*' replace with s.
  5469. // if ((*str == '*') && strlen(s) >= match) {
  5470. // full = xstrdup(s);
  5471. // strncpy(full+strlen(s)-match+1, str+1, match-1);
  5472. // } else
  5473. // full = xstrndup(str, match);
  5474. // match = strncmp(s, full, strlen(full));
  5475. // free(full);
  5476. //
  5477. *loc2 = c;
  5478. if (match) // if (!match)
  5479. return loc;
  5480. if (quotes && (unsigned char)*loc == CTLESC)
  5481. loc++;
  5482. loc++;
  5483. loc2++;
  5484. } while (c);
  5485. return 0;
  5486. }
  5487. static char *
  5488. scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
  5489. {
  5490. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5491. int try2optimize = match_at_start;
  5492. #endif
  5493. int esc = 0;
  5494. char *loc;
  5495. char *loc2;
  5496. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  5497. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  5498. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  5499. * Logic:
  5500. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  5501. * and on each iteration they go back two/one char until they reach the beginning.
  5502. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  5503. */
  5504. /* TODO: document in what other circumstances we are called. */
  5505. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  5506. int match;
  5507. char c = *loc2;
  5508. const char *s = loc2;
  5509. if (match_at_start) {
  5510. *loc2 = '\0';
  5511. s = rmesc;
  5512. }
  5513. match = pmatch(pattern, s);
  5514. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  5515. *loc2 = c;
  5516. if (match)
  5517. return loc;
  5518. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5519. if (try2optimize) {
  5520. /* Maybe we can optimize this:
  5521. * if pattern ends with unescaped *, we can avoid checking
  5522. * shorter strings: if "foo*" doesnt match "raw_value_of_v",
  5523. * it wont match truncated "raw_value_of_" strings too.
  5524. */
  5525. unsigned plen = strlen(pattern);
  5526. /* Does it end with "*"? */
  5527. if (plen != 0 && pattern[--plen] == '*') {
  5528. /* "xxxx*" is not escaped */
  5529. /* "xxx\*" is escaped */
  5530. /* "xx\\*" is not escaped */
  5531. /* "x\\\*" is escaped */
  5532. int slashes = 0;
  5533. while (plen != 0 && pattern[--plen] == '\\')
  5534. slashes++;
  5535. if (!(slashes & 1))
  5536. break; /* ends with unescaped "*" */
  5537. }
  5538. try2optimize = 0;
  5539. }
  5540. #endif
  5541. loc--;
  5542. if (quotes) {
  5543. if (--esc < 0) {
  5544. esc = esclen(startp, loc);
  5545. }
  5546. if (esc % 2) {
  5547. esc--;
  5548. loc--;
  5549. }
  5550. }
  5551. }
  5552. return 0;
  5553. }
  5554. static void varunset(const char *, const char *, const char *, int) NORETURN;
  5555. static void
  5556. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5557. {
  5558. const char *msg;
  5559. const char *tail;
  5560. tail = nullstr;
  5561. msg = "parameter not set";
  5562. if (umsg) {
  5563. if ((unsigned char)*end == CTLENDVAR) {
  5564. if (varflags & VSNUL)
  5565. tail = " or null";
  5566. } else {
  5567. msg = umsg;
  5568. }
  5569. }
  5570. ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
  5571. }
  5572. #if ENABLE_ASH_BASH_COMPAT
  5573. static char *
  5574. parse_sub_pattern(char *arg, int inquotes)
  5575. {
  5576. char *idx, *repl = NULL;
  5577. unsigned char c;
  5578. idx = arg;
  5579. while (1) {
  5580. c = *arg;
  5581. if (!c)
  5582. break;
  5583. if (c == '/') {
  5584. /* Only the first '/' seen is our separator */
  5585. if (!repl) {
  5586. repl = idx + 1;
  5587. c = '\0';
  5588. }
  5589. }
  5590. *idx++ = c;
  5591. if (!inquotes && c == '\\' && arg[1] == '\\')
  5592. arg++; /* skip both \\, not just first one */
  5593. arg++;
  5594. }
  5595. *idx = c; /* NUL */
  5596. return repl;
  5597. }
  5598. #endif /* ENABLE_ASH_BASH_COMPAT */
  5599. static const char *
  5600. subevalvar(char *p, char *str, int strloc, int subtype,
  5601. int startloc, int varflags, int quotes, struct strlist *var_str_list)
  5602. {
  5603. struct nodelist *saveargbackq = argbackq;
  5604. char *startp;
  5605. char *loc;
  5606. char *rmesc, *rmescend;
  5607. IF_ASH_BASH_COMPAT(char *repl = NULL;)
  5608. IF_ASH_BASH_COMPAT(char null = '\0';)
  5609. IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
  5610. int saveherefd = herefd;
  5611. int amount, workloc, resetloc;
  5612. int zero;
  5613. char *(*scan)(char*, char*, char*, char*, int, int);
  5614. herefd = -1;
  5615. argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
  5616. var_str_list);
  5617. STPUTC('\0', expdest);
  5618. herefd = saveherefd;
  5619. argbackq = saveargbackq;
  5620. startp = (char *)stackblock() + startloc;
  5621. switch (subtype) {
  5622. case VSASSIGN:
  5623. setvar(str, startp, 0);
  5624. amount = startp - expdest;
  5625. STADJUST(amount, expdest);
  5626. return startp;
  5627. #if ENABLE_ASH_BASH_COMPAT
  5628. case VSSUBSTR:
  5629. loc = str = stackblock() + strloc;
  5630. /* Read POS in ${var:POS:LEN} */
  5631. pos = atoi(loc); /* number(loc) errors out on "1:4" */
  5632. len = str - startp - 1;
  5633. /* *loc != '\0', guaranteed by parser */
  5634. if (quotes) {
  5635. char *ptr;
  5636. /* Adjust the length by the number of escapes */
  5637. for (ptr = startp; ptr < (str - 1); ptr++) {
  5638. if ((unsigned char)*ptr == CTLESC) {
  5639. len--;
  5640. ptr++;
  5641. }
  5642. }
  5643. }
  5644. orig_len = len;
  5645. if (*loc++ == ':') {
  5646. /* ${var::LEN} */
  5647. len = number(loc);
  5648. } else {
  5649. /* Skip POS in ${var:POS:LEN} */
  5650. len = orig_len;
  5651. while (*loc && *loc != ':') {
  5652. /* TODO?
  5653. * bash complains on: var=qwe; echo ${var:1a:123}
  5654. if (!isdigit(*loc))
  5655. ash_msg_and_raise_error(msg_illnum, str);
  5656. */
  5657. loc++;
  5658. }
  5659. if (*loc++ == ':') {
  5660. len = number(loc);
  5661. }
  5662. }
  5663. if (pos >= orig_len) {
  5664. pos = 0;
  5665. len = 0;
  5666. }
  5667. if (len > (orig_len - pos))
  5668. len = orig_len - pos;
  5669. for (str = startp; pos; str++, pos--) {
  5670. if (quotes && (unsigned char)*str == CTLESC)
  5671. str++;
  5672. }
  5673. for (loc = startp; len; len--) {
  5674. if (quotes && (unsigned char)*str == CTLESC)
  5675. *loc++ = *str++;
  5676. *loc++ = *str++;
  5677. }
  5678. *loc = '\0';
  5679. amount = loc - expdest;
  5680. STADJUST(amount, expdest);
  5681. return loc;
  5682. #endif
  5683. case VSQUESTION:
  5684. varunset(p, str, startp, varflags);
  5685. /* NOTREACHED */
  5686. }
  5687. resetloc = expdest - (char *)stackblock();
  5688. /* We'll comeback here if we grow the stack while handling
  5689. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  5690. * stack will need rebasing, and we'll need to remove our work
  5691. * areas each time
  5692. */
  5693. IF_ASH_BASH_COMPAT(restart:)
  5694. amount = expdest - ((char *)stackblock() + resetloc);
  5695. STADJUST(-amount, expdest);
  5696. startp = (char *)stackblock() + startloc;
  5697. rmesc = startp;
  5698. rmescend = (char *)stackblock() + strloc;
  5699. if (quotes) {
  5700. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  5701. if (rmesc != startp) {
  5702. rmescend = expdest;
  5703. startp = (char *)stackblock() + startloc;
  5704. }
  5705. }
  5706. rmescend--;
  5707. str = (char *)stackblock() + strloc;
  5708. preglob(str, varflags & VSQUOTE, 0);
  5709. workloc = expdest - (char *)stackblock();
  5710. #if ENABLE_ASH_BASH_COMPAT
  5711. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  5712. char *idx, *end;
  5713. if (!repl) {
  5714. repl = parse_sub_pattern(str, varflags & VSQUOTE);
  5715. if (!repl)
  5716. repl = &null;
  5717. }
  5718. /* If there's no pattern to match, return the expansion unmolested */
  5719. if (str[0] == '\0')
  5720. return 0;
  5721. len = 0;
  5722. idx = startp;
  5723. end = str - 1;
  5724. while (idx < end) {
  5725. try_to_match:
  5726. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  5727. if (!loc) {
  5728. /* No match, advance */
  5729. char *restart_detect = stackblock();
  5730. skip_matching:
  5731. STPUTC(*idx, expdest);
  5732. if (quotes && (unsigned char)*idx == CTLESC) {
  5733. idx++;
  5734. len++;
  5735. STPUTC(*idx, expdest);
  5736. }
  5737. if (stackblock() != restart_detect)
  5738. goto restart;
  5739. idx++;
  5740. len++;
  5741. rmesc++;
  5742. /* continue; - prone to quadratic behavior, smarter code: */
  5743. if (idx >= end)
  5744. break;
  5745. if (str[0] == '*') {
  5746. /* Pattern is "*foo". If "*foo" does not match "long_string",
  5747. * it would never match "ong_string" etc, no point in trying.
  5748. */
  5749. goto skip_matching;
  5750. }
  5751. goto try_to_match;
  5752. }
  5753. if (subtype == VSREPLACEALL) {
  5754. while (idx < loc) {
  5755. if (quotes && (unsigned char)*idx == CTLESC)
  5756. idx++;
  5757. idx++;
  5758. rmesc++;
  5759. }
  5760. } else {
  5761. idx = loc;
  5762. }
  5763. for (loc = repl; *loc; loc++) {
  5764. char *restart_detect = stackblock();
  5765. STPUTC(*loc, expdest);
  5766. if (stackblock() != restart_detect)
  5767. goto restart;
  5768. len++;
  5769. }
  5770. if (subtype == VSREPLACE) {
  5771. while (*idx) {
  5772. char *restart_detect = stackblock();
  5773. STPUTC(*idx, expdest);
  5774. if (stackblock() != restart_detect)
  5775. goto restart;
  5776. len++;
  5777. idx++;
  5778. }
  5779. break;
  5780. }
  5781. }
  5782. /* We've put the replaced text into a buffer at workloc, now
  5783. * move it to the right place and adjust the stack.
  5784. */
  5785. startp = stackblock() + startloc;
  5786. STPUTC('\0', expdest);
  5787. memmove(startp, stackblock() + workloc, len);
  5788. startp[len++] = '\0';
  5789. amount = expdest - ((char *)stackblock() + startloc + len - 1);
  5790. STADJUST(-amount, expdest);
  5791. return startp;
  5792. }
  5793. #endif /* ENABLE_ASH_BASH_COMPAT */
  5794. subtype -= VSTRIMRIGHT;
  5795. #if DEBUG
  5796. if (subtype < 0 || subtype > 7)
  5797. abort();
  5798. #endif
  5799. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  5800. zero = subtype >> 1;
  5801. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  5802. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  5803. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  5804. if (loc) {
  5805. if (zero) {
  5806. memmove(startp, loc, str - loc);
  5807. loc = startp + (str - loc) - 1;
  5808. }
  5809. *loc = '\0';
  5810. amount = loc - expdest;
  5811. STADJUST(amount, expdest);
  5812. }
  5813. return loc;
  5814. }
  5815. /*
  5816. * Add the value of a specialized variable to the stack string.
  5817. * name parameter (examples):
  5818. * ash -c 'echo $1' name:'1='
  5819. * ash -c 'echo $qwe' name:'qwe='
  5820. * ash -c 'echo $$' name:'$='
  5821. * ash -c 'echo ${$}' name:'$='
  5822. * ash -c 'echo ${$##q}' name:'$=q'
  5823. * ash -c 'echo ${#$}' name:'$='
  5824. * note: examples with bad shell syntax:
  5825. * ash -c 'echo ${#$1}' name:'$=1'
  5826. * ash -c 'echo ${#1#}' name:'1=#'
  5827. */
  5828. static NOINLINE ssize_t
  5829. varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
  5830. {
  5831. const char *p;
  5832. int num;
  5833. int i;
  5834. int sepq = 0;
  5835. ssize_t len = 0;
  5836. int subtype = varflags & VSTYPE;
  5837. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
  5838. int quoted = varflags & VSQUOTE;
  5839. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5840. switch (*name) {
  5841. case '$':
  5842. num = rootpid;
  5843. goto numvar;
  5844. case '?':
  5845. num = exitstatus;
  5846. goto numvar;
  5847. case '#':
  5848. num = shellparam.nparam;
  5849. goto numvar;
  5850. case '!':
  5851. num = backgndpid;
  5852. if (num == 0)
  5853. return -1;
  5854. numvar:
  5855. len = cvtnum(num);
  5856. goto check_1char_name;
  5857. case '-':
  5858. expdest = makestrspace(NOPTS, expdest);
  5859. for (i = NOPTS - 1; i >= 0; i--) {
  5860. if (optlist[i]) {
  5861. USTPUTC(optletters(i), expdest);
  5862. len++;
  5863. }
  5864. }
  5865. check_1char_name:
  5866. #if 0
  5867. /* handles cases similar to ${#$1} */
  5868. if (name[2] != '\0')
  5869. raise_error_syntax("bad substitution");
  5870. #endif
  5871. break;
  5872. case '@': {
  5873. char **ap;
  5874. int sep;
  5875. if (quoted && (flags & EXP_FULL)) {
  5876. /* note: this is not meant as PEOF value */
  5877. sep = 1 << CHAR_BIT;
  5878. goto param;
  5879. }
  5880. /* fall through */
  5881. case '*':
  5882. sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
  5883. i = SIT(sep, syntax);
  5884. if (quotes && (i == CCTL || i == CBACK))
  5885. sepq = 1;
  5886. param:
  5887. ap = shellparam.p;
  5888. if (!ap)
  5889. return -1;
  5890. while ((p = *ap++) != NULL) {
  5891. size_t partlen;
  5892. partlen = strlen(p);
  5893. len += partlen;
  5894. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5895. memtodest(p, partlen, syntax, quotes);
  5896. if (*ap && sep) {
  5897. char *q;
  5898. len++;
  5899. if (subtype == VSPLUS || subtype == VSLENGTH) {
  5900. continue;
  5901. }
  5902. q = expdest;
  5903. if (sepq)
  5904. STPUTC(CTLESC, q);
  5905. /* note: may put NUL despite sep != 0
  5906. * (see sep = 1 << CHAR_BIT above) */
  5907. STPUTC(sep, q);
  5908. expdest = q;
  5909. }
  5910. }
  5911. return len;
  5912. } /* case '@' and '*' */
  5913. case '0':
  5914. case '1':
  5915. case '2':
  5916. case '3':
  5917. case '4':
  5918. case '5':
  5919. case '6':
  5920. case '7':
  5921. case '8':
  5922. case '9':
  5923. num = atoi(name); /* number(name) fails on ${N#str} etc */
  5924. if (num < 0 || num > shellparam.nparam)
  5925. return -1;
  5926. p = num ? shellparam.p[num - 1] : arg0;
  5927. goto value;
  5928. default:
  5929. /* NB: name has form "VAR=..." */
  5930. /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
  5931. * which should be considered before we check variables. */
  5932. if (var_str_list) {
  5933. unsigned name_len = (strchrnul(name, '=') - name) + 1;
  5934. p = NULL;
  5935. do {
  5936. char *str, *eq;
  5937. str = var_str_list->text;
  5938. eq = strchr(str, '=');
  5939. if (!eq) /* stop at first non-assignment */
  5940. break;
  5941. eq++;
  5942. if (name_len == (unsigned)(eq - str)
  5943. && strncmp(str, name, name_len) == 0
  5944. ) {
  5945. p = eq;
  5946. /* goto value; - WRONG! */
  5947. /* think "A=1 A=2 B=$A" */
  5948. }
  5949. var_str_list = var_str_list->next;
  5950. } while (var_str_list);
  5951. if (p)
  5952. goto value;
  5953. }
  5954. p = lookupvar(name);
  5955. value:
  5956. if (!p)
  5957. return -1;
  5958. len = strlen(p);
  5959. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5960. memtodest(p, len, syntax, quotes);
  5961. return len;
  5962. }
  5963. if (subtype == VSPLUS || subtype == VSLENGTH)
  5964. STADJUST(-len, expdest);
  5965. return len;
  5966. }
  5967. /*
  5968. * Expand a variable, and return a pointer to the next character in the
  5969. * input string.
  5970. */
  5971. static char *
  5972. evalvar(char *p, int flags, struct strlist *var_str_list)
  5973. {
  5974. char varflags;
  5975. char subtype;
  5976. char quoted;
  5977. char easy;
  5978. char *var;
  5979. int patloc;
  5980. int startloc;
  5981. ssize_t varlen;
  5982. varflags = (unsigned char) *p++;
  5983. subtype = varflags & VSTYPE;
  5984. quoted = varflags & VSQUOTE;
  5985. var = p;
  5986. easy = (!quoted || (*var == '@' && shellparam.nparam));
  5987. startloc = expdest - (char *)stackblock();
  5988. p = strchr(p, '=') + 1;
  5989. again:
  5990. varlen = varvalue(var, varflags, flags, var_str_list);
  5991. if (varflags & VSNUL)
  5992. varlen--;
  5993. if (subtype == VSPLUS) {
  5994. varlen = -1 - varlen;
  5995. goto vsplus;
  5996. }
  5997. if (subtype == VSMINUS) {
  5998. vsplus:
  5999. if (varlen < 0) {
  6000. argstr(
  6001. p, flags | EXP_TILDE |
  6002. (quoted ? EXP_QWORD : EXP_WORD),
  6003. var_str_list
  6004. );
  6005. goto end;
  6006. }
  6007. if (easy)
  6008. goto record;
  6009. goto end;
  6010. }
  6011. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6012. if (varlen < 0) {
  6013. if (subevalvar(p, var, /* strloc: */ 0,
  6014. subtype, startloc, varflags,
  6015. /* quotes: */ 0,
  6016. var_str_list)
  6017. ) {
  6018. varflags &= ~VSNUL;
  6019. /*
  6020. * Remove any recorded regions beyond
  6021. * start of variable
  6022. */
  6023. removerecordregions(startloc);
  6024. goto again;
  6025. }
  6026. goto end;
  6027. }
  6028. if (easy)
  6029. goto record;
  6030. goto end;
  6031. }
  6032. if (varlen < 0 && uflag)
  6033. varunset(p, var, 0, 0);
  6034. if (subtype == VSLENGTH) {
  6035. cvtnum(varlen > 0 ? varlen : 0);
  6036. goto record;
  6037. }
  6038. if (subtype == VSNORMAL) {
  6039. if (easy)
  6040. goto record;
  6041. goto end;
  6042. }
  6043. #if DEBUG
  6044. switch (subtype) {
  6045. case VSTRIMLEFT:
  6046. case VSTRIMLEFTMAX:
  6047. case VSTRIMRIGHT:
  6048. case VSTRIMRIGHTMAX:
  6049. #if ENABLE_ASH_BASH_COMPAT
  6050. case VSSUBSTR:
  6051. case VSREPLACE:
  6052. case VSREPLACEALL:
  6053. #endif
  6054. break;
  6055. default:
  6056. abort();
  6057. }
  6058. #endif
  6059. if (varlen >= 0) {
  6060. /*
  6061. * Terminate the string and start recording the pattern
  6062. * right after it
  6063. */
  6064. STPUTC('\0', expdest);
  6065. patloc = expdest - (char *)stackblock();
  6066. if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
  6067. startloc, varflags,
  6068. //TODO: | EXP_REDIR too? All other such places do it too
  6069. /* quotes: */ flags & (EXP_FULL | EXP_CASE),
  6070. var_str_list)
  6071. ) {
  6072. int amount = expdest - (
  6073. (char *)stackblock() + patloc - 1
  6074. );
  6075. STADJUST(-amount, expdest);
  6076. }
  6077. /* Remove any recorded regions beyond start of variable */
  6078. removerecordregions(startloc);
  6079. record:
  6080. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6081. }
  6082. end:
  6083. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6084. int nesting = 1;
  6085. for (;;) {
  6086. unsigned char c = *p++;
  6087. if (c == CTLESC)
  6088. p++;
  6089. else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
  6090. if (varlen >= 0)
  6091. argbackq = argbackq->next;
  6092. } else if (c == CTLVAR) {
  6093. if ((*p++ & VSTYPE) != VSNORMAL)
  6094. nesting++;
  6095. } else if (c == CTLENDVAR) {
  6096. if (--nesting == 0)
  6097. break;
  6098. }
  6099. }
  6100. }
  6101. return p;
  6102. }
  6103. /*
  6104. * Break the argument string into pieces based upon IFS and add the
  6105. * strings to the argument list. The regions of the string to be
  6106. * searched for IFS characters have been stored by recordregion.
  6107. */
  6108. static void
  6109. ifsbreakup(char *string, struct arglist *arglist)
  6110. {
  6111. struct ifsregion *ifsp;
  6112. struct strlist *sp;
  6113. char *start;
  6114. char *p;
  6115. char *q;
  6116. const char *ifs, *realifs;
  6117. int ifsspc;
  6118. int nulonly;
  6119. start = string;
  6120. if (ifslastp != NULL) {
  6121. ifsspc = 0;
  6122. nulonly = 0;
  6123. realifs = ifsset() ? ifsval() : defifs;
  6124. ifsp = &ifsfirst;
  6125. do {
  6126. p = string + ifsp->begoff;
  6127. nulonly = ifsp->nulonly;
  6128. ifs = nulonly ? nullstr : realifs;
  6129. ifsspc = 0;
  6130. while (p < string + ifsp->endoff) {
  6131. q = p;
  6132. if ((unsigned char)*p == CTLESC)
  6133. p++;
  6134. if (!strchr(ifs, *p)) {
  6135. p++;
  6136. continue;
  6137. }
  6138. if (!nulonly)
  6139. ifsspc = (strchr(defifs, *p) != NULL);
  6140. /* Ignore IFS whitespace at start */
  6141. if (q == start && ifsspc) {
  6142. p++;
  6143. start = p;
  6144. continue;
  6145. }
  6146. *q = '\0';
  6147. sp = stzalloc(sizeof(*sp));
  6148. sp->text = start;
  6149. *arglist->lastp = sp;
  6150. arglist->lastp = &sp->next;
  6151. p++;
  6152. if (!nulonly) {
  6153. for (;;) {
  6154. if (p >= string + ifsp->endoff) {
  6155. break;
  6156. }
  6157. q = p;
  6158. if ((unsigned char)*p == CTLESC)
  6159. p++;
  6160. if (strchr(ifs, *p) == NULL) {
  6161. p = q;
  6162. break;
  6163. }
  6164. if (strchr(defifs, *p) == NULL) {
  6165. if (ifsspc) {
  6166. p++;
  6167. ifsspc = 0;
  6168. } else {
  6169. p = q;
  6170. break;
  6171. }
  6172. } else
  6173. p++;
  6174. }
  6175. }
  6176. start = p;
  6177. } /* while */
  6178. ifsp = ifsp->next;
  6179. } while (ifsp != NULL);
  6180. if (nulonly)
  6181. goto add;
  6182. }
  6183. if (!*start)
  6184. return;
  6185. add:
  6186. sp = stzalloc(sizeof(*sp));
  6187. sp->text = start;
  6188. *arglist->lastp = sp;
  6189. arglist->lastp = &sp->next;
  6190. }
  6191. static void
  6192. ifsfree(void)
  6193. {
  6194. struct ifsregion *p;
  6195. INT_OFF;
  6196. p = ifsfirst.next;
  6197. do {
  6198. struct ifsregion *ifsp;
  6199. ifsp = p->next;
  6200. free(p);
  6201. p = ifsp;
  6202. } while (p);
  6203. ifslastp = NULL;
  6204. ifsfirst.next = NULL;
  6205. INT_ON;
  6206. }
  6207. /*
  6208. * Add a file name to the list.
  6209. */
  6210. static void
  6211. addfname(const char *name)
  6212. {
  6213. struct strlist *sp;
  6214. sp = stzalloc(sizeof(*sp));
  6215. sp->text = ststrdup(name);
  6216. *exparg.lastp = sp;
  6217. exparg.lastp = &sp->next;
  6218. }
  6219. static char *expdir;
  6220. /*
  6221. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6222. */
  6223. static void
  6224. expmeta(char *enddir, char *name)
  6225. {
  6226. char *p;
  6227. const char *cp;
  6228. char *start;
  6229. char *endname;
  6230. int metaflag;
  6231. struct stat statb;
  6232. DIR *dirp;
  6233. struct dirent *dp;
  6234. int atend;
  6235. int matchdot;
  6236. metaflag = 0;
  6237. start = name;
  6238. for (p = name; *p; p++) {
  6239. if (*p == '*' || *p == '?')
  6240. metaflag = 1;
  6241. else if (*p == '[') {
  6242. char *q = p + 1;
  6243. if (*q == '!')
  6244. q++;
  6245. for (;;) {
  6246. if (*q == '\\')
  6247. q++;
  6248. if (*q == '/' || *q == '\0')
  6249. break;
  6250. if (*++q == ']') {
  6251. metaflag = 1;
  6252. break;
  6253. }
  6254. }
  6255. } else if (*p == '\\')
  6256. p++;
  6257. else if (*p == '/') {
  6258. if (metaflag)
  6259. goto out;
  6260. start = p + 1;
  6261. }
  6262. }
  6263. out:
  6264. if (metaflag == 0) { /* we've reached the end of the file name */
  6265. if (enddir != expdir)
  6266. metaflag++;
  6267. p = name;
  6268. do {
  6269. if (*p == '\\')
  6270. p++;
  6271. *enddir++ = *p;
  6272. } while (*p++);
  6273. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6274. addfname(expdir);
  6275. return;
  6276. }
  6277. endname = p;
  6278. if (name < start) {
  6279. p = name;
  6280. do {
  6281. if (*p == '\\')
  6282. p++;
  6283. *enddir++ = *p++;
  6284. } while (p < start);
  6285. }
  6286. if (enddir == expdir) {
  6287. cp = ".";
  6288. } else if (enddir == expdir + 1 && *expdir == '/') {
  6289. cp = "/";
  6290. } else {
  6291. cp = expdir;
  6292. enddir[-1] = '\0';
  6293. }
  6294. dirp = opendir(cp);
  6295. if (dirp == NULL)
  6296. return;
  6297. if (enddir != expdir)
  6298. enddir[-1] = '/';
  6299. if (*endname == 0) {
  6300. atend = 1;
  6301. } else {
  6302. atend = 0;
  6303. *endname++ = '\0';
  6304. }
  6305. matchdot = 0;
  6306. p = start;
  6307. if (*p == '\\')
  6308. p++;
  6309. if (*p == '.')
  6310. matchdot++;
  6311. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  6312. if (dp->d_name[0] == '.' && !matchdot)
  6313. continue;
  6314. if (pmatch(start, dp->d_name)) {
  6315. if (atend) {
  6316. strcpy(enddir, dp->d_name);
  6317. addfname(expdir);
  6318. } else {
  6319. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6320. continue;
  6321. p[-1] = '/';
  6322. expmeta(p, endname);
  6323. }
  6324. }
  6325. }
  6326. closedir(dirp);
  6327. if (!atend)
  6328. endname[-1] = '/';
  6329. }
  6330. static struct strlist *
  6331. msort(struct strlist *list, int len)
  6332. {
  6333. struct strlist *p, *q = NULL;
  6334. struct strlist **lpp;
  6335. int half;
  6336. int n;
  6337. if (len <= 1)
  6338. return list;
  6339. half = len >> 1;
  6340. p = list;
  6341. for (n = half; --n >= 0;) {
  6342. q = p;
  6343. p = p->next;
  6344. }
  6345. q->next = NULL; /* terminate first half of list */
  6346. q = msort(list, half); /* sort first half of list */
  6347. p = msort(p, len - half); /* sort second half */
  6348. lpp = &list;
  6349. for (;;) {
  6350. #if ENABLE_LOCALE_SUPPORT
  6351. if (strcoll(p->text, q->text) < 0)
  6352. #else
  6353. if (strcmp(p->text, q->text) < 0)
  6354. #endif
  6355. {
  6356. *lpp = p;
  6357. lpp = &p->next;
  6358. p = *lpp;
  6359. if (p == NULL) {
  6360. *lpp = q;
  6361. break;
  6362. }
  6363. } else {
  6364. *lpp = q;
  6365. lpp = &q->next;
  6366. q = *lpp;
  6367. if (q == NULL) {
  6368. *lpp = p;
  6369. break;
  6370. }
  6371. }
  6372. }
  6373. return list;
  6374. }
  6375. /*
  6376. * Sort the results of file name expansion. It calculates the number of
  6377. * strings to sort and then calls msort (short for merge sort) to do the
  6378. * work.
  6379. */
  6380. static struct strlist *
  6381. expsort(struct strlist *str)
  6382. {
  6383. int len;
  6384. struct strlist *sp;
  6385. len = 0;
  6386. for (sp = str; sp; sp = sp->next)
  6387. len++;
  6388. return msort(str, len);
  6389. }
  6390. static void
  6391. expandmeta(struct strlist *str /*, int flag*/)
  6392. {
  6393. static const char metachars[] ALIGN1 = {
  6394. '*', '?', '[', 0
  6395. };
  6396. /* TODO - EXP_REDIR */
  6397. while (str) {
  6398. struct strlist **savelastp;
  6399. struct strlist *sp;
  6400. char *p;
  6401. if (fflag)
  6402. goto nometa;
  6403. if (!strpbrk(str->text, metachars))
  6404. goto nometa;
  6405. savelastp = exparg.lastp;
  6406. INT_OFF;
  6407. p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6408. {
  6409. int i = strlen(str->text);
  6410. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  6411. }
  6412. expmeta(expdir, p);
  6413. free(expdir);
  6414. if (p != str->text)
  6415. free(p);
  6416. INT_ON;
  6417. if (exparg.lastp == savelastp) {
  6418. /*
  6419. * no matches
  6420. */
  6421. nometa:
  6422. *exparg.lastp = str;
  6423. rmescapes(str->text, 0);
  6424. exparg.lastp = &str->next;
  6425. } else {
  6426. *exparg.lastp = NULL;
  6427. *savelastp = sp = expsort(*savelastp);
  6428. while (sp->next != NULL)
  6429. sp = sp->next;
  6430. exparg.lastp = &sp->next;
  6431. }
  6432. str = str->next;
  6433. }
  6434. }
  6435. /*
  6436. * Perform variable substitution and command substitution on an argument,
  6437. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6438. * perform splitting and file name expansion. When arglist is NULL, perform
  6439. * here document expansion.
  6440. */
  6441. static void
  6442. expandarg(union node *arg, struct arglist *arglist, int flag)
  6443. {
  6444. struct strlist *sp;
  6445. char *p;
  6446. argbackq = arg->narg.backquote;
  6447. STARTSTACKSTR(expdest);
  6448. ifsfirst.next = NULL;
  6449. ifslastp = NULL;
  6450. argstr(arg->narg.text, flag,
  6451. /* var_str_list: */ arglist ? arglist->list : NULL);
  6452. p = _STPUTC('\0', expdest);
  6453. expdest = p - 1;
  6454. if (arglist == NULL) {
  6455. return; /* here document expanded */
  6456. }
  6457. p = grabstackstr(p);
  6458. exparg.lastp = &exparg.list;
  6459. /*
  6460. * TODO - EXP_REDIR
  6461. */
  6462. if (flag & EXP_FULL) {
  6463. ifsbreakup(p, &exparg);
  6464. *exparg.lastp = NULL;
  6465. exparg.lastp = &exparg.list;
  6466. expandmeta(exparg.list /*, flag*/);
  6467. } else {
  6468. if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
  6469. rmescapes(p, 0);
  6470. sp = stzalloc(sizeof(*sp));
  6471. sp->text = p;
  6472. *exparg.lastp = sp;
  6473. exparg.lastp = &sp->next;
  6474. }
  6475. if (ifsfirst.next)
  6476. ifsfree();
  6477. *exparg.lastp = NULL;
  6478. if (exparg.list) {
  6479. *arglist->lastp = exparg.list;
  6480. arglist->lastp = exparg.lastp;
  6481. }
  6482. }
  6483. /*
  6484. * Expand shell variables and backquotes inside a here document.
  6485. */
  6486. static void
  6487. expandhere(union node *arg, int fd)
  6488. {
  6489. herefd = fd;
  6490. expandarg(arg, (struct arglist *)NULL, 0);
  6491. full_write(fd, stackblock(), expdest - (char *)stackblock());
  6492. }
  6493. /*
  6494. * Returns true if the pattern matches the string.
  6495. */
  6496. static int
  6497. patmatch(char *pattern, const char *string)
  6498. {
  6499. return pmatch(preglob(pattern, 0, 0), string);
  6500. }
  6501. /*
  6502. * See if a pattern matches in a case statement.
  6503. */
  6504. static int
  6505. casematch(union node *pattern, char *val)
  6506. {
  6507. struct stackmark smark;
  6508. int result;
  6509. setstackmark(&smark);
  6510. argbackq = pattern->narg.backquote;
  6511. STARTSTACKSTR(expdest);
  6512. ifslastp = NULL;
  6513. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
  6514. /* var_str_list: */ NULL);
  6515. STACKSTRNUL(expdest);
  6516. result = patmatch(stackblock(), val);
  6517. popstackmark(&smark);
  6518. return result;
  6519. }
  6520. /* ============ find_command */
  6521. struct builtincmd {
  6522. const char *name;
  6523. int (*builtin)(int, char **) FAST_FUNC;
  6524. /* unsigned flags; */
  6525. };
  6526. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  6527. /* "regular" builtins always take precedence over commands,
  6528. * regardless of PATH=....%builtin... position */
  6529. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  6530. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  6531. struct cmdentry {
  6532. smallint cmdtype; /* CMDxxx */
  6533. union param {
  6534. int index;
  6535. /* index >= 0 for commands without path (slashes) */
  6536. /* (TODO: what exactly does the value mean? PATH position?) */
  6537. /* index == -1 for commands with slashes */
  6538. /* index == (-2 - applet_no) for NOFORK applets */
  6539. const struct builtincmd *cmd;
  6540. struct funcnode *func;
  6541. } u;
  6542. };
  6543. /* values of cmdtype */
  6544. #define CMDUNKNOWN -1 /* no entry in table for command */
  6545. #define CMDNORMAL 0 /* command is an executable program */
  6546. #define CMDFUNCTION 1 /* command is a shell function */
  6547. #define CMDBUILTIN 2 /* command is a shell builtin */
  6548. /* action to find_command() */
  6549. #define DO_ERR 0x01 /* prints errors */
  6550. #define DO_ABS 0x02 /* checks absolute paths */
  6551. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  6552. #define DO_ALTPATH 0x08 /* using alternate path */
  6553. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  6554. static void find_command(char *, struct cmdentry *, int, const char *);
  6555. /* ============ Hashing commands */
  6556. /*
  6557. * When commands are first encountered, they are entered in a hash table.
  6558. * This ensures that a full path search will not have to be done for them
  6559. * on each invocation.
  6560. *
  6561. * We should investigate converting to a linear search, even though that
  6562. * would make the command name "hash" a misnomer.
  6563. */
  6564. struct tblentry {
  6565. struct tblentry *next; /* next entry in hash chain */
  6566. union param param; /* definition of builtin function */
  6567. smallint cmdtype; /* CMDxxx */
  6568. char rehash; /* if set, cd done since entry created */
  6569. char cmdname[1]; /* name of command */
  6570. };
  6571. static struct tblentry **cmdtable;
  6572. #define INIT_G_cmdtable() do { \
  6573. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  6574. } while (0)
  6575. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  6576. static void
  6577. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
  6578. {
  6579. int repeated = 0;
  6580. #if ENABLE_FEATURE_SH_STANDALONE
  6581. if (applet_no >= 0) {
  6582. if (APPLET_IS_NOEXEC(applet_no)) {
  6583. while (*envp)
  6584. putenv(*envp++);
  6585. run_applet_no_and_exit(applet_no, argv);
  6586. }
  6587. /* re-exec ourselves with the new arguments */
  6588. execve(bb_busybox_exec_path, argv, envp);
  6589. /* If they called chroot or otherwise made the binary no longer
  6590. * executable, fall through */
  6591. }
  6592. #endif
  6593. repeat:
  6594. #ifdef SYSV
  6595. do {
  6596. execve(cmd, argv, envp);
  6597. } while (errno == EINTR);
  6598. #else
  6599. execve(cmd, argv, envp);
  6600. #endif
  6601. if (repeated) {
  6602. free(argv);
  6603. return;
  6604. }
  6605. if (errno == ENOEXEC) {
  6606. char **ap;
  6607. char **new;
  6608. for (ap = argv; *ap; ap++)
  6609. continue;
  6610. ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
  6611. ap[1] = cmd;
  6612. ap[0] = cmd = (char *)DEFAULT_SHELL;
  6613. ap += 2;
  6614. argv++;
  6615. while ((*ap++ = *argv++) != NULL)
  6616. continue;
  6617. argv = new;
  6618. repeated++;
  6619. goto repeat;
  6620. }
  6621. }
  6622. /*
  6623. * Exec a program. Never returns. If you change this routine, you may
  6624. * have to change the find_command routine as well.
  6625. */
  6626. static void shellexec(char **, const char *, int) NORETURN;
  6627. static void
  6628. shellexec(char **argv, const char *path, int idx)
  6629. {
  6630. char *cmdname;
  6631. int e;
  6632. char **envp;
  6633. int exerrno;
  6634. #if ENABLE_FEATURE_SH_STANDALONE
  6635. int applet_no = -1;
  6636. #endif
  6637. clearredir(/*drop:*/ 1);
  6638. envp = listvars(VEXPORT, VUNSET, 0);
  6639. if (strchr(argv[0], '/') != NULL
  6640. #if ENABLE_FEATURE_SH_STANDALONE
  6641. || (applet_no = find_applet_by_name(argv[0])) >= 0
  6642. #endif
  6643. ) {
  6644. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
  6645. e = errno;
  6646. } else {
  6647. e = ENOENT;
  6648. while ((cmdname = path_advance(&path, argv[0])) != NULL) {
  6649. if (--idx < 0 && pathopt == NULL) {
  6650. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  6651. if (errno != ENOENT && errno != ENOTDIR)
  6652. e = errno;
  6653. }
  6654. stunalloc(cmdname);
  6655. }
  6656. }
  6657. /* Map to POSIX errors */
  6658. switch (e) {
  6659. case EACCES:
  6660. exerrno = 126;
  6661. break;
  6662. case ENOENT:
  6663. exerrno = 127;
  6664. break;
  6665. default:
  6666. exerrno = 2;
  6667. break;
  6668. }
  6669. exitstatus = exerrno;
  6670. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  6671. argv[0], e, suppress_int));
  6672. ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
  6673. /* NOTREACHED */
  6674. }
  6675. static void
  6676. printentry(struct tblentry *cmdp)
  6677. {
  6678. int idx;
  6679. const char *path;
  6680. char *name;
  6681. idx = cmdp->param.index;
  6682. path = pathval();
  6683. do {
  6684. name = path_advance(&path, cmdp->cmdname);
  6685. stunalloc(name);
  6686. } while (--idx >= 0);
  6687. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  6688. }
  6689. /*
  6690. * Clear out command entries. The argument specifies the first entry in
  6691. * PATH which has changed.
  6692. */
  6693. static void
  6694. clearcmdentry(int firstchange)
  6695. {
  6696. struct tblentry **tblp;
  6697. struct tblentry **pp;
  6698. struct tblentry *cmdp;
  6699. INT_OFF;
  6700. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  6701. pp = tblp;
  6702. while ((cmdp = *pp) != NULL) {
  6703. if ((cmdp->cmdtype == CMDNORMAL &&
  6704. cmdp->param.index >= firstchange)
  6705. || (cmdp->cmdtype == CMDBUILTIN &&
  6706. builtinloc >= firstchange)
  6707. ) {
  6708. *pp = cmdp->next;
  6709. free(cmdp);
  6710. } else {
  6711. pp = &cmdp->next;
  6712. }
  6713. }
  6714. }
  6715. INT_ON;
  6716. }
  6717. /*
  6718. * Locate a command in the command hash table. If "add" is nonzero,
  6719. * add the command to the table if it is not already present. The
  6720. * variable "lastcmdentry" is set to point to the address of the link
  6721. * pointing to the entry, so that delete_cmd_entry can delete the
  6722. * entry.
  6723. *
  6724. * Interrupts must be off if called with add != 0.
  6725. */
  6726. static struct tblentry **lastcmdentry;
  6727. static struct tblentry *
  6728. cmdlookup(const char *name, int add)
  6729. {
  6730. unsigned int hashval;
  6731. const char *p;
  6732. struct tblentry *cmdp;
  6733. struct tblentry **pp;
  6734. p = name;
  6735. hashval = (unsigned char)*p << 4;
  6736. while (*p)
  6737. hashval += (unsigned char)*p++;
  6738. hashval &= 0x7FFF;
  6739. pp = &cmdtable[hashval % CMDTABLESIZE];
  6740. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6741. if (strcmp(cmdp->cmdname, name) == 0)
  6742. break;
  6743. pp = &cmdp->next;
  6744. }
  6745. if (add && cmdp == NULL) {
  6746. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  6747. + strlen(name)
  6748. /* + 1 - already done because
  6749. * tblentry::cmdname is char[1] */);
  6750. /*cmdp->next = NULL; - ckzalloc did it */
  6751. cmdp->cmdtype = CMDUNKNOWN;
  6752. strcpy(cmdp->cmdname, name);
  6753. }
  6754. lastcmdentry = pp;
  6755. return cmdp;
  6756. }
  6757. /*
  6758. * Delete the command entry returned on the last lookup.
  6759. */
  6760. static void
  6761. delete_cmd_entry(void)
  6762. {
  6763. struct tblentry *cmdp;
  6764. INT_OFF;
  6765. cmdp = *lastcmdentry;
  6766. *lastcmdentry = cmdp->next;
  6767. if (cmdp->cmdtype == CMDFUNCTION)
  6768. freefunc(cmdp->param.func);
  6769. free(cmdp);
  6770. INT_ON;
  6771. }
  6772. /*
  6773. * Add a new command entry, replacing any existing command entry for
  6774. * the same name - except special builtins.
  6775. */
  6776. static void
  6777. addcmdentry(char *name, struct cmdentry *entry)
  6778. {
  6779. struct tblentry *cmdp;
  6780. cmdp = cmdlookup(name, 1);
  6781. if (cmdp->cmdtype == CMDFUNCTION) {
  6782. freefunc(cmdp->param.func);
  6783. }
  6784. cmdp->cmdtype = entry->cmdtype;
  6785. cmdp->param = entry->u;
  6786. cmdp->rehash = 0;
  6787. }
  6788. static int FAST_FUNC
  6789. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6790. {
  6791. struct tblentry **pp;
  6792. struct tblentry *cmdp;
  6793. int c;
  6794. struct cmdentry entry;
  6795. char *name;
  6796. if (nextopt("r") != '\0') {
  6797. clearcmdentry(0);
  6798. return 0;
  6799. }
  6800. if (*argptr == NULL) {
  6801. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6802. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6803. if (cmdp->cmdtype == CMDNORMAL)
  6804. printentry(cmdp);
  6805. }
  6806. }
  6807. return 0;
  6808. }
  6809. c = 0;
  6810. while ((name = *argptr) != NULL) {
  6811. cmdp = cmdlookup(name, 0);
  6812. if (cmdp != NULL
  6813. && (cmdp->cmdtype == CMDNORMAL
  6814. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  6815. ) {
  6816. delete_cmd_entry();
  6817. }
  6818. find_command(name, &entry, DO_ERR, pathval());
  6819. if (entry.cmdtype == CMDUNKNOWN)
  6820. c = 1;
  6821. argptr++;
  6822. }
  6823. return c;
  6824. }
  6825. /*
  6826. * Called when a cd is done. Marks all commands so the next time they
  6827. * are executed they will be rehashed.
  6828. */
  6829. static void
  6830. hashcd(void)
  6831. {
  6832. struct tblentry **pp;
  6833. struct tblentry *cmdp;
  6834. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6835. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6836. if (cmdp->cmdtype == CMDNORMAL
  6837. || (cmdp->cmdtype == CMDBUILTIN
  6838. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  6839. && builtinloc > 0)
  6840. ) {
  6841. cmdp->rehash = 1;
  6842. }
  6843. }
  6844. }
  6845. }
  6846. /*
  6847. * Fix command hash table when PATH changed.
  6848. * Called before PATH is changed. The argument is the new value of PATH;
  6849. * pathval() still returns the old value at this point.
  6850. * Called with interrupts off.
  6851. */
  6852. static void FAST_FUNC
  6853. changepath(const char *new)
  6854. {
  6855. const char *old;
  6856. int firstchange;
  6857. int idx;
  6858. int idx_bltin;
  6859. old = pathval();
  6860. firstchange = 9999; /* assume no change */
  6861. idx = 0;
  6862. idx_bltin = -1;
  6863. for (;;) {
  6864. if (*old != *new) {
  6865. firstchange = idx;
  6866. if ((*old == '\0' && *new == ':')
  6867. || (*old == ':' && *new == '\0'))
  6868. firstchange++;
  6869. old = new; /* ignore subsequent differences */
  6870. }
  6871. if (*new == '\0')
  6872. break;
  6873. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  6874. idx_bltin = idx;
  6875. if (*new == ':')
  6876. idx++;
  6877. new++, old++;
  6878. }
  6879. if (builtinloc < 0 && idx_bltin >= 0)
  6880. builtinloc = idx_bltin; /* zap builtins */
  6881. if (builtinloc >= 0 && idx_bltin < 0)
  6882. firstchange = 0;
  6883. clearcmdentry(firstchange);
  6884. builtinloc = idx_bltin;
  6885. }
  6886. #define TEOF 0
  6887. #define TNL 1
  6888. #define TREDIR 2
  6889. #define TWORD 3
  6890. #define TSEMI 4
  6891. #define TBACKGND 5
  6892. #define TAND 6
  6893. #define TOR 7
  6894. #define TPIPE 8
  6895. #define TLP 9
  6896. #define TRP 10
  6897. #define TENDCASE 11
  6898. #define TENDBQUOTE 12
  6899. #define TNOT 13
  6900. #define TCASE 14
  6901. #define TDO 15
  6902. #define TDONE 16
  6903. #define TELIF 17
  6904. #define TELSE 18
  6905. #define TESAC 19
  6906. #define TFI 20
  6907. #define TFOR 21
  6908. #define TIF 22
  6909. #define TIN 23
  6910. #define TTHEN 24
  6911. #define TUNTIL 25
  6912. #define TWHILE 26
  6913. #define TBEGIN 27
  6914. #define TEND 28
  6915. typedef smallint token_id_t;
  6916. /* first char is indicating which tokens mark the end of a list */
  6917. static const char *const tokname_array[] = {
  6918. "\1end of file",
  6919. "\0newline",
  6920. "\0redirection",
  6921. "\0word",
  6922. "\0;",
  6923. "\0&",
  6924. "\0&&",
  6925. "\0||",
  6926. "\0|",
  6927. "\0(",
  6928. "\1)",
  6929. "\1;;",
  6930. "\1`",
  6931. #define KWDOFFSET 13
  6932. /* the following are keywords */
  6933. "\0!",
  6934. "\0case",
  6935. "\1do",
  6936. "\1done",
  6937. "\1elif",
  6938. "\1else",
  6939. "\1esac",
  6940. "\1fi",
  6941. "\0for",
  6942. "\0if",
  6943. "\0in",
  6944. "\1then",
  6945. "\0until",
  6946. "\0while",
  6947. "\0{",
  6948. "\1}",
  6949. };
  6950. static const char *
  6951. tokname(int tok)
  6952. {
  6953. static char buf[16];
  6954. //try this:
  6955. //if (tok < TSEMI) return tokname_array[tok] + 1;
  6956. //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
  6957. //return buf;
  6958. if (tok >= TSEMI)
  6959. buf[0] = '"';
  6960. sprintf(buf + (tok >= TSEMI), "%s%c",
  6961. tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
  6962. return buf;
  6963. }
  6964. /* Wrapper around strcmp for qsort/bsearch/... */
  6965. static int
  6966. pstrcmp(const void *a, const void *b)
  6967. {
  6968. return strcmp((char*) a, (*(char**) b) + 1);
  6969. }
  6970. static const char *const *
  6971. findkwd(const char *s)
  6972. {
  6973. return bsearch(s, tokname_array + KWDOFFSET,
  6974. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  6975. sizeof(tokname_array[0]), pstrcmp);
  6976. }
  6977. /*
  6978. * Locate and print what a word is...
  6979. */
  6980. static int
  6981. describe_command(char *command, int describe_command_verbose)
  6982. {
  6983. struct cmdentry entry;
  6984. struct tblentry *cmdp;
  6985. #if ENABLE_ASH_ALIAS
  6986. const struct alias *ap;
  6987. #endif
  6988. const char *path = pathval();
  6989. if (describe_command_verbose) {
  6990. out1str(command);
  6991. }
  6992. /* First look at the keywords */
  6993. if (findkwd(command)) {
  6994. out1str(describe_command_verbose ? " is a shell keyword" : command);
  6995. goto out;
  6996. }
  6997. #if ENABLE_ASH_ALIAS
  6998. /* Then look at the aliases */
  6999. ap = lookupalias(command, 0);
  7000. if (ap != NULL) {
  7001. if (!describe_command_verbose) {
  7002. out1str("alias ");
  7003. printalias(ap);
  7004. return 0;
  7005. }
  7006. out1fmt(" is an alias for %s", ap->val);
  7007. goto out;
  7008. }
  7009. #endif
  7010. /* Then check if it is a tracked alias */
  7011. cmdp = cmdlookup(command, 0);
  7012. if (cmdp != NULL) {
  7013. entry.cmdtype = cmdp->cmdtype;
  7014. entry.u = cmdp->param;
  7015. } else {
  7016. /* Finally use brute force */
  7017. find_command(command, &entry, DO_ABS, path);
  7018. }
  7019. switch (entry.cmdtype) {
  7020. case CMDNORMAL: {
  7021. int j = entry.u.index;
  7022. char *p;
  7023. if (j < 0) {
  7024. p = command;
  7025. } else {
  7026. do {
  7027. p = path_advance(&path, command);
  7028. stunalloc(p);
  7029. } while (--j >= 0);
  7030. }
  7031. if (describe_command_verbose) {
  7032. out1fmt(" is%s %s",
  7033. (cmdp ? " a tracked alias for" : nullstr), p
  7034. );
  7035. } else {
  7036. out1str(p);
  7037. }
  7038. break;
  7039. }
  7040. case CMDFUNCTION:
  7041. if (describe_command_verbose) {
  7042. out1str(" is a shell function");
  7043. } else {
  7044. out1str(command);
  7045. }
  7046. break;
  7047. case CMDBUILTIN:
  7048. if (describe_command_verbose) {
  7049. out1fmt(" is a %sshell builtin",
  7050. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7051. "special " : nullstr
  7052. );
  7053. } else {
  7054. out1str(command);
  7055. }
  7056. break;
  7057. default:
  7058. if (describe_command_verbose) {
  7059. out1str(": not found\n");
  7060. }
  7061. return 127;
  7062. }
  7063. out:
  7064. out1str("\n");
  7065. return 0;
  7066. }
  7067. static int FAST_FUNC
  7068. typecmd(int argc UNUSED_PARAM, char **argv)
  7069. {
  7070. int i = 1;
  7071. int err = 0;
  7072. int verbose = 1;
  7073. /* type -p ... ? (we don't bother checking for 'p') */
  7074. if (argv[1] && argv[1][0] == '-') {
  7075. i++;
  7076. verbose = 0;
  7077. }
  7078. while (argv[i]) {
  7079. err |= describe_command(argv[i++], verbose);
  7080. }
  7081. return err;
  7082. }
  7083. #if ENABLE_ASH_CMDCMD
  7084. static int FAST_FUNC
  7085. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7086. {
  7087. int c;
  7088. enum {
  7089. VERIFY_BRIEF = 1,
  7090. VERIFY_VERBOSE = 2,
  7091. } verify = 0;
  7092. while ((c = nextopt("pvV")) != '\0')
  7093. if (c == 'V')
  7094. verify |= VERIFY_VERBOSE;
  7095. else if (c == 'v')
  7096. verify |= VERIFY_BRIEF;
  7097. #if DEBUG
  7098. else if (c != 'p')
  7099. abort();
  7100. #endif
  7101. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7102. if (verify && (*argptr != NULL)) {
  7103. return describe_command(*argptr, verify - VERIFY_BRIEF);
  7104. }
  7105. return 0;
  7106. }
  7107. #endif
  7108. /* ============ eval.c */
  7109. static int funcblocksize; /* size of structures in function */
  7110. static int funcstringsize; /* size of strings in node */
  7111. static void *funcblock; /* block to allocate function from */
  7112. static char *funcstring; /* block to allocate strings from */
  7113. /* flags in argument to evaltree */
  7114. #define EV_EXIT 01 /* exit after evaluating tree */
  7115. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  7116. #define EV_BACKCMD 04 /* command executing within back quotes */
  7117. static const uint8_t nodesize[N_NUMBER] = {
  7118. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7119. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7120. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7121. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7122. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7123. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7124. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7125. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7126. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7127. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7128. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7129. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7130. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7131. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7132. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7133. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7134. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7135. #if ENABLE_ASH_BASH_COMPAT
  7136. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7137. #endif
  7138. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7139. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7140. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7141. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7142. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7143. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7144. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7145. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7146. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7147. };
  7148. static void calcsize(union node *n);
  7149. static void
  7150. sizenodelist(struct nodelist *lp)
  7151. {
  7152. while (lp) {
  7153. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7154. calcsize(lp->n);
  7155. lp = lp->next;
  7156. }
  7157. }
  7158. static void
  7159. calcsize(union node *n)
  7160. {
  7161. if (n == NULL)
  7162. return;
  7163. funcblocksize += nodesize[n->type];
  7164. switch (n->type) {
  7165. case NCMD:
  7166. calcsize(n->ncmd.redirect);
  7167. calcsize(n->ncmd.args);
  7168. calcsize(n->ncmd.assign);
  7169. break;
  7170. case NPIPE:
  7171. sizenodelist(n->npipe.cmdlist);
  7172. break;
  7173. case NREDIR:
  7174. case NBACKGND:
  7175. case NSUBSHELL:
  7176. calcsize(n->nredir.redirect);
  7177. calcsize(n->nredir.n);
  7178. break;
  7179. case NAND:
  7180. case NOR:
  7181. case NSEMI:
  7182. case NWHILE:
  7183. case NUNTIL:
  7184. calcsize(n->nbinary.ch2);
  7185. calcsize(n->nbinary.ch1);
  7186. break;
  7187. case NIF:
  7188. calcsize(n->nif.elsepart);
  7189. calcsize(n->nif.ifpart);
  7190. calcsize(n->nif.test);
  7191. break;
  7192. case NFOR:
  7193. funcstringsize += strlen(n->nfor.var) + 1;
  7194. calcsize(n->nfor.body);
  7195. calcsize(n->nfor.args);
  7196. break;
  7197. case NCASE:
  7198. calcsize(n->ncase.cases);
  7199. calcsize(n->ncase.expr);
  7200. break;
  7201. case NCLIST:
  7202. calcsize(n->nclist.body);
  7203. calcsize(n->nclist.pattern);
  7204. calcsize(n->nclist.next);
  7205. break;
  7206. case NDEFUN:
  7207. case NARG:
  7208. sizenodelist(n->narg.backquote);
  7209. funcstringsize += strlen(n->narg.text) + 1;
  7210. calcsize(n->narg.next);
  7211. break;
  7212. case NTO:
  7213. #if ENABLE_ASH_BASH_COMPAT
  7214. case NTO2:
  7215. #endif
  7216. case NCLOBBER:
  7217. case NFROM:
  7218. case NFROMTO:
  7219. case NAPPEND:
  7220. calcsize(n->nfile.fname);
  7221. calcsize(n->nfile.next);
  7222. break;
  7223. case NTOFD:
  7224. case NFROMFD:
  7225. calcsize(n->ndup.vname);
  7226. calcsize(n->ndup.next);
  7227. break;
  7228. case NHERE:
  7229. case NXHERE:
  7230. calcsize(n->nhere.doc);
  7231. calcsize(n->nhere.next);
  7232. break;
  7233. case NNOT:
  7234. calcsize(n->nnot.com);
  7235. break;
  7236. };
  7237. }
  7238. static char *
  7239. nodeckstrdup(char *s)
  7240. {
  7241. char *rtn = funcstring;
  7242. strcpy(funcstring, s);
  7243. funcstring += strlen(s) + 1;
  7244. return rtn;
  7245. }
  7246. static union node *copynode(union node *);
  7247. static struct nodelist *
  7248. copynodelist(struct nodelist *lp)
  7249. {
  7250. struct nodelist *start;
  7251. struct nodelist **lpp;
  7252. lpp = &start;
  7253. while (lp) {
  7254. *lpp = funcblock;
  7255. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  7256. (*lpp)->n = copynode(lp->n);
  7257. lp = lp->next;
  7258. lpp = &(*lpp)->next;
  7259. }
  7260. *lpp = NULL;
  7261. return start;
  7262. }
  7263. static union node *
  7264. copynode(union node *n)
  7265. {
  7266. union node *new;
  7267. if (n == NULL)
  7268. return NULL;
  7269. new = funcblock;
  7270. funcblock = (char *) funcblock + nodesize[n->type];
  7271. switch (n->type) {
  7272. case NCMD:
  7273. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7274. new->ncmd.args = copynode(n->ncmd.args);
  7275. new->ncmd.assign = copynode(n->ncmd.assign);
  7276. break;
  7277. case NPIPE:
  7278. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7279. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7280. break;
  7281. case NREDIR:
  7282. case NBACKGND:
  7283. case NSUBSHELL:
  7284. new->nredir.redirect = copynode(n->nredir.redirect);
  7285. new->nredir.n = copynode(n->nredir.n);
  7286. break;
  7287. case NAND:
  7288. case NOR:
  7289. case NSEMI:
  7290. case NWHILE:
  7291. case NUNTIL:
  7292. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7293. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7294. break;
  7295. case NIF:
  7296. new->nif.elsepart = copynode(n->nif.elsepart);
  7297. new->nif.ifpart = copynode(n->nif.ifpart);
  7298. new->nif.test = copynode(n->nif.test);
  7299. break;
  7300. case NFOR:
  7301. new->nfor.var = nodeckstrdup(n->nfor.var);
  7302. new->nfor.body = copynode(n->nfor.body);
  7303. new->nfor.args = copynode(n->nfor.args);
  7304. break;
  7305. case NCASE:
  7306. new->ncase.cases = copynode(n->ncase.cases);
  7307. new->ncase.expr = copynode(n->ncase.expr);
  7308. break;
  7309. case NCLIST:
  7310. new->nclist.body = copynode(n->nclist.body);
  7311. new->nclist.pattern = copynode(n->nclist.pattern);
  7312. new->nclist.next = copynode(n->nclist.next);
  7313. break;
  7314. case NDEFUN:
  7315. case NARG:
  7316. new->narg.backquote = copynodelist(n->narg.backquote);
  7317. new->narg.text = nodeckstrdup(n->narg.text);
  7318. new->narg.next = copynode(n->narg.next);
  7319. break;
  7320. case NTO:
  7321. #if ENABLE_ASH_BASH_COMPAT
  7322. case NTO2:
  7323. #endif
  7324. case NCLOBBER:
  7325. case NFROM:
  7326. case NFROMTO:
  7327. case NAPPEND:
  7328. new->nfile.fname = copynode(n->nfile.fname);
  7329. new->nfile.fd = n->nfile.fd;
  7330. new->nfile.next = copynode(n->nfile.next);
  7331. break;
  7332. case NTOFD:
  7333. case NFROMFD:
  7334. new->ndup.vname = copynode(n->ndup.vname);
  7335. new->ndup.dupfd = n->ndup.dupfd;
  7336. new->ndup.fd = n->ndup.fd;
  7337. new->ndup.next = copynode(n->ndup.next);
  7338. break;
  7339. case NHERE:
  7340. case NXHERE:
  7341. new->nhere.doc = copynode(n->nhere.doc);
  7342. new->nhere.fd = n->nhere.fd;
  7343. new->nhere.next = copynode(n->nhere.next);
  7344. break;
  7345. case NNOT:
  7346. new->nnot.com = copynode(n->nnot.com);
  7347. break;
  7348. };
  7349. new->type = n->type;
  7350. return new;
  7351. }
  7352. /*
  7353. * Make a copy of a parse tree.
  7354. */
  7355. static struct funcnode *
  7356. copyfunc(union node *n)
  7357. {
  7358. struct funcnode *f;
  7359. size_t blocksize;
  7360. funcblocksize = offsetof(struct funcnode, n);
  7361. funcstringsize = 0;
  7362. calcsize(n);
  7363. blocksize = funcblocksize;
  7364. f = ckmalloc(blocksize + funcstringsize);
  7365. funcblock = (char *) f + offsetof(struct funcnode, n);
  7366. funcstring = (char *) f + blocksize;
  7367. copynode(n);
  7368. f->count = 0;
  7369. return f;
  7370. }
  7371. /*
  7372. * Define a shell function.
  7373. */
  7374. static void
  7375. defun(char *name, union node *func)
  7376. {
  7377. struct cmdentry entry;
  7378. INT_OFF;
  7379. entry.cmdtype = CMDFUNCTION;
  7380. entry.u.func = copyfunc(func);
  7381. addcmdentry(name, &entry);
  7382. INT_ON;
  7383. }
  7384. /* Reasons for skipping commands (see comment on breakcmd routine) */
  7385. #define SKIPBREAK (1 << 0)
  7386. #define SKIPCONT (1 << 1)
  7387. #define SKIPFUNC (1 << 2)
  7388. #define SKIPFILE (1 << 3)
  7389. #define SKIPEVAL (1 << 4)
  7390. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  7391. static int skipcount; /* number of levels to skip */
  7392. static int funcnest; /* depth of function calls */
  7393. static int loopnest; /* current loop nesting level */
  7394. /* Forward decl way out to parsing code - dotrap needs it */
  7395. static int evalstring(char *s, int mask);
  7396. /* Called to execute a trap.
  7397. * Single callsite - at the end of evaltree().
  7398. * If we return non-zero, exaltree raises EXEXIT exception.
  7399. *
  7400. * Perhaps we should avoid entering new trap handlers
  7401. * while we are executing a trap handler. [is it a TODO?]
  7402. */
  7403. static int
  7404. dotrap(void)
  7405. {
  7406. uint8_t *g;
  7407. int sig;
  7408. uint8_t savestatus;
  7409. savestatus = exitstatus;
  7410. pending_sig = 0;
  7411. xbarrier();
  7412. TRACE(("dotrap entered\n"));
  7413. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  7414. int want_exexit;
  7415. char *t;
  7416. if (*g == 0)
  7417. continue;
  7418. t = trap[sig];
  7419. /* non-trapped SIGINT is handled separately by raise_interrupt,
  7420. * don't upset it by resetting gotsig[SIGINT-1] */
  7421. if (sig == SIGINT && !t)
  7422. continue;
  7423. TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
  7424. *g = 0;
  7425. if (!t)
  7426. continue;
  7427. want_exexit = evalstring(t, SKIPEVAL);
  7428. exitstatus = savestatus;
  7429. if (want_exexit) {
  7430. TRACE(("dotrap returns %d\n", want_exexit));
  7431. return want_exexit;
  7432. }
  7433. }
  7434. TRACE(("dotrap returns 0\n"));
  7435. return 0;
  7436. }
  7437. /* forward declarations - evaluation is fairly recursive business... */
  7438. static void evalloop(union node *, int);
  7439. static void evalfor(union node *, int);
  7440. static void evalcase(union node *, int);
  7441. static void evalsubshell(union node *, int);
  7442. static void expredir(union node *);
  7443. static void evalpipe(union node *, int);
  7444. static void evalcommand(union node *, int);
  7445. static int evalbltin(const struct builtincmd *, int, char **);
  7446. static void prehash(union node *);
  7447. /*
  7448. * Evaluate a parse tree. The value is left in the global variable
  7449. * exitstatus.
  7450. */
  7451. static void
  7452. evaltree(union node *n, int flags)
  7453. {
  7454. struct jmploc *volatile savehandler = exception_handler;
  7455. struct jmploc jmploc;
  7456. int checkexit = 0;
  7457. void (*evalfn)(union node *, int);
  7458. int status;
  7459. int int_level;
  7460. SAVE_INT(int_level);
  7461. if (n == NULL) {
  7462. TRACE(("evaltree(NULL) called\n"));
  7463. goto out1;
  7464. }
  7465. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  7466. exception_handler = &jmploc;
  7467. {
  7468. int err = setjmp(jmploc.loc);
  7469. if (err) {
  7470. /* if it was a signal, check for trap handlers */
  7471. if (exception_type == EXSIG) {
  7472. TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
  7473. exception_type, err));
  7474. goto out;
  7475. }
  7476. /* continue on the way out */
  7477. TRACE(("exception %d in evaltree, propagating err=%d\n",
  7478. exception_type, err));
  7479. exception_handler = savehandler;
  7480. longjmp(exception_handler->loc, err);
  7481. }
  7482. }
  7483. switch (n->type) {
  7484. default:
  7485. #if DEBUG
  7486. out1fmt("Node type = %d\n", n->type);
  7487. fflush_all();
  7488. break;
  7489. #endif
  7490. case NNOT:
  7491. evaltree(n->nnot.com, EV_TESTED);
  7492. status = !exitstatus;
  7493. goto setstatus;
  7494. case NREDIR:
  7495. expredir(n->nredir.redirect);
  7496. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  7497. if (!status) {
  7498. evaltree(n->nredir.n, flags & EV_TESTED);
  7499. status = exitstatus;
  7500. }
  7501. popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
  7502. goto setstatus;
  7503. case NCMD:
  7504. evalfn = evalcommand;
  7505. checkexit:
  7506. if (eflag && !(flags & EV_TESTED))
  7507. checkexit = ~0;
  7508. goto calleval;
  7509. case NFOR:
  7510. evalfn = evalfor;
  7511. goto calleval;
  7512. case NWHILE:
  7513. case NUNTIL:
  7514. evalfn = evalloop;
  7515. goto calleval;
  7516. case NSUBSHELL:
  7517. case NBACKGND:
  7518. evalfn = evalsubshell;
  7519. goto calleval;
  7520. case NPIPE:
  7521. evalfn = evalpipe;
  7522. goto checkexit;
  7523. case NCASE:
  7524. evalfn = evalcase;
  7525. goto calleval;
  7526. case NAND:
  7527. case NOR:
  7528. case NSEMI: {
  7529. #if NAND + 1 != NOR
  7530. #error NAND + 1 != NOR
  7531. #endif
  7532. #if NOR + 1 != NSEMI
  7533. #error NOR + 1 != NSEMI
  7534. #endif
  7535. unsigned is_or = n->type - NAND;
  7536. evaltree(
  7537. n->nbinary.ch1,
  7538. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  7539. );
  7540. if (!exitstatus == is_or)
  7541. break;
  7542. if (!evalskip) {
  7543. n = n->nbinary.ch2;
  7544. evaln:
  7545. evalfn = evaltree;
  7546. calleval:
  7547. evalfn(n, flags);
  7548. break;
  7549. }
  7550. break;
  7551. }
  7552. case NIF:
  7553. evaltree(n->nif.test, EV_TESTED);
  7554. if (evalskip)
  7555. break;
  7556. if (exitstatus == 0) {
  7557. n = n->nif.ifpart;
  7558. goto evaln;
  7559. }
  7560. if (n->nif.elsepart) {
  7561. n = n->nif.elsepart;
  7562. goto evaln;
  7563. }
  7564. goto success;
  7565. case NDEFUN:
  7566. defun(n->narg.text, n->narg.next);
  7567. success:
  7568. status = 0;
  7569. setstatus:
  7570. exitstatus = status;
  7571. break;
  7572. }
  7573. out:
  7574. exception_handler = savehandler;
  7575. out1:
  7576. if (checkexit & exitstatus)
  7577. evalskip |= SKIPEVAL;
  7578. else if (pending_sig && dotrap())
  7579. goto exexit;
  7580. if (flags & EV_EXIT) {
  7581. exexit:
  7582. raise_exception(EXEXIT);
  7583. }
  7584. RESTORE_INT(int_level);
  7585. TRACE(("leaving evaltree (no interrupts)\n"));
  7586. }
  7587. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  7588. static
  7589. #endif
  7590. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  7591. static void
  7592. evalloop(union node *n, int flags)
  7593. {
  7594. int status;
  7595. loopnest++;
  7596. status = 0;
  7597. flags &= EV_TESTED;
  7598. for (;;) {
  7599. int i;
  7600. evaltree(n->nbinary.ch1, EV_TESTED);
  7601. if (evalskip) {
  7602. skipping:
  7603. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7604. evalskip = 0;
  7605. continue;
  7606. }
  7607. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7608. evalskip = 0;
  7609. break;
  7610. }
  7611. i = exitstatus;
  7612. if (n->type != NWHILE)
  7613. i = !i;
  7614. if (i != 0)
  7615. break;
  7616. evaltree(n->nbinary.ch2, flags);
  7617. status = exitstatus;
  7618. if (evalskip)
  7619. goto skipping;
  7620. }
  7621. loopnest--;
  7622. exitstatus = status;
  7623. }
  7624. static void
  7625. evalfor(union node *n, int flags)
  7626. {
  7627. struct arglist arglist;
  7628. union node *argp;
  7629. struct strlist *sp;
  7630. struct stackmark smark;
  7631. setstackmark(&smark);
  7632. arglist.list = NULL;
  7633. arglist.lastp = &arglist.list;
  7634. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  7635. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
  7636. /* XXX */
  7637. if (evalskip)
  7638. goto out;
  7639. }
  7640. *arglist.lastp = NULL;
  7641. exitstatus = 0;
  7642. loopnest++;
  7643. flags &= EV_TESTED;
  7644. for (sp = arglist.list; sp; sp = sp->next) {
  7645. setvar(n->nfor.var, sp->text, 0);
  7646. evaltree(n->nfor.body, flags);
  7647. if (evalskip) {
  7648. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7649. evalskip = 0;
  7650. continue;
  7651. }
  7652. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7653. evalskip = 0;
  7654. break;
  7655. }
  7656. }
  7657. loopnest--;
  7658. out:
  7659. popstackmark(&smark);
  7660. }
  7661. static void
  7662. evalcase(union node *n, int flags)
  7663. {
  7664. union node *cp;
  7665. union node *patp;
  7666. struct arglist arglist;
  7667. struct stackmark smark;
  7668. setstackmark(&smark);
  7669. arglist.list = NULL;
  7670. arglist.lastp = &arglist.list;
  7671. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  7672. exitstatus = 0;
  7673. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  7674. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  7675. if (casematch(patp, arglist.list->text)) {
  7676. if (evalskip == 0) {
  7677. evaltree(cp->nclist.body, flags);
  7678. }
  7679. goto out;
  7680. }
  7681. }
  7682. }
  7683. out:
  7684. popstackmark(&smark);
  7685. }
  7686. /*
  7687. * Kick off a subshell to evaluate a tree.
  7688. */
  7689. static void
  7690. evalsubshell(union node *n, int flags)
  7691. {
  7692. struct job *jp;
  7693. int backgnd = (n->type == NBACKGND);
  7694. int status;
  7695. expredir(n->nredir.redirect);
  7696. if (!backgnd && flags & EV_EXIT && !trap[0])
  7697. goto nofork;
  7698. INT_OFF;
  7699. jp = makejob(/*n,*/ 1);
  7700. if (forkshell(jp, n, backgnd) == 0) {
  7701. INT_ON;
  7702. flags |= EV_EXIT;
  7703. if (backgnd)
  7704. flags &=~ EV_TESTED;
  7705. nofork:
  7706. redirect(n->nredir.redirect, 0);
  7707. evaltreenr(n->nredir.n, flags);
  7708. /* never returns */
  7709. }
  7710. status = 0;
  7711. if (!backgnd)
  7712. status = waitforjob(jp);
  7713. exitstatus = status;
  7714. INT_ON;
  7715. }
  7716. /*
  7717. * Compute the names of the files in a redirection list.
  7718. */
  7719. static void fixredir(union node *, const char *, int);
  7720. static void
  7721. expredir(union node *n)
  7722. {
  7723. union node *redir;
  7724. for (redir = n; redir; redir = redir->nfile.next) {
  7725. struct arglist fn;
  7726. fn.list = NULL;
  7727. fn.lastp = &fn.list;
  7728. switch (redir->type) {
  7729. case NFROMTO:
  7730. case NFROM:
  7731. case NTO:
  7732. #if ENABLE_ASH_BASH_COMPAT
  7733. case NTO2:
  7734. #endif
  7735. case NCLOBBER:
  7736. case NAPPEND:
  7737. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  7738. #if ENABLE_ASH_BASH_COMPAT
  7739. store_expfname:
  7740. #endif
  7741. redir->nfile.expfname = fn.list->text;
  7742. break;
  7743. case NFROMFD:
  7744. case NTOFD: /* >& */
  7745. if (redir->ndup.vname) {
  7746. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  7747. if (fn.list == NULL)
  7748. ash_msg_and_raise_error("redir error");
  7749. #if ENABLE_ASH_BASH_COMPAT
  7750. //FIXME: we used expandarg with different args!
  7751. if (!isdigit_str9(fn.list->text)) {
  7752. /* >&file, not >&fd */
  7753. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  7754. ash_msg_and_raise_error("redir error");
  7755. redir->type = NTO2;
  7756. goto store_expfname;
  7757. }
  7758. #endif
  7759. fixredir(redir, fn.list->text, 1);
  7760. }
  7761. break;
  7762. }
  7763. }
  7764. }
  7765. /*
  7766. * Evaluate a pipeline. All the processes in the pipeline are children
  7767. * of the process creating the pipeline. (This differs from some versions
  7768. * of the shell, which make the last process in a pipeline the parent
  7769. * of all the rest.)
  7770. */
  7771. static void
  7772. evalpipe(union node *n, int flags)
  7773. {
  7774. struct job *jp;
  7775. struct nodelist *lp;
  7776. int pipelen;
  7777. int prevfd;
  7778. int pip[2];
  7779. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  7780. pipelen = 0;
  7781. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  7782. pipelen++;
  7783. flags |= EV_EXIT;
  7784. INT_OFF;
  7785. jp = makejob(/*n,*/ pipelen);
  7786. prevfd = -1;
  7787. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  7788. prehash(lp->n);
  7789. pip[1] = -1;
  7790. if (lp->next) {
  7791. if (pipe(pip) < 0) {
  7792. close(prevfd);
  7793. ash_msg_and_raise_error("pipe call failed");
  7794. }
  7795. }
  7796. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  7797. INT_ON;
  7798. if (pip[1] >= 0) {
  7799. close(pip[0]);
  7800. }
  7801. if (prevfd > 0) {
  7802. dup2(prevfd, 0);
  7803. close(prevfd);
  7804. }
  7805. if (pip[1] > 1) {
  7806. dup2(pip[1], 1);
  7807. close(pip[1]);
  7808. }
  7809. evaltreenr(lp->n, flags);
  7810. /* never returns */
  7811. }
  7812. if (prevfd >= 0)
  7813. close(prevfd);
  7814. prevfd = pip[0];
  7815. /* Don't want to trigger debugging */
  7816. if (pip[1] != -1)
  7817. close(pip[1]);
  7818. }
  7819. if (n->npipe.pipe_backgnd == 0) {
  7820. exitstatus = waitforjob(jp);
  7821. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  7822. }
  7823. INT_ON;
  7824. }
  7825. /*
  7826. * Controls whether the shell is interactive or not.
  7827. */
  7828. static void
  7829. setinteractive(int on)
  7830. {
  7831. static smallint is_interactive;
  7832. if (++on == is_interactive)
  7833. return;
  7834. is_interactive = on;
  7835. setsignal(SIGINT);
  7836. setsignal(SIGQUIT);
  7837. setsignal(SIGTERM);
  7838. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7839. if (is_interactive > 1) {
  7840. /* Looks like they want an interactive shell */
  7841. static smallint did_banner;
  7842. if (!did_banner) {
  7843. /* note: ash and hush share this string */
  7844. out1fmt("\n\n%s %s\n"
  7845. "Enter 'help' for a list of built-in commands."
  7846. "\n\n",
  7847. bb_banner,
  7848. "built-in shell (ash)"
  7849. );
  7850. did_banner = 1;
  7851. }
  7852. }
  7853. #endif
  7854. }
  7855. static void
  7856. optschanged(void)
  7857. {
  7858. #if DEBUG
  7859. opentrace();
  7860. #endif
  7861. setinteractive(iflag);
  7862. setjobctl(mflag);
  7863. #if ENABLE_FEATURE_EDITING_VI
  7864. if (viflag)
  7865. line_input_state->flags |= VI_MODE;
  7866. else
  7867. line_input_state->flags &= ~VI_MODE;
  7868. #else
  7869. viflag = 0; /* forcibly keep the option off */
  7870. #endif
  7871. }
  7872. static struct localvar *localvars;
  7873. /*
  7874. * Called after a function returns.
  7875. * Interrupts must be off.
  7876. */
  7877. static void
  7878. poplocalvars(void)
  7879. {
  7880. struct localvar *lvp;
  7881. struct var *vp;
  7882. while ((lvp = localvars) != NULL) {
  7883. localvars = lvp->next;
  7884. vp = lvp->vp;
  7885. TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
  7886. if (vp == NULL) { /* $- saved */
  7887. memcpy(optlist, lvp->text, sizeof(optlist));
  7888. free((char*)lvp->text);
  7889. optschanged();
  7890. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  7891. unsetvar(vp->text);
  7892. } else {
  7893. if (vp->func)
  7894. (*vp->func)(strchrnul(lvp->text, '=') + 1);
  7895. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  7896. free((char*)vp->text);
  7897. vp->flags = lvp->flags;
  7898. vp->text = lvp->text;
  7899. }
  7900. free(lvp);
  7901. }
  7902. }
  7903. static int
  7904. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  7905. {
  7906. volatile struct shparam saveparam;
  7907. struct localvar *volatile savelocalvars;
  7908. struct jmploc *volatile savehandler;
  7909. struct jmploc jmploc;
  7910. int e;
  7911. saveparam = shellparam;
  7912. savelocalvars = localvars;
  7913. e = setjmp(jmploc.loc);
  7914. if (e) {
  7915. goto funcdone;
  7916. }
  7917. INT_OFF;
  7918. savehandler = exception_handler;
  7919. exception_handler = &jmploc;
  7920. localvars = NULL;
  7921. shellparam.malloced = 0;
  7922. func->count++;
  7923. funcnest++;
  7924. INT_ON;
  7925. shellparam.nparam = argc - 1;
  7926. shellparam.p = argv + 1;
  7927. #if ENABLE_ASH_GETOPTS
  7928. shellparam.optind = 1;
  7929. shellparam.optoff = -1;
  7930. #endif
  7931. evaltree(&func->n, flags & EV_TESTED);
  7932. funcdone:
  7933. INT_OFF;
  7934. funcnest--;
  7935. freefunc(func);
  7936. poplocalvars();
  7937. localvars = savelocalvars;
  7938. freeparam(&shellparam);
  7939. shellparam = saveparam;
  7940. exception_handler = savehandler;
  7941. INT_ON;
  7942. evalskip &= ~SKIPFUNC;
  7943. return e;
  7944. }
  7945. #if ENABLE_ASH_CMDCMD
  7946. static char **
  7947. parse_command_args(char **argv, const char **path)
  7948. {
  7949. char *cp, c;
  7950. for (;;) {
  7951. cp = *++argv;
  7952. if (!cp)
  7953. return 0;
  7954. if (*cp++ != '-')
  7955. break;
  7956. c = *cp++;
  7957. if (!c)
  7958. break;
  7959. if (c == '-' && !*cp) {
  7960. argv++;
  7961. break;
  7962. }
  7963. do {
  7964. switch (c) {
  7965. case 'p':
  7966. *path = bb_default_path;
  7967. break;
  7968. default:
  7969. /* run 'typecmd' for other options */
  7970. return 0;
  7971. }
  7972. c = *cp++;
  7973. } while (c);
  7974. }
  7975. return argv;
  7976. }
  7977. #endif
  7978. /*
  7979. * Make a variable a local variable. When a variable is made local, it's
  7980. * value and flags are saved in a localvar structure. The saved values
  7981. * will be restored when the shell function returns. We handle the name
  7982. * "-" as a special case.
  7983. */
  7984. static void
  7985. mklocal(char *name)
  7986. {
  7987. struct localvar *lvp;
  7988. struct var **vpp;
  7989. struct var *vp;
  7990. INT_OFF;
  7991. lvp = ckzalloc(sizeof(struct localvar));
  7992. if (LONE_DASH(name)) {
  7993. char *p;
  7994. p = ckmalloc(sizeof(optlist));
  7995. lvp->text = memcpy(p, optlist, sizeof(optlist));
  7996. vp = NULL;
  7997. } else {
  7998. char *eq;
  7999. vpp = hashvar(name);
  8000. vp = *findvar(vpp, name);
  8001. eq = strchr(name, '=');
  8002. if (vp == NULL) {
  8003. if (eq)
  8004. setvareq(name, VSTRFIXED);
  8005. else
  8006. setvar(name, NULL, VSTRFIXED);
  8007. vp = *vpp; /* the new variable */
  8008. lvp->flags = VUNSET;
  8009. } else {
  8010. lvp->text = vp->text;
  8011. lvp->flags = vp->flags;
  8012. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8013. if (eq)
  8014. setvareq(name, 0);
  8015. }
  8016. }
  8017. lvp->vp = vp;
  8018. lvp->next = localvars;
  8019. localvars = lvp;
  8020. INT_ON;
  8021. }
  8022. /*
  8023. * The "local" command.
  8024. */
  8025. static int FAST_FUNC
  8026. localcmd(int argc UNUSED_PARAM, char **argv)
  8027. {
  8028. char *name;
  8029. argv = argptr;
  8030. while ((name = *argv++) != NULL) {
  8031. mklocal(name);
  8032. }
  8033. return 0;
  8034. }
  8035. static int FAST_FUNC
  8036. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8037. {
  8038. return 1;
  8039. }
  8040. static int FAST_FUNC
  8041. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8042. {
  8043. return 0;
  8044. }
  8045. static int FAST_FUNC
  8046. execcmd(int argc UNUSED_PARAM, char **argv)
  8047. {
  8048. if (argv[1]) {
  8049. iflag = 0; /* exit on error */
  8050. mflag = 0;
  8051. optschanged();
  8052. shellexec(argv + 1, pathval(), 0);
  8053. }
  8054. return 0;
  8055. }
  8056. /*
  8057. * The return command.
  8058. */
  8059. static int FAST_FUNC
  8060. returncmd(int argc UNUSED_PARAM, char **argv)
  8061. {
  8062. /*
  8063. * If called outside a function, do what ksh does;
  8064. * skip the rest of the file.
  8065. */
  8066. evalskip = funcnest ? SKIPFUNC : SKIPFILE;
  8067. return argv[1] ? number(argv[1]) : exitstatus;
  8068. }
  8069. /* Forward declarations for builtintab[] */
  8070. static int breakcmd(int, char **) FAST_FUNC;
  8071. static int dotcmd(int, char **) FAST_FUNC;
  8072. static int evalcmd(int, char **) FAST_FUNC;
  8073. static int exitcmd(int, char **) FAST_FUNC;
  8074. static int exportcmd(int, char **) FAST_FUNC;
  8075. #if ENABLE_ASH_GETOPTS
  8076. static int getoptscmd(int, char **) FAST_FUNC;
  8077. #endif
  8078. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8079. static int helpcmd(int, char **) FAST_FUNC;
  8080. #endif
  8081. #if ENABLE_SH_MATH_SUPPORT
  8082. static int letcmd(int, char **) FAST_FUNC;
  8083. #endif
  8084. static int readcmd(int, char **) FAST_FUNC;
  8085. static int setcmd(int, char **) FAST_FUNC;
  8086. static int shiftcmd(int, char **) FAST_FUNC;
  8087. static int timescmd(int, char **) FAST_FUNC;
  8088. static int trapcmd(int, char **) FAST_FUNC;
  8089. static int umaskcmd(int, char **) FAST_FUNC;
  8090. static int unsetcmd(int, char **) FAST_FUNC;
  8091. static int ulimitcmd(int, char **) FAST_FUNC;
  8092. #define BUILTIN_NOSPEC "0"
  8093. #define BUILTIN_SPECIAL "1"
  8094. #define BUILTIN_REGULAR "2"
  8095. #define BUILTIN_SPEC_REG "3"
  8096. #define BUILTIN_ASSIGN "4"
  8097. #define BUILTIN_SPEC_ASSG "5"
  8098. #define BUILTIN_REG_ASSG "6"
  8099. #define BUILTIN_SPEC_REG_ASSG "7"
  8100. /* Stubs for calling non-FAST_FUNC's */
  8101. #if ENABLE_ASH_BUILTIN_ECHO
  8102. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8103. #endif
  8104. #if ENABLE_ASH_BUILTIN_PRINTF
  8105. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8106. #endif
  8107. #if ENABLE_ASH_BUILTIN_TEST
  8108. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8109. #endif
  8110. /* Keep these in proper order since it is searched via bsearch() */
  8111. static const struct builtincmd builtintab[] = {
  8112. { BUILTIN_SPEC_REG "." , dotcmd },
  8113. { BUILTIN_SPEC_REG ":" , truecmd },
  8114. #if ENABLE_ASH_BUILTIN_TEST
  8115. { BUILTIN_REGULAR "[" , testcmd },
  8116. #if ENABLE_ASH_BASH_COMPAT
  8117. { BUILTIN_REGULAR "[[" , testcmd },
  8118. #endif
  8119. #endif
  8120. #if ENABLE_ASH_ALIAS
  8121. { BUILTIN_REG_ASSG "alias" , aliascmd },
  8122. #endif
  8123. #if JOBS
  8124. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  8125. #endif
  8126. { BUILTIN_SPEC_REG "break" , breakcmd },
  8127. { BUILTIN_REGULAR "cd" , cdcmd },
  8128. { BUILTIN_NOSPEC "chdir" , cdcmd },
  8129. #if ENABLE_ASH_CMDCMD
  8130. { BUILTIN_REGULAR "command" , commandcmd },
  8131. #endif
  8132. { BUILTIN_SPEC_REG "continue", breakcmd },
  8133. #if ENABLE_ASH_BUILTIN_ECHO
  8134. { BUILTIN_REGULAR "echo" , echocmd },
  8135. #endif
  8136. { BUILTIN_SPEC_REG "eval" , evalcmd },
  8137. { BUILTIN_SPEC_REG "exec" , execcmd },
  8138. { BUILTIN_SPEC_REG "exit" , exitcmd },
  8139. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  8140. { BUILTIN_REGULAR "false" , falsecmd },
  8141. #if JOBS
  8142. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  8143. #endif
  8144. #if ENABLE_ASH_GETOPTS
  8145. { BUILTIN_REGULAR "getopts" , getoptscmd },
  8146. #endif
  8147. { BUILTIN_NOSPEC "hash" , hashcmd },
  8148. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8149. { BUILTIN_NOSPEC "help" , helpcmd },
  8150. #endif
  8151. #if JOBS
  8152. { BUILTIN_REGULAR "jobs" , jobscmd },
  8153. { BUILTIN_REGULAR "kill" , killcmd },
  8154. #endif
  8155. #if ENABLE_SH_MATH_SUPPORT
  8156. { BUILTIN_NOSPEC "let" , letcmd },
  8157. #endif
  8158. { BUILTIN_ASSIGN "local" , localcmd },
  8159. #if ENABLE_ASH_BUILTIN_PRINTF
  8160. { BUILTIN_REGULAR "printf" , printfcmd },
  8161. #endif
  8162. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  8163. { BUILTIN_REGULAR "read" , readcmd },
  8164. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  8165. { BUILTIN_SPEC_REG "return" , returncmd },
  8166. { BUILTIN_SPEC_REG "set" , setcmd },
  8167. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  8168. { BUILTIN_SPEC_REG "source" , dotcmd },
  8169. #if ENABLE_ASH_BUILTIN_TEST
  8170. { BUILTIN_REGULAR "test" , testcmd },
  8171. #endif
  8172. { BUILTIN_SPEC_REG "times" , timescmd },
  8173. { BUILTIN_SPEC_REG "trap" , trapcmd },
  8174. { BUILTIN_REGULAR "true" , truecmd },
  8175. { BUILTIN_NOSPEC "type" , typecmd },
  8176. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  8177. { BUILTIN_REGULAR "umask" , umaskcmd },
  8178. #if ENABLE_ASH_ALIAS
  8179. { BUILTIN_REGULAR "unalias" , unaliascmd },
  8180. #endif
  8181. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  8182. { BUILTIN_REGULAR "wait" , waitcmd },
  8183. };
  8184. /* Should match the above table! */
  8185. #define COMMANDCMD (builtintab + \
  8186. 2 + \
  8187. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8188. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8189. 1 * ENABLE_ASH_ALIAS + \
  8190. 1 * ENABLE_ASH_JOB_CONTROL + \
  8191. 3)
  8192. #define EXECCMD (builtintab + \
  8193. 2 + \
  8194. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8195. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8196. 1 * ENABLE_ASH_ALIAS + \
  8197. 1 * ENABLE_ASH_JOB_CONTROL + \
  8198. 3 + \
  8199. 1 * ENABLE_ASH_CMDCMD + \
  8200. 1 + \
  8201. ENABLE_ASH_BUILTIN_ECHO + \
  8202. 1)
  8203. /*
  8204. * Search the table of builtin commands.
  8205. */
  8206. static struct builtincmd *
  8207. find_builtin(const char *name)
  8208. {
  8209. struct builtincmd *bp;
  8210. bp = bsearch(
  8211. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  8212. pstrcmp
  8213. );
  8214. return bp;
  8215. }
  8216. /*
  8217. * Execute a simple command.
  8218. */
  8219. static int
  8220. isassignment(const char *p)
  8221. {
  8222. const char *q = endofname(p);
  8223. if (p == q)
  8224. return 0;
  8225. return *q == '=';
  8226. }
  8227. static int FAST_FUNC
  8228. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8229. {
  8230. /* Preserve exitstatus of a previous possible redirection
  8231. * as POSIX mandates */
  8232. return back_exitstatus;
  8233. }
  8234. static void
  8235. evalcommand(union node *cmd, int flags)
  8236. {
  8237. static const struct builtincmd null_bltin = {
  8238. "\0\0", bltincmd /* why three NULs? */
  8239. };
  8240. struct stackmark smark;
  8241. union node *argp;
  8242. struct arglist arglist;
  8243. struct arglist varlist;
  8244. char **argv;
  8245. int argc;
  8246. const struct strlist *sp;
  8247. struct cmdentry cmdentry;
  8248. struct job *jp;
  8249. char *lastarg;
  8250. const char *path;
  8251. int spclbltin;
  8252. int status;
  8253. char **nargv;
  8254. struct builtincmd *bcmd;
  8255. smallint cmd_is_exec;
  8256. smallint pseudovarflag = 0;
  8257. /* First expand the arguments. */
  8258. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  8259. setstackmark(&smark);
  8260. back_exitstatus = 0;
  8261. cmdentry.cmdtype = CMDBUILTIN;
  8262. cmdentry.u.cmd = &null_bltin;
  8263. varlist.lastp = &varlist.list;
  8264. *varlist.lastp = NULL;
  8265. arglist.lastp = &arglist.list;
  8266. *arglist.lastp = NULL;
  8267. argc = 0;
  8268. if (cmd->ncmd.args) {
  8269. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  8270. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  8271. }
  8272. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  8273. struct strlist **spp;
  8274. spp = arglist.lastp;
  8275. if (pseudovarflag && isassignment(argp->narg.text))
  8276. expandarg(argp, &arglist, EXP_VARTILDE);
  8277. else
  8278. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8279. for (sp = *spp; sp; sp = sp->next)
  8280. argc++;
  8281. }
  8282. argv = nargv = stalloc(sizeof(char *) * (argc + 1));
  8283. for (sp = arglist.list; sp; sp = sp->next) {
  8284. TRACE(("evalcommand arg: %s\n", sp->text));
  8285. *nargv++ = sp->text;
  8286. }
  8287. *nargv = NULL;
  8288. lastarg = NULL;
  8289. if (iflag && funcnest == 0 && argc > 0)
  8290. lastarg = nargv[-1];
  8291. preverrout_fd = 2;
  8292. expredir(cmd->ncmd.redirect);
  8293. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  8294. path = vpath.text;
  8295. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  8296. struct strlist **spp;
  8297. char *p;
  8298. spp = varlist.lastp;
  8299. expandarg(argp, &varlist, EXP_VARTILDE);
  8300. /*
  8301. * Modify the command lookup path, if a PATH= assignment
  8302. * is present
  8303. */
  8304. p = (*spp)->text;
  8305. if (varequal(p, path))
  8306. path = p;
  8307. }
  8308. /* Print the command if xflag is set. */
  8309. if (xflag) {
  8310. int n;
  8311. const char *p = " %s";
  8312. p++;
  8313. fdprintf(preverrout_fd, p, expandstr(ps4val()));
  8314. sp = varlist.list;
  8315. for (n = 0; n < 2; n++) {
  8316. while (sp) {
  8317. fdprintf(preverrout_fd, p, sp->text);
  8318. sp = sp->next;
  8319. if (*p == '%') {
  8320. p--;
  8321. }
  8322. }
  8323. sp = arglist.list;
  8324. }
  8325. safe_write(preverrout_fd, "\n", 1);
  8326. }
  8327. cmd_is_exec = 0;
  8328. spclbltin = -1;
  8329. /* Now locate the command. */
  8330. if (argc) {
  8331. const char *oldpath;
  8332. int cmd_flag = DO_ERR;
  8333. path += 5;
  8334. oldpath = path;
  8335. for (;;) {
  8336. find_command(argv[0], &cmdentry, cmd_flag, path);
  8337. if (cmdentry.cmdtype == CMDUNKNOWN) {
  8338. flush_stdout_stderr();
  8339. status = 127;
  8340. goto bail;
  8341. }
  8342. /* implement bltin and command here */
  8343. if (cmdentry.cmdtype != CMDBUILTIN)
  8344. break;
  8345. if (spclbltin < 0)
  8346. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  8347. if (cmdentry.u.cmd == EXECCMD)
  8348. cmd_is_exec = 1;
  8349. #if ENABLE_ASH_CMDCMD
  8350. if (cmdentry.u.cmd == COMMANDCMD) {
  8351. path = oldpath;
  8352. nargv = parse_command_args(argv, &path);
  8353. if (!nargv)
  8354. break;
  8355. argc -= nargv - argv;
  8356. argv = nargv;
  8357. cmd_flag |= DO_NOFUNC;
  8358. } else
  8359. #endif
  8360. break;
  8361. }
  8362. }
  8363. if (status) {
  8364. /* We have a redirection error. */
  8365. if (spclbltin > 0)
  8366. raise_exception(EXERROR);
  8367. bail:
  8368. exitstatus = status;
  8369. goto out;
  8370. }
  8371. /* Execute the command. */
  8372. switch (cmdentry.cmdtype) {
  8373. default:
  8374. #if ENABLE_FEATURE_SH_NOFORK
  8375. /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
  8376. * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
  8377. {
  8378. /* find_command() encodes applet_no as (-2 - applet_no) */
  8379. int applet_no = (- cmdentry.u.index - 2);
  8380. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  8381. listsetvar(varlist.list, VEXPORT|VSTACK);
  8382. /* run <applet>_main() */
  8383. exitstatus = run_nofork_applet(applet_no, argv);
  8384. break;
  8385. }
  8386. }
  8387. #endif
  8388. /* Fork off a child process if necessary. */
  8389. if (!(flags & EV_EXIT) || trap[0]) {
  8390. INT_OFF;
  8391. jp = makejob(/*cmd,*/ 1);
  8392. if (forkshell(jp, cmd, FORK_FG) != 0) {
  8393. exitstatus = waitforjob(jp);
  8394. INT_ON;
  8395. TRACE(("forked child exited with %d\n", exitstatus));
  8396. break;
  8397. }
  8398. FORCE_INT_ON;
  8399. }
  8400. listsetvar(varlist.list, VEXPORT|VSTACK);
  8401. shellexec(argv, path, cmdentry.u.index);
  8402. /* NOTREACHED */
  8403. case CMDBUILTIN:
  8404. cmdenviron = varlist.list;
  8405. if (cmdenviron) {
  8406. struct strlist *list = cmdenviron;
  8407. int i = VNOSET;
  8408. if (spclbltin > 0 || argc == 0) {
  8409. i = 0;
  8410. if (cmd_is_exec && argc > 1)
  8411. i = VEXPORT;
  8412. }
  8413. listsetvar(list, i);
  8414. }
  8415. /* Tight loop with builtins only:
  8416. * "while kill -0 $child; do true; done"
  8417. * will never exit even if $child died, unless we do this
  8418. * to reap the zombie and make kill detect that it's gone: */
  8419. dowait(DOWAIT_NONBLOCK, NULL);
  8420. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  8421. int exit_status;
  8422. int i = exception_type;
  8423. if (i == EXEXIT)
  8424. goto raise;
  8425. exit_status = 2;
  8426. if (i == EXINT)
  8427. exit_status = 128 + SIGINT;
  8428. if (i == EXSIG)
  8429. exit_status = 128 + pending_sig;
  8430. exitstatus = exit_status;
  8431. if (i == EXINT || spclbltin > 0) {
  8432. raise:
  8433. longjmp(exception_handler->loc, 1);
  8434. }
  8435. FORCE_INT_ON;
  8436. }
  8437. break;
  8438. case CMDFUNCTION:
  8439. listsetvar(varlist.list, 0);
  8440. /* See above for the rationale */
  8441. dowait(DOWAIT_NONBLOCK, NULL);
  8442. if (evalfun(cmdentry.u.func, argc, argv, flags))
  8443. goto raise;
  8444. break;
  8445. }
  8446. out:
  8447. popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
  8448. if (lastarg) {
  8449. /* dsl: I think this is intended to be used to support
  8450. * '_' in 'vi' command mode during line editing...
  8451. * However I implemented that within libedit itself.
  8452. */
  8453. setvar("_", lastarg, 0);
  8454. }
  8455. popstackmark(&smark);
  8456. }
  8457. static int
  8458. evalbltin(const struct builtincmd *cmd, int argc, char **argv)
  8459. {
  8460. char *volatile savecmdname;
  8461. struct jmploc *volatile savehandler;
  8462. struct jmploc jmploc;
  8463. int i;
  8464. savecmdname = commandname;
  8465. i = setjmp(jmploc.loc);
  8466. if (i)
  8467. goto cmddone;
  8468. savehandler = exception_handler;
  8469. exception_handler = &jmploc;
  8470. commandname = argv[0];
  8471. argptr = argv + 1;
  8472. optptr = NULL; /* initialize nextopt */
  8473. exitstatus = (*cmd->builtin)(argc, argv);
  8474. flush_stdout_stderr();
  8475. cmddone:
  8476. exitstatus |= ferror(stdout);
  8477. clearerr(stdout);
  8478. commandname = savecmdname;
  8479. exception_handler = savehandler;
  8480. return i;
  8481. }
  8482. static int
  8483. goodname(const char *p)
  8484. {
  8485. return !*endofname(p);
  8486. }
  8487. /*
  8488. * Search for a command. This is called before we fork so that the
  8489. * location of the command will be available in the parent as well as
  8490. * the child. The check for "goodname" is an overly conservative
  8491. * check that the name will not be subject to expansion.
  8492. */
  8493. static void
  8494. prehash(union node *n)
  8495. {
  8496. struct cmdentry entry;
  8497. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  8498. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  8499. }
  8500. /* ============ Builtin commands
  8501. *
  8502. * Builtin commands whose functions are closely tied to evaluation
  8503. * are implemented here.
  8504. */
  8505. /*
  8506. * Handle break and continue commands. Break, continue, and return are
  8507. * all handled by setting the evalskip flag. The evaluation routines
  8508. * above all check this flag, and if it is set they start skipping
  8509. * commands rather than executing them. The variable skipcount is
  8510. * the number of loops to break/continue, or the number of function
  8511. * levels to return. (The latter is always 1.) It should probably
  8512. * be an error to break out of more loops than exist, but it isn't
  8513. * in the standard shell so we don't make it one here.
  8514. */
  8515. static int FAST_FUNC
  8516. breakcmd(int argc UNUSED_PARAM, char **argv)
  8517. {
  8518. int n = argv[1] ? number(argv[1]) : 1;
  8519. if (n <= 0)
  8520. ash_msg_and_raise_error(msg_illnum, argv[1]);
  8521. if (n > loopnest)
  8522. n = loopnest;
  8523. if (n > 0) {
  8524. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  8525. skipcount = n;
  8526. }
  8527. return 0;
  8528. }
  8529. /* ============ input.c
  8530. *
  8531. * This implements the input routines used by the parser.
  8532. */
  8533. enum {
  8534. INPUT_PUSH_FILE = 1,
  8535. INPUT_NOFILE_OK = 2,
  8536. };
  8537. static smallint checkkwd;
  8538. /* values of checkkwd variable */
  8539. #define CHKALIAS 0x1
  8540. #define CHKKWD 0x2
  8541. #define CHKNL 0x4
  8542. /*
  8543. * Push a string back onto the input at this current parsefile level.
  8544. * We handle aliases this way.
  8545. */
  8546. #if !ENABLE_ASH_ALIAS
  8547. #define pushstring(s, ap) pushstring(s)
  8548. #endif
  8549. static void
  8550. pushstring(char *s, struct alias *ap)
  8551. {
  8552. struct strpush *sp;
  8553. int len;
  8554. len = strlen(s);
  8555. INT_OFF;
  8556. if (g_parsefile->strpush) {
  8557. sp = ckzalloc(sizeof(*sp));
  8558. sp->prev = g_parsefile->strpush;
  8559. } else {
  8560. sp = &(g_parsefile->basestrpush);
  8561. }
  8562. g_parsefile->strpush = sp;
  8563. sp->prev_string = g_parsefile->next_to_pgetc;
  8564. sp->prev_left_in_line = g_parsefile->left_in_line;
  8565. #if ENABLE_ASH_ALIAS
  8566. sp->ap = ap;
  8567. if (ap) {
  8568. ap->flag |= ALIASINUSE;
  8569. sp->string = s;
  8570. }
  8571. #endif
  8572. g_parsefile->next_to_pgetc = s;
  8573. g_parsefile->left_in_line = len;
  8574. INT_ON;
  8575. }
  8576. static void
  8577. popstring(void)
  8578. {
  8579. struct strpush *sp = g_parsefile->strpush;
  8580. INT_OFF;
  8581. #if ENABLE_ASH_ALIAS
  8582. if (sp->ap) {
  8583. if (g_parsefile->next_to_pgetc[-1] == ' '
  8584. || g_parsefile->next_to_pgetc[-1] == '\t'
  8585. ) {
  8586. checkkwd |= CHKALIAS;
  8587. }
  8588. if (sp->string != sp->ap->val) {
  8589. free(sp->string);
  8590. }
  8591. sp->ap->flag &= ~ALIASINUSE;
  8592. if (sp->ap->flag & ALIASDEAD) {
  8593. unalias(sp->ap->name);
  8594. }
  8595. }
  8596. #endif
  8597. g_parsefile->next_to_pgetc = sp->prev_string;
  8598. g_parsefile->left_in_line = sp->prev_left_in_line;
  8599. g_parsefile->strpush = sp->prev;
  8600. if (sp != &(g_parsefile->basestrpush))
  8601. free(sp);
  8602. INT_ON;
  8603. }
  8604. //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
  8605. //it peeks whether it is &>, and then pushes back both chars.
  8606. //This function needs to save last *next_to_pgetc to buf[0]
  8607. //to make two pungetc() reliable. Currently,
  8608. // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
  8609. static int
  8610. preadfd(void)
  8611. {
  8612. int nr;
  8613. char *buf = g_parsefile->buf;
  8614. g_parsefile->next_to_pgetc = buf;
  8615. #if ENABLE_FEATURE_EDITING
  8616. retry:
  8617. if (!iflag || g_parsefile->fd != STDIN_FILENO)
  8618. nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
  8619. else {
  8620. #if ENABLE_FEATURE_TAB_COMPLETION
  8621. line_input_state->path_lookup = pathval();
  8622. #endif
  8623. nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
  8624. if (nr == 0) {
  8625. /* Ctrl+C pressed */
  8626. if (trap[SIGINT]) {
  8627. buf[0] = '\n';
  8628. buf[1] = '\0';
  8629. raise(SIGINT);
  8630. return 1;
  8631. }
  8632. goto retry;
  8633. }
  8634. if (nr < 0 && errno == 0) {
  8635. /* Ctrl+D pressed */
  8636. nr = 0;
  8637. }
  8638. }
  8639. #else
  8640. nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
  8641. #endif
  8642. #if 0
  8643. /* nonblock_safe_read() handles this problem */
  8644. if (nr < 0) {
  8645. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  8646. int flags = fcntl(0, F_GETFL);
  8647. if (flags >= 0 && (flags & O_NONBLOCK)) {
  8648. flags &= ~O_NONBLOCK;
  8649. if (fcntl(0, F_SETFL, flags) >= 0) {
  8650. out2str("sh: turning off NDELAY mode\n");
  8651. goto retry;
  8652. }
  8653. }
  8654. }
  8655. }
  8656. #endif
  8657. return nr;
  8658. }
  8659. /*
  8660. * Refill the input buffer and return the next input character:
  8661. *
  8662. * 1) If a string was pushed back on the input, pop it;
  8663. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  8664. * or we are reading from a string so we can't refill the buffer,
  8665. * return EOF.
  8666. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  8667. * 4) Process input up to the next newline, deleting nul characters.
  8668. */
  8669. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  8670. #define pgetc_debug(...) ((void)0)
  8671. static int
  8672. preadbuffer(void)
  8673. {
  8674. char *q;
  8675. int more;
  8676. while (g_parsefile->strpush) {
  8677. #if ENABLE_ASH_ALIAS
  8678. if (g_parsefile->left_in_line == -1
  8679. && g_parsefile->strpush->ap
  8680. && g_parsefile->next_to_pgetc[-1] != ' '
  8681. && g_parsefile->next_to_pgetc[-1] != '\t'
  8682. ) {
  8683. pgetc_debug("preadbuffer PEOA");
  8684. return PEOA;
  8685. }
  8686. #endif
  8687. popstring();
  8688. /* try "pgetc" now: */
  8689. pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
  8690. g_parsefile->left_in_line,
  8691. g_parsefile->next_to_pgetc,
  8692. g_parsefile->next_to_pgetc);
  8693. if (--g_parsefile->left_in_line >= 0)
  8694. return (unsigned char)(*g_parsefile->next_to_pgetc++);
  8695. }
  8696. /* on both branches above g_parsefile->left_in_line < 0.
  8697. * "pgetc" needs refilling.
  8698. */
  8699. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  8700. * pungetc() may increment it a few times.
  8701. * Assuming it won't increment it to less than -90.
  8702. */
  8703. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  8704. pgetc_debug("preadbuffer PEOF1");
  8705. /* even in failure keep left_in_line and next_to_pgetc
  8706. * in lock step, for correct multi-layer pungetc.
  8707. * left_in_line was decremented before preadbuffer(),
  8708. * must inc next_to_pgetc: */
  8709. g_parsefile->next_to_pgetc++;
  8710. return PEOF;
  8711. }
  8712. more = g_parsefile->left_in_buffer;
  8713. if (more <= 0) {
  8714. flush_stdout_stderr();
  8715. again:
  8716. more = preadfd();
  8717. if (more <= 0) {
  8718. /* don't try reading again */
  8719. g_parsefile->left_in_line = -99;
  8720. pgetc_debug("preadbuffer PEOF2");
  8721. g_parsefile->next_to_pgetc++;
  8722. return PEOF;
  8723. }
  8724. }
  8725. /* Find out where's the end of line.
  8726. * Set g_parsefile->left_in_line
  8727. * and g_parsefile->left_in_buffer acordingly.
  8728. * NUL chars are deleted.
  8729. */
  8730. q = g_parsefile->next_to_pgetc;
  8731. for (;;) {
  8732. char c;
  8733. more--;
  8734. c = *q;
  8735. if (c == '\0') {
  8736. memmove(q, q + 1, more);
  8737. } else {
  8738. q++;
  8739. if (c == '\n') {
  8740. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8741. break;
  8742. }
  8743. }
  8744. if (more <= 0) {
  8745. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8746. if (g_parsefile->left_in_line < 0)
  8747. goto again;
  8748. break;
  8749. }
  8750. }
  8751. g_parsefile->left_in_buffer = more;
  8752. if (vflag) {
  8753. char save = *q;
  8754. *q = '\0';
  8755. out2str(g_parsefile->next_to_pgetc);
  8756. *q = save;
  8757. }
  8758. pgetc_debug("preadbuffer at %d:%p'%s'",
  8759. g_parsefile->left_in_line,
  8760. g_parsefile->next_to_pgetc,
  8761. g_parsefile->next_to_pgetc);
  8762. return (unsigned char)*g_parsefile->next_to_pgetc++;
  8763. }
  8764. #define pgetc_as_macro() \
  8765. (--g_parsefile->left_in_line >= 0 \
  8766. ? (unsigned char)*g_parsefile->next_to_pgetc++ \
  8767. : preadbuffer() \
  8768. )
  8769. static int
  8770. pgetc(void)
  8771. {
  8772. pgetc_debug("pgetc_fast at %d:%p'%s'",
  8773. g_parsefile->left_in_line,
  8774. g_parsefile->next_to_pgetc,
  8775. g_parsefile->next_to_pgetc);
  8776. return pgetc_as_macro();
  8777. }
  8778. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  8779. # define pgetc_fast() pgetc()
  8780. #else
  8781. # define pgetc_fast() pgetc_as_macro()
  8782. #endif
  8783. #if ENABLE_ASH_ALIAS
  8784. static int
  8785. pgetc_without_PEOA(void)
  8786. {
  8787. int c;
  8788. do {
  8789. pgetc_debug("pgetc_fast at %d:%p'%s'",
  8790. g_parsefile->left_in_line,
  8791. g_parsefile->next_to_pgetc,
  8792. g_parsefile->next_to_pgetc);
  8793. c = pgetc_fast();
  8794. } while (c == PEOA);
  8795. return c;
  8796. }
  8797. #else
  8798. # define pgetc_without_PEOA() pgetc()
  8799. #endif
  8800. /*
  8801. * Read a line from the script.
  8802. */
  8803. static char *
  8804. pfgets(char *line, int len)
  8805. {
  8806. char *p = line;
  8807. int nleft = len;
  8808. int c;
  8809. while (--nleft > 0) {
  8810. c = pgetc_without_PEOA();
  8811. if (c == PEOF) {
  8812. if (p == line)
  8813. return NULL;
  8814. break;
  8815. }
  8816. *p++ = c;
  8817. if (c == '\n')
  8818. break;
  8819. }
  8820. *p = '\0';
  8821. return line;
  8822. }
  8823. /*
  8824. * Undo the last call to pgetc. Only one character may be pushed back.
  8825. * PEOF may be pushed back.
  8826. */
  8827. static void
  8828. pungetc(void)
  8829. {
  8830. g_parsefile->left_in_line++;
  8831. g_parsefile->next_to_pgetc--;
  8832. pgetc_debug("pushed back to %d:%p'%s'",
  8833. g_parsefile->left_in_line,
  8834. g_parsefile->next_to_pgetc,
  8835. g_parsefile->next_to_pgetc);
  8836. }
  8837. /*
  8838. * To handle the "." command, a stack of input files is used. Pushfile
  8839. * adds a new entry to the stack and popfile restores the previous level.
  8840. */
  8841. static void
  8842. pushfile(void)
  8843. {
  8844. struct parsefile *pf;
  8845. pf = ckzalloc(sizeof(*pf));
  8846. pf->prev = g_parsefile;
  8847. pf->fd = -1;
  8848. /*pf->strpush = NULL; - ckzalloc did it */
  8849. /*pf->basestrpush.prev = NULL;*/
  8850. g_parsefile = pf;
  8851. }
  8852. static void
  8853. popfile(void)
  8854. {
  8855. struct parsefile *pf = g_parsefile;
  8856. INT_OFF;
  8857. if (pf->fd >= 0)
  8858. close(pf->fd);
  8859. free(pf->buf);
  8860. while (pf->strpush)
  8861. popstring();
  8862. g_parsefile = pf->prev;
  8863. free(pf);
  8864. INT_ON;
  8865. }
  8866. /*
  8867. * Return to top level.
  8868. */
  8869. static void
  8870. popallfiles(void)
  8871. {
  8872. while (g_parsefile != &basepf)
  8873. popfile();
  8874. }
  8875. /*
  8876. * Close the file(s) that the shell is reading commands from. Called
  8877. * after a fork is done.
  8878. */
  8879. static void
  8880. closescript(void)
  8881. {
  8882. popallfiles();
  8883. if (g_parsefile->fd > 0) {
  8884. close(g_parsefile->fd);
  8885. g_parsefile->fd = 0;
  8886. }
  8887. }
  8888. /*
  8889. * Like setinputfile, but takes an open file descriptor. Call this with
  8890. * interrupts off.
  8891. */
  8892. static void
  8893. setinputfd(int fd, int push)
  8894. {
  8895. close_on_exec_on(fd);
  8896. if (push) {
  8897. pushfile();
  8898. g_parsefile->buf = NULL;
  8899. }
  8900. g_parsefile->fd = fd;
  8901. if (g_parsefile->buf == NULL)
  8902. g_parsefile->buf = ckmalloc(IBUFSIZ);
  8903. g_parsefile->left_in_buffer = 0;
  8904. g_parsefile->left_in_line = 0;
  8905. g_parsefile->linno = 1;
  8906. }
  8907. /*
  8908. * Set the input to take input from a file. If push is set, push the
  8909. * old input onto the stack first.
  8910. */
  8911. static int
  8912. setinputfile(const char *fname, int flags)
  8913. {
  8914. int fd;
  8915. int fd2;
  8916. INT_OFF;
  8917. fd = open(fname, O_RDONLY);
  8918. if (fd < 0) {
  8919. if (flags & INPUT_NOFILE_OK)
  8920. goto out;
  8921. ash_msg_and_raise_error("can't open '%s'", fname);
  8922. }
  8923. if (fd < 10) {
  8924. fd2 = copyfd(fd, 10);
  8925. close(fd);
  8926. if (fd2 < 0)
  8927. ash_msg_and_raise_error("out of file descriptors");
  8928. fd = fd2;
  8929. }
  8930. setinputfd(fd, flags & INPUT_PUSH_FILE);
  8931. out:
  8932. INT_ON;
  8933. return fd;
  8934. }
  8935. /*
  8936. * Like setinputfile, but takes input from a string.
  8937. */
  8938. static void
  8939. setinputstring(char *string)
  8940. {
  8941. INT_OFF;
  8942. pushfile();
  8943. g_parsefile->next_to_pgetc = string;
  8944. g_parsefile->left_in_line = strlen(string);
  8945. g_parsefile->buf = NULL;
  8946. g_parsefile->linno = 1;
  8947. INT_ON;
  8948. }
  8949. /* ============ mail.c
  8950. *
  8951. * Routines to check for mail.
  8952. */
  8953. #if ENABLE_ASH_MAIL
  8954. #define MAXMBOXES 10
  8955. /* times of mailboxes */
  8956. static time_t mailtime[MAXMBOXES];
  8957. /* Set if MAIL or MAILPATH is changed. */
  8958. static smallint mail_var_path_changed;
  8959. /*
  8960. * Print appropriate message(s) if mail has arrived.
  8961. * If mail_var_path_changed is set,
  8962. * then the value of MAIL has mail_var_path_changed,
  8963. * so we just update the values.
  8964. */
  8965. static void
  8966. chkmail(void)
  8967. {
  8968. const char *mpath;
  8969. char *p;
  8970. char *q;
  8971. time_t *mtp;
  8972. struct stackmark smark;
  8973. struct stat statb;
  8974. setstackmark(&smark);
  8975. mpath = mpathset() ? mpathval() : mailval();
  8976. for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
  8977. p = path_advance(&mpath, nullstr);
  8978. if (p == NULL)
  8979. break;
  8980. if (*p == '\0')
  8981. continue;
  8982. for (q = p; *q; q++)
  8983. continue;
  8984. #if DEBUG
  8985. if (q[-1] != '/')
  8986. abort();
  8987. #endif
  8988. q[-1] = '\0'; /* delete trailing '/' */
  8989. if (stat(p, &statb) < 0) {
  8990. *mtp = 0;
  8991. continue;
  8992. }
  8993. if (!mail_var_path_changed && statb.st_mtime != *mtp) {
  8994. fprintf(
  8995. stderr, snlfmt,
  8996. pathopt ? pathopt : "you have mail"
  8997. );
  8998. }
  8999. *mtp = statb.st_mtime;
  9000. }
  9001. mail_var_path_changed = 0;
  9002. popstackmark(&smark);
  9003. }
  9004. static void FAST_FUNC
  9005. changemail(const char *val UNUSED_PARAM)
  9006. {
  9007. mail_var_path_changed = 1;
  9008. }
  9009. #endif /* ASH_MAIL */
  9010. /* ============ ??? */
  9011. /*
  9012. * Set the shell parameters.
  9013. */
  9014. static void
  9015. setparam(char **argv)
  9016. {
  9017. char **newparam;
  9018. char **ap;
  9019. int nparam;
  9020. for (nparam = 0; argv[nparam]; nparam++)
  9021. continue;
  9022. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  9023. while (*argv) {
  9024. *ap++ = ckstrdup(*argv++);
  9025. }
  9026. *ap = NULL;
  9027. freeparam(&shellparam);
  9028. shellparam.malloced = 1;
  9029. shellparam.nparam = nparam;
  9030. shellparam.p = newparam;
  9031. #if ENABLE_ASH_GETOPTS
  9032. shellparam.optind = 1;
  9033. shellparam.optoff = -1;
  9034. #endif
  9035. }
  9036. /*
  9037. * Process shell options. The global variable argptr contains a pointer
  9038. * to the argument list; we advance it past the options.
  9039. *
  9040. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  9041. * For a non-interactive shell, an error condition encountered
  9042. * by a special built-in ... shall cause the shell to write a diagnostic message
  9043. * to standard error and exit as shown in the following table:
  9044. * Error Special Built-In
  9045. * ...
  9046. * Utility syntax error (option or operand error) Shall exit
  9047. * ...
  9048. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  9049. * we see that bash does not do that (set "finishes" with error code 1 instead,
  9050. * and shell continues), and people rely on this behavior!
  9051. * Testcase:
  9052. * set -o barfoo 2>/dev/null
  9053. * echo $?
  9054. *
  9055. * Oh well. Let's mimic that.
  9056. */
  9057. static int
  9058. plus_minus_o(char *name, int val)
  9059. {
  9060. int i;
  9061. if (name) {
  9062. for (i = 0; i < NOPTS; i++) {
  9063. if (strcmp(name, optnames(i)) == 0) {
  9064. optlist[i] = val;
  9065. return 0;
  9066. }
  9067. }
  9068. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  9069. return 1;
  9070. }
  9071. for (i = 0; i < NOPTS; i++) {
  9072. if (val) {
  9073. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  9074. } else {
  9075. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  9076. }
  9077. }
  9078. return 0;
  9079. }
  9080. static void
  9081. setoption(int flag, int val)
  9082. {
  9083. int i;
  9084. for (i = 0; i < NOPTS; i++) {
  9085. if (optletters(i) == flag) {
  9086. optlist[i] = val;
  9087. return;
  9088. }
  9089. }
  9090. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  9091. /* NOTREACHED */
  9092. }
  9093. static int
  9094. options(int cmdline)
  9095. {
  9096. char *p;
  9097. int val;
  9098. int c;
  9099. if (cmdline)
  9100. minusc = NULL;
  9101. while ((p = *argptr) != NULL) {
  9102. c = *p++;
  9103. if (c != '-' && c != '+')
  9104. break;
  9105. argptr++;
  9106. val = 0; /* val = 0 if c == '+' */
  9107. if (c == '-') {
  9108. val = 1;
  9109. if (p[0] == '\0' || LONE_DASH(p)) {
  9110. if (!cmdline) {
  9111. /* "-" means turn off -x and -v */
  9112. if (p[0] == '\0')
  9113. xflag = vflag = 0;
  9114. /* "--" means reset params */
  9115. else if (*argptr == NULL)
  9116. setparam(argptr);
  9117. }
  9118. break; /* "-" or "--" terminates options */
  9119. }
  9120. }
  9121. /* first char was + or - */
  9122. while ((c = *p++) != '\0') {
  9123. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  9124. if (c == 'c' && cmdline) {
  9125. minusc = p; /* command is after shell args */
  9126. } else if (c == 'o') {
  9127. if (plus_minus_o(*argptr, val)) {
  9128. /* it already printed err message */
  9129. return 1; /* error */
  9130. }
  9131. if (*argptr)
  9132. argptr++;
  9133. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  9134. isloginsh = 1;
  9135. /* bash does not accept +-login, we also won't */
  9136. } else if (cmdline && val && (c == '-')) { /* long options */
  9137. if (strcmp(p, "login") == 0)
  9138. isloginsh = 1;
  9139. break;
  9140. } else {
  9141. setoption(c, val);
  9142. }
  9143. }
  9144. }
  9145. return 0;
  9146. }
  9147. /*
  9148. * The shift builtin command.
  9149. */
  9150. static int FAST_FUNC
  9151. shiftcmd(int argc UNUSED_PARAM, char **argv)
  9152. {
  9153. int n;
  9154. char **ap1, **ap2;
  9155. n = 1;
  9156. if (argv[1])
  9157. n = number(argv[1]);
  9158. if (n > shellparam.nparam)
  9159. n = 0; /* bash compat, was = shellparam.nparam; */
  9160. INT_OFF;
  9161. shellparam.nparam -= n;
  9162. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  9163. if (shellparam.malloced)
  9164. free(*ap1);
  9165. }
  9166. ap2 = shellparam.p;
  9167. while ((*ap2++ = *ap1++) != NULL)
  9168. continue;
  9169. #if ENABLE_ASH_GETOPTS
  9170. shellparam.optind = 1;
  9171. shellparam.optoff = -1;
  9172. #endif
  9173. INT_ON;
  9174. return 0;
  9175. }
  9176. /*
  9177. * POSIX requires that 'set' (but not export or readonly) output the
  9178. * variables in lexicographic order - by the locale's collating order (sigh).
  9179. * Maybe we could keep them in an ordered balanced binary tree
  9180. * instead of hashed lists.
  9181. * For now just roll 'em through qsort for printing...
  9182. */
  9183. static int
  9184. showvars(const char *sep_prefix, int on, int off)
  9185. {
  9186. const char *sep;
  9187. char **ep, **epend;
  9188. ep = listvars(on, off, &epend);
  9189. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  9190. sep = *sep_prefix ? " " : sep_prefix;
  9191. for (; ep < epend; ep++) {
  9192. const char *p;
  9193. const char *q;
  9194. p = strchrnul(*ep, '=');
  9195. q = nullstr;
  9196. if (*p)
  9197. q = single_quote(++p);
  9198. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  9199. }
  9200. return 0;
  9201. }
  9202. /*
  9203. * The set command builtin.
  9204. */
  9205. static int FAST_FUNC
  9206. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9207. {
  9208. int retval;
  9209. if (!argv[1])
  9210. return showvars(nullstr, 0, VUNSET);
  9211. INT_OFF;
  9212. retval = 1;
  9213. if (!options(0)) { /* if no parse error... */
  9214. retval = 0;
  9215. optschanged();
  9216. if (*argptr != NULL) {
  9217. setparam(argptr);
  9218. }
  9219. }
  9220. INT_ON;
  9221. return retval;
  9222. }
  9223. #if ENABLE_ASH_RANDOM_SUPPORT
  9224. static void FAST_FUNC
  9225. change_random(const char *value)
  9226. {
  9227. uint32_t t;
  9228. if (value == NULL) {
  9229. /* "get", generate */
  9230. t = next_random(&random_gen);
  9231. /* set without recursion */
  9232. setvar(vrandom.text, utoa(t), VNOFUNC);
  9233. vrandom.flags &= ~VNOFUNC;
  9234. } else {
  9235. /* set/reset */
  9236. t = strtoul(value, NULL, 10);
  9237. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  9238. }
  9239. }
  9240. #endif
  9241. #if ENABLE_ASH_GETOPTS
  9242. static int
  9243. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  9244. {
  9245. char *p, *q;
  9246. char c = '?';
  9247. int done = 0;
  9248. int err = 0;
  9249. char s[12];
  9250. char **optnext;
  9251. if (*param_optind < 1)
  9252. return 1;
  9253. optnext = optfirst + *param_optind - 1;
  9254. if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
  9255. p = NULL;
  9256. else
  9257. p = optnext[-1] + *optoff;
  9258. if (p == NULL || *p == '\0') {
  9259. /* Current word is done, advance */
  9260. p = *optnext;
  9261. if (p == NULL || *p != '-' || *++p == '\0') {
  9262. atend:
  9263. p = NULL;
  9264. done = 1;
  9265. goto out;
  9266. }
  9267. optnext++;
  9268. if (LONE_DASH(p)) /* check for "--" */
  9269. goto atend;
  9270. }
  9271. c = *p++;
  9272. for (q = optstr; *q != c;) {
  9273. if (*q == '\0') {
  9274. if (optstr[0] == ':') {
  9275. s[0] = c;
  9276. s[1] = '\0';
  9277. err |= setvarsafe("OPTARG", s, 0);
  9278. } else {
  9279. fprintf(stderr, "Illegal option -%c\n", c);
  9280. unsetvar("OPTARG");
  9281. }
  9282. c = '?';
  9283. goto out;
  9284. }
  9285. if (*++q == ':')
  9286. q++;
  9287. }
  9288. if (*++q == ':') {
  9289. if (*p == '\0' && (p = *optnext) == NULL) {
  9290. if (optstr[0] == ':') {
  9291. s[0] = c;
  9292. s[1] = '\0';
  9293. err |= setvarsafe("OPTARG", s, 0);
  9294. c = ':';
  9295. } else {
  9296. fprintf(stderr, "No arg for -%c option\n", c);
  9297. unsetvar("OPTARG");
  9298. c = '?';
  9299. }
  9300. goto out;
  9301. }
  9302. if (p == *optnext)
  9303. optnext++;
  9304. err |= setvarsafe("OPTARG", p, 0);
  9305. p = NULL;
  9306. } else
  9307. err |= setvarsafe("OPTARG", nullstr, 0);
  9308. out:
  9309. *optoff = p ? p - *(optnext - 1) : -1;
  9310. *param_optind = optnext - optfirst + 1;
  9311. fmtstr(s, sizeof(s), "%d", *param_optind);
  9312. err |= setvarsafe("OPTIND", s, VNOFUNC);
  9313. s[0] = c;
  9314. s[1] = '\0';
  9315. err |= setvarsafe(optvar, s, 0);
  9316. if (err) {
  9317. *param_optind = 1;
  9318. *optoff = -1;
  9319. flush_stdout_stderr();
  9320. raise_exception(EXERROR);
  9321. }
  9322. return done;
  9323. }
  9324. /*
  9325. * The getopts builtin. Shellparam.optnext points to the next argument
  9326. * to be processed. Shellparam.optptr points to the next character to
  9327. * be processed in the current argument. If shellparam.optnext is NULL,
  9328. * then it's the first time getopts has been called.
  9329. */
  9330. static int FAST_FUNC
  9331. getoptscmd(int argc, char **argv)
  9332. {
  9333. char **optbase;
  9334. if (argc < 3)
  9335. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  9336. if (argc == 3) {
  9337. optbase = shellparam.p;
  9338. if (shellparam.optind > shellparam.nparam + 1) {
  9339. shellparam.optind = 1;
  9340. shellparam.optoff = -1;
  9341. }
  9342. } else {
  9343. optbase = &argv[3];
  9344. if (shellparam.optind > argc - 2) {
  9345. shellparam.optind = 1;
  9346. shellparam.optoff = -1;
  9347. }
  9348. }
  9349. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  9350. &shellparam.optoff);
  9351. }
  9352. #endif /* ASH_GETOPTS */
  9353. /* ============ Shell parser */
  9354. struct heredoc {
  9355. struct heredoc *next; /* next here document in list */
  9356. union node *here; /* redirection node */
  9357. char *eofmark; /* string indicating end of input */
  9358. smallint striptabs; /* if set, strip leading tabs */
  9359. };
  9360. static smallint tokpushback; /* last token pushed back */
  9361. static smallint parsebackquote; /* nonzero if we are inside backquotes */
  9362. static smallint quoteflag; /* set if (part of) last token was quoted */
  9363. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  9364. static struct heredoc *heredoclist; /* list of here documents to read */
  9365. static char *wordtext; /* text of last word returned by readtoken */
  9366. static struct nodelist *backquotelist;
  9367. static union node *redirnode;
  9368. static struct heredoc *heredoc;
  9369. /*
  9370. * Called when an unexpected token is read during the parse. The argument
  9371. * is the token that is expected, or -1 if more than one type of token can
  9372. * occur at this point.
  9373. */
  9374. static void raise_error_unexpected_syntax(int) NORETURN;
  9375. static void
  9376. raise_error_unexpected_syntax(int token)
  9377. {
  9378. char msg[64];
  9379. int l;
  9380. l = sprintf(msg, "unexpected %s", tokname(lasttoken));
  9381. if (token >= 0)
  9382. sprintf(msg + l, " (expecting %s)", tokname(token));
  9383. raise_error_syntax(msg);
  9384. /* NOTREACHED */
  9385. }
  9386. #define EOFMARKLEN 79
  9387. /* parsing is heavily cross-recursive, need these forward decls */
  9388. static union node *andor(void);
  9389. static union node *pipeline(void);
  9390. static union node *parse_command(void);
  9391. static void parseheredoc(void);
  9392. static char peektoken(void);
  9393. static int readtoken(void);
  9394. static union node *
  9395. list(int nlflag)
  9396. {
  9397. union node *n1, *n2, *n3;
  9398. int tok;
  9399. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9400. if (nlflag == 2 && peektoken())
  9401. return NULL;
  9402. n1 = NULL;
  9403. for (;;) {
  9404. n2 = andor();
  9405. tok = readtoken();
  9406. if (tok == TBACKGND) {
  9407. if (n2->type == NPIPE) {
  9408. n2->npipe.pipe_backgnd = 1;
  9409. } else {
  9410. if (n2->type != NREDIR) {
  9411. n3 = stzalloc(sizeof(struct nredir));
  9412. n3->nredir.n = n2;
  9413. /*n3->nredir.redirect = NULL; - stzalloc did it */
  9414. n2 = n3;
  9415. }
  9416. n2->type = NBACKGND;
  9417. }
  9418. }
  9419. if (n1 == NULL) {
  9420. n1 = n2;
  9421. } else {
  9422. n3 = stzalloc(sizeof(struct nbinary));
  9423. n3->type = NSEMI;
  9424. n3->nbinary.ch1 = n1;
  9425. n3->nbinary.ch2 = n2;
  9426. n1 = n3;
  9427. }
  9428. switch (tok) {
  9429. case TBACKGND:
  9430. case TSEMI:
  9431. tok = readtoken();
  9432. /* fall through */
  9433. case TNL:
  9434. if (tok == TNL) {
  9435. parseheredoc();
  9436. if (nlflag == 1)
  9437. return n1;
  9438. } else {
  9439. tokpushback = 1;
  9440. }
  9441. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9442. if (peektoken())
  9443. return n1;
  9444. break;
  9445. case TEOF:
  9446. if (heredoclist)
  9447. parseheredoc();
  9448. else
  9449. pungetc(); /* push back EOF on input */
  9450. return n1;
  9451. default:
  9452. if (nlflag == 1)
  9453. raise_error_unexpected_syntax(-1);
  9454. tokpushback = 1;
  9455. return n1;
  9456. }
  9457. }
  9458. }
  9459. static union node *
  9460. andor(void)
  9461. {
  9462. union node *n1, *n2, *n3;
  9463. int t;
  9464. n1 = pipeline();
  9465. for (;;) {
  9466. t = readtoken();
  9467. if (t == TAND) {
  9468. t = NAND;
  9469. } else if (t == TOR) {
  9470. t = NOR;
  9471. } else {
  9472. tokpushback = 1;
  9473. return n1;
  9474. }
  9475. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9476. n2 = pipeline();
  9477. n3 = stzalloc(sizeof(struct nbinary));
  9478. n3->type = t;
  9479. n3->nbinary.ch1 = n1;
  9480. n3->nbinary.ch2 = n2;
  9481. n1 = n3;
  9482. }
  9483. }
  9484. static union node *
  9485. pipeline(void)
  9486. {
  9487. union node *n1, *n2, *pipenode;
  9488. struct nodelist *lp, *prev;
  9489. int negate;
  9490. negate = 0;
  9491. TRACE(("pipeline: entered\n"));
  9492. if (readtoken() == TNOT) {
  9493. negate = !negate;
  9494. checkkwd = CHKKWD | CHKALIAS;
  9495. } else
  9496. tokpushback = 1;
  9497. n1 = parse_command();
  9498. if (readtoken() == TPIPE) {
  9499. pipenode = stzalloc(sizeof(struct npipe));
  9500. pipenode->type = NPIPE;
  9501. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  9502. lp = stzalloc(sizeof(struct nodelist));
  9503. pipenode->npipe.cmdlist = lp;
  9504. lp->n = n1;
  9505. do {
  9506. prev = lp;
  9507. lp = stzalloc(sizeof(struct nodelist));
  9508. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9509. lp->n = parse_command();
  9510. prev->next = lp;
  9511. } while (readtoken() == TPIPE);
  9512. lp->next = NULL;
  9513. n1 = pipenode;
  9514. }
  9515. tokpushback = 1;
  9516. if (negate) {
  9517. n2 = stzalloc(sizeof(struct nnot));
  9518. n2->type = NNOT;
  9519. n2->nnot.com = n1;
  9520. return n2;
  9521. }
  9522. return n1;
  9523. }
  9524. static union node *
  9525. makename(void)
  9526. {
  9527. union node *n;
  9528. n = stzalloc(sizeof(struct narg));
  9529. n->type = NARG;
  9530. /*n->narg.next = NULL; - stzalloc did it */
  9531. n->narg.text = wordtext;
  9532. n->narg.backquote = backquotelist;
  9533. return n;
  9534. }
  9535. static void
  9536. fixredir(union node *n, const char *text, int err)
  9537. {
  9538. int fd;
  9539. TRACE(("Fix redir %s %d\n", text, err));
  9540. if (!err)
  9541. n->ndup.vname = NULL;
  9542. fd = bb_strtou(text, NULL, 10);
  9543. if (!errno && fd >= 0)
  9544. n->ndup.dupfd = fd;
  9545. else if (LONE_DASH(text))
  9546. n->ndup.dupfd = -1;
  9547. else {
  9548. if (err)
  9549. raise_error_syntax("bad fd number");
  9550. n->ndup.vname = makename();
  9551. }
  9552. }
  9553. /*
  9554. * Returns true if the text contains nothing to expand (no dollar signs
  9555. * or backquotes).
  9556. */
  9557. static int
  9558. noexpand(const char *text)
  9559. {
  9560. unsigned char c;
  9561. while ((c = *text++) != '\0') {
  9562. if (c == CTLQUOTEMARK)
  9563. continue;
  9564. if (c == CTLESC)
  9565. text++;
  9566. else if (SIT(c, BASESYNTAX) == CCTL)
  9567. return 0;
  9568. }
  9569. return 1;
  9570. }
  9571. static void
  9572. parsefname(void)
  9573. {
  9574. union node *n = redirnode;
  9575. if (readtoken() != TWORD)
  9576. raise_error_unexpected_syntax(-1);
  9577. if (n->type == NHERE) {
  9578. struct heredoc *here = heredoc;
  9579. struct heredoc *p;
  9580. int i;
  9581. if (quoteflag == 0)
  9582. n->type = NXHERE;
  9583. TRACE(("Here document %d\n", n->type));
  9584. if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  9585. raise_error_syntax("illegal eof marker for << redirection");
  9586. rmescapes(wordtext, 0);
  9587. here->eofmark = wordtext;
  9588. here->next = NULL;
  9589. if (heredoclist == NULL)
  9590. heredoclist = here;
  9591. else {
  9592. for (p = heredoclist; p->next; p = p->next)
  9593. continue;
  9594. p->next = here;
  9595. }
  9596. } else if (n->type == NTOFD || n->type == NFROMFD) {
  9597. fixredir(n, wordtext, 0);
  9598. } else {
  9599. n->nfile.fname = makename();
  9600. }
  9601. }
  9602. static union node *
  9603. simplecmd(void)
  9604. {
  9605. union node *args, **app;
  9606. union node *n = NULL;
  9607. union node *vars, **vpp;
  9608. union node **rpp, *redir;
  9609. int savecheckkwd;
  9610. #if ENABLE_ASH_BASH_COMPAT
  9611. smallint double_brackets_flag = 0;
  9612. #endif
  9613. args = NULL;
  9614. app = &args;
  9615. vars = NULL;
  9616. vpp = &vars;
  9617. redir = NULL;
  9618. rpp = &redir;
  9619. savecheckkwd = CHKALIAS;
  9620. for (;;) {
  9621. int t;
  9622. checkkwd = savecheckkwd;
  9623. t = readtoken();
  9624. switch (t) {
  9625. #if ENABLE_ASH_BASH_COMPAT
  9626. case TAND: /* "&&" */
  9627. case TOR: /* "||" */
  9628. if (!double_brackets_flag) {
  9629. tokpushback = 1;
  9630. goto out;
  9631. }
  9632. wordtext = (char *) (t == TAND ? "-a" : "-o");
  9633. #endif
  9634. case TWORD:
  9635. n = stzalloc(sizeof(struct narg));
  9636. n->type = NARG;
  9637. /*n->narg.next = NULL; - stzalloc did it */
  9638. n->narg.text = wordtext;
  9639. #if ENABLE_ASH_BASH_COMPAT
  9640. if (strcmp("[[", wordtext) == 0)
  9641. double_brackets_flag = 1;
  9642. else if (strcmp("]]", wordtext) == 0)
  9643. double_brackets_flag = 0;
  9644. #endif
  9645. n->narg.backquote = backquotelist;
  9646. if (savecheckkwd && isassignment(wordtext)) {
  9647. *vpp = n;
  9648. vpp = &n->narg.next;
  9649. } else {
  9650. *app = n;
  9651. app = &n->narg.next;
  9652. savecheckkwd = 0;
  9653. }
  9654. break;
  9655. case TREDIR:
  9656. *rpp = n = redirnode;
  9657. rpp = &n->nfile.next;
  9658. parsefname(); /* read name of redirection file */
  9659. break;
  9660. case TLP:
  9661. if (args && app == &args->narg.next
  9662. && !vars && !redir
  9663. ) {
  9664. struct builtincmd *bcmd;
  9665. const char *name;
  9666. /* We have a function */
  9667. if (readtoken() != TRP)
  9668. raise_error_unexpected_syntax(TRP);
  9669. name = n->narg.text;
  9670. if (!goodname(name)
  9671. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  9672. ) {
  9673. raise_error_syntax("bad function name");
  9674. }
  9675. n->type = NDEFUN;
  9676. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9677. n->narg.next = parse_command();
  9678. return n;
  9679. }
  9680. /* fall through */
  9681. default:
  9682. tokpushback = 1;
  9683. goto out;
  9684. }
  9685. }
  9686. out:
  9687. *app = NULL;
  9688. *vpp = NULL;
  9689. *rpp = NULL;
  9690. n = stzalloc(sizeof(struct ncmd));
  9691. n->type = NCMD;
  9692. n->ncmd.args = args;
  9693. n->ncmd.assign = vars;
  9694. n->ncmd.redirect = redir;
  9695. return n;
  9696. }
  9697. static union node *
  9698. parse_command(void)
  9699. {
  9700. union node *n1, *n2;
  9701. union node *ap, **app;
  9702. union node *cp, **cpp;
  9703. union node *redir, **rpp;
  9704. union node **rpp2;
  9705. int t;
  9706. redir = NULL;
  9707. rpp2 = &redir;
  9708. switch (readtoken()) {
  9709. default:
  9710. raise_error_unexpected_syntax(-1);
  9711. /* NOTREACHED */
  9712. case TIF:
  9713. n1 = stzalloc(sizeof(struct nif));
  9714. n1->type = NIF;
  9715. n1->nif.test = list(0);
  9716. if (readtoken() != TTHEN)
  9717. raise_error_unexpected_syntax(TTHEN);
  9718. n1->nif.ifpart = list(0);
  9719. n2 = n1;
  9720. while (readtoken() == TELIF) {
  9721. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  9722. n2 = n2->nif.elsepart;
  9723. n2->type = NIF;
  9724. n2->nif.test = list(0);
  9725. if (readtoken() != TTHEN)
  9726. raise_error_unexpected_syntax(TTHEN);
  9727. n2->nif.ifpart = list(0);
  9728. }
  9729. if (lasttoken == TELSE)
  9730. n2->nif.elsepart = list(0);
  9731. else {
  9732. n2->nif.elsepart = NULL;
  9733. tokpushback = 1;
  9734. }
  9735. t = TFI;
  9736. break;
  9737. case TWHILE:
  9738. case TUNTIL: {
  9739. int got;
  9740. n1 = stzalloc(sizeof(struct nbinary));
  9741. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  9742. n1->nbinary.ch1 = list(0);
  9743. got = readtoken();
  9744. if (got != TDO) {
  9745. TRACE(("expecting DO got %s %s\n", tokname(got),
  9746. got == TWORD ? wordtext : ""));
  9747. raise_error_unexpected_syntax(TDO);
  9748. }
  9749. n1->nbinary.ch2 = list(0);
  9750. t = TDONE;
  9751. break;
  9752. }
  9753. case TFOR:
  9754. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  9755. raise_error_syntax("bad for loop variable");
  9756. n1 = stzalloc(sizeof(struct nfor));
  9757. n1->type = NFOR;
  9758. n1->nfor.var = wordtext;
  9759. checkkwd = CHKKWD | CHKALIAS;
  9760. if (readtoken() == TIN) {
  9761. app = &ap;
  9762. while (readtoken() == TWORD) {
  9763. n2 = stzalloc(sizeof(struct narg));
  9764. n2->type = NARG;
  9765. /*n2->narg.next = NULL; - stzalloc did it */
  9766. n2->narg.text = wordtext;
  9767. n2->narg.backquote = backquotelist;
  9768. *app = n2;
  9769. app = &n2->narg.next;
  9770. }
  9771. *app = NULL;
  9772. n1->nfor.args = ap;
  9773. if (lasttoken != TNL && lasttoken != TSEMI)
  9774. raise_error_unexpected_syntax(-1);
  9775. } else {
  9776. n2 = stzalloc(sizeof(struct narg));
  9777. n2->type = NARG;
  9778. /*n2->narg.next = NULL; - stzalloc did it */
  9779. n2->narg.text = (char *)dolatstr;
  9780. /*n2->narg.backquote = NULL;*/
  9781. n1->nfor.args = n2;
  9782. /*
  9783. * Newline or semicolon here is optional (but note
  9784. * that the original Bourne shell only allowed NL).
  9785. */
  9786. if (lasttoken != TNL && lasttoken != TSEMI)
  9787. tokpushback = 1;
  9788. }
  9789. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9790. if (readtoken() != TDO)
  9791. raise_error_unexpected_syntax(TDO);
  9792. n1->nfor.body = list(0);
  9793. t = TDONE;
  9794. break;
  9795. case TCASE:
  9796. n1 = stzalloc(sizeof(struct ncase));
  9797. n1->type = NCASE;
  9798. if (readtoken() != TWORD)
  9799. raise_error_unexpected_syntax(TWORD);
  9800. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  9801. n2->type = NARG;
  9802. /*n2->narg.next = NULL; - stzalloc did it */
  9803. n2->narg.text = wordtext;
  9804. n2->narg.backquote = backquotelist;
  9805. do {
  9806. checkkwd = CHKKWD | CHKALIAS;
  9807. } while (readtoken() == TNL);
  9808. if (lasttoken != TIN)
  9809. raise_error_unexpected_syntax(TIN);
  9810. cpp = &n1->ncase.cases;
  9811. next_case:
  9812. checkkwd = CHKNL | CHKKWD;
  9813. t = readtoken();
  9814. while (t != TESAC) {
  9815. if (lasttoken == TLP)
  9816. readtoken();
  9817. *cpp = cp = stzalloc(sizeof(struct nclist));
  9818. cp->type = NCLIST;
  9819. app = &cp->nclist.pattern;
  9820. for (;;) {
  9821. *app = ap = stzalloc(sizeof(struct narg));
  9822. ap->type = NARG;
  9823. /*ap->narg.next = NULL; - stzalloc did it */
  9824. ap->narg.text = wordtext;
  9825. ap->narg.backquote = backquotelist;
  9826. if (readtoken() != TPIPE)
  9827. break;
  9828. app = &ap->narg.next;
  9829. readtoken();
  9830. }
  9831. //ap->narg.next = NULL;
  9832. if (lasttoken != TRP)
  9833. raise_error_unexpected_syntax(TRP);
  9834. cp->nclist.body = list(2);
  9835. cpp = &cp->nclist.next;
  9836. checkkwd = CHKNL | CHKKWD;
  9837. t = readtoken();
  9838. if (t != TESAC) {
  9839. if (t != TENDCASE)
  9840. raise_error_unexpected_syntax(TENDCASE);
  9841. goto next_case;
  9842. }
  9843. }
  9844. *cpp = NULL;
  9845. goto redir;
  9846. case TLP:
  9847. n1 = stzalloc(sizeof(struct nredir));
  9848. n1->type = NSUBSHELL;
  9849. n1->nredir.n = list(0);
  9850. /*n1->nredir.redirect = NULL; - stzalloc did it */
  9851. t = TRP;
  9852. break;
  9853. case TBEGIN:
  9854. n1 = list(0);
  9855. t = TEND;
  9856. break;
  9857. case TWORD:
  9858. case TREDIR:
  9859. tokpushback = 1;
  9860. return simplecmd();
  9861. }
  9862. if (readtoken() != t)
  9863. raise_error_unexpected_syntax(t);
  9864. redir:
  9865. /* Now check for redirection which may follow command */
  9866. checkkwd = CHKKWD | CHKALIAS;
  9867. rpp = rpp2;
  9868. while (readtoken() == TREDIR) {
  9869. *rpp = n2 = redirnode;
  9870. rpp = &n2->nfile.next;
  9871. parsefname();
  9872. }
  9873. tokpushback = 1;
  9874. *rpp = NULL;
  9875. if (redir) {
  9876. if (n1->type != NSUBSHELL) {
  9877. n2 = stzalloc(sizeof(struct nredir));
  9878. n2->type = NREDIR;
  9879. n2->nredir.n = n1;
  9880. n1 = n2;
  9881. }
  9882. n1->nredir.redirect = redir;
  9883. }
  9884. return n1;
  9885. }
  9886. #if ENABLE_ASH_BASH_COMPAT
  9887. static int decode_dollar_squote(void)
  9888. {
  9889. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  9890. int c, cnt;
  9891. char *p;
  9892. char buf[4];
  9893. c = pgetc();
  9894. p = strchr(C_escapes, c);
  9895. if (p) {
  9896. buf[0] = c;
  9897. p = buf;
  9898. cnt = 3;
  9899. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  9900. do {
  9901. c = pgetc();
  9902. *++p = c;
  9903. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  9904. pungetc();
  9905. } else if (c == 'x') { /* \xHH */
  9906. do {
  9907. c = pgetc();
  9908. *++p = c;
  9909. } while (isxdigit(c) && --cnt);
  9910. pungetc();
  9911. if (cnt == 3) { /* \x but next char is "bad" */
  9912. c = 'x';
  9913. goto unrecognized;
  9914. }
  9915. } else { /* simple seq like \\ or \t */
  9916. p++;
  9917. }
  9918. *p = '\0';
  9919. p = buf;
  9920. c = bb_process_escape_sequence((void*)&p);
  9921. } else { /* unrecognized "\z": print both chars unless ' or " */
  9922. if (c != '\'' && c != '"') {
  9923. unrecognized:
  9924. c |= 0x100; /* "please encode \, then me" */
  9925. }
  9926. }
  9927. return c;
  9928. }
  9929. #endif
  9930. /*
  9931. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  9932. * is not NULL, read a here document. In the latter case, eofmark is the
  9933. * word which marks the end of the document and striptabs is true if
  9934. * leading tabs should be stripped from the document. The argument c
  9935. * is the first character of the input token or document.
  9936. *
  9937. * Because C does not have internal subroutines, I have simulated them
  9938. * using goto's to implement the subroutine linkage. The following macros
  9939. * will run code that appears at the end of readtoken1.
  9940. */
  9941. #define CHECKEND() {goto checkend; checkend_return:;}
  9942. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  9943. #define PARSESUB() {goto parsesub; parsesub_return:;}
  9944. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  9945. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  9946. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  9947. static int
  9948. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  9949. {
  9950. /* NB: syntax parameter fits into smallint */
  9951. /* c parameter is an unsigned char or PEOF or PEOA */
  9952. char *out;
  9953. int len;
  9954. char line[EOFMARKLEN + 1];
  9955. struct nodelist *bqlist;
  9956. smallint quotef;
  9957. smallint dblquote;
  9958. smallint oldstyle;
  9959. smallint prevsyntax; /* syntax before arithmetic */
  9960. #if ENABLE_ASH_EXPAND_PRMT
  9961. smallint pssyntax; /* we are expanding a prompt string */
  9962. #endif
  9963. int varnest; /* levels of variables expansion */
  9964. int arinest; /* levels of arithmetic expansion */
  9965. int parenlevel; /* levels of parens in arithmetic */
  9966. int dqvarnest; /* levels of variables expansion within double quotes */
  9967. IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
  9968. #if __GNUC__
  9969. /* Avoid longjmp clobbering */
  9970. (void) &out;
  9971. (void) &quotef;
  9972. (void) &dblquote;
  9973. (void) &varnest;
  9974. (void) &arinest;
  9975. (void) &parenlevel;
  9976. (void) &dqvarnest;
  9977. (void) &oldstyle;
  9978. (void) &prevsyntax;
  9979. (void) &syntax;
  9980. #endif
  9981. startlinno = g_parsefile->linno;
  9982. bqlist = NULL;
  9983. quotef = 0;
  9984. oldstyle = 0;
  9985. prevsyntax = 0;
  9986. #if ENABLE_ASH_EXPAND_PRMT
  9987. pssyntax = (syntax == PSSYNTAX);
  9988. if (pssyntax)
  9989. syntax = DQSYNTAX;
  9990. #endif
  9991. dblquote = (syntax == DQSYNTAX);
  9992. varnest = 0;
  9993. arinest = 0;
  9994. parenlevel = 0;
  9995. dqvarnest = 0;
  9996. STARTSTACKSTR(out);
  9997. loop:
  9998. /* For each line, until end of word */
  9999. {
  10000. CHECKEND(); /* set c to PEOF if at end of here document */
  10001. for (;;) { /* until end of line or end of word */
  10002. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  10003. switch (SIT(c, syntax)) {
  10004. case CNL: /* '\n' */
  10005. if (syntax == BASESYNTAX)
  10006. goto endword; /* exit outer loop */
  10007. USTPUTC(c, out);
  10008. g_parsefile->linno++;
  10009. if (doprompt)
  10010. setprompt(2);
  10011. c = pgetc();
  10012. goto loop; /* continue outer loop */
  10013. case CWORD:
  10014. USTPUTC(c, out);
  10015. break;
  10016. case CCTL:
  10017. if (eofmark == NULL || dblquote)
  10018. USTPUTC(CTLESC, out);
  10019. #if ENABLE_ASH_BASH_COMPAT
  10020. if (c == '\\' && bash_dollar_squote) {
  10021. c = decode_dollar_squote();
  10022. if (c & 0x100) {
  10023. USTPUTC('\\', out);
  10024. c = (unsigned char)c;
  10025. }
  10026. }
  10027. #endif
  10028. USTPUTC(c, out);
  10029. break;
  10030. case CBACK: /* backslash */
  10031. c = pgetc_without_PEOA();
  10032. if (c == PEOF) {
  10033. USTPUTC(CTLESC, out);
  10034. USTPUTC('\\', out);
  10035. pungetc();
  10036. } else if (c == '\n') {
  10037. if (doprompt)
  10038. setprompt(2);
  10039. } else {
  10040. #if ENABLE_ASH_EXPAND_PRMT
  10041. if (c == '$' && pssyntax) {
  10042. USTPUTC(CTLESC, out);
  10043. USTPUTC('\\', out);
  10044. }
  10045. #endif
  10046. if (dblquote && c != '\\'
  10047. && c != '`' && c != '$'
  10048. && (c != '"' || eofmark != NULL)
  10049. ) {
  10050. USTPUTC(CTLESC, out);
  10051. USTPUTC('\\', out);
  10052. }
  10053. if (SIT(c, SQSYNTAX) == CCTL)
  10054. USTPUTC(CTLESC, out);
  10055. USTPUTC(c, out);
  10056. quotef = 1;
  10057. }
  10058. break;
  10059. case CSQUOTE:
  10060. syntax = SQSYNTAX;
  10061. quotemark:
  10062. if (eofmark == NULL) {
  10063. USTPUTC(CTLQUOTEMARK, out);
  10064. }
  10065. break;
  10066. case CDQUOTE:
  10067. syntax = DQSYNTAX;
  10068. dblquote = 1;
  10069. goto quotemark;
  10070. case CENDQUOTE:
  10071. IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
  10072. if (eofmark != NULL && arinest == 0
  10073. && varnest == 0
  10074. ) {
  10075. USTPUTC(c, out);
  10076. } else {
  10077. if (dqvarnest == 0) {
  10078. syntax = BASESYNTAX;
  10079. dblquote = 0;
  10080. }
  10081. quotef = 1;
  10082. goto quotemark;
  10083. }
  10084. break;
  10085. case CVAR: /* '$' */
  10086. PARSESUB(); /* parse substitution */
  10087. break;
  10088. case CENDVAR: /* '}' */
  10089. if (varnest > 0) {
  10090. varnest--;
  10091. if (dqvarnest > 0) {
  10092. dqvarnest--;
  10093. }
  10094. USTPUTC(CTLENDVAR, out);
  10095. } else {
  10096. USTPUTC(c, out);
  10097. }
  10098. break;
  10099. #if ENABLE_SH_MATH_SUPPORT
  10100. case CLP: /* '(' in arithmetic */
  10101. parenlevel++;
  10102. USTPUTC(c, out);
  10103. break;
  10104. case CRP: /* ')' in arithmetic */
  10105. if (parenlevel > 0) {
  10106. USTPUTC(c, out);
  10107. --parenlevel;
  10108. } else {
  10109. if (pgetc() == ')') {
  10110. if (--arinest == 0) {
  10111. USTPUTC(CTLENDARI, out);
  10112. syntax = prevsyntax;
  10113. dblquote = (syntax == DQSYNTAX);
  10114. } else
  10115. USTPUTC(')', out);
  10116. } else {
  10117. /*
  10118. * unbalanced parens
  10119. * (don't 2nd guess - no error)
  10120. */
  10121. pungetc();
  10122. USTPUTC(')', out);
  10123. }
  10124. }
  10125. break;
  10126. #endif
  10127. case CBQUOTE: /* '`' */
  10128. PARSEBACKQOLD();
  10129. break;
  10130. case CENDFILE:
  10131. goto endword; /* exit outer loop */
  10132. case CIGN:
  10133. break;
  10134. default:
  10135. if (varnest == 0) {
  10136. #if ENABLE_ASH_BASH_COMPAT
  10137. if (c == '&') {
  10138. if (pgetc() == '>')
  10139. c = 0x100 + '>'; /* flag &> */
  10140. pungetc();
  10141. }
  10142. #endif
  10143. goto endword; /* exit outer loop */
  10144. }
  10145. IF_ASH_ALIAS(if (c != PEOA))
  10146. USTPUTC(c, out);
  10147. }
  10148. c = pgetc_fast();
  10149. } /* for (;;) */
  10150. }
  10151. endword:
  10152. #if ENABLE_SH_MATH_SUPPORT
  10153. if (syntax == ARISYNTAX)
  10154. raise_error_syntax("missing '))'");
  10155. #endif
  10156. if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
  10157. raise_error_syntax("unterminated quoted string");
  10158. if (varnest != 0) {
  10159. startlinno = g_parsefile->linno;
  10160. /* { */
  10161. raise_error_syntax("missing '}'");
  10162. }
  10163. USTPUTC('\0', out);
  10164. len = out - (char *)stackblock();
  10165. out = stackblock();
  10166. if (eofmark == NULL) {
  10167. if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
  10168. && quotef == 0
  10169. ) {
  10170. if (isdigit_str9(out)) {
  10171. PARSEREDIR(); /* passed as params: out, c */
  10172. lasttoken = TREDIR;
  10173. return lasttoken;
  10174. }
  10175. /* else: non-number X seen, interpret it
  10176. * as "NNNX>file" = "NNNX >file" */
  10177. }
  10178. pungetc();
  10179. }
  10180. quoteflag = quotef;
  10181. backquotelist = bqlist;
  10182. grabstackblock(len);
  10183. wordtext = out;
  10184. lasttoken = TWORD;
  10185. return lasttoken;
  10186. /* end of readtoken routine */
  10187. /*
  10188. * Check to see whether we are at the end of the here document. When this
  10189. * is called, c is set to the first character of the next input line. If
  10190. * we are at the end of the here document, this routine sets the c to PEOF.
  10191. */
  10192. checkend: {
  10193. if (eofmark) {
  10194. #if ENABLE_ASH_ALIAS
  10195. if (c == PEOA)
  10196. c = pgetc_without_PEOA();
  10197. #endif
  10198. if (striptabs) {
  10199. while (c == '\t') {
  10200. c = pgetc_without_PEOA();
  10201. }
  10202. }
  10203. if (c == *eofmark) {
  10204. if (pfgets(line, sizeof(line)) != NULL) {
  10205. char *p, *q;
  10206. p = line;
  10207. for (q = eofmark + 1; *q && *p == *q; p++, q++)
  10208. continue;
  10209. if (*p == '\n' && *q == '\0') {
  10210. c = PEOF;
  10211. g_parsefile->linno++;
  10212. needprompt = doprompt;
  10213. } else {
  10214. pushstring(line, NULL);
  10215. }
  10216. }
  10217. }
  10218. }
  10219. goto checkend_return;
  10220. }
  10221. /*
  10222. * Parse a redirection operator. The variable "out" points to a string
  10223. * specifying the fd to be redirected. The variable "c" contains the
  10224. * first character of the redirection operator.
  10225. */
  10226. parseredir: {
  10227. /* out is already checked to be a valid number or "" */
  10228. int fd = (*out == '\0' ? -1 : atoi(out));
  10229. union node *np;
  10230. np = stzalloc(sizeof(struct nfile));
  10231. if (c == '>') {
  10232. np->nfile.fd = 1;
  10233. c = pgetc();
  10234. if (c == '>')
  10235. np->type = NAPPEND;
  10236. else if (c == '|')
  10237. np->type = NCLOBBER;
  10238. else if (c == '&')
  10239. np->type = NTOFD;
  10240. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  10241. else {
  10242. np->type = NTO;
  10243. pungetc();
  10244. }
  10245. }
  10246. #if ENABLE_ASH_BASH_COMPAT
  10247. else if (c == 0x100 + '>') { /* this flags &> redirection */
  10248. np->nfile.fd = 1;
  10249. pgetc(); /* this is '>', no need to check */
  10250. np->type = NTO2;
  10251. }
  10252. #endif
  10253. else { /* c == '<' */
  10254. /*np->nfile.fd = 0; - stzalloc did it */
  10255. c = pgetc();
  10256. switch (c) {
  10257. case '<':
  10258. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  10259. np = stzalloc(sizeof(struct nhere));
  10260. /*np->nfile.fd = 0; - stzalloc did it */
  10261. }
  10262. np->type = NHERE;
  10263. heredoc = stzalloc(sizeof(struct heredoc));
  10264. heredoc->here = np;
  10265. c = pgetc();
  10266. if (c == '-') {
  10267. heredoc->striptabs = 1;
  10268. } else {
  10269. /*heredoc->striptabs = 0; - stzalloc did it */
  10270. pungetc();
  10271. }
  10272. break;
  10273. case '&':
  10274. np->type = NFROMFD;
  10275. break;
  10276. case '>':
  10277. np->type = NFROMTO;
  10278. break;
  10279. default:
  10280. np->type = NFROM;
  10281. pungetc();
  10282. break;
  10283. }
  10284. }
  10285. if (fd >= 0)
  10286. np->nfile.fd = fd;
  10287. redirnode = np;
  10288. goto parseredir_return;
  10289. }
  10290. /*
  10291. * Parse a substitution. At this point, we have read the dollar sign
  10292. * and nothing else.
  10293. */
  10294. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  10295. * (assuming ascii char codes, as the original implementation did) */
  10296. #define is_special(c) \
  10297. (((unsigned)(c) - 33 < 32) \
  10298. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  10299. parsesub: {
  10300. unsigned char subtype;
  10301. int typeloc;
  10302. int flags;
  10303. char *p;
  10304. static const char types[] ALIGN1 = "}-+?=";
  10305. c = pgetc();
  10306. if (c > 255 /* PEOA or PEOF */
  10307. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  10308. ) {
  10309. #if ENABLE_ASH_BASH_COMPAT
  10310. if (c == '\'')
  10311. bash_dollar_squote = 1;
  10312. else
  10313. #endif
  10314. USTPUTC('$', out);
  10315. pungetc();
  10316. } else if (c == '(') { /* $(command) or $((arith)) */
  10317. if (pgetc() == '(') {
  10318. #if ENABLE_SH_MATH_SUPPORT
  10319. PARSEARITH();
  10320. #else
  10321. raise_error_syntax("you disabled math support for $((arith)) syntax");
  10322. #endif
  10323. } else {
  10324. pungetc();
  10325. PARSEBACKQNEW();
  10326. }
  10327. } else {
  10328. USTPUTC(CTLVAR, out);
  10329. typeloc = out - (char *)stackblock();
  10330. USTPUTC(VSNORMAL, out);
  10331. subtype = VSNORMAL;
  10332. if (c == '{') {
  10333. c = pgetc();
  10334. if (c == '#') {
  10335. c = pgetc();
  10336. if (c == '}')
  10337. c = '#';
  10338. else
  10339. subtype = VSLENGTH;
  10340. } else
  10341. subtype = 0;
  10342. }
  10343. if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
  10344. do {
  10345. STPUTC(c, out);
  10346. c = pgetc();
  10347. } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
  10348. } else if (isdigit(c)) {
  10349. do {
  10350. STPUTC(c, out);
  10351. c = pgetc();
  10352. } while (isdigit(c));
  10353. } else if (is_special(c)) {
  10354. USTPUTC(c, out);
  10355. c = pgetc();
  10356. } else {
  10357. badsub:
  10358. raise_error_syntax("bad substitution");
  10359. }
  10360. if (c != '}' && subtype == VSLENGTH)
  10361. goto badsub;
  10362. STPUTC('=', out);
  10363. flags = 0;
  10364. if (subtype == 0) {
  10365. switch (c) {
  10366. case ':':
  10367. c = pgetc();
  10368. #if ENABLE_ASH_BASH_COMPAT
  10369. if (c == ':' || c == '$' || isdigit(c)) {
  10370. pungetc();
  10371. subtype = VSSUBSTR;
  10372. break;
  10373. }
  10374. #endif
  10375. flags = VSNUL;
  10376. /*FALLTHROUGH*/
  10377. default:
  10378. p = strchr(types, c);
  10379. if (p == NULL)
  10380. goto badsub;
  10381. subtype = p - types + VSNORMAL;
  10382. break;
  10383. case '%':
  10384. case '#': {
  10385. int cc = c;
  10386. subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
  10387. c = pgetc();
  10388. if (c == cc)
  10389. subtype++;
  10390. else
  10391. pungetc();
  10392. break;
  10393. }
  10394. #if ENABLE_ASH_BASH_COMPAT
  10395. case '/':
  10396. subtype = VSREPLACE;
  10397. c = pgetc();
  10398. if (c == '/')
  10399. subtype++; /* VSREPLACEALL */
  10400. else
  10401. pungetc();
  10402. break;
  10403. #endif
  10404. }
  10405. } else {
  10406. pungetc();
  10407. }
  10408. if (dblquote || arinest)
  10409. flags |= VSQUOTE;
  10410. ((unsigned char *)stackblock())[typeloc] = subtype | flags;
  10411. if (subtype != VSNORMAL) {
  10412. varnest++;
  10413. if (dblquote || arinest) {
  10414. dqvarnest++;
  10415. }
  10416. }
  10417. }
  10418. goto parsesub_return;
  10419. }
  10420. /*
  10421. * Called to parse command substitutions. Newstyle is set if the command
  10422. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  10423. * list of commands (passed by reference), and savelen is the number of
  10424. * characters on the top of the stack which must be preserved.
  10425. */
  10426. parsebackq: {
  10427. struct nodelist **nlpp;
  10428. smallint savepbq;
  10429. union node *n;
  10430. char *volatile str;
  10431. struct jmploc jmploc;
  10432. struct jmploc *volatile savehandler;
  10433. size_t savelen;
  10434. smallint saveprompt = 0;
  10435. #ifdef __GNUC__
  10436. (void) &saveprompt;
  10437. #endif
  10438. savepbq = parsebackquote;
  10439. if (setjmp(jmploc.loc)) {
  10440. free(str);
  10441. parsebackquote = 0;
  10442. exception_handler = savehandler;
  10443. longjmp(exception_handler->loc, 1);
  10444. }
  10445. INT_OFF;
  10446. str = NULL;
  10447. savelen = out - (char *)stackblock();
  10448. if (savelen > 0) {
  10449. str = ckmalloc(savelen);
  10450. memcpy(str, stackblock(), savelen);
  10451. }
  10452. savehandler = exception_handler;
  10453. exception_handler = &jmploc;
  10454. INT_ON;
  10455. if (oldstyle) {
  10456. /* We must read until the closing backquote, giving special
  10457. treatment to some slashes, and then push the string and
  10458. reread it as input, interpreting it normally. */
  10459. char *pout;
  10460. int pc;
  10461. size_t psavelen;
  10462. char *pstr;
  10463. STARTSTACKSTR(pout);
  10464. for (;;) {
  10465. if (needprompt) {
  10466. setprompt(2);
  10467. }
  10468. pc = pgetc();
  10469. switch (pc) {
  10470. case '`':
  10471. goto done;
  10472. case '\\':
  10473. pc = pgetc();
  10474. if (pc == '\n') {
  10475. g_parsefile->linno++;
  10476. if (doprompt)
  10477. setprompt(2);
  10478. /*
  10479. * If eating a newline, avoid putting
  10480. * the newline into the new character
  10481. * stream (via the STPUTC after the
  10482. * switch).
  10483. */
  10484. continue;
  10485. }
  10486. if (pc != '\\' && pc != '`' && pc != '$'
  10487. && (!dblquote || pc != '"')
  10488. ) {
  10489. STPUTC('\\', pout);
  10490. }
  10491. if (pc <= 255 /* not PEOA or PEOF */) {
  10492. break;
  10493. }
  10494. /* fall through */
  10495. case PEOF:
  10496. IF_ASH_ALIAS(case PEOA:)
  10497. startlinno = g_parsefile->linno;
  10498. raise_error_syntax("EOF in backquote substitution");
  10499. case '\n':
  10500. g_parsefile->linno++;
  10501. needprompt = doprompt;
  10502. break;
  10503. default:
  10504. break;
  10505. }
  10506. STPUTC(pc, pout);
  10507. }
  10508. done:
  10509. STPUTC('\0', pout);
  10510. psavelen = pout - (char *)stackblock();
  10511. if (psavelen > 0) {
  10512. pstr = grabstackstr(pout);
  10513. setinputstring(pstr);
  10514. }
  10515. }
  10516. nlpp = &bqlist;
  10517. while (*nlpp)
  10518. nlpp = &(*nlpp)->next;
  10519. *nlpp = stzalloc(sizeof(**nlpp));
  10520. /* (*nlpp)->next = NULL; - stzalloc did it */
  10521. parsebackquote = oldstyle;
  10522. if (oldstyle) {
  10523. saveprompt = doprompt;
  10524. doprompt = 0;
  10525. }
  10526. n = list(2);
  10527. if (oldstyle)
  10528. doprompt = saveprompt;
  10529. else if (readtoken() != TRP)
  10530. raise_error_unexpected_syntax(TRP);
  10531. (*nlpp)->n = n;
  10532. if (oldstyle) {
  10533. /*
  10534. * Start reading from old file again, ignoring any pushed back
  10535. * tokens left from the backquote parsing
  10536. */
  10537. popfile();
  10538. tokpushback = 0;
  10539. }
  10540. while (stackblocksize() <= savelen)
  10541. growstackblock();
  10542. STARTSTACKSTR(out);
  10543. if (str) {
  10544. memcpy(out, str, savelen);
  10545. STADJUST(savelen, out);
  10546. INT_OFF;
  10547. free(str);
  10548. str = NULL;
  10549. INT_ON;
  10550. }
  10551. parsebackquote = savepbq;
  10552. exception_handler = savehandler;
  10553. if (arinest || dblquote)
  10554. USTPUTC(CTLBACKQ | CTLQUOTE, out);
  10555. else
  10556. USTPUTC(CTLBACKQ, out);
  10557. if (oldstyle)
  10558. goto parsebackq_oldreturn;
  10559. goto parsebackq_newreturn;
  10560. }
  10561. #if ENABLE_SH_MATH_SUPPORT
  10562. /*
  10563. * Parse an arithmetic expansion (indicate start of one and set state)
  10564. */
  10565. parsearith: {
  10566. if (++arinest == 1) {
  10567. prevsyntax = syntax;
  10568. syntax = ARISYNTAX;
  10569. USTPUTC(CTLARI, out);
  10570. if (dblquote)
  10571. USTPUTC('"', out);
  10572. else
  10573. USTPUTC(' ', out);
  10574. } else {
  10575. /*
  10576. * we collapse embedded arithmetic expansion to
  10577. * parenthesis, which should be equivalent
  10578. */
  10579. USTPUTC('(', out);
  10580. }
  10581. goto parsearith_return;
  10582. }
  10583. #endif
  10584. } /* end of readtoken */
  10585. /*
  10586. * Read the next input token.
  10587. * If the token is a word, we set backquotelist to the list of cmds in
  10588. * backquotes. We set quoteflag to true if any part of the word was
  10589. * quoted.
  10590. * If the token is TREDIR, then we set redirnode to a structure containing
  10591. * the redirection.
  10592. * In all cases, the variable startlinno is set to the number of the line
  10593. * on which the token starts.
  10594. *
  10595. * [Change comment: here documents and internal procedures]
  10596. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  10597. * word parsing code into a separate routine. In this case, readtoken
  10598. * doesn't need to have any internal procedures, but parseword does.
  10599. * We could also make parseoperator in essence the main routine, and
  10600. * have parseword (readtoken1?) handle both words and redirection.]
  10601. */
  10602. #define NEW_xxreadtoken
  10603. #ifdef NEW_xxreadtoken
  10604. /* singles must be first! */
  10605. static const char xxreadtoken_chars[7] ALIGN1 = {
  10606. '\n', '(', ')', /* singles */
  10607. '&', '|', ';', /* doubles */
  10608. 0
  10609. };
  10610. #define xxreadtoken_singles 3
  10611. #define xxreadtoken_doubles 3
  10612. static const char xxreadtoken_tokens[] ALIGN1 = {
  10613. TNL, TLP, TRP, /* only single occurrence allowed */
  10614. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  10615. TEOF, /* corresponds to trailing nul */
  10616. TAND, TOR, TENDCASE /* if double occurrence */
  10617. };
  10618. static int
  10619. xxreadtoken(void)
  10620. {
  10621. int c;
  10622. if (tokpushback) {
  10623. tokpushback = 0;
  10624. return lasttoken;
  10625. }
  10626. if (needprompt) {
  10627. setprompt(2);
  10628. }
  10629. startlinno = g_parsefile->linno;
  10630. for (;;) { /* until token or start of word found */
  10631. c = pgetc_fast();
  10632. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  10633. continue;
  10634. if (c == '#') {
  10635. while ((c = pgetc()) != '\n' && c != PEOF)
  10636. continue;
  10637. pungetc();
  10638. } else if (c == '\\') {
  10639. if (pgetc() != '\n') {
  10640. pungetc();
  10641. break; /* return readtoken1(...) */
  10642. }
  10643. startlinno = ++g_parsefile->linno;
  10644. if (doprompt)
  10645. setprompt(2);
  10646. } else {
  10647. const char *p;
  10648. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  10649. if (c != PEOF) {
  10650. if (c == '\n') {
  10651. g_parsefile->linno++;
  10652. needprompt = doprompt;
  10653. }
  10654. p = strchr(xxreadtoken_chars, c);
  10655. if (p == NULL)
  10656. break; /* return readtoken1(...) */
  10657. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  10658. int cc = pgetc();
  10659. if (cc == c) { /* double occurrence? */
  10660. p += xxreadtoken_doubles + 1;
  10661. } else {
  10662. pungetc();
  10663. #if ENABLE_ASH_BASH_COMPAT
  10664. if (c == '&' && cc == '>') /* &> */
  10665. break; /* return readtoken1(...) */
  10666. #endif
  10667. }
  10668. }
  10669. }
  10670. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  10671. return lasttoken;
  10672. }
  10673. } /* for (;;) */
  10674. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  10675. }
  10676. #else /* old xxreadtoken */
  10677. #define RETURN(token) return lasttoken = token
  10678. static int
  10679. xxreadtoken(void)
  10680. {
  10681. int c;
  10682. if (tokpushback) {
  10683. tokpushback = 0;
  10684. return lasttoken;
  10685. }
  10686. if (needprompt) {
  10687. setprompt(2);
  10688. }
  10689. startlinno = g_parsefile->linno;
  10690. for (;;) { /* until token or start of word found */
  10691. c = pgetc_fast();
  10692. switch (c) {
  10693. case ' ': case '\t':
  10694. IF_ASH_ALIAS(case PEOA:)
  10695. continue;
  10696. case '#':
  10697. while ((c = pgetc()) != '\n' && c != PEOF)
  10698. continue;
  10699. pungetc();
  10700. continue;
  10701. case '\\':
  10702. if (pgetc() == '\n') {
  10703. startlinno = ++g_parsefile->linno;
  10704. if (doprompt)
  10705. setprompt(2);
  10706. continue;
  10707. }
  10708. pungetc();
  10709. goto breakloop;
  10710. case '\n':
  10711. g_parsefile->linno++;
  10712. needprompt = doprompt;
  10713. RETURN(TNL);
  10714. case PEOF:
  10715. RETURN(TEOF);
  10716. case '&':
  10717. if (pgetc() == '&')
  10718. RETURN(TAND);
  10719. pungetc();
  10720. RETURN(TBACKGND);
  10721. case '|':
  10722. if (pgetc() == '|')
  10723. RETURN(TOR);
  10724. pungetc();
  10725. RETURN(TPIPE);
  10726. case ';':
  10727. if (pgetc() == ';')
  10728. RETURN(TENDCASE);
  10729. pungetc();
  10730. RETURN(TSEMI);
  10731. case '(':
  10732. RETURN(TLP);
  10733. case ')':
  10734. RETURN(TRP);
  10735. default:
  10736. goto breakloop;
  10737. }
  10738. }
  10739. breakloop:
  10740. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  10741. #undef RETURN
  10742. }
  10743. #endif /* old xxreadtoken */
  10744. static int
  10745. readtoken(void)
  10746. {
  10747. int t;
  10748. #if DEBUG
  10749. smallint alreadyseen = tokpushback;
  10750. #endif
  10751. #if ENABLE_ASH_ALIAS
  10752. top:
  10753. #endif
  10754. t = xxreadtoken();
  10755. /*
  10756. * eat newlines
  10757. */
  10758. if (checkkwd & CHKNL) {
  10759. while (t == TNL) {
  10760. parseheredoc();
  10761. t = xxreadtoken();
  10762. }
  10763. }
  10764. if (t != TWORD || quoteflag) {
  10765. goto out;
  10766. }
  10767. /*
  10768. * check for keywords
  10769. */
  10770. if (checkkwd & CHKKWD) {
  10771. const char *const *pp;
  10772. pp = findkwd(wordtext);
  10773. if (pp) {
  10774. lasttoken = t = pp - tokname_array;
  10775. TRACE(("keyword %s recognized\n", tokname(t)));
  10776. goto out;
  10777. }
  10778. }
  10779. if (checkkwd & CHKALIAS) {
  10780. #if ENABLE_ASH_ALIAS
  10781. struct alias *ap;
  10782. ap = lookupalias(wordtext, 1);
  10783. if (ap != NULL) {
  10784. if (*ap->val) {
  10785. pushstring(ap->val, ap);
  10786. }
  10787. goto top;
  10788. }
  10789. #endif
  10790. }
  10791. out:
  10792. checkkwd = 0;
  10793. #if DEBUG
  10794. if (!alreadyseen)
  10795. TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  10796. else
  10797. TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  10798. #endif
  10799. return t;
  10800. }
  10801. static char
  10802. peektoken(void)
  10803. {
  10804. int t;
  10805. t = readtoken();
  10806. tokpushback = 1;
  10807. return tokname_array[t][0];
  10808. }
  10809. /*
  10810. * Read and parse a command. Returns NODE_EOF on end of file.
  10811. * (NULL is a valid parse tree indicating a blank line.)
  10812. */
  10813. static union node *
  10814. parsecmd(int interact)
  10815. {
  10816. int t;
  10817. tokpushback = 0;
  10818. doprompt = interact;
  10819. if (doprompt)
  10820. setprompt(doprompt);
  10821. needprompt = 0;
  10822. t = readtoken();
  10823. if (t == TEOF)
  10824. return NODE_EOF;
  10825. if (t == TNL)
  10826. return NULL;
  10827. tokpushback = 1;
  10828. return list(1);
  10829. }
  10830. /*
  10831. * Input any here documents.
  10832. */
  10833. static void
  10834. parseheredoc(void)
  10835. {
  10836. struct heredoc *here;
  10837. union node *n;
  10838. here = heredoclist;
  10839. heredoclist = NULL;
  10840. while (here) {
  10841. if (needprompt) {
  10842. setprompt(2);
  10843. }
  10844. readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
  10845. here->eofmark, here->striptabs);
  10846. n = stzalloc(sizeof(struct narg));
  10847. n->narg.type = NARG;
  10848. /*n->narg.next = NULL; - stzalloc did it */
  10849. n->narg.text = wordtext;
  10850. n->narg.backquote = backquotelist;
  10851. here->here->nhere.doc = n;
  10852. here = here->next;
  10853. }
  10854. }
  10855. /*
  10856. * called by editline -- any expansions to the prompt should be added here.
  10857. */
  10858. #if ENABLE_ASH_EXPAND_PRMT
  10859. static const char *
  10860. expandstr(const char *ps)
  10861. {
  10862. union node n;
  10863. /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
  10864. * and token processing _can_ alter it (delete NULs etc). */
  10865. setinputstring((char *)ps);
  10866. readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
  10867. popfile();
  10868. n.narg.type = NARG;
  10869. n.narg.next = NULL;
  10870. n.narg.text = wordtext;
  10871. n.narg.backquote = backquotelist;
  10872. expandarg(&n, NULL, 0);
  10873. return stackblock();
  10874. }
  10875. #endif
  10876. /*
  10877. * Execute a command or commands contained in a string.
  10878. */
  10879. static int
  10880. evalstring(char *s, int mask)
  10881. {
  10882. union node *n;
  10883. struct stackmark smark;
  10884. int skip;
  10885. setinputstring(s);
  10886. setstackmark(&smark);
  10887. skip = 0;
  10888. while ((n = parsecmd(0)) != NODE_EOF) {
  10889. evaltree(n, 0);
  10890. popstackmark(&smark);
  10891. skip = evalskip;
  10892. if (skip)
  10893. break;
  10894. }
  10895. popfile();
  10896. skip &= mask;
  10897. evalskip = skip;
  10898. return skip;
  10899. }
  10900. /*
  10901. * The eval command.
  10902. */
  10903. static int FAST_FUNC
  10904. evalcmd(int argc UNUSED_PARAM, char **argv)
  10905. {
  10906. char *p;
  10907. char *concat;
  10908. if (argv[1]) {
  10909. p = argv[1];
  10910. argv += 2;
  10911. if (argv[0]) {
  10912. STARTSTACKSTR(concat);
  10913. for (;;) {
  10914. concat = stack_putstr(p, concat);
  10915. p = *argv++;
  10916. if (p == NULL)
  10917. break;
  10918. STPUTC(' ', concat);
  10919. }
  10920. STPUTC('\0', concat);
  10921. p = grabstackstr(concat);
  10922. }
  10923. evalstring(p, ~SKIPEVAL);
  10924. }
  10925. return exitstatus;
  10926. }
  10927. /*
  10928. * Read and execute commands.
  10929. * "Top" is nonzero for the top level command loop;
  10930. * it turns on prompting if the shell is interactive.
  10931. */
  10932. static int
  10933. cmdloop(int top)
  10934. {
  10935. union node *n;
  10936. struct stackmark smark;
  10937. int inter;
  10938. int numeof = 0;
  10939. TRACE(("cmdloop(%d) called\n", top));
  10940. for (;;) {
  10941. int skip;
  10942. setstackmark(&smark);
  10943. #if JOBS
  10944. if (doing_jobctl)
  10945. showjobs(stderr, SHOW_CHANGED);
  10946. #endif
  10947. inter = 0;
  10948. if (iflag && top) {
  10949. inter++;
  10950. #if ENABLE_ASH_MAIL
  10951. chkmail();
  10952. #endif
  10953. }
  10954. n = parsecmd(inter);
  10955. #if DEBUG
  10956. if (DEBUG > 2 && debug && (n != NODE_EOF))
  10957. showtree(n);
  10958. #endif
  10959. if (n == NODE_EOF) {
  10960. if (!top || numeof >= 50)
  10961. break;
  10962. if (!stoppedjobs()) {
  10963. if (!Iflag)
  10964. break;
  10965. out2str("\nUse \"exit\" to leave shell.\n");
  10966. }
  10967. numeof++;
  10968. } else if (nflag == 0) {
  10969. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  10970. job_warning >>= 1;
  10971. numeof = 0;
  10972. evaltree(n, 0);
  10973. }
  10974. popstackmark(&smark);
  10975. skip = evalskip;
  10976. if (skip) {
  10977. evalskip = 0;
  10978. return skip & SKIPEVAL;
  10979. }
  10980. }
  10981. return 0;
  10982. }
  10983. /*
  10984. * Take commands from a file. To be compatible we should do a path
  10985. * search for the file, which is necessary to find sub-commands.
  10986. */
  10987. static char *
  10988. find_dot_file(char *name)
  10989. {
  10990. char *fullname;
  10991. const char *path = pathval();
  10992. struct stat statb;
  10993. /* don't try this for absolute or relative paths */
  10994. if (strchr(name, '/'))
  10995. return name;
  10996. /* IIRC standards do not say whether . is to be searched.
  10997. * And it is even smaller this way, making it unconditional for now:
  10998. */
  10999. if (1) { /* ENABLE_ASH_BASH_COMPAT */
  11000. fullname = name;
  11001. goto try_cur_dir;
  11002. }
  11003. while ((fullname = path_advance(&path, name)) != NULL) {
  11004. try_cur_dir:
  11005. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  11006. /*
  11007. * Don't bother freeing here, since it will
  11008. * be freed by the caller.
  11009. */
  11010. return fullname;
  11011. }
  11012. if (fullname != name)
  11013. stunalloc(fullname);
  11014. }
  11015. /* not found in the PATH */
  11016. ash_msg_and_raise_error("%s: not found", name);
  11017. /* NOTREACHED */
  11018. }
  11019. static int FAST_FUNC
  11020. dotcmd(int argc, char **argv)
  11021. {
  11022. struct strlist *sp;
  11023. volatile struct shparam saveparam;
  11024. int status = 0;
  11025. for (sp = cmdenviron; sp; sp = sp->next)
  11026. setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  11027. if (argv[1]) { /* That's what SVR2 does */
  11028. char *fullname = find_dot_file(argv[1]);
  11029. argv += 2;
  11030. argc -= 2;
  11031. if (argc) { /* argc > 0, argv[0] != NULL */
  11032. saveparam = shellparam;
  11033. shellparam.malloced = 0;
  11034. shellparam.nparam = argc;
  11035. shellparam.p = argv;
  11036. };
  11037. setinputfile(fullname, INPUT_PUSH_FILE);
  11038. commandname = fullname;
  11039. cmdloop(0);
  11040. popfile();
  11041. if (argc) {
  11042. freeparam(&shellparam);
  11043. shellparam = saveparam;
  11044. };
  11045. status = exitstatus;
  11046. }
  11047. return status;
  11048. }
  11049. static int FAST_FUNC
  11050. exitcmd(int argc UNUSED_PARAM, char **argv)
  11051. {
  11052. if (stoppedjobs())
  11053. return 0;
  11054. if (argv[1])
  11055. exitstatus = number(argv[1]);
  11056. raise_exception(EXEXIT);
  11057. /* NOTREACHED */
  11058. }
  11059. /*
  11060. * Read a file containing shell functions.
  11061. */
  11062. static void
  11063. readcmdfile(char *name)
  11064. {
  11065. setinputfile(name, INPUT_PUSH_FILE);
  11066. cmdloop(0);
  11067. popfile();
  11068. }
  11069. /* ============ find_command inplementation */
  11070. /*
  11071. * Resolve a command name. If you change this routine, you may have to
  11072. * change the shellexec routine as well.
  11073. */
  11074. static void
  11075. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  11076. {
  11077. struct tblentry *cmdp;
  11078. int idx;
  11079. int prev;
  11080. char *fullname;
  11081. struct stat statb;
  11082. int e;
  11083. int updatetbl;
  11084. struct builtincmd *bcmd;
  11085. /* If name contains a slash, don't use PATH or hash table */
  11086. if (strchr(name, '/') != NULL) {
  11087. entry->u.index = -1;
  11088. if (act & DO_ABS) {
  11089. while (stat(name, &statb) < 0) {
  11090. #ifdef SYSV
  11091. if (errno == EINTR)
  11092. continue;
  11093. #endif
  11094. entry->cmdtype = CMDUNKNOWN;
  11095. return;
  11096. }
  11097. }
  11098. entry->cmdtype = CMDNORMAL;
  11099. return;
  11100. }
  11101. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  11102. updatetbl = (path == pathval());
  11103. if (!updatetbl) {
  11104. act |= DO_ALTPATH;
  11105. if (strstr(path, "%builtin") != NULL)
  11106. act |= DO_ALTBLTIN;
  11107. }
  11108. /* If name is in the table, check answer will be ok */
  11109. cmdp = cmdlookup(name, 0);
  11110. if (cmdp != NULL) {
  11111. int bit;
  11112. switch (cmdp->cmdtype) {
  11113. default:
  11114. #if DEBUG
  11115. abort();
  11116. #endif
  11117. case CMDNORMAL:
  11118. bit = DO_ALTPATH;
  11119. break;
  11120. case CMDFUNCTION:
  11121. bit = DO_NOFUNC;
  11122. break;
  11123. case CMDBUILTIN:
  11124. bit = DO_ALTBLTIN;
  11125. break;
  11126. }
  11127. if (act & bit) {
  11128. updatetbl = 0;
  11129. cmdp = NULL;
  11130. } else if (cmdp->rehash == 0)
  11131. /* if not invalidated by cd, we're done */
  11132. goto success;
  11133. }
  11134. /* If %builtin not in path, check for builtin next */
  11135. bcmd = find_builtin(name);
  11136. if (bcmd) {
  11137. if (IS_BUILTIN_REGULAR(bcmd))
  11138. goto builtin_success;
  11139. if (act & DO_ALTPATH) {
  11140. if (!(act & DO_ALTBLTIN))
  11141. goto builtin_success;
  11142. } else if (builtinloc <= 0) {
  11143. goto builtin_success;
  11144. }
  11145. }
  11146. #if ENABLE_FEATURE_SH_STANDALONE
  11147. {
  11148. int applet_no = find_applet_by_name(name);
  11149. if (applet_no >= 0) {
  11150. entry->cmdtype = CMDNORMAL;
  11151. entry->u.index = -2 - applet_no;
  11152. return;
  11153. }
  11154. }
  11155. #endif
  11156. /* We have to search path. */
  11157. prev = -1; /* where to start */
  11158. if (cmdp && cmdp->rehash) { /* doing a rehash */
  11159. if (cmdp->cmdtype == CMDBUILTIN)
  11160. prev = builtinloc;
  11161. else
  11162. prev = cmdp->param.index;
  11163. }
  11164. e = ENOENT;
  11165. idx = -1;
  11166. loop:
  11167. while ((fullname = path_advance(&path, name)) != NULL) {
  11168. stunalloc(fullname);
  11169. /* NB: code below will still use fullname
  11170. * despite it being "unallocated" */
  11171. idx++;
  11172. if (pathopt) {
  11173. if (prefix(pathopt, "builtin")) {
  11174. if (bcmd)
  11175. goto builtin_success;
  11176. continue;
  11177. }
  11178. if ((act & DO_NOFUNC)
  11179. || !prefix(pathopt, "func")
  11180. ) { /* ignore unimplemented options */
  11181. continue;
  11182. }
  11183. }
  11184. /* if rehash, don't redo absolute path names */
  11185. if (fullname[0] == '/' && idx <= prev) {
  11186. if (idx < prev)
  11187. continue;
  11188. TRACE(("searchexec \"%s\": no change\n", name));
  11189. goto success;
  11190. }
  11191. while (stat(fullname, &statb) < 0) {
  11192. #ifdef SYSV
  11193. if (errno == EINTR)
  11194. continue;
  11195. #endif
  11196. if (errno != ENOENT && errno != ENOTDIR)
  11197. e = errno;
  11198. goto loop;
  11199. }
  11200. e = EACCES; /* if we fail, this will be the error */
  11201. if (!S_ISREG(statb.st_mode))
  11202. continue;
  11203. if (pathopt) { /* this is a %func directory */
  11204. stalloc(strlen(fullname) + 1);
  11205. /* NB: stalloc will return space pointed by fullname
  11206. * (because we don't have any intervening allocations
  11207. * between stunalloc above and this stalloc) */
  11208. readcmdfile(fullname);
  11209. cmdp = cmdlookup(name, 0);
  11210. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  11211. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  11212. stunalloc(fullname);
  11213. goto success;
  11214. }
  11215. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  11216. if (!updatetbl) {
  11217. entry->cmdtype = CMDNORMAL;
  11218. entry->u.index = idx;
  11219. return;
  11220. }
  11221. INT_OFF;
  11222. cmdp = cmdlookup(name, 1);
  11223. cmdp->cmdtype = CMDNORMAL;
  11224. cmdp->param.index = idx;
  11225. INT_ON;
  11226. goto success;
  11227. }
  11228. /* We failed. If there was an entry for this command, delete it */
  11229. if (cmdp && updatetbl)
  11230. delete_cmd_entry();
  11231. if (act & DO_ERR)
  11232. ash_msg("%s: %s", name, errmsg(e, "not found"));
  11233. entry->cmdtype = CMDUNKNOWN;
  11234. return;
  11235. builtin_success:
  11236. if (!updatetbl) {
  11237. entry->cmdtype = CMDBUILTIN;
  11238. entry->u.cmd = bcmd;
  11239. return;
  11240. }
  11241. INT_OFF;
  11242. cmdp = cmdlookup(name, 1);
  11243. cmdp->cmdtype = CMDBUILTIN;
  11244. cmdp->param.cmd = bcmd;
  11245. INT_ON;
  11246. success:
  11247. cmdp->rehash = 0;
  11248. entry->cmdtype = cmdp->cmdtype;
  11249. entry->u = cmdp->param;
  11250. }
  11251. /* ============ trap.c */
  11252. /*
  11253. * The trap builtin.
  11254. */
  11255. static int FAST_FUNC
  11256. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11257. {
  11258. char *action;
  11259. char **ap;
  11260. int signo, exitcode;
  11261. nextopt(nullstr);
  11262. ap = argptr;
  11263. if (!*ap) {
  11264. for (signo = 0; signo < NSIG; signo++) {
  11265. char *tr = trap_ptr[signo];
  11266. if (tr) {
  11267. /* note: bash adds "SIG", but only if invoked
  11268. * as "bash". If called as "sh", or if set -o posix,
  11269. * then it prints short signal names.
  11270. * We are printing short names: */
  11271. out1fmt("trap -- %s %s\n",
  11272. single_quote(tr),
  11273. get_signame(signo));
  11274. /* trap_ptr != trap only if we are in special-cased `trap` code.
  11275. * In this case, we will exit very soon, no need to free(). */
  11276. /* if (trap_ptr != trap && tp[0]) */
  11277. /* free(tr); */
  11278. }
  11279. }
  11280. /*
  11281. if (trap_ptr != trap) {
  11282. free(trap_ptr);
  11283. trap_ptr = trap;
  11284. }
  11285. */
  11286. return 0;
  11287. }
  11288. action = NULL;
  11289. if (ap[1])
  11290. action = *ap++;
  11291. exitcode = 0;
  11292. while (*ap) {
  11293. signo = get_signum(*ap);
  11294. if (signo < 0) {
  11295. /* Mimic bash message exactly */
  11296. ash_msg("%s: invalid signal specification", *ap);
  11297. exitcode = 1;
  11298. goto next;
  11299. }
  11300. INT_OFF;
  11301. if (action) {
  11302. if (LONE_DASH(action))
  11303. action = NULL;
  11304. else
  11305. action = ckstrdup(action);
  11306. }
  11307. free(trap[signo]);
  11308. trap[signo] = action;
  11309. if (signo != 0)
  11310. setsignal(signo);
  11311. INT_ON;
  11312. next:
  11313. ap++;
  11314. }
  11315. return exitcode;
  11316. }
  11317. /* ============ Builtins */
  11318. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  11319. /*
  11320. * Lists available builtins
  11321. */
  11322. static int FAST_FUNC
  11323. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11324. {
  11325. unsigned col;
  11326. unsigned i;
  11327. out1fmt(
  11328. "Built-in commands:\n"
  11329. "------------------\n");
  11330. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  11331. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  11332. builtintab[i].name + 1);
  11333. if (col > 60) {
  11334. out1fmt("\n");
  11335. col = 0;
  11336. }
  11337. }
  11338. #if ENABLE_FEATURE_SH_STANDALONE
  11339. {
  11340. const char *a = applet_names;
  11341. while (*a) {
  11342. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  11343. if (col > 60) {
  11344. out1fmt("\n");
  11345. col = 0;
  11346. }
  11347. a += strlen(a) + 1;
  11348. }
  11349. }
  11350. #endif
  11351. out1fmt("\n\n");
  11352. return EXIT_SUCCESS;
  11353. }
  11354. #endif /* FEATURE_SH_EXTRA_QUIET */
  11355. /*
  11356. * The export and readonly commands.
  11357. */
  11358. static int FAST_FUNC
  11359. exportcmd(int argc UNUSED_PARAM, char **argv)
  11360. {
  11361. struct var *vp;
  11362. char *name;
  11363. const char *p;
  11364. char **aptr;
  11365. int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
  11366. if (nextopt("p") != 'p') {
  11367. aptr = argptr;
  11368. name = *aptr;
  11369. if (name) {
  11370. do {
  11371. p = strchr(name, '=');
  11372. if (p != NULL) {
  11373. p++;
  11374. } else {
  11375. vp = *findvar(hashvar(name), name);
  11376. if (vp) {
  11377. vp->flags |= flag;
  11378. continue;
  11379. }
  11380. }
  11381. setvar(name, p, flag);
  11382. } while ((name = *++aptr) != NULL);
  11383. return 0;
  11384. }
  11385. }
  11386. showvars(argv[0], flag, 0);
  11387. return 0;
  11388. }
  11389. /*
  11390. * Delete a function if it exists.
  11391. */
  11392. static void
  11393. unsetfunc(const char *name)
  11394. {
  11395. struct tblentry *cmdp;
  11396. cmdp = cmdlookup(name, 0);
  11397. if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
  11398. delete_cmd_entry();
  11399. }
  11400. /*
  11401. * The unset builtin command. We unset the function before we unset the
  11402. * variable to allow a function to be unset when there is a readonly variable
  11403. * with the same name.
  11404. */
  11405. static int FAST_FUNC
  11406. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11407. {
  11408. char **ap;
  11409. int i;
  11410. int flag = 0;
  11411. int ret = 0;
  11412. while ((i = nextopt("vf")) != '\0') {
  11413. flag = i;
  11414. }
  11415. for (ap = argptr; *ap; ap++) {
  11416. if (flag != 'f') {
  11417. i = unsetvar(*ap);
  11418. ret |= i;
  11419. if (!(i & 2))
  11420. continue;
  11421. }
  11422. if (flag != 'v')
  11423. unsetfunc(*ap);
  11424. }
  11425. return ret & 1;
  11426. }
  11427. /* setmode.c */
  11428. #include <sys/times.h>
  11429. static const unsigned char timescmd_str[] ALIGN1 = {
  11430. ' ', offsetof(struct tms, tms_utime),
  11431. '\n', offsetof(struct tms, tms_stime),
  11432. ' ', offsetof(struct tms, tms_cutime),
  11433. '\n', offsetof(struct tms, tms_cstime),
  11434. 0
  11435. };
  11436. static int FAST_FUNC
  11437. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11438. {
  11439. long clk_tck, s, t;
  11440. const unsigned char *p;
  11441. struct tms buf;
  11442. clk_tck = sysconf(_SC_CLK_TCK);
  11443. times(&buf);
  11444. p = timescmd_str;
  11445. do {
  11446. t = *(clock_t *)(((char *) &buf) + p[1]);
  11447. s = t / clk_tck;
  11448. out1fmt("%ldm%ld.%.3lds%c",
  11449. s/60, s%60,
  11450. ((t - s * clk_tck) * 1000) / clk_tck,
  11451. p[0]);
  11452. } while (*(p += 2));
  11453. return 0;
  11454. }
  11455. #if ENABLE_SH_MATH_SUPPORT
  11456. /*
  11457. * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
  11458. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  11459. *
  11460. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11461. */
  11462. static int FAST_FUNC
  11463. letcmd(int argc UNUSED_PARAM, char **argv)
  11464. {
  11465. arith_t i;
  11466. argv++;
  11467. if (!*argv)
  11468. ash_msg_and_raise_error("expression expected");
  11469. do {
  11470. i = ash_arith(*argv);
  11471. } while (*++argv);
  11472. return !i;
  11473. }
  11474. #endif /* SH_MATH_SUPPORT */
  11475. /* ============ miscbltin.c
  11476. *
  11477. * Miscellaneous builtins.
  11478. */
  11479. #undef rflag
  11480. #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
  11481. typedef enum __rlimit_resource rlim_t;
  11482. #endif
  11483. /*
  11484. * The read builtin. Options:
  11485. * -r Do not interpret '\' specially
  11486. * -s Turn off echo (tty only)
  11487. * -n NCHARS Read NCHARS max
  11488. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  11489. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  11490. * -u FD Read from given FD instead of fd 0
  11491. * This uses unbuffered input, which may be avoidable in some cases.
  11492. * TODO: bash also has:
  11493. * -a ARRAY Read into array[0],[1],etc
  11494. * -d DELIM End on DELIM char, not newline
  11495. * -e Use line editing (tty only)
  11496. */
  11497. static int FAST_FUNC
  11498. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11499. {
  11500. char *opt_n = NULL;
  11501. char *opt_p = NULL;
  11502. char *opt_t = NULL;
  11503. char *opt_u = NULL;
  11504. int read_flags = 0;
  11505. const char *r;
  11506. int i;
  11507. while ((i = nextopt("p:u:rt:n:s")) != '\0') {
  11508. switch (i) {
  11509. case 'p':
  11510. opt_p = optionarg;
  11511. break;
  11512. case 'n':
  11513. opt_n = optionarg;
  11514. break;
  11515. case 's':
  11516. read_flags |= BUILTIN_READ_SILENT;
  11517. break;
  11518. case 't':
  11519. opt_t = optionarg;
  11520. break;
  11521. case 'r':
  11522. read_flags |= BUILTIN_READ_RAW;
  11523. break;
  11524. case 'u':
  11525. opt_u = optionarg;
  11526. break;
  11527. default:
  11528. break;
  11529. }
  11530. }
  11531. r = shell_builtin_read(setvar2,
  11532. argptr,
  11533. bltinlookup("IFS"), /* can be NULL */
  11534. read_flags,
  11535. opt_n,
  11536. opt_p,
  11537. opt_t,
  11538. opt_u
  11539. );
  11540. if ((uintptr_t)r > 1)
  11541. ash_msg_and_raise_error(r);
  11542. return (uintptr_t)r;
  11543. }
  11544. static int FAST_FUNC
  11545. umaskcmd(int argc UNUSED_PARAM, char **argv)
  11546. {
  11547. static const char permuser[3] ALIGN1 = "ugo";
  11548. static const char permmode[3] ALIGN1 = "rwx";
  11549. static const short permmask[] ALIGN2 = {
  11550. S_IRUSR, S_IWUSR, S_IXUSR,
  11551. S_IRGRP, S_IWGRP, S_IXGRP,
  11552. S_IROTH, S_IWOTH, S_IXOTH
  11553. };
  11554. /* TODO: use bb_parse_mode() instead */
  11555. char *ap;
  11556. mode_t mask;
  11557. int i;
  11558. int symbolic_mode = 0;
  11559. while (nextopt("S") != '\0') {
  11560. symbolic_mode = 1;
  11561. }
  11562. INT_OFF;
  11563. mask = umask(0);
  11564. umask(mask);
  11565. INT_ON;
  11566. ap = *argptr;
  11567. if (ap == NULL) {
  11568. if (symbolic_mode) {
  11569. char buf[18];
  11570. char *p = buf;
  11571. for (i = 0; i < 3; i++) {
  11572. int j;
  11573. *p++ = permuser[i];
  11574. *p++ = '=';
  11575. for (j = 0; j < 3; j++) {
  11576. if ((mask & permmask[3 * i + j]) == 0) {
  11577. *p++ = permmode[j];
  11578. }
  11579. }
  11580. *p++ = ',';
  11581. }
  11582. *--p = 0;
  11583. puts(buf);
  11584. } else {
  11585. out1fmt("%.4o\n", mask);
  11586. }
  11587. } else {
  11588. if (isdigit((unsigned char) *ap)) {
  11589. mask = 0;
  11590. do {
  11591. if (*ap >= '8' || *ap < '0')
  11592. ash_msg_and_raise_error(msg_illnum, argv[1]);
  11593. mask = (mask << 3) + (*ap - '0');
  11594. } while (*++ap != '\0');
  11595. umask(mask);
  11596. } else {
  11597. mask = ~mask & 0777;
  11598. if (!bb_parse_mode(ap, &mask)) {
  11599. ash_msg_and_raise_error("illegal mode: %s", ap);
  11600. }
  11601. umask(~mask & 0777);
  11602. }
  11603. }
  11604. return 0;
  11605. }
  11606. static int FAST_FUNC
  11607. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  11608. {
  11609. return shell_builtin_ulimit(argv);
  11610. }
  11611. /* ============ main() and helpers */
  11612. /*
  11613. * Called to exit the shell.
  11614. */
  11615. static void exitshell(void) NORETURN;
  11616. static void
  11617. exitshell(void)
  11618. {
  11619. struct jmploc loc;
  11620. char *p;
  11621. int status;
  11622. status = exitstatus;
  11623. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  11624. if (setjmp(loc.loc)) {
  11625. if (exception_type == EXEXIT)
  11626. /* dash bug: it just does _exit(exitstatus) here
  11627. * but we have to do setjobctl(0) first!
  11628. * (bug is still not fixed in dash-0.5.3 - if you run dash
  11629. * under Midnight Commander, on exit from dash MC is backgrounded) */
  11630. status = exitstatus;
  11631. goto out;
  11632. }
  11633. exception_handler = &loc;
  11634. p = trap[0];
  11635. if (p) {
  11636. trap[0] = NULL;
  11637. evalstring(p, 0);
  11638. free(p);
  11639. }
  11640. flush_stdout_stderr();
  11641. out:
  11642. setjobctl(0);
  11643. _exit(status);
  11644. /* NOTREACHED */
  11645. }
  11646. static void
  11647. init(void)
  11648. {
  11649. /* from input.c: */
  11650. basepf.next_to_pgetc = basepf.buf = basebuf;
  11651. /* from trap.c: */
  11652. signal(SIGCHLD, SIG_DFL);
  11653. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  11654. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  11655. */
  11656. signal(SIGHUP, SIG_DFL);
  11657. /* from var.c: */
  11658. {
  11659. char **envp;
  11660. const char *p;
  11661. struct stat st1, st2;
  11662. initvar();
  11663. for (envp = environ; envp && *envp; envp++) {
  11664. if (strchr(*envp, '=')) {
  11665. setvareq(*envp, VEXPORT|VTEXTFIXED);
  11666. }
  11667. }
  11668. setvar("PPID", utoa(getppid()), 0);
  11669. p = lookupvar("PWD");
  11670. if (p)
  11671. if (*p != '/' || stat(p, &st1) || stat(".", &st2)
  11672. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
  11673. p = '\0';
  11674. setpwd(p, 0);
  11675. }
  11676. }
  11677. /*
  11678. * Process the shell command line arguments.
  11679. */
  11680. static void
  11681. procargs(char **argv)
  11682. {
  11683. int i;
  11684. const char *xminusc;
  11685. char **xargv;
  11686. xargv = argv;
  11687. arg0 = xargv[0];
  11688. /* if (xargv[0]) - mmm, this is always true! */
  11689. xargv++;
  11690. for (i = 0; i < NOPTS; i++)
  11691. optlist[i] = 2;
  11692. argptr = xargv;
  11693. if (options(1)) {
  11694. /* it already printed err message */
  11695. raise_exception(EXERROR);
  11696. }
  11697. xargv = argptr;
  11698. xminusc = minusc;
  11699. if (*xargv == NULL) {
  11700. if (xminusc)
  11701. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  11702. sflag = 1;
  11703. }
  11704. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  11705. iflag = 1;
  11706. if (mflag == 2)
  11707. mflag = iflag;
  11708. for (i = 0; i < NOPTS; i++)
  11709. if (optlist[i] == 2)
  11710. optlist[i] = 0;
  11711. #if DEBUG == 2
  11712. debug = 1;
  11713. #endif
  11714. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  11715. if (xminusc) {
  11716. minusc = *xargv++;
  11717. if (*xargv)
  11718. goto setarg0;
  11719. } else if (!sflag) {
  11720. setinputfile(*xargv, 0);
  11721. setarg0:
  11722. arg0 = *xargv++;
  11723. commandname = arg0;
  11724. }
  11725. shellparam.p = xargv;
  11726. #if ENABLE_ASH_GETOPTS
  11727. shellparam.optind = 1;
  11728. shellparam.optoff = -1;
  11729. #endif
  11730. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  11731. while (*xargv) {
  11732. shellparam.nparam++;
  11733. xargv++;
  11734. }
  11735. optschanged();
  11736. }
  11737. /*
  11738. * Read /etc/profile or .profile.
  11739. */
  11740. static void
  11741. read_profile(const char *name)
  11742. {
  11743. int skip;
  11744. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  11745. return;
  11746. skip = cmdloop(0);
  11747. popfile();
  11748. if (skip)
  11749. exitshell();
  11750. }
  11751. /*
  11752. * This routine is called when an error or an interrupt occurs in an
  11753. * interactive shell and control is returned to the main command loop.
  11754. */
  11755. static void
  11756. reset(void)
  11757. {
  11758. /* from eval.c: */
  11759. evalskip = 0;
  11760. loopnest = 0;
  11761. /* from input.c: */
  11762. g_parsefile->left_in_buffer = 0;
  11763. g_parsefile->left_in_line = 0; /* clear input buffer */
  11764. popallfiles();
  11765. /* from parser.c: */
  11766. tokpushback = 0;
  11767. checkkwd = 0;
  11768. /* from redir.c: */
  11769. clearredir(/*drop:*/ 0);
  11770. }
  11771. #if PROFILE
  11772. static short profile_buf[16384];
  11773. extern int etext();
  11774. #endif
  11775. /*
  11776. * Main routine. We initialize things, parse the arguments, execute
  11777. * profiles if we're a login shell, and then call cmdloop to execute
  11778. * commands. The setjmp call sets up the location to jump to when an
  11779. * exception occurs. When an exception occurs the variable "state"
  11780. * is used to figure out how far we had gotten.
  11781. */
  11782. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  11783. int ash_main(int argc UNUSED_PARAM, char **argv)
  11784. {
  11785. const char *shinit;
  11786. volatile smallint state;
  11787. struct jmploc jmploc;
  11788. struct stackmark smark;
  11789. /* Initialize global data */
  11790. INIT_G_misc();
  11791. INIT_G_memstack();
  11792. INIT_G_var();
  11793. #if ENABLE_ASH_ALIAS
  11794. INIT_G_alias();
  11795. #endif
  11796. INIT_G_cmdtable();
  11797. #if PROFILE
  11798. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  11799. #endif
  11800. #if ENABLE_FEATURE_EDITING
  11801. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  11802. #endif
  11803. state = 0;
  11804. if (setjmp(jmploc.loc)) {
  11805. smallint e;
  11806. smallint s;
  11807. reset();
  11808. e = exception_type;
  11809. if (e == EXERROR)
  11810. exitstatus = 2;
  11811. s = state;
  11812. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
  11813. exitshell();
  11814. if (e == EXINT)
  11815. outcslow('\n', stderr);
  11816. popstackmark(&smark);
  11817. FORCE_INT_ON; /* enable interrupts */
  11818. if (s == 1)
  11819. goto state1;
  11820. if (s == 2)
  11821. goto state2;
  11822. if (s == 3)
  11823. goto state3;
  11824. goto state4;
  11825. }
  11826. exception_handler = &jmploc;
  11827. #if DEBUG
  11828. opentrace();
  11829. TRACE(("Shell args: "));
  11830. trace_puts_args(argv);
  11831. #endif
  11832. rootpid = getpid();
  11833. init();
  11834. setstackmark(&smark);
  11835. procargs(argv);
  11836. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  11837. if (iflag) {
  11838. const char *hp = lookupvar("HISTFILE");
  11839. if (hp == NULL) {
  11840. hp = lookupvar("HOME");
  11841. if (hp != NULL) {
  11842. char *defhp = concat_path_file(hp, ".ash_history");
  11843. setvar("HISTFILE", defhp, 0);
  11844. free(defhp);
  11845. }
  11846. }
  11847. }
  11848. #endif
  11849. if (/* argv[0] && */ argv[0][0] == '-')
  11850. isloginsh = 1;
  11851. if (isloginsh) {
  11852. state = 1;
  11853. read_profile("/etc/profile");
  11854. state1:
  11855. state = 2;
  11856. read_profile(".profile");
  11857. }
  11858. state2:
  11859. state = 3;
  11860. if (
  11861. #ifndef linux
  11862. getuid() == geteuid() && getgid() == getegid() &&
  11863. #endif
  11864. iflag
  11865. ) {
  11866. shinit = lookupvar("ENV");
  11867. if (shinit != NULL && *shinit != '\0') {
  11868. read_profile(shinit);
  11869. }
  11870. }
  11871. state3:
  11872. state = 4;
  11873. if (minusc) {
  11874. /* evalstring pushes parsefile stack.
  11875. * Ensure we don't falsely claim that 0 (stdin)
  11876. * is one of stacked source fds.
  11877. * Testcase: ash -c 'exec 1>&0' must not complain. */
  11878. if (!sflag)
  11879. g_parsefile->fd = -1;
  11880. evalstring(minusc, 0);
  11881. }
  11882. if (sflag || minusc == NULL) {
  11883. #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  11884. if (iflag) {
  11885. const char *hp = lookupvar("HISTFILE");
  11886. if (hp)
  11887. line_input_state->hist_file = hp;
  11888. }
  11889. #endif
  11890. state4: /* XXX ??? - why isn't this before the "if" statement */
  11891. cmdloop(1);
  11892. }
  11893. #if PROFILE
  11894. monitor(0);
  11895. #endif
  11896. #ifdef GPROF
  11897. {
  11898. extern void _mcleanup(void);
  11899. _mcleanup();
  11900. }
  11901. #endif
  11902. exitshell();
  11903. /* NOTREACHED */
  11904. }
  11905. /*-
  11906. * Copyright (c) 1989, 1991, 1993, 1994
  11907. * The Regents of the University of California. All rights reserved.
  11908. *
  11909. * This code is derived from software contributed to Berkeley by
  11910. * Kenneth Almquist.
  11911. *
  11912. * Redistribution and use in source and binary forms, with or without
  11913. * modification, are permitted provided that the following conditions
  11914. * are met:
  11915. * 1. Redistributions of source code must retain the above copyright
  11916. * notice, this list of conditions and the following disclaimer.
  11917. * 2. Redistributions in binary form must reproduce the above copyright
  11918. * notice, this list of conditions and the following disclaimer in the
  11919. * documentation and/or other materials provided with the distribution.
  11920. * 3. Neither the name of the University nor the names of its contributors
  11921. * may be used to endorse or promote products derived from this software
  11922. * without specific prior written permission.
  11923. *
  11924. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  11925. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  11926. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  11927. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  11928. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  11929. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  11930. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  11931. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  11932. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  11933. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  11934. * SUCH DAMAGE.
  11935. */