3
0

ash.c 291 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * This code is derived from software contributed to Berkeley by
  6. * Kenneth Almquist.
  7. *
  8. * Original BSD copyright notice is retained at the end of this file.
  9. *
  10. * Copyright (c) 1989, 1991, 1993, 1994
  11. * The Regents of the University of California. All rights reserved.
  12. *
  13. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  14. * was re-ported from NetBSD and debianized.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  17. */
  18. /*
  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. #include <paths.h>
  36. #include <setjmp.h>
  37. #include <fnmatch.h>
  38. #include <sys/times.h>
  39. #include "busybox.h" /* for applet_names */
  40. #include "unicode.h"
  41. #include "shell_common.h"
  42. #if ENABLE_SH_MATH_SUPPORT
  43. # include "math.h"
  44. #endif
  45. #if ENABLE_ASH_RANDOM_SUPPORT
  46. # include "random.h"
  47. #else
  48. # define CLEAR_RANDOM_T(rnd) ((void)0)
  49. #endif
  50. #include "NUM_APPLETS.h"
  51. #if NUM_APPLETS == 1
  52. /* STANDALONE does not make sense, and won't compile */
  53. # undef CONFIG_FEATURE_SH_STANDALONE
  54. # undef ENABLE_FEATURE_SH_STANDALONE
  55. # undef IF_FEATURE_SH_STANDALONE
  56. # undef IF_NOT_FEATURE_SH_STANDALONE
  57. # define ENABLE_FEATURE_SH_STANDALONE 0
  58. # define IF_FEATURE_SH_STANDALONE(...)
  59. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  60. #endif
  61. #ifndef PIPE_BUF
  62. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  63. #endif
  64. #if !BB_MMU
  65. # error "Do not even bother, ash will not run on NOMMU machine"
  66. #endif
  67. //config:config ASH
  68. //config: bool "ash"
  69. //config: default y
  70. //config: depends on !NOMMU
  71. //config: help
  72. //config: Tha 'ash' shell adds about 60k in the default configuration and is
  73. //config: the most complete and most pedantically correct shell included with
  74. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  75. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  76. //config: (written by Kenneth Almquist) from NetBSD.
  77. //config:
  78. //config:config ASH_BASH_COMPAT
  79. //config: bool "bash-compatible extensions"
  80. //config: default y
  81. //config: depends on ASH
  82. //config: help
  83. //config: Enable bash-compatible extensions.
  84. //config:
  85. //config:config ASH_IDLE_TIMEOUT
  86. //config: bool "Idle timeout variable"
  87. //config: default n
  88. //config: depends on ASH
  89. //config: help
  90. //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
  91. //config:
  92. //config:config ASH_JOB_CONTROL
  93. //config: bool "Job control"
  94. //config: default y
  95. //config: depends on ASH
  96. //config: help
  97. //config: Enable job control in the ash shell.
  98. //config:
  99. //config:config ASH_ALIAS
  100. //config: bool "Alias support"
  101. //config: default y
  102. //config: depends on ASH
  103. //config: help
  104. //config: Enable alias support in the ash shell.
  105. //config:
  106. //config:config ASH_GETOPTS
  107. //config: bool "Builtin getopt to parse positional parameters"
  108. //config: default y
  109. //config: depends on ASH
  110. //config: help
  111. //config: Enable support for getopts builtin in ash.
  112. //config:
  113. //config:config ASH_BUILTIN_ECHO
  114. //config: bool "Builtin version of 'echo'"
  115. //config: default y
  116. //config: depends on ASH
  117. //config: help
  118. //config: Enable support for echo builtin in ash.
  119. //config:
  120. //config:config ASH_BUILTIN_PRINTF
  121. //config: bool "Builtin version of 'printf'"
  122. //config: default y
  123. //config: depends on ASH
  124. //config: help
  125. //config: Enable support for printf builtin in ash.
  126. //config:
  127. //config:config ASH_BUILTIN_TEST
  128. //config: bool "Builtin version of 'test'"
  129. //config: default y
  130. //config: depends on ASH
  131. //config: help
  132. //config: Enable support for test builtin in ash.
  133. //config:
  134. //config:config ASH_CMDCMD
  135. //config: bool "'command' command to override shell builtins"
  136. //config: default y
  137. //config: depends on ASH
  138. //config: help
  139. //config: Enable support for the ash 'command' builtin, which allows
  140. //config: you to run the specified command with the specified arguments,
  141. //config: even when there is an ash builtin command with the same name.
  142. //config:
  143. //config:config ASH_MAIL
  144. //config: bool "Check for new mail on interactive shells"
  145. //config: default n
  146. //config: depends on ASH
  147. //config: help
  148. //config: Enable "check for new mail" function in the ash shell.
  149. //config:
  150. //config:config ASH_OPTIMIZE_FOR_SIZE
  151. //config: bool "Optimize for size instead of speed"
  152. //config: default y
  153. //config: depends on ASH
  154. //config: help
  155. //config: Compile ash for reduced size at the price of speed.
  156. //config:
  157. //config:config ASH_RANDOM_SUPPORT
  158. //config: bool "Pseudorandom generator and $RANDOM variable"
  159. //config: default y
  160. //config: depends on ASH
  161. //config: help
  162. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  163. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  164. //config: You can reset the generator by using a specified start value.
  165. //config: After "unset RANDOM" the generator will switch off and this
  166. //config: variable will no longer have special treatment.
  167. //config:
  168. //config:config ASH_EXPAND_PRMT
  169. //config: bool "Expand prompt string"
  170. //config: default y
  171. //config: depends on ASH
  172. //config: help
  173. //config: "PS#" may contain volatile content, such as backquote commands.
  174. //config: This option recreates the prompt string from the environment
  175. //config: variable each time it is displayed.
  176. //config:
  177. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  178. //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
  179. //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
  180. //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
  181. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  182. /* ============ Hash table sizes. Configurable. */
  183. #define VTABSIZE 39
  184. #define ATABSIZE 39
  185. #define CMDTABLESIZE 31 /* should be prime */
  186. /* ============ Shell options */
  187. static const char *const optletters_optnames[] = {
  188. "e" "errexit",
  189. "f" "noglob",
  190. "I" "ignoreeof",
  191. "i" "interactive",
  192. "m" "monitor",
  193. "n" "noexec",
  194. "s" "stdin",
  195. "x" "xtrace",
  196. "v" "verbose",
  197. "C" "noclobber",
  198. "a" "allexport",
  199. "b" "notify",
  200. "u" "nounset",
  201. "\0" "vi"
  202. #if ENABLE_ASH_BASH_COMPAT
  203. ,"\0" "pipefail"
  204. #endif
  205. #if DEBUG
  206. ,"\0" "nolog"
  207. ,"\0" "debug"
  208. #endif
  209. };
  210. #define optletters(n) optletters_optnames[n][0]
  211. #define optnames(n) (optletters_optnames[n] + 1)
  212. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  213. /* ============ Misc data */
  214. #define msg_illnum "Illegal number: %s"
  215. /*
  216. * We enclose jmp_buf in a structure so that we can declare pointers to
  217. * jump locations. The global variable handler contains the location to
  218. * jump to when an exception occurs, and the global variable exception_type
  219. * contains a code identifying the exception. To implement nested
  220. * exception handlers, the user should save the value of handler on entry
  221. * to an inner scope, set handler to point to a jmploc structure for the
  222. * inner scope, and restore handler on exit from the scope.
  223. */
  224. struct jmploc {
  225. jmp_buf loc;
  226. };
  227. struct globals_misc {
  228. /* pid of main shell */
  229. int rootpid;
  230. /* shell level: 0 for the main shell, 1 for its children, and so on */
  231. int shlvl;
  232. #define rootshell (!shlvl)
  233. char *minusc; /* argument to -c option */
  234. char *curdir; // = nullstr; /* current working directory */
  235. char *physdir; // = nullstr; /* physical working directory */
  236. char *arg0; /* value of $0 */
  237. struct jmploc *exception_handler;
  238. volatile int suppress_int; /* counter */
  239. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  240. /* last pending signal */
  241. volatile /*sig_atomic_t*/ smallint pending_sig;
  242. smallint exception_type; /* kind of exception (0..5) */
  243. /* exceptions */
  244. #define EXINT 0 /* SIGINT received */
  245. #define EXERROR 1 /* a generic error */
  246. #define EXSHELLPROC 2 /* execute a shell procedure */
  247. #define EXEXEC 3 /* command execution failed */
  248. #define EXEXIT 4 /* exit the shell */
  249. #define EXSIG 5 /* trapped signal in wait(1) */
  250. smallint isloginsh;
  251. char nullstr[1]; /* zero length string */
  252. char optlist[NOPTS];
  253. #define eflag optlist[0]
  254. #define fflag optlist[1]
  255. #define Iflag optlist[2]
  256. #define iflag optlist[3]
  257. #define mflag optlist[4]
  258. #define nflag optlist[5]
  259. #define sflag optlist[6]
  260. #define xflag optlist[7]
  261. #define vflag optlist[8]
  262. #define Cflag optlist[9]
  263. #define aflag optlist[10]
  264. #define bflag optlist[11]
  265. #define uflag optlist[12]
  266. #define viflag optlist[13]
  267. #if ENABLE_ASH_BASH_COMPAT
  268. # define pipefail optlist[14]
  269. #else
  270. # define pipefail 0
  271. #endif
  272. #if DEBUG
  273. # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
  274. # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
  275. #endif
  276. /* trap handler commands */
  277. /*
  278. * Sigmode records the current value of the signal handlers for the various
  279. * modes. A value of zero means that the current handler is not known.
  280. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  281. */
  282. char sigmode[NSIG - 1];
  283. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  284. #define S_CATCH 2 /* signal is caught */
  285. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  286. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  287. /* indicates specified signal received */
  288. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  289. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  290. char *trap[NSIG];
  291. char **trap_ptr; /* used only by "trap hack" */
  292. /* Rarely referenced stuff */
  293. #if ENABLE_ASH_RANDOM_SUPPORT
  294. random_t random_gen;
  295. #endif
  296. pid_t backgndpid; /* pid of last background process */
  297. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  298. };
  299. extern struct globals_misc *const ash_ptr_to_globals_misc;
  300. #define G_misc (*ash_ptr_to_globals_misc)
  301. #define rootpid (G_misc.rootpid )
  302. #define shlvl (G_misc.shlvl )
  303. #define minusc (G_misc.minusc )
  304. #define curdir (G_misc.curdir )
  305. #define physdir (G_misc.physdir )
  306. #define arg0 (G_misc.arg0 )
  307. #define exception_handler (G_misc.exception_handler)
  308. #define exception_type (G_misc.exception_type )
  309. #define suppress_int (G_misc.suppress_int )
  310. #define pending_int (G_misc.pending_int )
  311. #define pending_sig (G_misc.pending_sig )
  312. #define isloginsh (G_misc.isloginsh )
  313. #define nullstr (G_misc.nullstr )
  314. #define optlist (G_misc.optlist )
  315. #define sigmode (G_misc.sigmode )
  316. #define gotsig (G_misc.gotsig )
  317. #define may_have_traps (G_misc.may_have_traps )
  318. #define trap (G_misc.trap )
  319. #define trap_ptr (G_misc.trap_ptr )
  320. #define random_gen (G_misc.random_gen )
  321. #define backgndpid (G_misc.backgndpid )
  322. #define job_warning (G_misc.job_warning)
  323. #define INIT_G_misc() do { \
  324. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  325. barrier(); \
  326. curdir = nullstr; \
  327. physdir = nullstr; \
  328. trap_ptr = trap; \
  329. } while (0)
  330. /* ============ DEBUG */
  331. #if DEBUG
  332. static void trace_printf(const char *fmt, ...);
  333. static void trace_vprintf(const char *fmt, va_list va);
  334. # define TRACE(param) trace_printf param
  335. # define TRACEV(param) trace_vprintf param
  336. # define close(fd) do { \
  337. int dfd = (fd); \
  338. if (close(dfd) < 0) \
  339. bb_error_msg("bug on %d: closing %d(0x%x)", \
  340. __LINE__, dfd, dfd); \
  341. } while (0)
  342. #else
  343. # define TRACE(param)
  344. # define TRACEV(param)
  345. #endif
  346. /* ============ Utility functions */
  347. #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
  348. static int isdigit_str9(const char *str)
  349. {
  350. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  351. while (--maxlen && isdigit(*str))
  352. str++;
  353. return (*str == '\0');
  354. }
  355. static const char *var_end(const char *var)
  356. {
  357. while (*var)
  358. if (*var++ == '=')
  359. break;
  360. return var;
  361. }
  362. /* ============ Interrupts / exceptions */
  363. static void exitshell(void) NORETURN;
  364. /*
  365. * These macros allow the user to suspend the handling of interrupt signals
  366. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  367. * much more efficient and portable. (But hacking the kernel is so much
  368. * more fun than worrying about efficiency and portability. :-))
  369. */
  370. #define INT_OFF do { \
  371. suppress_int++; \
  372. xbarrier(); \
  373. } while (0)
  374. /*
  375. * Called to raise an exception. Since C doesn't include exceptions, we
  376. * just do a longjmp to the exception handler. The type of exception is
  377. * stored in the global variable "exception_type".
  378. */
  379. static void raise_exception(int) NORETURN;
  380. static void
  381. raise_exception(int e)
  382. {
  383. #if DEBUG
  384. if (exception_handler == NULL)
  385. abort();
  386. #endif
  387. INT_OFF;
  388. exception_type = e;
  389. longjmp(exception_handler->loc, 1);
  390. }
  391. #if DEBUG
  392. #define raise_exception(e) do { \
  393. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  394. raise_exception(e); \
  395. } while (0)
  396. #endif
  397. /*
  398. * Called from trap.c when a SIGINT is received. (If the user specifies
  399. * that SIGINT is to be trapped or ignored using the trap builtin, then
  400. * this routine is not called.) Suppressint is nonzero when interrupts
  401. * are held using the INT_OFF macro. (The test for iflag is just
  402. * defensive programming.)
  403. */
  404. static void raise_interrupt(void) NORETURN;
  405. static void
  406. raise_interrupt(void)
  407. {
  408. int ex_type;
  409. pending_int = 0;
  410. /* Signal is not automatically unmasked after it is raised,
  411. * do it ourself - unmask all signals */
  412. sigprocmask_allsigs(SIG_UNBLOCK);
  413. /* pending_sig = 0; - now done in signal_handler() */
  414. ex_type = EXSIG;
  415. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  416. if (!(rootshell && iflag)) {
  417. /* Kill ourself with SIGINT */
  418. signal(SIGINT, SIG_DFL);
  419. raise(SIGINT);
  420. }
  421. ex_type = EXINT;
  422. }
  423. raise_exception(ex_type);
  424. /* NOTREACHED */
  425. }
  426. #if DEBUG
  427. #define raise_interrupt() do { \
  428. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  429. raise_interrupt(); \
  430. } while (0)
  431. #endif
  432. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  433. int_on(void)
  434. {
  435. xbarrier();
  436. if (--suppress_int == 0 && pending_int) {
  437. raise_interrupt();
  438. }
  439. }
  440. #define INT_ON int_on()
  441. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  442. force_int_on(void)
  443. {
  444. xbarrier();
  445. suppress_int = 0;
  446. if (pending_int)
  447. raise_interrupt();
  448. }
  449. #define FORCE_INT_ON force_int_on()
  450. #define SAVE_INT(v) ((v) = suppress_int)
  451. #define RESTORE_INT(v) do { \
  452. xbarrier(); \
  453. suppress_int = (v); \
  454. if (suppress_int == 0 && pending_int) \
  455. raise_interrupt(); \
  456. } while (0)
  457. /* ============ Stdout/stderr output */
  458. static void
  459. outstr(const char *p, FILE *file)
  460. {
  461. INT_OFF;
  462. fputs(p, file);
  463. INT_ON;
  464. }
  465. static void
  466. flush_stdout_stderr(void)
  467. {
  468. INT_OFF;
  469. fflush_all();
  470. INT_ON;
  471. }
  472. static void
  473. outcslow(int c, FILE *dest)
  474. {
  475. INT_OFF;
  476. putc(c, dest);
  477. fflush(dest);
  478. INT_ON;
  479. }
  480. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  481. static int
  482. out1fmt(const char *fmt, ...)
  483. {
  484. va_list ap;
  485. int r;
  486. INT_OFF;
  487. va_start(ap, fmt);
  488. r = vprintf(fmt, ap);
  489. va_end(ap);
  490. INT_ON;
  491. return r;
  492. }
  493. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  494. static int
  495. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  496. {
  497. va_list ap;
  498. int ret;
  499. va_start(ap, fmt);
  500. INT_OFF;
  501. ret = vsnprintf(outbuf, length, fmt, ap);
  502. va_end(ap);
  503. INT_ON;
  504. return ret;
  505. }
  506. static void
  507. out1str(const char *p)
  508. {
  509. outstr(p, stdout);
  510. }
  511. static void
  512. out2str(const char *p)
  513. {
  514. outstr(p, stderr);
  515. flush_stdout_stderr();
  516. }
  517. /* ============ Parser structures */
  518. /* control characters in argument strings */
  519. #define CTL_FIRST CTLESC
  520. #define CTLESC ((unsigned char)'\201') /* escape next character */
  521. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  522. #define CTLENDVAR ((unsigned char)'\203')
  523. #define CTLBACKQ ((unsigned char)'\204')
  524. #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
  525. /* CTLBACKQ | CTLQUOTE == '\205' */
  526. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  527. #define CTLENDARI ((unsigned char)'\207')
  528. #define CTLQUOTEMARK ((unsigned char)'\210')
  529. #define CTL_LAST CTLQUOTEMARK
  530. /* variable substitution byte (follows CTLVAR) */
  531. #define VSTYPE 0x0f /* type of variable substitution */
  532. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  533. #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
  534. /* values of VSTYPE field */
  535. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  536. #define VSMINUS 0x2 /* ${var-text} */
  537. #define VSPLUS 0x3 /* ${var+text} */
  538. #define VSQUESTION 0x4 /* ${var?message} */
  539. #define VSASSIGN 0x5 /* ${var=text} */
  540. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  541. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  542. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  543. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  544. #define VSLENGTH 0xa /* ${#var} */
  545. #if ENABLE_ASH_BASH_COMPAT
  546. #define VSSUBSTR 0xc /* ${var:position:length} */
  547. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  548. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  549. #endif
  550. static const char dolatstr[] ALIGN1 = {
  551. CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
  552. };
  553. #define NCMD 0
  554. #define NPIPE 1
  555. #define NREDIR 2
  556. #define NBACKGND 3
  557. #define NSUBSHELL 4
  558. #define NAND 5
  559. #define NOR 6
  560. #define NSEMI 7
  561. #define NIF 8
  562. #define NWHILE 9
  563. #define NUNTIL 10
  564. #define NFOR 11
  565. #define NCASE 12
  566. #define NCLIST 13
  567. #define NDEFUN 14
  568. #define NARG 15
  569. #define NTO 16
  570. #if ENABLE_ASH_BASH_COMPAT
  571. #define NTO2 17
  572. #endif
  573. #define NCLOBBER 18
  574. #define NFROM 19
  575. #define NFROMTO 20
  576. #define NAPPEND 21
  577. #define NTOFD 22
  578. #define NFROMFD 23
  579. #define NHERE 24
  580. #define NXHERE 25
  581. #define NNOT 26
  582. #define N_NUMBER 27
  583. union node;
  584. struct ncmd {
  585. smallint type; /* Nxxxx */
  586. union node *assign;
  587. union node *args;
  588. union node *redirect;
  589. };
  590. struct npipe {
  591. smallint type;
  592. smallint pipe_backgnd;
  593. struct nodelist *cmdlist;
  594. };
  595. struct nredir {
  596. smallint type;
  597. union node *n;
  598. union node *redirect;
  599. };
  600. struct nbinary {
  601. smallint type;
  602. union node *ch1;
  603. union node *ch2;
  604. };
  605. struct nif {
  606. smallint type;
  607. union node *test;
  608. union node *ifpart;
  609. union node *elsepart;
  610. };
  611. struct nfor {
  612. smallint type;
  613. union node *args;
  614. union node *body;
  615. char *var;
  616. };
  617. struct ncase {
  618. smallint type;
  619. union node *expr;
  620. union node *cases;
  621. };
  622. struct nclist {
  623. smallint type;
  624. union node *next;
  625. union node *pattern;
  626. union node *body;
  627. };
  628. struct narg {
  629. smallint type;
  630. union node *next;
  631. char *text;
  632. struct nodelist *backquote;
  633. };
  634. /* nfile and ndup layout must match!
  635. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  636. * that it is actually NTO2 (>&file), and change its type.
  637. */
  638. struct nfile {
  639. smallint type;
  640. union node *next;
  641. int fd;
  642. int _unused_dupfd;
  643. union node *fname;
  644. char *expfname;
  645. };
  646. struct ndup {
  647. smallint type;
  648. union node *next;
  649. int fd;
  650. int dupfd;
  651. union node *vname;
  652. char *_unused_expfname;
  653. };
  654. struct nhere {
  655. smallint type;
  656. union node *next;
  657. int fd;
  658. union node *doc;
  659. };
  660. struct nnot {
  661. smallint type;
  662. union node *com;
  663. };
  664. union node {
  665. smallint type;
  666. struct ncmd ncmd;
  667. struct npipe npipe;
  668. struct nredir nredir;
  669. struct nbinary nbinary;
  670. struct nif nif;
  671. struct nfor nfor;
  672. struct ncase ncase;
  673. struct nclist nclist;
  674. struct narg narg;
  675. struct nfile nfile;
  676. struct ndup ndup;
  677. struct nhere nhere;
  678. struct nnot nnot;
  679. };
  680. /*
  681. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  682. * It must be distinct from NULL.
  683. */
  684. #define NODE_EOF ((union node *) -1L)
  685. struct nodelist {
  686. struct nodelist *next;
  687. union node *n;
  688. };
  689. struct funcnode {
  690. int count;
  691. union node n;
  692. };
  693. /*
  694. * Free a parse tree.
  695. */
  696. static void
  697. freefunc(struct funcnode *f)
  698. {
  699. if (f && --f->count < 0)
  700. free(f);
  701. }
  702. /* ============ Debugging output */
  703. #if DEBUG
  704. static FILE *tracefile;
  705. static void
  706. trace_printf(const char *fmt, ...)
  707. {
  708. va_list va;
  709. if (debug != 1)
  710. return;
  711. if (DEBUG_TIME)
  712. fprintf(tracefile, "%u ", (int) time(NULL));
  713. if (DEBUG_PID)
  714. fprintf(tracefile, "[%u] ", (int) getpid());
  715. if (DEBUG_SIG)
  716. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  717. va_start(va, fmt);
  718. vfprintf(tracefile, fmt, va);
  719. va_end(va);
  720. }
  721. static void
  722. trace_vprintf(const char *fmt, va_list va)
  723. {
  724. if (debug != 1)
  725. return;
  726. if (DEBUG_TIME)
  727. fprintf(tracefile, "%u ", (int) time(NULL));
  728. if (DEBUG_PID)
  729. fprintf(tracefile, "[%u] ", (int) getpid());
  730. if (DEBUG_SIG)
  731. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  732. vfprintf(tracefile, fmt, va);
  733. }
  734. static void
  735. trace_puts(const char *s)
  736. {
  737. if (debug != 1)
  738. return;
  739. fputs(s, tracefile);
  740. }
  741. static void
  742. trace_puts_quoted(char *s)
  743. {
  744. char *p;
  745. char c;
  746. if (debug != 1)
  747. return;
  748. putc('"', tracefile);
  749. for (p = s; *p; p++) {
  750. switch ((unsigned char)*p) {
  751. case '\n': c = 'n'; goto backslash;
  752. case '\t': c = 't'; goto backslash;
  753. case '\r': c = 'r'; goto backslash;
  754. case '\"': c = '\"'; goto backslash;
  755. case '\\': c = '\\'; goto backslash;
  756. case CTLESC: c = 'e'; goto backslash;
  757. case CTLVAR: c = 'v'; goto backslash;
  758. case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
  759. case CTLBACKQ: c = 'q'; goto backslash;
  760. case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
  761. backslash:
  762. putc('\\', tracefile);
  763. putc(c, tracefile);
  764. break;
  765. default:
  766. if (*p >= ' ' && *p <= '~')
  767. putc(*p, tracefile);
  768. else {
  769. putc('\\', tracefile);
  770. putc((*p >> 6) & 03, tracefile);
  771. putc((*p >> 3) & 07, tracefile);
  772. putc(*p & 07, tracefile);
  773. }
  774. break;
  775. }
  776. }
  777. putc('"', tracefile);
  778. }
  779. static void
  780. trace_puts_args(char **ap)
  781. {
  782. if (debug != 1)
  783. return;
  784. if (!*ap)
  785. return;
  786. while (1) {
  787. trace_puts_quoted(*ap);
  788. if (!*++ap) {
  789. putc('\n', tracefile);
  790. break;
  791. }
  792. putc(' ', tracefile);
  793. }
  794. }
  795. static void
  796. opentrace(void)
  797. {
  798. char s[100];
  799. #ifdef O_APPEND
  800. int flags;
  801. #endif
  802. if (debug != 1) {
  803. if (tracefile)
  804. fflush(tracefile);
  805. /* leave open because libedit might be using it */
  806. return;
  807. }
  808. strcpy(s, "./trace");
  809. if (tracefile) {
  810. if (!freopen(s, "a", tracefile)) {
  811. fprintf(stderr, "Can't re-open %s\n", s);
  812. debug = 0;
  813. return;
  814. }
  815. } else {
  816. tracefile = fopen(s, "a");
  817. if (tracefile == NULL) {
  818. fprintf(stderr, "Can't open %s\n", s);
  819. debug = 0;
  820. return;
  821. }
  822. }
  823. #ifdef O_APPEND
  824. flags = fcntl(fileno(tracefile), F_GETFL);
  825. if (flags >= 0)
  826. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  827. #endif
  828. setlinebuf(tracefile);
  829. fputs("\nTracing started.\n", tracefile);
  830. }
  831. static void
  832. indent(int amount, char *pfx, FILE *fp)
  833. {
  834. int i;
  835. for (i = 0; i < amount; i++) {
  836. if (pfx && i == amount - 1)
  837. fputs(pfx, fp);
  838. putc('\t', fp);
  839. }
  840. }
  841. /* little circular references here... */
  842. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  843. static void
  844. sharg(union node *arg, FILE *fp)
  845. {
  846. char *p;
  847. struct nodelist *bqlist;
  848. unsigned char subtype;
  849. if (arg->type != NARG) {
  850. out1fmt("<node type %d>\n", arg->type);
  851. abort();
  852. }
  853. bqlist = arg->narg.backquote;
  854. for (p = arg->narg.text; *p; p++) {
  855. switch ((unsigned char)*p) {
  856. case CTLESC:
  857. p++;
  858. putc(*p, fp);
  859. break;
  860. case CTLVAR:
  861. putc('$', fp);
  862. putc('{', fp);
  863. subtype = *++p;
  864. if (subtype == VSLENGTH)
  865. putc('#', fp);
  866. while (*p != '=') {
  867. putc(*p, fp);
  868. p++;
  869. }
  870. if (subtype & VSNUL)
  871. putc(':', fp);
  872. switch (subtype & VSTYPE) {
  873. case VSNORMAL:
  874. putc('}', fp);
  875. break;
  876. case VSMINUS:
  877. putc('-', fp);
  878. break;
  879. case VSPLUS:
  880. putc('+', fp);
  881. break;
  882. case VSQUESTION:
  883. putc('?', fp);
  884. break;
  885. case VSASSIGN:
  886. putc('=', fp);
  887. break;
  888. case VSTRIMLEFT:
  889. putc('#', fp);
  890. break;
  891. case VSTRIMLEFTMAX:
  892. putc('#', fp);
  893. putc('#', fp);
  894. break;
  895. case VSTRIMRIGHT:
  896. putc('%', fp);
  897. break;
  898. case VSTRIMRIGHTMAX:
  899. putc('%', fp);
  900. putc('%', fp);
  901. break;
  902. case VSLENGTH:
  903. break;
  904. default:
  905. out1fmt("<subtype %d>", subtype);
  906. }
  907. break;
  908. case CTLENDVAR:
  909. putc('}', fp);
  910. break;
  911. case CTLBACKQ:
  912. case CTLBACKQ|CTLQUOTE:
  913. putc('$', fp);
  914. putc('(', fp);
  915. shtree(bqlist->n, -1, NULL, fp);
  916. putc(')', fp);
  917. break;
  918. default:
  919. putc(*p, fp);
  920. break;
  921. }
  922. }
  923. }
  924. static void
  925. shcmd(union node *cmd, FILE *fp)
  926. {
  927. union node *np;
  928. int first;
  929. const char *s;
  930. int dftfd;
  931. first = 1;
  932. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  933. if (!first)
  934. putc(' ', fp);
  935. sharg(np, fp);
  936. first = 0;
  937. }
  938. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  939. if (!first)
  940. putc(' ', fp);
  941. dftfd = 0;
  942. switch (np->nfile.type) {
  943. case NTO: s = ">>"+1; dftfd = 1; break;
  944. case NCLOBBER: s = ">|"; dftfd = 1; break;
  945. case NAPPEND: s = ">>"; dftfd = 1; break;
  946. #if ENABLE_ASH_BASH_COMPAT
  947. case NTO2:
  948. #endif
  949. case NTOFD: s = ">&"; dftfd = 1; break;
  950. case NFROM: s = "<"; break;
  951. case NFROMFD: s = "<&"; break;
  952. case NFROMTO: s = "<>"; break;
  953. default: s = "*error*"; break;
  954. }
  955. if (np->nfile.fd != dftfd)
  956. fprintf(fp, "%d", np->nfile.fd);
  957. fputs(s, fp);
  958. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  959. fprintf(fp, "%d", np->ndup.dupfd);
  960. } else {
  961. sharg(np->nfile.fname, fp);
  962. }
  963. first = 0;
  964. }
  965. }
  966. static void
  967. shtree(union node *n, int ind, char *pfx, FILE *fp)
  968. {
  969. struct nodelist *lp;
  970. const char *s;
  971. if (n == NULL)
  972. return;
  973. indent(ind, pfx, fp);
  974. if (n == NODE_EOF) {
  975. fputs("<EOF>", fp);
  976. return;
  977. }
  978. switch (n->type) {
  979. case NSEMI:
  980. s = "; ";
  981. goto binop;
  982. case NAND:
  983. s = " && ";
  984. goto binop;
  985. case NOR:
  986. s = " || ";
  987. binop:
  988. shtree(n->nbinary.ch1, ind, NULL, fp);
  989. /* if (ind < 0) */
  990. fputs(s, fp);
  991. shtree(n->nbinary.ch2, ind, NULL, fp);
  992. break;
  993. case NCMD:
  994. shcmd(n, fp);
  995. if (ind >= 0)
  996. putc('\n', fp);
  997. break;
  998. case NPIPE:
  999. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1000. shtree(lp->n, 0, NULL, fp);
  1001. if (lp->next)
  1002. fputs(" | ", fp);
  1003. }
  1004. if (n->npipe.pipe_backgnd)
  1005. fputs(" &", fp);
  1006. if (ind >= 0)
  1007. putc('\n', fp);
  1008. break;
  1009. default:
  1010. fprintf(fp, "<node type %d>", n->type);
  1011. if (ind >= 0)
  1012. putc('\n', fp);
  1013. break;
  1014. }
  1015. }
  1016. static void
  1017. showtree(union node *n)
  1018. {
  1019. trace_puts("showtree called\n");
  1020. shtree(n, 1, NULL, stderr);
  1021. }
  1022. #endif /* DEBUG */
  1023. /* ============ Parser data */
  1024. /*
  1025. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1026. */
  1027. struct strlist {
  1028. struct strlist *next;
  1029. char *text;
  1030. };
  1031. struct alias;
  1032. struct strpush {
  1033. struct strpush *prev; /* preceding string on stack */
  1034. char *prev_string;
  1035. int prev_left_in_line;
  1036. #if ENABLE_ASH_ALIAS
  1037. struct alias *ap; /* if push was associated with an alias */
  1038. #endif
  1039. char *string; /* remember the string since it may change */
  1040. };
  1041. struct parsefile {
  1042. struct parsefile *prev; /* preceding file on stack */
  1043. int linno; /* current line */
  1044. int pf_fd; /* file descriptor (or -1 if string) */
  1045. int left_in_line; /* number of chars left in this line */
  1046. int left_in_buffer; /* number of chars left in this buffer past the line */
  1047. char *next_to_pgetc; /* next char in buffer */
  1048. char *buf; /* input buffer */
  1049. struct strpush *strpush; /* for pushing strings at this level */
  1050. struct strpush basestrpush; /* so pushing one is fast */
  1051. };
  1052. static struct parsefile basepf; /* top level input file */
  1053. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1054. static int startlinno; /* line # where last token started */
  1055. static char *commandname; /* currently executing command */
  1056. static struct strlist *cmdenviron; /* environment for builtin command */
  1057. static uint8_t exitstatus; /* exit status of last command */
  1058. /* ============ Message printing */
  1059. static void
  1060. ash_vmsg(const char *msg, va_list ap)
  1061. {
  1062. fprintf(stderr, "%s: ", arg0);
  1063. if (commandname) {
  1064. if (strcmp(arg0, commandname))
  1065. fprintf(stderr, "%s: ", commandname);
  1066. if (!iflag || g_parsefile->pf_fd > 0)
  1067. fprintf(stderr, "line %d: ", startlinno);
  1068. }
  1069. vfprintf(stderr, msg, ap);
  1070. outcslow('\n', stderr);
  1071. }
  1072. /*
  1073. * Exverror is called to raise the error exception. If the second argument
  1074. * is not NULL then error prints an error message using printf style
  1075. * formatting. It then raises the error exception.
  1076. */
  1077. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1078. static void
  1079. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1080. {
  1081. #if DEBUG
  1082. if (msg) {
  1083. TRACE(("ash_vmsg_and_raise(%d, \"", cond));
  1084. TRACEV((msg, ap));
  1085. TRACE(("\") pid=%d\n", getpid()));
  1086. } else
  1087. TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
  1088. if (msg)
  1089. #endif
  1090. ash_vmsg(msg, ap);
  1091. flush_stdout_stderr();
  1092. raise_exception(cond);
  1093. /* NOTREACHED */
  1094. }
  1095. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1096. static void
  1097. ash_msg_and_raise_error(const char *msg, ...)
  1098. {
  1099. va_list ap;
  1100. va_start(ap, msg);
  1101. ash_vmsg_and_raise(EXERROR, msg, ap);
  1102. /* NOTREACHED */
  1103. va_end(ap);
  1104. }
  1105. static void raise_error_syntax(const char *) NORETURN;
  1106. static void
  1107. raise_error_syntax(const char *msg)
  1108. {
  1109. ash_msg_and_raise_error("syntax error: %s", msg);
  1110. /* NOTREACHED */
  1111. }
  1112. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1113. static void
  1114. ash_msg_and_raise(int cond, const char *msg, ...)
  1115. {
  1116. va_list ap;
  1117. va_start(ap, msg);
  1118. ash_vmsg_and_raise(cond, msg, ap);
  1119. /* NOTREACHED */
  1120. va_end(ap);
  1121. }
  1122. /*
  1123. * error/warning routines for external builtins
  1124. */
  1125. static void
  1126. ash_msg(const char *fmt, ...)
  1127. {
  1128. va_list ap;
  1129. va_start(ap, fmt);
  1130. ash_vmsg(fmt, ap);
  1131. va_end(ap);
  1132. }
  1133. /*
  1134. * Return a string describing an error. The returned string may be a
  1135. * pointer to a static buffer that will be overwritten on the next call.
  1136. * Action describes the operation that got the error.
  1137. */
  1138. static const char *
  1139. errmsg(int e, const char *em)
  1140. {
  1141. if (e == ENOENT || e == ENOTDIR) {
  1142. return em;
  1143. }
  1144. return strerror(e);
  1145. }
  1146. /* ============ Memory allocation */
  1147. #if 0
  1148. /* I consider these wrappers nearly useless:
  1149. * ok, they return you to nearest exception handler, but
  1150. * how much memory do you leak in the process, making
  1151. * memory starvation worse?
  1152. */
  1153. static void *
  1154. ckrealloc(void * p, size_t nbytes)
  1155. {
  1156. p = realloc(p, nbytes);
  1157. if (!p)
  1158. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1159. return p;
  1160. }
  1161. static void *
  1162. ckmalloc(size_t nbytes)
  1163. {
  1164. return ckrealloc(NULL, nbytes);
  1165. }
  1166. static void *
  1167. ckzalloc(size_t nbytes)
  1168. {
  1169. return memset(ckmalloc(nbytes), 0, nbytes);
  1170. }
  1171. static char *
  1172. ckstrdup(const char *s)
  1173. {
  1174. char *p = strdup(s);
  1175. if (!p)
  1176. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1177. return p;
  1178. }
  1179. #else
  1180. /* Using bbox equivalents. They exit if out of memory */
  1181. # define ckrealloc xrealloc
  1182. # define ckmalloc xmalloc
  1183. # define ckzalloc xzalloc
  1184. # define ckstrdup xstrdup
  1185. #endif
  1186. /*
  1187. * It appears that grabstackstr() will barf with such alignments
  1188. * because stalloc() will return a string allocated in a new stackblock.
  1189. */
  1190. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1191. enum {
  1192. /* Most machines require the value returned from malloc to be aligned
  1193. * in some way. The following macro will get this right
  1194. * on many machines. */
  1195. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1196. /* Minimum size of a block */
  1197. MINSIZE = SHELL_ALIGN(504),
  1198. };
  1199. struct stack_block {
  1200. struct stack_block *prev;
  1201. char space[MINSIZE];
  1202. };
  1203. struct stackmark {
  1204. struct stack_block *stackp;
  1205. char *stacknxt;
  1206. size_t stacknleft;
  1207. struct stackmark *marknext;
  1208. };
  1209. struct globals_memstack {
  1210. struct stack_block *g_stackp; // = &stackbase;
  1211. struct stackmark *markp;
  1212. char *g_stacknxt; // = stackbase.space;
  1213. char *sstrend; // = stackbase.space + MINSIZE;
  1214. size_t g_stacknleft; // = MINSIZE;
  1215. int herefd; // = -1;
  1216. struct stack_block stackbase;
  1217. };
  1218. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1219. #define G_memstack (*ash_ptr_to_globals_memstack)
  1220. #define g_stackp (G_memstack.g_stackp )
  1221. #define markp (G_memstack.markp )
  1222. #define g_stacknxt (G_memstack.g_stacknxt )
  1223. #define sstrend (G_memstack.sstrend )
  1224. #define g_stacknleft (G_memstack.g_stacknleft)
  1225. #define herefd (G_memstack.herefd )
  1226. #define stackbase (G_memstack.stackbase )
  1227. #define INIT_G_memstack() do { \
  1228. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1229. barrier(); \
  1230. g_stackp = &stackbase; \
  1231. g_stacknxt = stackbase.space; \
  1232. g_stacknleft = MINSIZE; \
  1233. sstrend = stackbase.space + MINSIZE; \
  1234. herefd = -1; \
  1235. } while (0)
  1236. #define stackblock() ((void *)g_stacknxt)
  1237. #define stackblocksize() g_stacknleft
  1238. /*
  1239. * Parse trees for commands are allocated in lifo order, so we use a stack
  1240. * to make this more efficient, and also to avoid all sorts of exception
  1241. * handling code to handle interrupts in the middle of a parse.
  1242. *
  1243. * The size 504 was chosen because the Ultrix malloc handles that size
  1244. * well.
  1245. */
  1246. static void *
  1247. stalloc(size_t nbytes)
  1248. {
  1249. char *p;
  1250. size_t aligned;
  1251. aligned = SHELL_ALIGN(nbytes);
  1252. if (aligned > g_stacknleft) {
  1253. size_t len;
  1254. size_t blocksize;
  1255. struct stack_block *sp;
  1256. blocksize = aligned;
  1257. if (blocksize < MINSIZE)
  1258. blocksize = MINSIZE;
  1259. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1260. if (len < blocksize)
  1261. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1262. INT_OFF;
  1263. sp = ckmalloc(len);
  1264. sp->prev = g_stackp;
  1265. g_stacknxt = sp->space;
  1266. g_stacknleft = blocksize;
  1267. sstrend = g_stacknxt + blocksize;
  1268. g_stackp = sp;
  1269. INT_ON;
  1270. }
  1271. p = g_stacknxt;
  1272. g_stacknxt += aligned;
  1273. g_stacknleft -= aligned;
  1274. return p;
  1275. }
  1276. static void *
  1277. stzalloc(size_t nbytes)
  1278. {
  1279. return memset(stalloc(nbytes), 0, nbytes);
  1280. }
  1281. static void
  1282. stunalloc(void *p)
  1283. {
  1284. #if DEBUG
  1285. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1286. write(STDERR_FILENO, "stunalloc\n", 10);
  1287. abort();
  1288. }
  1289. #endif
  1290. g_stacknleft += g_stacknxt - (char *)p;
  1291. g_stacknxt = p;
  1292. }
  1293. /*
  1294. * Like strdup but works with the ash stack.
  1295. */
  1296. static char *
  1297. ststrdup(const char *p)
  1298. {
  1299. size_t len = strlen(p) + 1;
  1300. return memcpy(stalloc(len), p, len);
  1301. }
  1302. static void
  1303. setstackmark(struct stackmark *mark)
  1304. {
  1305. mark->stackp = g_stackp;
  1306. mark->stacknxt = g_stacknxt;
  1307. mark->stacknleft = g_stacknleft;
  1308. mark->marknext = markp;
  1309. markp = mark;
  1310. }
  1311. static void
  1312. popstackmark(struct stackmark *mark)
  1313. {
  1314. struct stack_block *sp;
  1315. if (!mark->stackp)
  1316. return;
  1317. INT_OFF;
  1318. markp = mark->marknext;
  1319. while (g_stackp != mark->stackp) {
  1320. sp = g_stackp;
  1321. g_stackp = sp->prev;
  1322. free(sp);
  1323. }
  1324. g_stacknxt = mark->stacknxt;
  1325. g_stacknleft = mark->stacknleft;
  1326. sstrend = mark->stacknxt + mark->stacknleft;
  1327. INT_ON;
  1328. }
  1329. /*
  1330. * When the parser reads in a string, it wants to stick the string on the
  1331. * stack and only adjust the stack pointer when it knows how big the
  1332. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1333. * of space on top of the stack and stackblocklen returns the length of
  1334. * this block. Growstackblock will grow this space by at least one byte,
  1335. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1336. * part of the block that has been used.
  1337. */
  1338. static void
  1339. growstackblock(void)
  1340. {
  1341. size_t newlen;
  1342. newlen = g_stacknleft * 2;
  1343. if (newlen < g_stacknleft)
  1344. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1345. if (newlen < 128)
  1346. newlen += 128;
  1347. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1348. struct stack_block *oldstackp;
  1349. struct stackmark *xmark;
  1350. struct stack_block *sp;
  1351. struct stack_block *prevstackp;
  1352. size_t grosslen;
  1353. INT_OFF;
  1354. oldstackp = g_stackp;
  1355. sp = g_stackp;
  1356. prevstackp = sp->prev;
  1357. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1358. sp = ckrealloc(sp, grosslen);
  1359. sp->prev = prevstackp;
  1360. g_stackp = sp;
  1361. g_stacknxt = sp->space;
  1362. g_stacknleft = newlen;
  1363. sstrend = sp->space + newlen;
  1364. /*
  1365. * Stack marks pointing to the start of the old block
  1366. * must be relocated to point to the new block
  1367. */
  1368. xmark = markp;
  1369. while (xmark != NULL && xmark->stackp == oldstackp) {
  1370. xmark->stackp = g_stackp;
  1371. xmark->stacknxt = g_stacknxt;
  1372. xmark->stacknleft = g_stacknleft;
  1373. xmark = xmark->marknext;
  1374. }
  1375. INT_ON;
  1376. } else {
  1377. char *oldspace = g_stacknxt;
  1378. size_t oldlen = g_stacknleft;
  1379. char *p = stalloc(newlen);
  1380. /* free the space we just allocated */
  1381. g_stacknxt = memcpy(p, oldspace, oldlen);
  1382. g_stacknleft += newlen;
  1383. }
  1384. }
  1385. static void
  1386. grabstackblock(size_t len)
  1387. {
  1388. len = SHELL_ALIGN(len);
  1389. g_stacknxt += len;
  1390. g_stacknleft -= len;
  1391. }
  1392. /*
  1393. * The following routines are somewhat easier to use than the above.
  1394. * The user declares a variable of type STACKSTR, which may be declared
  1395. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1396. * the user uses the macro STPUTC to add characters to the string. In
  1397. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1398. * grown as necessary. When the user is done, she can just leave the
  1399. * string there and refer to it using stackblock(). Or she can allocate
  1400. * the space for it using grabstackstr(). If it is necessary to allow
  1401. * someone else to use the stack temporarily and then continue to grow
  1402. * the string, the user should use grabstack to allocate the space, and
  1403. * then call ungrabstr(p) to return to the previous mode of operation.
  1404. *
  1405. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1406. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1407. * is space for at least one character.
  1408. */
  1409. static void *
  1410. growstackstr(void)
  1411. {
  1412. size_t len = stackblocksize();
  1413. if (herefd >= 0 && len >= 1024) {
  1414. full_write(herefd, stackblock(), len);
  1415. return stackblock();
  1416. }
  1417. growstackblock();
  1418. return (char *)stackblock() + len;
  1419. }
  1420. /*
  1421. * Called from CHECKSTRSPACE.
  1422. */
  1423. static char *
  1424. makestrspace(size_t newlen, char *p)
  1425. {
  1426. size_t len = p - g_stacknxt;
  1427. size_t size = stackblocksize();
  1428. for (;;) {
  1429. size_t nleft;
  1430. size = stackblocksize();
  1431. nleft = size - len;
  1432. if (nleft >= newlen)
  1433. break;
  1434. growstackblock();
  1435. }
  1436. return (char *)stackblock() + len;
  1437. }
  1438. static char *
  1439. stack_nputstr(const char *s, size_t n, char *p)
  1440. {
  1441. p = makestrspace(n, p);
  1442. p = (char *)memcpy(p, s, n) + n;
  1443. return p;
  1444. }
  1445. static char *
  1446. stack_putstr(const char *s, char *p)
  1447. {
  1448. return stack_nputstr(s, strlen(s), p);
  1449. }
  1450. static char *
  1451. _STPUTC(int c, char *p)
  1452. {
  1453. if (p == sstrend)
  1454. p = growstackstr();
  1455. *p++ = c;
  1456. return p;
  1457. }
  1458. #define STARTSTACKSTR(p) ((p) = stackblock())
  1459. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1460. #define CHECKSTRSPACE(n, p) do { \
  1461. char *q = (p); \
  1462. size_t l = (n); \
  1463. size_t m = sstrend - q; \
  1464. if (l > m) \
  1465. (p) = makestrspace(l, q); \
  1466. } while (0)
  1467. #define USTPUTC(c, p) (*(p)++ = (c))
  1468. #define STACKSTRNUL(p) do { \
  1469. if ((p) == sstrend) \
  1470. (p) = growstackstr(); \
  1471. *(p) = '\0'; \
  1472. } while (0)
  1473. #define STUNPUTC(p) (--(p))
  1474. #define STTOPC(p) ((p)[-1])
  1475. #define STADJUST(amount, p) ((p) += (amount))
  1476. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1477. #define ungrabstackstr(s, p) stunalloc(s)
  1478. #define stackstrend() ((void *)sstrend)
  1479. /* ============ String helpers */
  1480. /*
  1481. * prefix -- see if pfx is a prefix of string.
  1482. */
  1483. static char *
  1484. prefix(const char *string, const char *pfx)
  1485. {
  1486. while (*pfx) {
  1487. if (*pfx++ != *string++)
  1488. return NULL;
  1489. }
  1490. return (char *) string;
  1491. }
  1492. /*
  1493. * Check for a valid number. This should be elsewhere.
  1494. */
  1495. static int
  1496. is_number(const char *p)
  1497. {
  1498. do {
  1499. if (!isdigit(*p))
  1500. return 0;
  1501. } while (*++p != '\0');
  1502. return 1;
  1503. }
  1504. /*
  1505. * Convert a string of digits to an integer, printing an error message on
  1506. * failure.
  1507. */
  1508. static int
  1509. number(const char *s)
  1510. {
  1511. if (!is_number(s))
  1512. ash_msg_and_raise_error(msg_illnum, s);
  1513. return atoi(s);
  1514. }
  1515. /*
  1516. * Produce a possibly single quoted string suitable as input to the shell.
  1517. * The return string is allocated on the stack.
  1518. */
  1519. static char *
  1520. single_quote(const char *s)
  1521. {
  1522. char *p;
  1523. STARTSTACKSTR(p);
  1524. do {
  1525. char *q;
  1526. size_t len;
  1527. len = strchrnul(s, '\'') - s;
  1528. q = p = makestrspace(len + 3, p);
  1529. *q++ = '\'';
  1530. q = (char *)memcpy(q, s, len) + len;
  1531. *q++ = '\'';
  1532. s += len;
  1533. STADJUST(q - p, p);
  1534. if (*s != '\'')
  1535. break;
  1536. len = 0;
  1537. do len++; while (*++s == '\'');
  1538. q = p = makestrspace(len + 3, p);
  1539. *q++ = '"';
  1540. q = (char *)memcpy(q, s - len, len) + len;
  1541. *q++ = '"';
  1542. STADJUST(q - p, p);
  1543. } while (*s);
  1544. USTPUTC('\0', p);
  1545. return stackblock();
  1546. }
  1547. /* ============ nextopt */
  1548. static char **argptr; /* argument list for builtin commands */
  1549. static char *optionarg; /* set by nextopt (like getopt) */
  1550. static char *optptr; /* used by nextopt */
  1551. /*
  1552. * XXX - should get rid of. Have all builtins use getopt(3).
  1553. * The library getopt must have the BSD extension static variable
  1554. * "optreset", otherwise it can't be used within the shell safely.
  1555. *
  1556. * Standard option processing (a la getopt) for builtin routines.
  1557. * The only argument that is passed to nextopt is the option string;
  1558. * the other arguments are unnecessary. It returns the character,
  1559. * or '\0' on end of input.
  1560. */
  1561. static int
  1562. nextopt(const char *optstring)
  1563. {
  1564. char *p;
  1565. const char *q;
  1566. char c;
  1567. p = optptr;
  1568. if (p == NULL || *p == '\0') {
  1569. /* We ate entire "-param", take next one */
  1570. p = *argptr;
  1571. if (p == NULL)
  1572. return '\0';
  1573. if (*p != '-')
  1574. return '\0';
  1575. if (*++p == '\0') /* just "-" ? */
  1576. return '\0';
  1577. argptr++;
  1578. if (LONE_DASH(p)) /* "--" ? */
  1579. return '\0';
  1580. /* p => next "-param" */
  1581. }
  1582. /* p => some option char in the middle of a "-param" */
  1583. c = *p++;
  1584. for (q = optstring; *q != c;) {
  1585. if (*q == '\0')
  1586. ash_msg_and_raise_error("illegal option -%c", c);
  1587. if (*++q == ':')
  1588. q++;
  1589. }
  1590. if (*++q == ':') {
  1591. if (*p == '\0') {
  1592. p = *argptr++;
  1593. if (p == NULL)
  1594. ash_msg_and_raise_error("no arg for -%c option", c);
  1595. }
  1596. optionarg = p;
  1597. p = NULL;
  1598. }
  1599. optptr = p;
  1600. return c;
  1601. }
  1602. /* ============ Shell variables */
  1603. /*
  1604. * The parsefile structure pointed to by the global variable parsefile
  1605. * contains information about the current file being read.
  1606. */
  1607. struct shparam {
  1608. int nparam; /* # of positional parameters (without $0) */
  1609. #if ENABLE_ASH_GETOPTS
  1610. int optind; /* next parameter to be processed by getopts */
  1611. int optoff; /* used by getopts */
  1612. #endif
  1613. unsigned char malloced; /* if parameter list dynamically allocated */
  1614. char **p; /* parameter list */
  1615. };
  1616. /*
  1617. * Free the list of positional parameters.
  1618. */
  1619. static void
  1620. freeparam(volatile struct shparam *param)
  1621. {
  1622. if (param->malloced) {
  1623. char **ap, **ap1;
  1624. ap = ap1 = param->p;
  1625. while (*ap)
  1626. free(*ap++);
  1627. free(ap1);
  1628. }
  1629. }
  1630. #if ENABLE_ASH_GETOPTS
  1631. static void FAST_FUNC getoptsreset(const char *value);
  1632. #endif
  1633. struct var {
  1634. struct var *next; /* next entry in hash list */
  1635. int flags; /* flags are defined above */
  1636. const char *var_text; /* name=value */
  1637. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1638. /* the variable gets set/unset */
  1639. };
  1640. struct localvar {
  1641. struct localvar *next; /* next local variable in list */
  1642. struct var *vp; /* the variable that was made local */
  1643. int flags; /* saved flags */
  1644. const char *text; /* saved text */
  1645. };
  1646. /* flags */
  1647. #define VEXPORT 0x01 /* variable is exported */
  1648. #define VREADONLY 0x02 /* variable cannot be modified */
  1649. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1650. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1651. #define VSTACK 0x10 /* text is allocated on the stack */
  1652. #define VUNSET 0x20 /* the variable is not set */
  1653. #define VNOFUNC 0x40 /* don't call the callback function */
  1654. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1655. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1656. #if ENABLE_ASH_RANDOM_SUPPORT
  1657. # define VDYNAMIC 0x200 /* dynamic variable */
  1658. #else
  1659. # define VDYNAMIC 0
  1660. #endif
  1661. /* Need to be before varinit_data[] */
  1662. #if ENABLE_LOCALE_SUPPORT
  1663. static void FAST_FUNC
  1664. change_lc_all(const char *value)
  1665. {
  1666. if (value && *value != '\0')
  1667. setlocale(LC_ALL, value);
  1668. }
  1669. static void FAST_FUNC
  1670. change_lc_ctype(const char *value)
  1671. {
  1672. if (value && *value != '\0')
  1673. setlocale(LC_CTYPE, value);
  1674. }
  1675. #endif
  1676. #if ENABLE_ASH_MAIL
  1677. static void chkmail(void);
  1678. static void changemail(const char *var_value) FAST_FUNC;
  1679. #else
  1680. # define chkmail() ((void)0)
  1681. #endif
  1682. static void changepath(const char *) FAST_FUNC;
  1683. #if ENABLE_ASH_RANDOM_SUPPORT
  1684. static void change_random(const char *) FAST_FUNC;
  1685. #endif
  1686. static const struct {
  1687. int flags;
  1688. const char *var_text;
  1689. void (*var_func)(const char *) FAST_FUNC;
  1690. } varinit_data[] = {
  1691. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1692. #if ENABLE_ASH_MAIL
  1693. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1694. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1695. #endif
  1696. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1697. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1698. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1699. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1700. #if ENABLE_ASH_GETOPTS
  1701. { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
  1702. #endif
  1703. #if ENABLE_ASH_RANDOM_SUPPORT
  1704. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1705. #endif
  1706. #if ENABLE_LOCALE_SUPPORT
  1707. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1708. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1709. #endif
  1710. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1711. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1712. #endif
  1713. };
  1714. struct redirtab;
  1715. struct globals_var {
  1716. struct shparam shellparam; /* $@ current positional parameters */
  1717. struct redirtab *redirlist;
  1718. int g_nullredirs;
  1719. int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1720. struct var *vartab[VTABSIZE];
  1721. struct var varinit[ARRAY_SIZE(varinit_data)];
  1722. };
  1723. extern struct globals_var *const ash_ptr_to_globals_var;
  1724. #define G_var (*ash_ptr_to_globals_var)
  1725. #define shellparam (G_var.shellparam )
  1726. //#define redirlist (G_var.redirlist )
  1727. #define g_nullredirs (G_var.g_nullredirs )
  1728. #define preverrout_fd (G_var.preverrout_fd)
  1729. #define vartab (G_var.vartab )
  1730. #define varinit (G_var.varinit )
  1731. #define INIT_G_var() do { \
  1732. unsigned i; \
  1733. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1734. barrier(); \
  1735. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1736. varinit[i].flags = varinit_data[i].flags; \
  1737. varinit[i].var_text = varinit_data[i].var_text; \
  1738. varinit[i].var_func = varinit_data[i].var_func; \
  1739. } \
  1740. } while (0)
  1741. #define vifs varinit[0]
  1742. #if ENABLE_ASH_MAIL
  1743. # define vmail (&vifs)[1]
  1744. # define vmpath (&vmail)[1]
  1745. # define vpath (&vmpath)[1]
  1746. #else
  1747. # define vpath (&vifs)[1]
  1748. #endif
  1749. #define vps1 (&vpath)[1]
  1750. #define vps2 (&vps1)[1]
  1751. #define vps4 (&vps2)[1]
  1752. #if ENABLE_ASH_GETOPTS
  1753. # define voptind (&vps4)[1]
  1754. # if ENABLE_ASH_RANDOM_SUPPORT
  1755. # define vrandom (&voptind)[1]
  1756. # endif
  1757. #else
  1758. # if ENABLE_ASH_RANDOM_SUPPORT
  1759. # define vrandom (&vps4)[1]
  1760. # endif
  1761. #endif
  1762. /*
  1763. * The following macros access the values of the above variables.
  1764. * They have to skip over the name. They return the null string
  1765. * for unset variables.
  1766. */
  1767. #define ifsval() (vifs.var_text + 4)
  1768. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1769. #if ENABLE_ASH_MAIL
  1770. # define mailval() (vmail.var_text + 5)
  1771. # define mpathval() (vmpath.var_text + 9)
  1772. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1773. #endif
  1774. #define pathval() (vpath.var_text + 5)
  1775. #define ps1val() (vps1.var_text + 4)
  1776. #define ps2val() (vps2.var_text + 4)
  1777. #define ps4val() (vps4.var_text + 4)
  1778. #if ENABLE_ASH_GETOPTS
  1779. # define optindval() (voptind.var_text + 7)
  1780. #endif
  1781. #if ENABLE_ASH_GETOPTS
  1782. static void FAST_FUNC
  1783. getoptsreset(const char *value)
  1784. {
  1785. shellparam.optind = number(value);
  1786. shellparam.optoff = -1;
  1787. }
  1788. #endif
  1789. /* math.h has these, otherwise define our private copies */
  1790. #if !ENABLE_SH_MATH_SUPPORT
  1791. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  1792. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  1793. /*
  1794. * Return the pointer to the first char which is not part of a legal variable name
  1795. * (a letter or underscore followed by letters, underscores, and digits).
  1796. */
  1797. static const char*
  1798. endofname(const char *name)
  1799. {
  1800. if (!is_name(*name))
  1801. return name;
  1802. while (*++name) {
  1803. if (!is_in_name(*name))
  1804. break;
  1805. }
  1806. return name;
  1807. }
  1808. #endif
  1809. /*
  1810. * Compares two strings up to the first = or '\0'. The first
  1811. * string must be terminated by '='; the second may be terminated by
  1812. * either '=' or '\0'.
  1813. */
  1814. static int
  1815. varcmp(const char *p, const char *q)
  1816. {
  1817. int c, d;
  1818. while ((c = *p) == (d = *q)) {
  1819. if (!c || c == '=')
  1820. goto out;
  1821. p++;
  1822. q++;
  1823. }
  1824. if (c == '=')
  1825. c = '\0';
  1826. if (d == '=')
  1827. d = '\0';
  1828. out:
  1829. return c - d;
  1830. }
  1831. /*
  1832. * Find the appropriate entry in the hash table from the name.
  1833. */
  1834. static struct var **
  1835. hashvar(const char *p)
  1836. {
  1837. unsigned hashval;
  1838. hashval = ((unsigned char) *p) << 4;
  1839. while (*p && *p != '=')
  1840. hashval += (unsigned char) *p++;
  1841. return &vartab[hashval % VTABSIZE];
  1842. }
  1843. static int
  1844. vpcmp(const void *a, const void *b)
  1845. {
  1846. return varcmp(*(const char **)a, *(const char **)b);
  1847. }
  1848. /*
  1849. * This routine initializes the builtin variables.
  1850. */
  1851. static void
  1852. initvar(void)
  1853. {
  1854. struct var *vp;
  1855. struct var *end;
  1856. struct var **vpp;
  1857. /*
  1858. * PS1 depends on uid
  1859. */
  1860. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1861. vps1.var_text = "PS1=\\w \\$ ";
  1862. #else
  1863. if (!geteuid())
  1864. vps1.var_text = "PS1=# ";
  1865. #endif
  1866. vp = varinit;
  1867. end = vp + ARRAY_SIZE(varinit);
  1868. do {
  1869. vpp = hashvar(vp->var_text);
  1870. vp->next = *vpp;
  1871. *vpp = vp;
  1872. } while (++vp < end);
  1873. }
  1874. static struct var **
  1875. findvar(struct var **vpp, const char *name)
  1876. {
  1877. for (; *vpp; vpp = &(*vpp)->next) {
  1878. if (varcmp((*vpp)->var_text, name) == 0) {
  1879. break;
  1880. }
  1881. }
  1882. return vpp;
  1883. }
  1884. /*
  1885. * Find the value of a variable. Returns NULL if not set.
  1886. */
  1887. static const char* FAST_FUNC
  1888. lookupvar(const char *name)
  1889. {
  1890. struct var *v;
  1891. v = *findvar(hashvar(name), name);
  1892. if (v) {
  1893. #if ENABLE_ASH_RANDOM_SUPPORT
  1894. /*
  1895. * Dynamic variables are implemented roughly the same way they are
  1896. * in bash. Namely, they're "special" so long as they aren't unset.
  1897. * As soon as they're unset, they're no longer dynamic, and dynamic
  1898. * lookup will no longer happen at that point. -- PFM.
  1899. */
  1900. if (v->flags & VDYNAMIC)
  1901. v->var_func(NULL);
  1902. #endif
  1903. if (!(v->flags & VUNSET))
  1904. return var_end(v->var_text);
  1905. }
  1906. return NULL;
  1907. }
  1908. /*
  1909. * Search the environment of a builtin command.
  1910. */
  1911. static const char *
  1912. bltinlookup(const char *name)
  1913. {
  1914. struct strlist *sp;
  1915. for (sp = cmdenviron; sp; sp = sp->next) {
  1916. if (varcmp(sp->text, name) == 0)
  1917. return var_end(sp->text);
  1918. }
  1919. return lookupvar(name);
  1920. }
  1921. /*
  1922. * Same as setvar except that the variable and value are passed in
  1923. * the first argument as name=value. Since the first argument will
  1924. * be actually stored in the table, it should not be a string that
  1925. * will go away.
  1926. * Called with interrupts off.
  1927. */
  1928. static void
  1929. setvareq(char *s, int flags)
  1930. {
  1931. struct var *vp, **vpp;
  1932. vpp = hashvar(s);
  1933. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  1934. vp = *findvar(vpp, s);
  1935. if (vp) {
  1936. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  1937. const char *n;
  1938. if (flags & VNOSAVE)
  1939. free(s);
  1940. n = vp->var_text;
  1941. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  1942. }
  1943. if (flags & VNOSET)
  1944. return;
  1945. if (vp->var_func && !(flags & VNOFUNC))
  1946. vp->var_func(var_end(s));
  1947. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  1948. free((char*)vp->var_text);
  1949. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  1950. } else {
  1951. /* variable s is not found */
  1952. if (flags & VNOSET)
  1953. return;
  1954. vp = ckzalloc(sizeof(*vp));
  1955. vp->next = *vpp;
  1956. /*vp->func = NULL; - ckzalloc did it */
  1957. *vpp = vp;
  1958. }
  1959. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  1960. s = ckstrdup(s);
  1961. vp->var_text = s;
  1962. vp->flags = flags;
  1963. }
  1964. /*
  1965. * Set the value of a variable. The flags argument is ored with the
  1966. * flags of the variable. If val is NULL, the variable is unset.
  1967. */
  1968. static void
  1969. setvar(const char *name, const char *val, int flags)
  1970. {
  1971. const char *q;
  1972. char *p;
  1973. char *nameeq;
  1974. size_t namelen;
  1975. size_t vallen;
  1976. q = endofname(name);
  1977. p = strchrnul(q, '=');
  1978. namelen = p - name;
  1979. if (!namelen || p != q)
  1980. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  1981. vallen = 0;
  1982. if (val == NULL) {
  1983. flags |= VUNSET;
  1984. } else {
  1985. vallen = strlen(val);
  1986. }
  1987. INT_OFF;
  1988. nameeq = ckmalloc(namelen + vallen + 2);
  1989. p = memcpy(nameeq, name, namelen) + namelen;
  1990. if (val) {
  1991. *p++ = '=';
  1992. p = memcpy(p, val, vallen) + vallen;
  1993. }
  1994. *p = '\0';
  1995. setvareq(nameeq, flags | VNOSAVE);
  1996. INT_ON;
  1997. }
  1998. static void FAST_FUNC
  1999. setvar2(const char *name, const char *val)
  2000. {
  2001. setvar(name, val, 0);
  2002. }
  2003. #if ENABLE_ASH_GETOPTS
  2004. /*
  2005. * Safe version of setvar, returns 1 on success 0 on failure.
  2006. */
  2007. static int
  2008. setvarsafe(const char *name, const char *val, int flags)
  2009. {
  2010. int err;
  2011. volatile int saveint;
  2012. struct jmploc *volatile savehandler = exception_handler;
  2013. struct jmploc jmploc;
  2014. SAVE_INT(saveint);
  2015. if (setjmp(jmploc.loc))
  2016. err = 1;
  2017. else {
  2018. exception_handler = &jmploc;
  2019. setvar(name, val, flags);
  2020. err = 0;
  2021. }
  2022. exception_handler = savehandler;
  2023. RESTORE_INT(saveint);
  2024. return err;
  2025. }
  2026. #endif
  2027. /*
  2028. * Unset the specified variable.
  2029. */
  2030. static int
  2031. unsetvar(const char *s)
  2032. {
  2033. struct var **vpp;
  2034. struct var *vp;
  2035. int retval;
  2036. vpp = findvar(hashvar(s), s);
  2037. vp = *vpp;
  2038. retval = 2;
  2039. if (vp) {
  2040. int flags = vp->flags;
  2041. retval = 1;
  2042. if (flags & VREADONLY)
  2043. goto out;
  2044. #if ENABLE_ASH_RANDOM_SUPPORT
  2045. vp->flags &= ~VDYNAMIC;
  2046. #endif
  2047. if (flags & VUNSET)
  2048. goto ok;
  2049. if ((flags & VSTRFIXED) == 0) {
  2050. INT_OFF;
  2051. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  2052. free((char*)vp->var_text);
  2053. *vpp = vp->next;
  2054. free(vp);
  2055. INT_ON;
  2056. } else {
  2057. setvar(s, 0, 0);
  2058. vp->flags &= ~VEXPORT;
  2059. }
  2060. ok:
  2061. retval = 0;
  2062. }
  2063. out:
  2064. return retval;
  2065. }
  2066. /*
  2067. * Process a linked list of variable assignments.
  2068. */
  2069. static void
  2070. listsetvar(struct strlist *list_set_var, int flags)
  2071. {
  2072. struct strlist *lp = list_set_var;
  2073. if (!lp)
  2074. return;
  2075. INT_OFF;
  2076. do {
  2077. setvareq(lp->text, flags);
  2078. lp = lp->next;
  2079. } while (lp);
  2080. INT_ON;
  2081. }
  2082. /*
  2083. * Generate a list of variables satisfying the given conditions.
  2084. */
  2085. static char **
  2086. listvars(int on, int off, char ***end)
  2087. {
  2088. struct var **vpp;
  2089. struct var *vp;
  2090. char **ep;
  2091. int mask;
  2092. STARTSTACKSTR(ep);
  2093. vpp = vartab;
  2094. mask = on | off;
  2095. do {
  2096. for (vp = *vpp; vp; vp = vp->next) {
  2097. if ((vp->flags & mask) == on) {
  2098. if (ep == stackstrend())
  2099. ep = growstackstr();
  2100. *ep++ = (char*)vp->var_text;
  2101. }
  2102. }
  2103. } while (++vpp < vartab + VTABSIZE);
  2104. if (ep == stackstrend())
  2105. ep = growstackstr();
  2106. if (end)
  2107. *end = ep;
  2108. *ep++ = NULL;
  2109. return grabstackstr(ep);
  2110. }
  2111. /* ============ Path search helper
  2112. *
  2113. * The variable path (passed by reference) should be set to the start
  2114. * of the path before the first call; path_advance will update
  2115. * this value as it proceeds. Successive calls to path_advance will return
  2116. * the possible path expansions in sequence. If an option (indicated by
  2117. * a percent sign) appears in the path entry then the global variable
  2118. * pathopt will be set to point to it; otherwise pathopt will be set to
  2119. * NULL.
  2120. */
  2121. static const char *pathopt; /* set by path_advance */
  2122. static char *
  2123. path_advance(const char **path, const char *name)
  2124. {
  2125. const char *p;
  2126. char *q;
  2127. const char *start;
  2128. size_t len;
  2129. if (*path == NULL)
  2130. return NULL;
  2131. start = *path;
  2132. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2133. continue;
  2134. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2135. while (stackblocksize() < len)
  2136. growstackblock();
  2137. q = stackblock();
  2138. if (p != start) {
  2139. memcpy(q, start, p - start);
  2140. q += p - start;
  2141. *q++ = '/';
  2142. }
  2143. strcpy(q, name);
  2144. pathopt = NULL;
  2145. if (*p == '%') {
  2146. pathopt = ++p;
  2147. while (*p && *p != ':')
  2148. p++;
  2149. }
  2150. if (*p == ':')
  2151. *path = p + 1;
  2152. else
  2153. *path = NULL;
  2154. return stalloc(len);
  2155. }
  2156. /* ============ Prompt */
  2157. static smallint doprompt; /* if set, prompt the user */
  2158. static smallint needprompt; /* true if interactive and at start of line */
  2159. #if ENABLE_FEATURE_EDITING
  2160. static line_input_t *line_input_state;
  2161. static const char *cmdedit_prompt;
  2162. static void
  2163. putprompt(const char *s)
  2164. {
  2165. if (ENABLE_ASH_EXPAND_PRMT) {
  2166. free((char*)cmdedit_prompt);
  2167. cmdedit_prompt = ckstrdup(s);
  2168. return;
  2169. }
  2170. cmdedit_prompt = s;
  2171. }
  2172. #else
  2173. static void
  2174. putprompt(const char *s)
  2175. {
  2176. out2str(s);
  2177. }
  2178. #endif
  2179. #if ENABLE_ASH_EXPAND_PRMT
  2180. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2181. static const char *expandstr(const char *ps);
  2182. #else
  2183. #define expandstr(s) s
  2184. #endif
  2185. static void
  2186. setprompt_if(smallint do_set, int whichprompt)
  2187. {
  2188. const char *prompt;
  2189. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2190. if (!do_set)
  2191. return;
  2192. needprompt = 0;
  2193. switch (whichprompt) {
  2194. case 1:
  2195. prompt = ps1val();
  2196. break;
  2197. case 2:
  2198. prompt = ps2val();
  2199. break;
  2200. default: /* 0 */
  2201. prompt = nullstr;
  2202. }
  2203. #if ENABLE_ASH_EXPAND_PRMT
  2204. setstackmark(&smark);
  2205. stalloc(stackblocksize());
  2206. #endif
  2207. putprompt(expandstr(prompt));
  2208. #if ENABLE_ASH_EXPAND_PRMT
  2209. popstackmark(&smark);
  2210. #endif
  2211. }
  2212. /* ============ The cd and pwd commands */
  2213. #define CD_PHYSICAL 1
  2214. #define CD_PRINT 2
  2215. static int
  2216. cdopt(void)
  2217. {
  2218. int flags = 0;
  2219. int i, j;
  2220. j = 'L';
  2221. while ((i = nextopt("LP")) != '\0') {
  2222. if (i != j) {
  2223. flags ^= CD_PHYSICAL;
  2224. j = i;
  2225. }
  2226. }
  2227. return flags;
  2228. }
  2229. /*
  2230. * Update curdir (the name of the current directory) in response to a
  2231. * cd command.
  2232. */
  2233. static const char *
  2234. updatepwd(const char *dir)
  2235. {
  2236. char *new;
  2237. char *p;
  2238. char *cdcomppath;
  2239. const char *lim;
  2240. cdcomppath = ststrdup(dir);
  2241. STARTSTACKSTR(new);
  2242. if (*dir != '/') {
  2243. if (curdir == nullstr)
  2244. return 0;
  2245. new = stack_putstr(curdir, new);
  2246. }
  2247. new = makestrspace(strlen(dir) + 2, new);
  2248. lim = (char *)stackblock() + 1;
  2249. if (*dir != '/') {
  2250. if (new[-1] != '/')
  2251. USTPUTC('/', new);
  2252. if (new > lim && *lim == '/')
  2253. lim++;
  2254. } else {
  2255. USTPUTC('/', new);
  2256. cdcomppath++;
  2257. if (dir[1] == '/' && dir[2] != '/') {
  2258. USTPUTC('/', new);
  2259. cdcomppath++;
  2260. lim++;
  2261. }
  2262. }
  2263. p = strtok(cdcomppath, "/");
  2264. while (p) {
  2265. switch (*p) {
  2266. case '.':
  2267. if (p[1] == '.' && p[2] == '\0') {
  2268. while (new > lim) {
  2269. STUNPUTC(new);
  2270. if (new[-1] == '/')
  2271. break;
  2272. }
  2273. break;
  2274. }
  2275. if (p[1] == '\0')
  2276. break;
  2277. /* fall through */
  2278. default:
  2279. new = stack_putstr(p, new);
  2280. USTPUTC('/', new);
  2281. }
  2282. p = strtok(0, "/");
  2283. }
  2284. if (new > lim)
  2285. STUNPUTC(new);
  2286. *new = 0;
  2287. return stackblock();
  2288. }
  2289. /*
  2290. * Find out what the current directory is. If we already know the current
  2291. * directory, this routine returns immediately.
  2292. */
  2293. static char *
  2294. getpwd(void)
  2295. {
  2296. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2297. return dir ? dir : nullstr;
  2298. }
  2299. static void
  2300. setpwd(const char *val, int setold)
  2301. {
  2302. char *oldcur, *dir;
  2303. oldcur = dir = curdir;
  2304. if (setold) {
  2305. setvar("OLDPWD", oldcur, VEXPORT);
  2306. }
  2307. INT_OFF;
  2308. if (physdir != nullstr) {
  2309. if (physdir != oldcur)
  2310. free(physdir);
  2311. physdir = nullstr;
  2312. }
  2313. if (oldcur == val || !val) {
  2314. char *s = getpwd();
  2315. physdir = s;
  2316. if (!val)
  2317. dir = s;
  2318. } else
  2319. dir = ckstrdup(val);
  2320. if (oldcur != dir && oldcur != nullstr) {
  2321. free(oldcur);
  2322. }
  2323. curdir = dir;
  2324. INT_ON;
  2325. setvar("PWD", dir, VEXPORT);
  2326. }
  2327. static void hashcd(void);
  2328. /*
  2329. * Actually do the chdir. We also call hashcd to let the routines in exec.c
  2330. * know that the current directory has changed.
  2331. */
  2332. static int
  2333. docd(const char *dest, int flags)
  2334. {
  2335. const char *dir = NULL;
  2336. int err;
  2337. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2338. INT_OFF;
  2339. if (!(flags & CD_PHYSICAL)) {
  2340. dir = updatepwd(dest);
  2341. if (dir)
  2342. dest = dir;
  2343. }
  2344. err = chdir(dest);
  2345. if (err)
  2346. goto out;
  2347. setpwd(dir, 1);
  2348. hashcd();
  2349. out:
  2350. INT_ON;
  2351. return err;
  2352. }
  2353. static int FAST_FUNC
  2354. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2355. {
  2356. const char *dest;
  2357. const char *path;
  2358. const char *p;
  2359. char c;
  2360. struct stat statb;
  2361. int flags;
  2362. flags = cdopt();
  2363. dest = *argptr;
  2364. if (!dest)
  2365. dest = bltinlookup("HOME");
  2366. else if (LONE_DASH(dest)) {
  2367. dest = bltinlookup("OLDPWD");
  2368. flags |= CD_PRINT;
  2369. }
  2370. if (!dest)
  2371. dest = nullstr;
  2372. if (*dest == '/')
  2373. goto step7;
  2374. if (*dest == '.') {
  2375. c = dest[1];
  2376. dotdot:
  2377. switch (c) {
  2378. case '\0':
  2379. case '/':
  2380. goto step6;
  2381. case '.':
  2382. c = dest[2];
  2383. if (c != '.')
  2384. goto dotdot;
  2385. }
  2386. }
  2387. if (!*dest)
  2388. dest = ".";
  2389. path = bltinlookup("CDPATH");
  2390. if (!path) {
  2391. step6:
  2392. step7:
  2393. p = dest;
  2394. goto docd;
  2395. }
  2396. do {
  2397. c = *path;
  2398. p = path_advance(&path, dest);
  2399. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2400. if (c && c != ':')
  2401. flags |= CD_PRINT;
  2402. docd:
  2403. if (!docd(p, flags))
  2404. goto out;
  2405. break;
  2406. }
  2407. } while (path);
  2408. ash_msg_and_raise_error("can't cd to %s", dest);
  2409. /* NOTREACHED */
  2410. out:
  2411. if (flags & CD_PRINT)
  2412. out1fmt("%s\n", curdir);
  2413. return 0;
  2414. }
  2415. static int FAST_FUNC
  2416. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2417. {
  2418. int flags;
  2419. const char *dir = curdir;
  2420. flags = cdopt();
  2421. if (flags) {
  2422. if (physdir == nullstr)
  2423. setpwd(dir, 0);
  2424. dir = physdir;
  2425. }
  2426. out1fmt("%s\n", dir);
  2427. return 0;
  2428. }
  2429. /* ============ ... */
  2430. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2431. /* Syntax classes */
  2432. #define CWORD 0 /* character is nothing special */
  2433. #define CNL 1 /* newline character */
  2434. #define CBACK 2 /* a backslash character */
  2435. #define CSQUOTE 3 /* single quote */
  2436. #define CDQUOTE 4 /* double quote */
  2437. #define CENDQUOTE 5 /* a terminating quote */
  2438. #define CBQUOTE 6 /* backwards single quote */
  2439. #define CVAR 7 /* a dollar sign */
  2440. #define CENDVAR 8 /* a '}' character */
  2441. #define CLP 9 /* a left paren in arithmetic */
  2442. #define CRP 10 /* a right paren in arithmetic */
  2443. #define CENDFILE 11 /* end of file */
  2444. #define CCTL 12 /* like CWORD, except it must be escaped */
  2445. #define CSPCL 13 /* these terminate a word */
  2446. #define CIGN 14 /* character should be ignored */
  2447. #define PEOF 256
  2448. #if ENABLE_ASH_ALIAS
  2449. # define PEOA 257
  2450. #endif
  2451. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2452. #if ENABLE_SH_MATH_SUPPORT
  2453. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2454. #else
  2455. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2456. #endif
  2457. static const uint16_t S_I_T[] = {
  2458. #if ENABLE_ASH_ALIAS
  2459. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2460. #endif
  2461. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2462. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2463. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2464. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2465. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2466. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2467. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2468. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2469. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2470. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2471. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2472. #if !USE_SIT_FUNCTION
  2473. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2474. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2475. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2476. #endif
  2477. #undef SIT_ITEM
  2478. };
  2479. /* Constants below must match table above */
  2480. enum {
  2481. #if ENABLE_ASH_ALIAS
  2482. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2483. #endif
  2484. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2485. CNL_CNL_CNL_CNL , /* 2 */
  2486. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2487. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2488. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2489. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2490. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2491. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2492. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2493. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2494. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2495. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2496. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2497. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2498. };
  2499. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2500. * caller must ensure proper cast on it if c is *char_ptr!
  2501. */
  2502. /* Values for syntax param */
  2503. #define BASESYNTAX 0 /* not in quotes */
  2504. #define DQSYNTAX 1 /* in double quotes */
  2505. #define SQSYNTAX 2 /* in single quotes */
  2506. #define ARISYNTAX 3 /* in arithmetic */
  2507. #define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2508. #if USE_SIT_FUNCTION
  2509. static int
  2510. SIT(int c, int syntax)
  2511. {
  2512. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
  2513. # if ENABLE_ASH_ALIAS
  2514. static const uint8_t syntax_index_table[] ALIGN1 = {
  2515. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2516. 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
  2517. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2518. 11, 3 /* "}~" */
  2519. };
  2520. # else
  2521. static const uint8_t syntax_index_table[] ALIGN1 = {
  2522. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2523. 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
  2524. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2525. 10, 2 /* "}~" */
  2526. };
  2527. # endif
  2528. const char *s;
  2529. int indx;
  2530. if (c == PEOF)
  2531. return CENDFILE;
  2532. # if ENABLE_ASH_ALIAS
  2533. if (c == PEOA)
  2534. indx = 0;
  2535. else
  2536. # endif
  2537. {
  2538. /* Cast is purely for paranoia here,
  2539. * just in case someone passed signed char to us */
  2540. if ((unsigned char)c >= CTL_FIRST
  2541. && (unsigned char)c <= CTL_LAST
  2542. ) {
  2543. return CCTL;
  2544. }
  2545. s = strchrnul(spec_symbls, c);
  2546. if (*s == '\0')
  2547. return CWORD;
  2548. indx = syntax_index_table[s - spec_symbls];
  2549. }
  2550. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2551. }
  2552. #else /* !USE_SIT_FUNCTION */
  2553. static const uint8_t syntax_index_table[] = {
  2554. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2555. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2556. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2557. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2558. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2559. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2560. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2561. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2562. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2563. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2564. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2565. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2566. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2567. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2568. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2569. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2570. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2571. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2572. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2573. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2574. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2575. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2576. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2577. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2578. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2579. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2580. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2581. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2582. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2583. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2584. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2585. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2586. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2587. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2588. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2589. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2590. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2591. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2592. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2593. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2594. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2595. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2596. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2597. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2598. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2599. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2600. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2601. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2602. /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
  2603. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2604. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2605. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2606. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2607. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2608. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2609. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2610. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2611. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2612. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2613. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2614. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2615. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2616. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2617. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2618. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2619. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2620. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2621. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2622. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2623. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2624. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2625. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2626. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2627. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2628. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2629. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2630. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2631. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2632. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2633. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2634. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2635. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2636. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2637. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2638. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2639. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2640. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2641. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2642. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2643. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2644. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2645. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2646. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2647. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2648. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2649. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2650. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2651. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2652. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2653. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2654. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2655. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2656. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2657. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2658. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2659. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2660. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2661. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2662. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2663. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2664. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2665. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2666. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2667. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2668. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2669. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2670. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2671. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2672. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2673. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2674. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2675. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2676. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2677. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2678. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2679. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2680. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2681. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2682. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2683. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2684. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2685. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2686. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2687. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2688. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2689. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2690. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2691. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2692. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2693. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2694. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2695. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2696. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2697. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2698. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2699. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2700. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2701. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2702. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2703. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2704. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2705. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2706. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2707. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2708. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2709. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2710. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2711. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2712. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2713. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2714. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2715. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2716. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2717. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2718. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2719. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2720. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2721. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2722. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2723. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2724. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2725. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2726. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2727. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2728. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2729. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2730. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2731. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2732. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2733. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2734. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2735. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2736. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2737. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2738. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2739. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2740. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2741. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2742. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2743. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2744. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2745. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2746. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2747. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2748. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2749. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2750. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2751. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2752. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2753. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2755. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2756. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2757. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2758. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2759. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2760. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2761. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2762. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2763. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2764. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2765. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2766. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2767. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2768. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2769. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2770. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2771. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2781. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2811. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2812. # if ENABLE_ASH_ALIAS
  2813. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2814. # endif
  2815. };
  2816. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2817. #endif /* !USE_SIT_FUNCTION */
  2818. /* ============ Alias handling */
  2819. #if ENABLE_ASH_ALIAS
  2820. #define ALIASINUSE 1
  2821. #define ALIASDEAD 2
  2822. struct alias {
  2823. struct alias *next;
  2824. char *name;
  2825. char *val;
  2826. int flag;
  2827. };
  2828. static struct alias **atab; // [ATABSIZE];
  2829. #define INIT_G_alias() do { \
  2830. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2831. } while (0)
  2832. static struct alias **
  2833. __lookupalias(const char *name) {
  2834. unsigned int hashval;
  2835. struct alias **app;
  2836. const char *p;
  2837. unsigned int ch;
  2838. p = name;
  2839. ch = (unsigned char)*p;
  2840. hashval = ch << 4;
  2841. while (ch) {
  2842. hashval += ch;
  2843. ch = (unsigned char)*++p;
  2844. }
  2845. app = &atab[hashval % ATABSIZE];
  2846. for (; *app; app = &(*app)->next) {
  2847. if (strcmp(name, (*app)->name) == 0) {
  2848. break;
  2849. }
  2850. }
  2851. return app;
  2852. }
  2853. static struct alias *
  2854. lookupalias(const char *name, int check)
  2855. {
  2856. struct alias *ap = *__lookupalias(name);
  2857. if (check && ap && (ap->flag & ALIASINUSE))
  2858. return NULL;
  2859. return ap;
  2860. }
  2861. static struct alias *
  2862. freealias(struct alias *ap)
  2863. {
  2864. struct alias *next;
  2865. if (ap->flag & ALIASINUSE) {
  2866. ap->flag |= ALIASDEAD;
  2867. return ap;
  2868. }
  2869. next = ap->next;
  2870. free(ap->name);
  2871. free(ap->val);
  2872. free(ap);
  2873. return next;
  2874. }
  2875. static void
  2876. setalias(const char *name, const char *val)
  2877. {
  2878. struct alias *ap, **app;
  2879. app = __lookupalias(name);
  2880. ap = *app;
  2881. INT_OFF;
  2882. if (ap) {
  2883. if (!(ap->flag & ALIASINUSE)) {
  2884. free(ap->val);
  2885. }
  2886. ap->val = ckstrdup(val);
  2887. ap->flag &= ~ALIASDEAD;
  2888. } else {
  2889. /* not found */
  2890. ap = ckzalloc(sizeof(struct alias));
  2891. ap->name = ckstrdup(name);
  2892. ap->val = ckstrdup(val);
  2893. /*ap->flag = 0; - ckzalloc did it */
  2894. /*ap->next = NULL;*/
  2895. *app = ap;
  2896. }
  2897. INT_ON;
  2898. }
  2899. static int
  2900. unalias(const char *name)
  2901. {
  2902. struct alias **app;
  2903. app = __lookupalias(name);
  2904. if (*app) {
  2905. INT_OFF;
  2906. *app = freealias(*app);
  2907. INT_ON;
  2908. return 0;
  2909. }
  2910. return 1;
  2911. }
  2912. static void
  2913. rmaliases(void)
  2914. {
  2915. struct alias *ap, **app;
  2916. int i;
  2917. INT_OFF;
  2918. for (i = 0; i < ATABSIZE; i++) {
  2919. app = &atab[i];
  2920. for (ap = *app; ap; ap = *app) {
  2921. *app = freealias(*app);
  2922. if (ap == *app) {
  2923. app = &ap->next;
  2924. }
  2925. }
  2926. }
  2927. INT_ON;
  2928. }
  2929. static void
  2930. printalias(const struct alias *ap)
  2931. {
  2932. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  2933. }
  2934. /*
  2935. * TODO - sort output
  2936. */
  2937. static int FAST_FUNC
  2938. aliascmd(int argc UNUSED_PARAM, char **argv)
  2939. {
  2940. char *n, *v;
  2941. int ret = 0;
  2942. struct alias *ap;
  2943. if (!argv[1]) {
  2944. int i;
  2945. for (i = 0; i < ATABSIZE; i++) {
  2946. for (ap = atab[i]; ap; ap = ap->next) {
  2947. printalias(ap);
  2948. }
  2949. }
  2950. return 0;
  2951. }
  2952. while ((n = *++argv) != NULL) {
  2953. v = strchr(n+1, '=');
  2954. if (v == NULL) { /* n+1: funny ksh stuff */
  2955. ap = *__lookupalias(n);
  2956. if (ap == NULL) {
  2957. fprintf(stderr, "%s: %s not found\n", "alias", n);
  2958. ret = 1;
  2959. } else
  2960. printalias(ap);
  2961. } else {
  2962. *v++ = '\0';
  2963. setalias(n, v);
  2964. }
  2965. }
  2966. return ret;
  2967. }
  2968. static int FAST_FUNC
  2969. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2970. {
  2971. int i;
  2972. while ((i = nextopt("a")) != '\0') {
  2973. if (i == 'a') {
  2974. rmaliases();
  2975. return 0;
  2976. }
  2977. }
  2978. for (i = 0; *argptr; argptr++) {
  2979. if (unalias(*argptr)) {
  2980. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  2981. i = 1;
  2982. }
  2983. }
  2984. return i;
  2985. }
  2986. #endif /* ASH_ALIAS */
  2987. /* ============ jobs.c */
  2988. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  2989. #define FORK_FG 0
  2990. #define FORK_BG 1
  2991. #define FORK_NOJOB 2
  2992. /* mode flags for showjob(s) */
  2993. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  2994. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  2995. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  2996. /*
  2997. * A job structure contains information about a job. A job is either a
  2998. * single process or a set of processes contained in a pipeline. In the
  2999. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3000. * array of pids.
  3001. */
  3002. struct procstat {
  3003. pid_t ps_pid; /* process id */
  3004. int ps_status; /* last process status from wait() */
  3005. char *ps_cmd; /* text of command being run */
  3006. };
  3007. struct job {
  3008. struct procstat ps0; /* status of process */
  3009. struct procstat *ps; /* status or processes when more than one */
  3010. #if JOBS
  3011. int stopstatus; /* status of a stopped job */
  3012. #endif
  3013. uint32_t
  3014. nprocs: 16, /* number of processes */
  3015. state: 8,
  3016. #define JOBRUNNING 0 /* at least one proc running */
  3017. #define JOBSTOPPED 1 /* all procs are stopped */
  3018. #define JOBDONE 2 /* all procs are completed */
  3019. #if JOBS
  3020. sigint: 1, /* job was killed by SIGINT */
  3021. jobctl: 1, /* job running under job control */
  3022. #endif
  3023. waited: 1, /* true if this entry has been waited for */
  3024. used: 1, /* true if this entry is in used */
  3025. changed: 1; /* true if status has changed */
  3026. struct job *prev_job; /* previous job */
  3027. };
  3028. static struct job *makejob(/*union node *,*/ int);
  3029. static int forkshell(struct job *, union node *, int);
  3030. static int waitforjob(struct job *);
  3031. #if !JOBS
  3032. enum { doing_jobctl = 0 };
  3033. #define setjobctl(on) do {} while (0)
  3034. #else
  3035. static smallint doing_jobctl; //references:8
  3036. static void setjobctl(int);
  3037. #endif
  3038. /*
  3039. * Ignore a signal.
  3040. */
  3041. static void
  3042. ignoresig(int signo)
  3043. {
  3044. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3045. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3046. /* No, need to do it */
  3047. signal(signo, SIG_IGN);
  3048. }
  3049. sigmode[signo - 1] = S_HARD_IGN;
  3050. }
  3051. /*
  3052. * Only one usage site - in setsignal()
  3053. */
  3054. static void
  3055. signal_handler(int signo)
  3056. {
  3057. gotsig[signo - 1] = 1;
  3058. if (signo == SIGINT && !trap[SIGINT]) {
  3059. if (!suppress_int) {
  3060. pending_sig = 0;
  3061. raise_interrupt(); /* does not return */
  3062. }
  3063. pending_int = 1;
  3064. } else {
  3065. pending_sig = signo;
  3066. }
  3067. }
  3068. /*
  3069. * Set the signal handler for the specified signal. The routine figures
  3070. * out what it should be set to.
  3071. */
  3072. static void
  3073. setsignal(int signo)
  3074. {
  3075. char *t;
  3076. char cur_act, new_act;
  3077. struct sigaction act;
  3078. t = trap[signo];
  3079. new_act = S_DFL;
  3080. if (t != NULL) { /* trap for this sig is set */
  3081. new_act = S_CATCH;
  3082. if (t[0] == '\0') /* trap is "": ignore this sig */
  3083. new_act = S_IGN;
  3084. }
  3085. if (rootshell && new_act == S_DFL) {
  3086. switch (signo) {
  3087. case SIGINT:
  3088. if (iflag || minusc || sflag == 0)
  3089. new_act = S_CATCH;
  3090. break;
  3091. case SIGQUIT:
  3092. #if DEBUG
  3093. if (debug)
  3094. break;
  3095. #endif
  3096. /* man bash:
  3097. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3098. * commands run by bash have signal handlers
  3099. * set to the values inherited by the shell
  3100. * from its parent". */
  3101. new_act = S_IGN;
  3102. break;
  3103. case SIGTERM:
  3104. if (iflag)
  3105. new_act = S_IGN;
  3106. break;
  3107. #if JOBS
  3108. case SIGTSTP:
  3109. case SIGTTOU:
  3110. if (mflag)
  3111. new_act = S_IGN;
  3112. break;
  3113. #endif
  3114. }
  3115. }
  3116. //TODO: if !rootshell, we reset SIGQUIT to DFL,
  3117. //whereas we have to restore it to what shell got on entry
  3118. //from the parent. See comment above
  3119. t = &sigmode[signo - 1];
  3120. cur_act = *t;
  3121. if (cur_act == 0) {
  3122. /* current setting is not yet known */
  3123. if (sigaction(signo, NULL, &act)) {
  3124. /* pretend it worked; maybe we should give a warning,
  3125. * but other shells don't. We don't alter sigmode,
  3126. * so we retry every time.
  3127. * btw, in Linux it never fails. --vda */
  3128. return;
  3129. }
  3130. if (act.sa_handler == SIG_IGN) {
  3131. cur_act = S_HARD_IGN;
  3132. if (mflag
  3133. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3134. ) {
  3135. cur_act = S_IGN; /* don't hard ignore these */
  3136. }
  3137. }
  3138. }
  3139. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3140. return;
  3141. act.sa_handler = SIG_DFL;
  3142. switch (new_act) {
  3143. case S_CATCH:
  3144. act.sa_handler = signal_handler;
  3145. break;
  3146. case S_IGN:
  3147. act.sa_handler = SIG_IGN;
  3148. break;
  3149. }
  3150. /* flags and mask matter only if !DFL and !IGN, but we do it
  3151. * for all cases for more deterministic behavior:
  3152. */
  3153. act.sa_flags = 0;
  3154. sigfillset(&act.sa_mask);
  3155. sigaction_set(signo, &act);
  3156. *t = new_act;
  3157. }
  3158. /* mode flags for set_curjob */
  3159. #define CUR_DELETE 2
  3160. #define CUR_RUNNING 1
  3161. #define CUR_STOPPED 0
  3162. /* mode flags for dowait */
  3163. #define DOWAIT_NONBLOCK WNOHANG
  3164. #define DOWAIT_BLOCK 0
  3165. #if JOBS
  3166. /* pgrp of shell on invocation */
  3167. static int initialpgrp; //references:2
  3168. static int ttyfd = -1; //5
  3169. #endif
  3170. /* array of jobs */
  3171. static struct job *jobtab; //5
  3172. /* size of array */
  3173. static unsigned njobs; //4
  3174. /* current job */
  3175. static struct job *curjob; //lots
  3176. /* number of presumed living untracked jobs */
  3177. static int jobless; //4
  3178. static void
  3179. set_curjob(struct job *jp, unsigned mode)
  3180. {
  3181. struct job *jp1;
  3182. struct job **jpp, **curp;
  3183. /* first remove from list */
  3184. jpp = curp = &curjob;
  3185. while (1) {
  3186. jp1 = *jpp;
  3187. if (jp1 == jp)
  3188. break;
  3189. jpp = &jp1->prev_job;
  3190. }
  3191. *jpp = jp1->prev_job;
  3192. /* Then re-insert in correct position */
  3193. jpp = curp;
  3194. switch (mode) {
  3195. default:
  3196. #if DEBUG
  3197. abort();
  3198. #endif
  3199. case CUR_DELETE:
  3200. /* job being deleted */
  3201. break;
  3202. case CUR_RUNNING:
  3203. /* newly created job or backgrounded job,
  3204. put after all stopped jobs. */
  3205. while (1) {
  3206. jp1 = *jpp;
  3207. #if JOBS
  3208. if (!jp1 || jp1->state != JOBSTOPPED)
  3209. #endif
  3210. break;
  3211. jpp = &jp1->prev_job;
  3212. }
  3213. /* FALLTHROUGH */
  3214. #if JOBS
  3215. case CUR_STOPPED:
  3216. #endif
  3217. /* newly stopped job - becomes curjob */
  3218. jp->prev_job = *jpp;
  3219. *jpp = jp;
  3220. break;
  3221. }
  3222. }
  3223. #if JOBS || DEBUG
  3224. static int
  3225. jobno(const struct job *jp)
  3226. {
  3227. return jp - jobtab + 1;
  3228. }
  3229. #endif
  3230. /*
  3231. * Convert a job name to a job structure.
  3232. */
  3233. #if !JOBS
  3234. #define getjob(name, getctl) getjob(name)
  3235. #endif
  3236. static struct job *
  3237. getjob(const char *name, int getctl)
  3238. {
  3239. struct job *jp;
  3240. struct job *found;
  3241. const char *err_msg = "%s: no such job";
  3242. unsigned num;
  3243. int c;
  3244. const char *p;
  3245. char *(*match)(const char *, const char *);
  3246. jp = curjob;
  3247. p = name;
  3248. if (!p)
  3249. goto currentjob;
  3250. if (*p != '%')
  3251. goto err;
  3252. c = *++p;
  3253. if (!c)
  3254. goto currentjob;
  3255. if (!p[1]) {
  3256. if (c == '+' || c == '%') {
  3257. currentjob:
  3258. err_msg = "No current job";
  3259. goto check;
  3260. }
  3261. if (c == '-') {
  3262. if (jp)
  3263. jp = jp->prev_job;
  3264. err_msg = "No previous job";
  3265. check:
  3266. if (!jp)
  3267. goto err;
  3268. goto gotit;
  3269. }
  3270. }
  3271. if (is_number(p)) {
  3272. num = atoi(p);
  3273. if (num < njobs) {
  3274. jp = jobtab + num - 1;
  3275. if (jp->used)
  3276. goto gotit;
  3277. goto err;
  3278. }
  3279. }
  3280. match = prefix;
  3281. if (*p == '?') {
  3282. match = strstr;
  3283. p++;
  3284. }
  3285. found = NULL;
  3286. while (jp) {
  3287. if (match(jp->ps[0].ps_cmd, p)) {
  3288. if (found)
  3289. goto err;
  3290. found = jp;
  3291. err_msg = "%s: ambiguous";
  3292. }
  3293. jp = jp->prev_job;
  3294. }
  3295. if (!found)
  3296. goto err;
  3297. jp = found;
  3298. gotit:
  3299. #if JOBS
  3300. err_msg = "job %s not created under job control";
  3301. if (getctl && jp->jobctl == 0)
  3302. goto err;
  3303. #endif
  3304. return jp;
  3305. err:
  3306. ash_msg_and_raise_error(err_msg, name);
  3307. }
  3308. /*
  3309. * Mark a job structure as unused.
  3310. */
  3311. static void
  3312. freejob(struct job *jp)
  3313. {
  3314. struct procstat *ps;
  3315. int i;
  3316. INT_OFF;
  3317. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3318. if (ps->ps_cmd != nullstr)
  3319. free(ps->ps_cmd);
  3320. }
  3321. if (jp->ps != &jp->ps0)
  3322. free(jp->ps);
  3323. jp->used = 0;
  3324. set_curjob(jp, CUR_DELETE);
  3325. INT_ON;
  3326. }
  3327. #if JOBS
  3328. static void
  3329. xtcsetpgrp(int fd, pid_t pgrp)
  3330. {
  3331. if (tcsetpgrp(fd, pgrp))
  3332. ash_msg_and_raise_error("can't set tty process group (%m)");
  3333. }
  3334. /*
  3335. * Turn job control on and off.
  3336. *
  3337. * Note: This code assumes that the third arg to ioctl is a character
  3338. * pointer, which is true on Berkeley systems but not System V. Since
  3339. * System V doesn't have job control yet, this isn't a problem now.
  3340. *
  3341. * Called with interrupts off.
  3342. */
  3343. static void
  3344. setjobctl(int on)
  3345. {
  3346. int fd;
  3347. int pgrp;
  3348. if (on == doing_jobctl || rootshell == 0)
  3349. return;
  3350. if (on) {
  3351. int ofd;
  3352. ofd = fd = open(_PATH_TTY, O_RDWR);
  3353. if (fd < 0) {
  3354. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3355. * That sometimes helps to acquire controlling tty.
  3356. * Obviously, a workaround for bugs when someone
  3357. * failed to provide a controlling tty to bash! :) */
  3358. fd = 2;
  3359. while (!isatty(fd))
  3360. if (--fd < 0)
  3361. goto out;
  3362. }
  3363. fd = fcntl(fd, F_DUPFD, 10);
  3364. if (ofd >= 0)
  3365. close(ofd);
  3366. if (fd < 0)
  3367. goto out;
  3368. /* fd is a tty at this point */
  3369. close_on_exec_on(fd);
  3370. while (1) { /* while we are in the background */
  3371. pgrp = tcgetpgrp(fd);
  3372. if (pgrp < 0) {
  3373. out:
  3374. ash_msg("can't access tty; job control turned off");
  3375. mflag = on = 0;
  3376. goto close;
  3377. }
  3378. if (pgrp == getpgrp())
  3379. break;
  3380. killpg(0, SIGTTIN);
  3381. }
  3382. initialpgrp = pgrp;
  3383. setsignal(SIGTSTP);
  3384. setsignal(SIGTTOU);
  3385. setsignal(SIGTTIN);
  3386. pgrp = rootpid;
  3387. setpgid(0, pgrp);
  3388. xtcsetpgrp(fd, pgrp);
  3389. } else {
  3390. /* turning job control off */
  3391. fd = ttyfd;
  3392. pgrp = initialpgrp;
  3393. /* was xtcsetpgrp, but this can make exiting ash
  3394. * loop forever if pty is already deleted */
  3395. tcsetpgrp(fd, pgrp);
  3396. setpgid(0, pgrp);
  3397. setsignal(SIGTSTP);
  3398. setsignal(SIGTTOU);
  3399. setsignal(SIGTTIN);
  3400. close:
  3401. if (fd >= 0)
  3402. close(fd);
  3403. fd = -1;
  3404. }
  3405. ttyfd = fd;
  3406. doing_jobctl = on;
  3407. }
  3408. static int FAST_FUNC
  3409. killcmd(int argc, char **argv)
  3410. {
  3411. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3412. int i = 1;
  3413. do {
  3414. if (argv[i][0] == '%') {
  3415. /*
  3416. * "kill %N" - job kill
  3417. * Converting to pgrp / pid kill
  3418. */
  3419. struct job *jp;
  3420. char *dst;
  3421. int j, n;
  3422. jp = getjob(argv[i], 0);
  3423. /*
  3424. * In jobs started under job control, we signal
  3425. * entire process group by kill -PGRP_ID.
  3426. * This happens, f.e., in interactive shell.
  3427. *
  3428. * Otherwise, we signal each child via
  3429. * kill PID1 PID2 PID3.
  3430. * Testcases:
  3431. * sh -c 'sleep 1|sleep 1 & kill %1'
  3432. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3433. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3434. */
  3435. n = jp->nprocs; /* can't be 0 (I hope) */
  3436. if (jp->jobctl)
  3437. n = 1;
  3438. dst = alloca(n * sizeof(int)*4);
  3439. argv[i] = dst;
  3440. for (j = 0; j < n; j++) {
  3441. struct procstat *ps = &jp->ps[j];
  3442. /* Skip non-running and not-stopped members
  3443. * (i.e. dead members) of the job
  3444. */
  3445. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3446. continue;
  3447. /*
  3448. * kill_main has matching code to expect
  3449. * leading space. Needed to not confuse
  3450. * negative pids with "kill -SIGNAL_NO" syntax
  3451. */
  3452. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3453. }
  3454. *dst = '\0';
  3455. }
  3456. } while (argv[++i]);
  3457. }
  3458. return kill_main(argc, argv);
  3459. }
  3460. static void
  3461. showpipe(struct job *jp /*, FILE *out*/)
  3462. {
  3463. struct procstat *ps;
  3464. struct procstat *psend;
  3465. psend = jp->ps + jp->nprocs;
  3466. for (ps = jp->ps + 1; ps < psend; ps++)
  3467. printf(" | %s", ps->ps_cmd);
  3468. outcslow('\n', stdout);
  3469. flush_stdout_stderr();
  3470. }
  3471. static int
  3472. restartjob(struct job *jp, int mode)
  3473. {
  3474. struct procstat *ps;
  3475. int i;
  3476. int status;
  3477. pid_t pgid;
  3478. INT_OFF;
  3479. if (jp->state == JOBDONE)
  3480. goto out;
  3481. jp->state = JOBRUNNING;
  3482. pgid = jp->ps[0].ps_pid;
  3483. if (mode == FORK_FG)
  3484. xtcsetpgrp(ttyfd, pgid);
  3485. killpg(pgid, SIGCONT);
  3486. ps = jp->ps;
  3487. i = jp->nprocs;
  3488. do {
  3489. if (WIFSTOPPED(ps->ps_status)) {
  3490. ps->ps_status = -1;
  3491. }
  3492. ps++;
  3493. } while (--i);
  3494. out:
  3495. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3496. INT_ON;
  3497. return status;
  3498. }
  3499. static int FAST_FUNC
  3500. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3501. {
  3502. struct job *jp;
  3503. int mode;
  3504. int retval;
  3505. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3506. nextopt(nullstr);
  3507. argv = argptr;
  3508. do {
  3509. jp = getjob(*argv, 1);
  3510. if (mode == FORK_BG) {
  3511. set_curjob(jp, CUR_RUNNING);
  3512. printf("[%d] ", jobno(jp));
  3513. }
  3514. out1str(jp->ps[0].ps_cmd);
  3515. showpipe(jp /*, stdout*/);
  3516. retval = restartjob(jp, mode);
  3517. } while (*argv && *++argv);
  3518. return retval;
  3519. }
  3520. #endif
  3521. static int
  3522. sprint_status(char *s, int status, int sigonly)
  3523. {
  3524. int col;
  3525. int st;
  3526. col = 0;
  3527. if (!WIFEXITED(status)) {
  3528. #if JOBS
  3529. if (WIFSTOPPED(status))
  3530. st = WSTOPSIG(status);
  3531. else
  3532. #endif
  3533. st = WTERMSIG(status);
  3534. if (sigonly) {
  3535. if (st == SIGINT || st == SIGPIPE)
  3536. goto out;
  3537. #if JOBS
  3538. if (WIFSTOPPED(status))
  3539. goto out;
  3540. #endif
  3541. }
  3542. st &= 0x7f;
  3543. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3544. col = fmtstr(s, 32, strsignal(st));
  3545. if (WCOREDUMP(status)) {
  3546. col += fmtstr(s + col, 16, " (core dumped)");
  3547. }
  3548. } else if (!sigonly) {
  3549. st = WEXITSTATUS(status);
  3550. if (st)
  3551. col = fmtstr(s, 16, "Done(%d)", st);
  3552. else
  3553. col = fmtstr(s, 16, "Done");
  3554. }
  3555. out:
  3556. return col;
  3557. }
  3558. static int
  3559. dowait(int wait_flags, struct job *job)
  3560. {
  3561. int pid;
  3562. int status;
  3563. struct job *jp;
  3564. struct job *thisjob;
  3565. int state;
  3566. TRACE(("dowait(0x%x) called\n", wait_flags));
  3567. /* Do a wait system call. If job control is compiled in, we accept
  3568. * stopped processes. wait_flags may have WNOHANG, preventing blocking.
  3569. * NB: _not_ safe_waitpid, we need to detect EINTR */
  3570. if (doing_jobctl)
  3571. wait_flags |= WUNTRACED;
  3572. pid = waitpid(-1, &status, wait_flags);
  3573. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3574. pid, status, errno, strerror(errno)));
  3575. if (pid <= 0)
  3576. return pid;
  3577. INT_OFF;
  3578. thisjob = NULL;
  3579. for (jp = curjob; jp; jp = jp->prev_job) {
  3580. struct procstat *ps;
  3581. struct procstat *psend;
  3582. if (jp->state == JOBDONE)
  3583. continue;
  3584. state = JOBDONE;
  3585. ps = jp->ps;
  3586. psend = ps + jp->nprocs;
  3587. do {
  3588. if (ps->ps_pid == pid) {
  3589. TRACE(("Job %d: changing status of proc %d "
  3590. "from 0x%x to 0x%x\n",
  3591. jobno(jp), pid, ps->ps_status, status));
  3592. ps->ps_status = status;
  3593. thisjob = jp;
  3594. }
  3595. if (ps->ps_status == -1)
  3596. state = JOBRUNNING;
  3597. #if JOBS
  3598. if (state == JOBRUNNING)
  3599. continue;
  3600. if (WIFSTOPPED(ps->ps_status)) {
  3601. jp->stopstatus = ps->ps_status;
  3602. state = JOBSTOPPED;
  3603. }
  3604. #endif
  3605. } while (++ps < psend);
  3606. if (thisjob)
  3607. goto gotjob;
  3608. }
  3609. #if JOBS
  3610. if (!WIFSTOPPED(status))
  3611. #endif
  3612. jobless--;
  3613. goto out;
  3614. gotjob:
  3615. if (state != JOBRUNNING) {
  3616. thisjob->changed = 1;
  3617. if (thisjob->state != state) {
  3618. TRACE(("Job %d: changing state from %d to %d\n",
  3619. jobno(thisjob), thisjob->state, state));
  3620. thisjob->state = state;
  3621. #if JOBS
  3622. if (state == JOBSTOPPED) {
  3623. set_curjob(thisjob, CUR_STOPPED);
  3624. }
  3625. #endif
  3626. }
  3627. }
  3628. out:
  3629. INT_ON;
  3630. if (thisjob && thisjob == job) {
  3631. char s[48 + 1];
  3632. int len;
  3633. len = sprint_status(s, status, 1);
  3634. if (len) {
  3635. s[len] = '\n';
  3636. s[len + 1] = '\0';
  3637. out2str(s);
  3638. }
  3639. }
  3640. return pid;
  3641. }
  3642. static int
  3643. blocking_wait_with_raise_on_sig(void)
  3644. {
  3645. pid_t pid = dowait(DOWAIT_BLOCK, NULL);
  3646. if (pid <= 0 && pending_sig)
  3647. raise_exception(EXSIG);
  3648. return pid;
  3649. }
  3650. #if JOBS
  3651. static void
  3652. showjob(FILE *out, struct job *jp, int mode)
  3653. {
  3654. struct procstat *ps;
  3655. struct procstat *psend;
  3656. int col;
  3657. int indent_col;
  3658. char s[80];
  3659. ps = jp->ps;
  3660. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3661. /* just output process (group) id of pipeline */
  3662. fprintf(out, "%d\n", ps->ps_pid);
  3663. return;
  3664. }
  3665. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3666. indent_col = col;
  3667. if (jp == curjob)
  3668. s[col - 3] = '+';
  3669. else if (curjob && jp == curjob->prev_job)
  3670. s[col - 3] = '-';
  3671. if (mode & SHOW_PIDS)
  3672. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3673. psend = ps + jp->nprocs;
  3674. if (jp->state == JOBRUNNING) {
  3675. strcpy(s + col, "Running");
  3676. col += sizeof("Running") - 1;
  3677. } else {
  3678. int status = psend[-1].ps_status;
  3679. if (jp->state == JOBSTOPPED)
  3680. status = jp->stopstatus;
  3681. col += sprint_status(s + col, status, 0);
  3682. }
  3683. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3684. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3685. * or prints several "PID | <cmdN>" lines,
  3686. * depending on SHOW_PIDS bit.
  3687. * We do not print status of individual processes
  3688. * between PID and <cmdN>. bash does it, but not very well:
  3689. * first line shows overall job status, not process status,
  3690. * making it impossible to know 1st process status.
  3691. */
  3692. goto start;
  3693. do {
  3694. /* for each process */
  3695. s[0] = '\0';
  3696. col = 33;
  3697. if (mode & SHOW_PIDS)
  3698. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3699. start:
  3700. fprintf(out, "%s%*c%s%s",
  3701. s,
  3702. 33 - col >= 0 ? 33 - col : 0, ' ',
  3703. ps == jp->ps ? "" : "| ",
  3704. ps->ps_cmd
  3705. );
  3706. } while (++ps != psend);
  3707. outcslow('\n', out);
  3708. jp->changed = 0;
  3709. if (jp->state == JOBDONE) {
  3710. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3711. freejob(jp);
  3712. }
  3713. }
  3714. /*
  3715. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3716. * statuses have changed since the last call to showjobs.
  3717. */
  3718. static void
  3719. showjobs(FILE *out, int mode)
  3720. {
  3721. struct job *jp;
  3722. TRACE(("showjobs(0x%x) called\n", mode));
  3723. /* Handle all finished jobs */
  3724. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3725. continue;
  3726. for (jp = curjob; jp; jp = jp->prev_job) {
  3727. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3728. showjob(out, jp, mode);
  3729. }
  3730. }
  3731. }
  3732. static int FAST_FUNC
  3733. jobscmd(int argc UNUSED_PARAM, char **argv)
  3734. {
  3735. int mode, m;
  3736. mode = 0;
  3737. while ((m = nextopt("lp")) != '\0') {
  3738. if (m == 'l')
  3739. mode |= SHOW_PIDS;
  3740. else
  3741. mode |= SHOW_ONLY_PGID;
  3742. }
  3743. argv = argptr;
  3744. if (*argv) {
  3745. do
  3746. showjob(stdout, getjob(*argv, 0), mode);
  3747. while (*++argv);
  3748. } else {
  3749. showjobs(stdout, mode);
  3750. }
  3751. return 0;
  3752. }
  3753. #endif /* JOBS */
  3754. /* Called only on finished or stopped jobs (no members are running) */
  3755. static int
  3756. getstatus(struct job *job)
  3757. {
  3758. int status;
  3759. int retval;
  3760. struct procstat *ps;
  3761. /* Fetch last member's status */
  3762. ps = job->ps + job->nprocs - 1;
  3763. status = ps->ps_status;
  3764. if (pipefail) {
  3765. /* "set -o pipefail" mode: use last _nonzero_ status */
  3766. while (status == 0 && --ps >= job->ps)
  3767. status = ps->ps_status;
  3768. }
  3769. retval = WEXITSTATUS(status);
  3770. if (!WIFEXITED(status)) {
  3771. #if JOBS
  3772. retval = WSTOPSIG(status);
  3773. if (!WIFSTOPPED(status))
  3774. #endif
  3775. {
  3776. /* XXX: limits number of signals */
  3777. retval = WTERMSIG(status);
  3778. #if JOBS
  3779. if (retval == SIGINT)
  3780. job->sigint = 1;
  3781. #endif
  3782. }
  3783. retval += 128;
  3784. }
  3785. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  3786. jobno(job), job->nprocs, status, retval));
  3787. return retval;
  3788. }
  3789. static int FAST_FUNC
  3790. waitcmd(int argc UNUSED_PARAM, char **argv)
  3791. {
  3792. struct job *job;
  3793. int retval;
  3794. struct job *jp;
  3795. if (pending_sig)
  3796. raise_exception(EXSIG);
  3797. nextopt(nullstr);
  3798. retval = 0;
  3799. argv = argptr;
  3800. if (!*argv) {
  3801. /* wait for all jobs */
  3802. for (;;) {
  3803. jp = curjob;
  3804. while (1) {
  3805. if (!jp) /* no running procs */
  3806. goto ret;
  3807. if (jp->state == JOBRUNNING)
  3808. break;
  3809. jp->waited = 1;
  3810. jp = jp->prev_job;
  3811. }
  3812. blocking_wait_with_raise_on_sig();
  3813. /* man bash:
  3814. * "When bash is waiting for an asynchronous command via
  3815. * the wait builtin, the reception of a signal for which a trap
  3816. * has been set will cause the wait builtin to return immediately
  3817. * with an exit status greater than 128, immediately after which
  3818. * the trap is executed."
  3819. *
  3820. * blocking_wait_with_raise_on_sig raises signal handlers
  3821. * if it gets no pid (pid < 0). However,
  3822. * if child sends us a signal *and immediately exits*,
  3823. * blocking_wait_with_raise_on_sig gets pid > 0
  3824. * and does not handle pending_sig. Check this case: */
  3825. if (pending_sig)
  3826. raise_exception(EXSIG);
  3827. }
  3828. }
  3829. retval = 127;
  3830. do {
  3831. if (**argv != '%') {
  3832. pid_t pid = number(*argv);
  3833. job = curjob;
  3834. while (1) {
  3835. if (!job)
  3836. goto repeat;
  3837. if (job->ps[job->nprocs - 1].ps_pid == pid)
  3838. break;
  3839. job = job->prev_job;
  3840. }
  3841. } else {
  3842. job = getjob(*argv, 0);
  3843. }
  3844. /* loop until process terminated or stopped */
  3845. while (job->state == JOBRUNNING)
  3846. blocking_wait_with_raise_on_sig();
  3847. job->waited = 1;
  3848. retval = getstatus(job);
  3849. repeat: ;
  3850. } while (*++argv);
  3851. ret:
  3852. return retval;
  3853. }
  3854. static struct job *
  3855. growjobtab(void)
  3856. {
  3857. size_t len;
  3858. ptrdiff_t offset;
  3859. struct job *jp, *jq;
  3860. len = njobs * sizeof(*jp);
  3861. jq = jobtab;
  3862. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  3863. offset = (char *)jp - (char *)jq;
  3864. if (offset) {
  3865. /* Relocate pointers */
  3866. size_t l = len;
  3867. jq = (struct job *)((char *)jq + l);
  3868. while (l) {
  3869. l -= sizeof(*jp);
  3870. jq--;
  3871. #define joff(p) ((struct job *)((char *)(p) + l))
  3872. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  3873. if (joff(jp)->ps == &jq->ps0)
  3874. jmove(joff(jp)->ps);
  3875. if (joff(jp)->prev_job)
  3876. jmove(joff(jp)->prev_job);
  3877. }
  3878. if (curjob)
  3879. jmove(curjob);
  3880. #undef joff
  3881. #undef jmove
  3882. }
  3883. njobs += 4;
  3884. jobtab = jp;
  3885. jp = (struct job *)((char *)jp + len);
  3886. jq = jp + 3;
  3887. do {
  3888. jq->used = 0;
  3889. } while (--jq >= jp);
  3890. return jp;
  3891. }
  3892. /*
  3893. * Return a new job structure.
  3894. * Called with interrupts off.
  3895. */
  3896. static struct job *
  3897. makejob(/*union node *node,*/ int nprocs)
  3898. {
  3899. int i;
  3900. struct job *jp;
  3901. for (i = njobs, jp = jobtab; ; jp++) {
  3902. if (--i < 0) {
  3903. jp = growjobtab();
  3904. break;
  3905. }
  3906. if (jp->used == 0)
  3907. break;
  3908. if (jp->state != JOBDONE || !jp->waited)
  3909. continue;
  3910. #if JOBS
  3911. if (doing_jobctl)
  3912. continue;
  3913. #endif
  3914. freejob(jp);
  3915. break;
  3916. }
  3917. memset(jp, 0, sizeof(*jp));
  3918. #if JOBS
  3919. /* jp->jobctl is a bitfield.
  3920. * "jp->jobctl |= jobctl" likely to give awful code */
  3921. if (doing_jobctl)
  3922. jp->jobctl = 1;
  3923. #endif
  3924. jp->prev_job = curjob;
  3925. curjob = jp;
  3926. jp->used = 1;
  3927. jp->ps = &jp->ps0;
  3928. if (nprocs > 1) {
  3929. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  3930. }
  3931. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  3932. jobno(jp)));
  3933. return jp;
  3934. }
  3935. #if JOBS
  3936. /*
  3937. * Return a string identifying a command (to be printed by the
  3938. * jobs command).
  3939. */
  3940. static char *cmdnextc;
  3941. static void
  3942. cmdputs(const char *s)
  3943. {
  3944. static const char vstype[VSTYPE + 1][3] = {
  3945. "", "}", "-", "+", "?", "=",
  3946. "%", "%%", "#", "##"
  3947. IF_ASH_BASH_COMPAT(, ":", "/", "//")
  3948. };
  3949. const char *p, *str;
  3950. char cc[2];
  3951. char *nextc;
  3952. unsigned char c;
  3953. unsigned char subtype = 0;
  3954. int quoted = 0;
  3955. cc[1] = '\0';
  3956. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  3957. p = s;
  3958. while ((c = *p++) != '\0') {
  3959. str = NULL;
  3960. switch (c) {
  3961. case CTLESC:
  3962. c = *p++;
  3963. break;
  3964. case CTLVAR:
  3965. subtype = *p++;
  3966. if ((subtype & VSTYPE) == VSLENGTH)
  3967. str = "${#";
  3968. else
  3969. str = "${";
  3970. if (!(subtype & VSQUOTE) == !(quoted & 1))
  3971. goto dostr;
  3972. quoted ^= 1;
  3973. c = '"';
  3974. break;
  3975. case CTLENDVAR:
  3976. str = "\"}" + !(quoted & 1);
  3977. quoted >>= 1;
  3978. subtype = 0;
  3979. goto dostr;
  3980. case CTLBACKQ:
  3981. str = "$(...)";
  3982. goto dostr;
  3983. case CTLBACKQ+CTLQUOTE:
  3984. str = "\"$(...)\"";
  3985. goto dostr;
  3986. #if ENABLE_SH_MATH_SUPPORT
  3987. case CTLARI:
  3988. str = "$((";
  3989. goto dostr;
  3990. case CTLENDARI:
  3991. str = "))";
  3992. goto dostr;
  3993. #endif
  3994. case CTLQUOTEMARK:
  3995. quoted ^= 1;
  3996. c = '"';
  3997. break;
  3998. case '=':
  3999. if (subtype == 0)
  4000. break;
  4001. if ((subtype & VSTYPE) != VSNORMAL)
  4002. quoted <<= 1;
  4003. str = vstype[subtype & VSTYPE];
  4004. if (subtype & VSNUL)
  4005. c = ':';
  4006. else
  4007. goto checkstr;
  4008. break;
  4009. case '\'':
  4010. case '\\':
  4011. case '"':
  4012. case '$':
  4013. /* These can only happen inside quotes */
  4014. cc[0] = c;
  4015. str = cc;
  4016. c = '\\';
  4017. break;
  4018. default:
  4019. break;
  4020. }
  4021. USTPUTC(c, nextc);
  4022. checkstr:
  4023. if (!str)
  4024. continue;
  4025. dostr:
  4026. while ((c = *str++) != '\0') {
  4027. USTPUTC(c, nextc);
  4028. }
  4029. } /* while *p++ not NUL */
  4030. if (quoted & 1) {
  4031. USTPUTC('"', nextc);
  4032. }
  4033. *nextc = 0;
  4034. cmdnextc = nextc;
  4035. }
  4036. /* cmdtxt() and cmdlist() call each other */
  4037. static void cmdtxt(union node *n);
  4038. static void
  4039. cmdlist(union node *np, int sep)
  4040. {
  4041. for (; np; np = np->narg.next) {
  4042. if (!sep)
  4043. cmdputs(" ");
  4044. cmdtxt(np);
  4045. if (sep && np->narg.next)
  4046. cmdputs(" ");
  4047. }
  4048. }
  4049. static void
  4050. cmdtxt(union node *n)
  4051. {
  4052. union node *np;
  4053. struct nodelist *lp;
  4054. const char *p;
  4055. if (!n)
  4056. return;
  4057. switch (n->type) {
  4058. default:
  4059. #if DEBUG
  4060. abort();
  4061. #endif
  4062. case NPIPE:
  4063. lp = n->npipe.cmdlist;
  4064. for (;;) {
  4065. cmdtxt(lp->n);
  4066. lp = lp->next;
  4067. if (!lp)
  4068. break;
  4069. cmdputs(" | ");
  4070. }
  4071. break;
  4072. case NSEMI:
  4073. p = "; ";
  4074. goto binop;
  4075. case NAND:
  4076. p = " && ";
  4077. goto binop;
  4078. case NOR:
  4079. p = " || ";
  4080. binop:
  4081. cmdtxt(n->nbinary.ch1);
  4082. cmdputs(p);
  4083. n = n->nbinary.ch2;
  4084. goto donode;
  4085. case NREDIR:
  4086. case NBACKGND:
  4087. n = n->nredir.n;
  4088. goto donode;
  4089. case NNOT:
  4090. cmdputs("!");
  4091. n = n->nnot.com;
  4092. donode:
  4093. cmdtxt(n);
  4094. break;
  4095. case NIF:
  4096. cmdputs("if ");
  4097. cmdtxt(n->nif.test);
  4098. cmdputs("; then ");
  4099. if (n->nif.elsepart) {
  4100. cmdtxt(n->nif.ifpart);
  4101. cmdputs("; else ");
  4102. n = n->nif.elsepart;
  4103. } else {
  4104. n = n->nif.ifpart;
  4105. }
  4106. p = "; fi";
  4107. goto dotail;
  4108. case NSUBSHELL:
  4109. cmdputs("(");
  4110. n = n->nredir.n;
  4111. p = ")";
  4112. goto dotail;
  4113. case NWHILE:
  4114. p = "while ";
  4115. goto until;
  4116. case NUNTIL:
  4117. p = "until ";
  4118. until:
  4119. cmdputs(p);
  4120. cmdtxt(n->nbinary.ch1);
  4121. n = n->nbinary.ch2;
  4122. p = "; done";
  4123. dodo:
  4124. cmdputs("; do ");
  4125. dotail:
  4126. cmdtxt(n);
  4127. goto dotail2;
  4128. case NFOR:
  4129. cmdputs("for ");
  4130. cmdputs(n->nfor.var);
  4131. cmdputs(" in ");
  4132. cmdlist(n->nfor.args, 1);
  4133. n = n->nfor.body;
  4134. p = "; done";
  4135. goto dodo;
  4136. case NDEFUN:
  4137. cmdputs(n->narg.text);
  4138. p = "() { ... }";
  4139. goto dotail2;
  4140. case NCMD:
  4141. cmdlist(n->ncmd.args, 1);
  4142. cmdlist(n->ncmd.redirect, 0);
  4143. break;
  4144. case NARG:
  4145. p = n->narg.text;
  4146. dotail2:
  4147. cmdputs(p);
  4148. break;
  4149. case NHERE:
  4150. case NXHERE:
  4151. p = "<<...";
  4152. goto dotail2;
  4153. case NCASE:
  4154. cmdputs("case ");
  4155. cmdputs(n->ncase.expr->narg.text);
  4156. cmdputs(" in ");
  4157. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4158. cmdtxt(np->nclist.pattern);
  4159. cmdputs(") ");
  4160. cmdtxt(np->nclist.body);
  4161. cmdputs(";; ");
  4162. }
  4163. p = "esac";
  4164. goto dotail2;
  4165. case NTO:
  4166. p = ">";
  4167. goto redir;
  4168. case NCLOBBER:
  4169. p = ">|";
  4170. goto redir;
  4171. case NAPPEND:
  4172. p = ">>";
  4173. goto redir;
  4174. #if ENABLE_ASH_BASH_COMPAT
  4175. case NTO2:
  4176. #endif
  4177. case NTOFD:
  4178. p = ">&";
  4179. goto redir;
  4180. case NFROM:
  4181. p = "<";
  4182. goto redir;
  4183. case NFROMFD:
  4184. p = "<&";
  4185. goto redir;
  4186. case NFROMTO:
  4187. p = "<>";
  4188. redir:
  4189. cmdputs(utoa(n->nfile.fd));
  4190. cmdputs(p);
  4191. if (n->type == NTOFD || n->type == NFROMFD) {
  4192. cmdputs(utoa(n->ndup.dupfd));
  4193. break;
  4194. }
  4195. n = n->nfile.fname;
  4196. goto donode;
  4197. }
  4198. }
  4199. static char *
  4200. commandtext(union node *n)
  4201. {
  4202. char *name;
  4203. STARTSTACKSTR(cmdnextc);
  4204. cmdtxt(n);
  4205. name = stackblock();
  4206. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  4207. name, cmdnextc, cmdnextc));
  4208. return ckstrdup(name);
  4209. }
  4210. #endif /* JOBS */
  4211. /*
  4212. * Fork off a subshell. If we are doing job control, give the subshell its
  4213. * own process group. Jp is a job structure that the job is to be added to.
  4214. * N is the command that will be evaluated by the child. Both jp and n may
  4215. * be NULL. The mode parameter can be one of the following:
  4216. * FORK_FG - Fork off a foreground process.
  4217. * FORK_BG - Fork off a background process.
  4218. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4219. * process group even if job control is on.
  4220. *
  4221. * When job control is turned off, background processes have their standard
  4222. * input redirected to /dev/null (except for the second and later processes
  4223. * in a pipeline).
  4224. *
  4225. * Called with interrupts off.
  4226. */
  4227. /*
  4228. * Clear traps on a fork.
  4229. */
  4230. static void
  4231. clear_traps(void)
  4232. {
  4233. char **tp;
  4234. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4235. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4236. INT_OFF;
  4237. if (trap_ptr == trap)
  4238. free(*tp);
  4239. /* else: it "belongs" to trap_ptr vector, don't free */
  4240. *tp = NULL;
  4241. if ((tp - trap) != 0)
  4242. setsignal(tp - trap);
  4243. INT_ON;
  4244. }
  4245. }
  4246. may_have_traps = 0;
  4247. }
  4248. /* Lives far away from here, needed for forkchild */
  4249. static void closescript(void);
  4250. /* Called after fork(), in child */
  4251. static NOINLINE void
  4252. forkchild(struct job *jp, union node *n, int mode)
  4253. {
  4254. int oldlvl;
  4255. TRACE(("Child shell %d\n", getpid()));
  4256. oldlvl = shlvl;
  4257. shlvl++;
  4258. /* man bash: "Non-builtin commands run by bash have signal handlers
  4259. * set to the values inherited by the shell from its parent".
  4260. * Do we do it correctly? */
  4261. closescript();
  4262. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4263. && n && n->type == NCMD /* is it single cmd? */
  4264. /* && n->ncmd.args->type == NARG - always true? */
  4265. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4266. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4267. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4268. ) {
  4269. TRACE(("Trap hack\n"));
  4270. /* Awful hack for `trap` or $(trap).
  4271. *
  4272. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4273. * contains an example where "trap" is executed in a subshell:
  4274. *
  4275. * save_traps=$(trap)
  4276. * ...
  4277. * eval "$save_traps"
  4278. *
  4279. * Standard does not say that "trap" in subshell shall print
  4280. * parent shell's traps. It only says that its output
  4281. * must have suitable form, but then, in the above example
  4282. * (which is not supposed to be normative), it implies that.
  4283. *
  4284. * bash (and probably other shell) does implement it
  4285. * (traps are reset to defaults, but "trap" still shows them),
  4286. * but as a result, "trap" logic is hopelessly messed up:
  4287. *
  4288. * # trap
  4289. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4290. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4291. * # true | trap <--- trap is in subshell - no output (ditto)
  4292. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4293. * trap -- 'echo Ho' SIGWINCH
  4294. * # echo `(trap)` <--- in subshell in subshell - output
  4295. * trap -- 'echo Ho' SIGWINCH
  4296. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4297. * trap -- 'echo Ho' SIGWINCH
  4298. *
  4299. * The rules when to forget and when to not forget traps
  4300. * get really complex and nonsensical.
  4301. *
  4302. * Our solution: ONLY bare $(trap) or `trap` is special.
  4303. */
  4304. /* Save trap handler strings for trap builtin to print */
  4305. trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
  4306. /* Fall through into clearing traps */
  4307. }
  4308. clear_traps();
  4309. #if JOBS
  4310. /* do job control only in root shell */
  4311. doing_jobctl = 0;
  4312. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4313. pid_t pgrp;
  4314. if (jp->nprocs == 0)
  4315. pgrp = getpid();
  4316. else
  4317. pgrp = jp->ps[0].ps_pid;
  4318. /* this can fail because we are doing it in the parent also */
  4319. setpgid(0, pgrp);
  4320. if (mode == FORK_FG)
  4321. xtcsetpgrp(ttyfd, pgrp);
  4322. setsignal(SIGTSTP);
  4323. setsignal(SIGTTOU);
  4324. } else
  4325. #endif
  4326. if (mode == FORK_BG) {
  4327. /* man bash: "When job control is not in effect,
  4328. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4329. ignoresig(SIGINT);
  4330. ignoresig(SIGQUIT);
  4331. if (jp->nprocs == 0) {
  4332. close(0);
  4333. if (open(bb_dev_null, O_RDONLY) != 0)
  4334. ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
  4335. }
  4336. }
  4337. if (oldlvl == 0) {
  4338. if (iflag) { /* why if iflag only? */
  4339. setsignal(SIGINT);
  4340. setsignal(SIGTERM);
  4341. }
  4342. /* man bash:
  4343. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4344. * commands run by bash have signal handlers
  4345. * set to the values inherited by the shell
  4346. * from its parent".
  4347. * Take care of the second rule: */
  4348. setsignal(SIGQUIT);
  4349. }
  4350. #if JOBS
  4351. if (n && n->type == NCMD
  4352. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4353. ) {
  4354. TRACE(("Job hack\n"));
  4355. /* "jobs": we do not want to clear job list for it,
  4356. * instead we remove only _its_ own_ job from job list.
  4357. * This makes "jobs .... | cat" more useful.
  4358. */
  4359. freejob(curjob);
  4360. return;
  4361. }
  4362. #endif
  4363. for (jp = curjob; jp; jp = jp->prev_job)
  4364. freejob(jp);
  4365. jobless = 0;
  4366. }
  4367. /* Called after fork(), in parent */
  4368. #if !JOBS
  4369. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4370. #endif
  4371. static void
  4372. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4373. {
  4374. TRACE(("In parent shell: child = %d\n", pid));
  4375. if (!jp) {
  4376. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4377. continue;
  4378. jobless++;
  4379. return;
  4380. }
  4381. #if JOBS
  4382. if (mode != FORK_NOJOB && jp->jobctl) {
  4383. int pgrp;
  4384. if (jp->nprocs == 0)
  4385. pgrp = pid;
  4386. else
  4387. pgrp = jp->ps[0].ps_pid;
  4388. /* This can fail because we are doing it in the child also */
  4389. setpgid(pid, pgrp);
  4390. }
  4391. #endif
  4392. if (mode == FORK_BG) {
  4393. backgndpid = pid; /* set $! */
  4394. set_curjob(jp, CUR_RUNNING);
  4395. }
  4396. if (jp) {
  4397. struct procstat *ps = &jp->ps[jp->nprocs++];
  4398. ps->ps_pid = pid;
  4399. ps->ps_status = -1;
  4400. ps->ps_cmd = nullstr;
  4401. #if JOBS
  4402. if (doing_jobctl && n)
  4403. ps->ps_cmd = commandtext(n);
  4404. #endif
  4405. }
  4406. }
  4407. static int
  4408. forkshell(struct job *jp, union node *n, int mode)
  4409. {
  4410. int pid;
  4411. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4412. pid = fork();
  4413. if (pid < 0) {
  4414. TRACE(("Fork failed, errno=%d", errno));
  4415. if (jp)
  4416. freejob(jp);
  4417. ash_msg_and_raise_error("can't fork");
  4418. }
  4419. if (pid == 0) {
  4420. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4421. forkchild(jp, n, mode);
  4422. } else {
  4423. forkparent(jp, n, mode, pid);
  4424. }
  4425. return pid;
  4426. }
  4427. /*
  4428. * Wait for job to finish.
  4429. *
  4430. * Under job control we have the problem that while a child process
  4431. * is running interrupts generated by the user are sent to the child
  4432. * but not to the shell. This means that an infinite loop started by
  4433. * an interactive user may be hard to kill. With job control turned off,
  4434. * an interactive user may place an interactive program inside a loop.
  4435. * If the interactive program catches interrupts, the user doesn't want
  4436. * these interrupts to also abort the loop. The approach we take here
  4437. * is to have the shell ignore interrupt signals while waiting for a
  4438. * foreground process to terminate, and then send itself an interrupt
  4439. * signal if the child process was terminated by an interrupt signal.
  4440. * Unfortunately, some programs want to do a bit of cleanup and then
  4441. * exit on interrupt; unless these processes terminate themselves by
  4442. * sending a signal to themselves (instead of calling exit) they will
  4443. * confuse this approach.
  4444. *
  4445. * Called with interrupts off.
  4446. */
  4447. static int
  4448. waitforjob(struct job *jp)
  4449. {
  4450. int st;
  4451. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4452. INT_OFF;
  4453. while (jp->state == JOBRUNNING) {
  4454. /* In non-interactive shells, we _can_ get
  4455. * a keyboard signal here and be EINTRed,
  4456. * but we just loop back, waiting for command to complete.
  4457. *
  4458. * man bash:
  4459. * "If bash is waiting for a command to complete and receives
  4460. * a signal for which a trap has been set, the trap
  4461. * will not be executed until the command completes."
  4462. *
  4463. * Reality is that even if trap is not set, bash
  4464. * will not act on the signal until command completes.
  4465. * Try this. sleep5intoff.c:
  4466. * #include <signal.h>
  4467. * #include <unistd.h>
  4468. * int main() {
  4469. * sigset_t set;
  4470. * sigemptyset(&set);
  4471. * sigaddset(&set, SIGINT);
  4472. * sigaddset(&set, SIGQUIT);
  4473. * sigprocmask(SIG_BLOCK, &set, NULL);
  4474. * sleep(5);
  4475. * return 0;
  4476. * }
  4477. * $ bash -c './sleep5intoff; echo hi'
  4478. * ^C^C^C^C <--- pressing ^C once a second
  4479. * $ _
  4480. * $ bash -c './sleep5intoff; echo hi'
  4481. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4482. * $ _
  4483. */
  4484. dowait(DOWAIT_BLOCK, jp);
  4485. }
  4486. INT_ON;
  4487. st = getstatus(jp);
  4488. #if JOBS
  4489. if (jp->jobctl) {
  4490. xtcsetpgrp(ttyfd, rootpid);
  4491. /*
  4492. * This is truly gross.
  4493. * If we're doing job control, then we did a TIOCSPGRP which
  4494. * caused us (the shell) to no longer be in the controlling
  4495. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4496. * intuit from the subprocess exit status whether a SIGINT
  4497. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4498. */
  4499. if (jp->sigint) /* TODO: do the same with all signals */
  4500. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4501. }
  4502. if (jp->state == JOBDONE)
  4503. #endif
  4504. freejob(jp);
  4505. return st;
  4506. }
  4507. /*
  4508. * return 1 if there are stopped jobs, otherwise 0
  4509. */
  4510. static int
  4511. stoppedjobs(void)
  4512. {
  4513. struct job *jp;
  4514. int retval;
  4515. retval = 0;
  4516. if (job_warning)
  4517. goto out;
  4518. jp = curjob;
  4519. if (jp && jp->state == JOBSTOPPED) {
  4520. out2str("You have stopped jobs.\n");
  4521. job_warning = 2;
  4522. retval++;
  4523. }
  4524. out:
  4525. return retval;
  4526. }
  4527. /* ============ redir.c
  4528. *
  4529. * Code for dealing with input/output redirection.
  4530. */
  4531. #undef EMPTY
  4532. #undef CLOSED
  4533. #define EMPTY -2 /* marks an unused slot in redirtab */
  4534. #define CLOSED -3 /* marks a slot of previously-closed fd */
  4535. /*
  4536. * Open a file in noclobber mode.
  4537. * The code was copied from bash.
  4538. */
  4539. static int
  4540. noclobberopen(const char *fname)
  4541. {
  4542. int r, fd;
  4543. struct stat finfo, finfo2;
  4544. /*
  4545. * If the file exists and is a regular file, return an error
  4546. * immediately.
  4547. */
  4548. r = stat(fname, &finfo);
  4549. if (r == 0 && S_ISREG(finfo.st_mode)) {
  4550. errno = EEXIST;
  4551. return -1;
  4552. }
  4553. /*
  4554. * If the file was not present (r != 0), make sure we open it
  4555. * exclusively so that if it is created before we open it, our open
  4556. * will fail. Make sure that we do not truncate an existing file.
  4557. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  4558. * file was not a regular file, we leave O_EXCL off.
  4559. */
  4560. if (r != 0)
  4561. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4562. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  4563. /* If the open failed, return the file descriptor right away. */
  4564. if (fd < 0)
  4565. return fd;
  4566. /*
  4567. * OK, the open succeeded, but the file may have been changed from a
  4568. * non-regular file to a regular file between the stat and the open.
  4569. * We are assuming that the O_EXCL open handles the case where FILENAME
  4570. * did not exist and is symlinked to an existing file between the stat
  4571. * and open.
  4572. */
  4573. /*
  4574. * If we can open it and fstat the file descriptor, and neither check
  4575. * revealed that it was a regular file, and the file has not been
  4576. * replaced, return the file descriptor.
  4577. */
  4578. if (fstat(fd, &finfo2) == 0
  4579. && !S_ISREG(finfo2.st_mode)
  4580. && finfo.st_dev == finfo2.st_dev
  4581. && finfo.st_ino == finfo2.st_ino
  4582. ) {
  4583. return fd;
  4584. }
  4585. /* The file has been replaced. badness. */
  4586. close(fd);
  4587. errno = EEXIST;
  4588. return -1;
  4589. }
  4590. /*
  4591. * Handle here documents. Normally we fork off a process to write the
  4592. * data to a pipe. If the document is short, we can stuff the data in
  4593. * the pipe without forking.
  4594. */
  4595. /* openhere needs this forward reference */
  4596. static void expandhere(union node *arg, int fd);
  4597. static int
  4598. openhere(union node *redir)
  4599. {
  4600. int pip[2];
  4601. size_t len = 0;
  4602. if (pipe(pip) < 0)
  4603. ash_msg_and_raise_error("pipe call failed");
  4604. if (redir->type == NHERE) {
  4605. len = strlen(redir->nhere.doc->narg.text);
  4606. if (len <= PIPE_BUF) {
  4607. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4608. goto out;
  4609. }
  4610. }
  4611. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4612. /* child */
  4613. close(pip[0]);
  4614. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4615. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4616. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4617. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4618. signal(SIGPIPE, SIG_DFL);
  4619. if (redir->type == NHERE)
  4620. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4621. else /* NXHERE */
  4622. expandhere(redir->nhere.doc, pip[1]);
  4623. _exit(EXIT_SUCCESS);
  4624. }
  4625. out:
  4626. close(pip[1]);
  4627. return pip[0];
  4628. }
  4629. static int
  4630. openredirect(union node *redir)
  4631. {
  4632. char *fname;
  4633. int f;
  4634. switch (redir->nfile.type) {
  4635. case NFROM:
  4636. fname = redir->nfile.expfname;
  4637. f = open(fname, O_RDONLY);
  4638. if (f < 0)
  4639. goto eopen;
  4640. break;
  4641. case NFROMTO:
  4642. fname = redir->nfile.expfname;
  4643. f = open(fname, O_RDWR|O_CREAT, 0666);
  4644. if (f < 0)
  4645. goto ecreate;
  4646. break;
  4647. case NTO:
  4648. #if ENABLE_ASH_BASH_COMPAT
  4649. case NTO2:
  4650. #endif
  4651. /* Take care of noclobber mode. */
  4652. if (Cflag) {
  4653. fname = redir->nfile.expfname;
  4654. f = noclobberopen(fname);
  4655. if (f < 0)
  4656. goto ecreate;
  4657. break;
  4658. }
  4659. /* FALLTHROUGH */
  4660. case NCLOBBER:
  4661. fname = redir->nfile.expfname;
  4662. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4663. if (f < 0)
  4664. goto ecreate;
  4665. break;
  4666. case NAPPEND:
  4667. fname = redir->nfile.expfname;
  4668. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4669. if (f < 0)
  4670. goto ecreate;
  4671. break;
  4672. default:
  4673. #if DEBUG
  4674. abort();
  4675. #endif
  4676. /* Fall through to eliminate warning. */
  4677. /* Our single caller does this itself */
  4678. // case NTOFD:
  4679. // case NFROMFD:
  4680. // f = -1;
  4681. // break;
  4682. case NHERE:
  4683. case NXHERE:
  4684. f = openhere(redir);
  4685. break;
  4686. }
  4687. return f;
  4688. ecreate:
  4689. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4690. eopen:
  4691. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4692. }
  4693. /*
  4694. * Copy a file descriptor to be >= to. Returns -1
  4695. * if the source file descriptor is closed, EMPTY if there are no unused
  4696. * file descriptors left.
  4697. */
  4698. /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
  4699. * old code was doing close(to) prior to copyfd() to achieve the same */
  4700. enum {
  4701. COPYFD_EXACT = (int)~(INT_MAX),
  4702. COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
  4703. };
  4704. static int
  4705. copyfd(int from, int to)
  4706. {
  4707. int newfd;
  4708. if (to & COPYFD_EXACT) {
  4709. to &= ~COPYFD_EXACT;
  4710. /*if (from != to)*/
  4711. newfd = dup2(from, to);
  4712. } else {
  4713. newfd = fcntl(from, F_DUPFD, to);
  4714. }
  4715. if (newfd < 0) {
  4716. if (errno == EMFILE)
  4717. return EMPTY;
  4718. /* Happens when source fd is not open: try "echo >&99" */
  4719. ash_msg_and_raise_error("%d: %m", from);
  4720. }
  4721. return newfd;
  4722. }
  4723. /* Struct def and variable are moved down to the first usage site */
  4724. struct two_fd_t {
  4725. int orig, copy;
  4726. };
  4727. struct redirtab {
  4728. struct redirtab *next;
  4729. int nullredirs;
  4730. int pair_count;
  4731. struct two_fd_t two_fd[];
  4732. };
  4733. #define redirlist (G_var.redirlist)
  4734. static int need_to_remember(struct redirtab *rp, int fd)
  4735. {
  4736. int i;
  4737. if (!rp) /* remembering was not requested */
  4738. return 0;
  4739. for (i = 0; i < rp->pair_count; i++) {
  4740. if (rp->two_fd[i].orig == fd) {
  4741. /* already remembered */
  4742. return 0;
  4743. }
  4744. }
  4745. return 1;
  4746. }
  4747. /* "hidden" fd is a fd used to read scripts, or a copy of such */
  4748. static int is_hidden_fd(struct redirtab *rp, int fd)
  4749. {
  4750. int i;
  4751. struct parsefile *pf;
  4752. if (fd == -1)
  4753. return 0;
  4754. /* Check open scripts' fds */
  4755. pf = g_parsefile;
  4756. while (pf) {
  4757. /* We skip pf_fd == 0 case because of the following case:
  4758. * $ ash # running ash interactively
  4759. * $ . ./script.sh
  4760. * and in script.sh: "exec 9>&0".
  4761. * Even though top-level pf_fd _is_ 0,
  4762. * it's still ok to use it: "read" builtin uses it,
  4763. * why should we cripple "exec" builtin?
  4764. */
  4765. if (pf->pf_fd > 0 && fd == pf->pf_fd) {
  4766. return 1;
  4767. }
  4768. pf = pf->prev;
  4769. }
  4770. if (!rp)
  4771. return 0;
  4772. /* Check saved fds of redirects */
  4773. fd |= COPYFD_RESTORE;
  4774. for (i = 0; i < rp->pair_count; i++) {
  4775. if (rp->two_fd[i].copy == fd) {
  4776. return 1;
  4777. }
  4778. }
  4779. return 0;
  4780. }
  4781. /*
  4782. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  4783. * old file descriptors are stashed away so that the redirection can be
  4784. * undone by calling popredir.
  4785. */
  4786. /* flags passed to redirect */
  4787. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  4788. #define REDIR_SAVEFD2 03 /* set preverrout */
  4789. static void
  4790. redirect(union node *redir, int flags)
  4791. {
  4792. struct redirtab *sv;
  4793. int sv_pos;
  4794. int i;
  4795. int fd;
  4796. int newfd;
  4797. int copied_fd2 = -1;
  4798. g_nullredirs++;
  4799. if (!redir) {
  4800. return;
  4801. }
  4802. sv = NULL;
  4803. sv_pos = 0;
  4804. INT_OFF;
  4805. if (flags & REDIR_PUSH) {
  4806. union node *tmp = redir;
  4807. do {
  4808. sv_pos++;
  4809. #if ENABLE_ASH_BASH_COMPAT
  4810. if (tmp->nfile.type == NTO2)
  4811. sv_pos++;
  4812. #endif
  4813. tmp = tmp->nfile.next;
  4814. } while (tmp);
  4815. sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
  4816. sv->next = redirlist;
  4817. sv->pair_count = sv_pos;
  4818. redirlist = sv;
  4819. sv->nullredirs = g_nullredirs - 1;
  4820. g_nullredirs = 0;
  4821. while (sv_pos > 0) {
  4822. sv_pos--;
  4823. sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
  4824. }
  4825. }
  4826. do {
  4827. int right_fd = -1;
  4828. fd = redir->nfile.fd;
  4829. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  4830. right_fd = redir->ndup.dupfd;
  4831. //bb_error_msg("doing %d > %d", fd, right_fd);
  4832. /* redirect from/to same file descriptor? */
  4833. if (right_fd == fd)
  4834. continue;
  4835. /* "echo >&10" and 10 is a fd opened to a sh script? */
  4836. if (is_hidden_fd(sv, right_fd)) {
  4837. errno = EBADF; /* as if it is closed */
  4838. ash_msg_and_raise_error("%d: %m", right_fd);
  4839. }
  4840. newfd = -1;
  4841. } else {
  4842. newfd = openredirect(redir); /* always >= 0 */
  4843. if (fd == newfd) {
  4844. /* Descriptor wasn't open before redirect.
  4845. * Mark it for close in the future */
  4846. if (need_to_remember(sv, fd)) {
  4847. goto remember_to_close;
  4848. }
  4849. continue;
  4850. }
  4851. }
  4852. #if ENABLE_ASH_BASH_COMPAT
  4853. redirect_more:
  4854. #endif
  4855. if (need_to_remember(sv, fd)) {
  4856. /* Copy old descriptor */
  4857. /* Careful to not accidentally "save"
  4858. * to the same fd as right side fd in N>&M */
  4859. int minfd = right_fd < 10 ? 10 : right_fd + 1;
  4860. i = fcntl(fd, F_DUPFD, minfd);
  4861. /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
  4862. * are closed in popredir() in the child, preventing them from leaking
  4863. * into child. (popredir() also cleans up the mess in case of failures)
  4864. */
  4865. if (i == -1) {
  4866. i = errno;
  4867. if (i != EBADF) {
  4868. /* Strange error (e.g. "too many files" EMFILE?) */
  4869. if (newfd >= 0)
  4870. close(newfd);
  4871. errno = i;
  4872. ash_msg_and_raise_error("%d: %m", fd);
  4873. /* NOTREACHED */
  4874. }
  4875. /* EBADF: it is not open - good, remember to close it */
  4876. remember_to_close:
  4877. i = CLOSED;
  4878. } else { /* fd is open, save its copy */
  4879. /* "exec fd>&-" should not close fds
  4880. * which point to script file(s).
  4881. * Force them to be restored afterwards */
  4882. if (is_hidden_fd(sv, fd))
  4883. i |= COPYFD_RESTORE;
  4884. }
  4885. if (fd == 2)
  4886. copied_fd2 = i;
  4887. sv->two_fd[sv_pos].orig = fd;
  4888. sv->two_fd[sv_pos].copy = i;
  4889. sv_pos++;
  4890. }
  4891. if (newfd < 0) {
  4892. /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
  4893. if (redir->ndup.dupfd < 0) { /* "fd>&-" */
  4894. /* Don't want to trigger debugging */
  4895. if (fd != -1)
  4896. close(fd);
  4897. } else {
  4898. copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
  4899. }
  4900. } else if (fd != newfd) { /* move newfd to fd */
  4901. copyfd(newfd, fd | COPYFD_EXACT);
  4902. #if ENABLE_ASH_BASH_COMPAT
  4903. if (!(redir->nfile.type == NTO2 && fd == 2))
  4904. #endif
  4905. close(newfd);
  4906. }
  4907. #if ENABLE_ASH_BASH_COMPAT
  4908. if (redir->nfile.type == NTO2 && fd == 1) {
  4909. /* We already redirected it to fd 1, now copy it to 2 */
  4910. newfd = 1;
  4911. fd = 2;
  4912. goto redirect_more;
  4913. }
  4914. #endif
  4915. } while ((redir = redir->nfile.next) != NULL);
  4916. INT_ON;
  4917. if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  4918. preverrout_fd = copied_fd2;
  4919. }
  4920. /*
  4921. * Undo the effects of the last redirection.
  4922. */
  4923. static void
  4924. popredir(int drop, int restore)
  4925. {
  4926. struct redirtab *rp;
  4927. int i;
  4928. if (--g_nullredirs >= 0)
  4929. return;
  4930. INT_OFF;
  4931. rp = redirlist;
  4932. for (i = 0; i < rp->pair_count; i++) {
  4933. int fd = rp->two_fd[i].orig;
  4934. int copy = rp->two_fd[i].copy;
  4935. if (copy == CLOSED) {
  4936. if (!drop)
  4937. close(fd);
  4938. continue;
  4939. }
  4940. if (copy != EMPTY) {
  4941. if (!drop || (restore && (copy & COPYFD_RESTORE))) {
  4942. copy &= ~COPYFD_RESTORE;
  4943. /*close(fd);*/
  4944. copyfd(copy, fd | COPYFD_EXACT);
  4945. }
  4946. close(copy & ~COPYFD_RESTORE);
  4947. }
  4948. }
  4949. redirlist = rp->next;
  4950. g_nullredirs = rp->nullredirs;
  4951. free(rp);
  4952. INT_ON;
  4953. }
  4954. /*
  4955. * Undo all redirections. Called on error or interrupt.
  4956. */
  4957. /*
  4958. * Discard all saved file descriptors.
  4959. */
  4960. static void
  4961. clearredir(int drop)
  4962. {
  4963. for (;;) {
  4964. g_nullredirs = 0;
  4965. if (!redirlist)
  4966. break;
  4967. popredir(drop, /*restore:*/ 0);
  4968. }
  4969. }
  4970. static int
  4971. redirectsafe(union node *redir, int flags)
  4972. {
  4973. int err;
  4974. volatile int saveint;
  4975. struct jmploc *volatile savehandler = exception_handler;
  4976. struct jmploc jmploc;
  4977. SAVE_INT(saveint);
  4978. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  4979. err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
  4980. if (!err) {
  4981. exception_handler = &jmploc;
  4982. redirect(redir, flags);
  4983. }
  4984. exception_handler = savehandler;
  4985. if (err && exception_type != EXERROR)
  4986. longjmp(exception_handler->loc, 1);
  4987. RESTORE_INT(saveint);
  4988. return err;
  4989. }
  4990. /* ============ Routines to expand arguments to commands
  4991. *
  4992. * We have to deal with backquotes, shell variables, and file metacharacters.
  4993. */
  4994. #if ENABLE_SH_MATH_SUPPORT
  4995. static arith_t
  4996. ash_arith(const char *s)
  4997. {
  4998. arith_state_t math_state;
  4999. arith_t result;
  5000. math_state.lookupvar = lookupvar;
  5001. math_state.setvar = setvar2;
  5002. //math_state.endofname = endofname;
  5003. INT_OFF;
  5004. result = arith(&math_state, s);
  5005. if (math_state.errmsg)
  5006. ash_msg_and_raise_error(math_state.errmsg);
  5007. INT_ON;
  5008. return result;
  5009. }
  5010. #endif
  5011. /*
  5012. * expandarg flags
  5013. */
  5014. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5015. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5016. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5017. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5018. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5019. #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
  5020. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  5021. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  5022. #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
  5023. /*
  5024. * rmescape() flags
  5025. */
  5026. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5027. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5028. #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
  5029. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5030. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5031. /*
  5032. * Structure specifying which parts of the string should be searched
  5033. * for IFS characters.
  5034. */
  5035. struct ifsregion {
  5036. struct ifsregion *next; /* next region in list */
  5037. int begoff; /* offset of start of region */
  5038. int endoff; /* offset of end of region */
  5039. int nulonly; /* search for nul bytes only */
  5040. };
  5041. struct arglist {
  5042. struct strlist *list;
  5043. struct strlist **lastp;
  5044. };
  5045. /* output of current string */
  5046. static char *expdest;
  5047. /* list of back quote expressions */
  5048. static struct nodelist *argbackq;
  5049. /* first struct in list of ifs regions */
  5050. static struct ifsregion ifsfirst;
  5051. /* last struct in list */
  5052. static struct ifsregion *ifslastp;
  5053. /* holds expanded arg list */
  5054. static struct arglist exparg;
  5055. /*
  5056. * Our own itoa().
  5057. */
  5058. #if !ENABLE_SH_MATH_SUPPORT
  5059. /* cvtnum() is used even if math support is off (to prepare $? values and such) */
  5060. typedef long arith_t;
  5061. # define ARITH_FMT "%ld"
  5062. #endif
  5063. static int
  5064. cvtnum(arith_t num)
  5065. {
  5066. int len;
  5067. expdest = makestrspace(32, expdest);
  5068. len = fmtstr(expdest, 32, ARITH_FMT, num);
  5069. STADJUST(len, expdest);
  5070. return len;
  5071. }
  5072. static size_t
  5073. esclen(const char *start, const char *p)
  5074. {
  5075. size_t esc = 0;
  5076. while (p > start && (unsigned char)*--p == CTLESC) {
  5077. esc++;
  5078. }
  5079. return esc;
  5080. }
  5081. /*
  5082. * Remove any CTLESC characters from a string.
  5083. */
  5084. static char *
  5085. rmescapes(char *str, int flag)
  5086. {
  5087. static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
  5088. char *p, *q, *r;
  5089. unsigned inquotes;
  5090. unsigned protect_against_glob;
  5091. unsigned globbing;
  5092. p = strpbrk(str, qchars);
  5093. if (!p)
  5094. return str;
  5095. q = p;
  5096. r = str;
  5097. if (flag & RMESCAPE_ALLOC) {
  5098. size_t len = p - str;
  5099. size_t fulllen = len + strlen(p) + 1;
  5100. if (flag & RMESCAPE_GROW) {
  5101. int strloc = str - (char *)stackblock();
  5102. r = makestrspace(fulllen, expdest);
  5103. /* p and str may be invalidated by makestrspace */
  5104. str = (char *)stackblock() + strloc;
  5105. p = str + len;
  5106. } else if (flag & RMESCAPE_HEAP) {
  5107. r = ckmalloc(fulllen);
  5108. } else {
  5109. r = stalloc(fulllen);
  5110. }
  5111. q = r;
  5112. if (len > 0) {
  5113. q = (char *)memcpy(q, str, len) + len;
  5114. }
  5115. }
  5116. inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
  5117. globbing = flag & RMESCAPE_GLOB;
  5118. protect_against_glob = globbing;
  5119. while (*p) {
  5120. if ((unsigned char)*p == CTLQUOTEMARK) {
  5121. // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
  5122. // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
  5123. // Note: both inquotes and protect_against_glob only affect whether
  5124. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5125. inquotes = ~inquotes;
  5126. p++;
  5127. protect_against_glob = globbing;
  5128. continue;
  5129. }
  5130. if (*p == '\\') {
  5131. /* naked back slash */
  5132. protect_against_glob = 0;
  5133. goto copy;
  5134. }
  5135. if ((unsigned char)*p == CTLESC) {
  5136. p++;
  5137. if (protect_against_glob && inquotes && *p != '/') {
  5138. *q++ = '\\';
  5139. }
  5140. }
  5141. protect_against_glob = globbing;
  5142. copy:
  5143. *q++ = *p++;
  5144. }
  5145. *q = '\0';
  5146. if (flag & RMESCAPE_GROW) {
  5147. expdest = r;
  5148. STADJUST(q - r + 1, expdest);
  5149. }
  5150. return r;
  5151. }
  5152. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5153. /*
  5154. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5155. *
  5156. * Returns an stalloced string.
  5157. */
  5158. static char *
  5159. preglob(const char *pattern, int quoted, int flag)
  5160. {
  5161. flag |= RMESCAPE_GLOB;
  5162. if (quoted) {
  5163. flag |= RMESCAPE_QUOTED;
  5164. }
  5165. return rmescapes((char *)pattern, flag);
  5166. }
  5167. /*
  5168. * Put a string on the stack.
  5169. */
  5170. static void
  5171. memtodest(const char *p, size_t len, int syntax, int quotes)
  5172. {
  5173. char *q = expdest;
  5174. q = makestrspace(quotes ? len * 2 : len, q);
  5175. while (len--) {
  5176. unsigned char c = *p++;
  5177. if (c == '\0')
  5178. continue;
  5179. if (quotes) {
  5180. int n = SIT(c, syntax);
  5181. if (n == CCTL || n == CBACK)
  5182. USTPUTC(CTLESC, q);
  5183. }
  5184. USTPUTC(c, q);
  5185. }
  5186. expdest = q;
  5187. }
  5188. static void
  5189. strtodest(const char *p, int syntax, int quotes)
  5190. {
  5191. memtodest(p, strlen(p), syntax, quotes);
  5192. }
  5193. /*
  5194. * Record the fact that we have to scan this region of the
  5195. * string for IFS characters.
  5196. */
  5197. static void
  5198. recordregion(int start, int end, int nulonly)
  5199. {
  5200. struct ifsregion *ifsp;
  5201. if (ifslastp == NULL) {
  5202. ifsp = &ifsfirst;
  5203. } else {
  5204. INT_OFF;
  5205. ifsp = ckzalloc(sizeof(*ifsp));
  5206. /*ifsp->next = NULL; - ckzalloc did it */
  5207. ifslastp->next = ifsp;
  5208. INT_ON;
  5209. }
  5210. ifslastp = ifsp;
  5211. ifslastp->begoff = start;
  5212. ifslastp->endoff = end;
  5213. ifslastp->nulonly = nulonly;
  5214. }
  5215. static void
  5216. removerecordregions(int endoff)
  5217. {
  5218. if (ifslastp == NULL)
  5219. return;
  5220. if (ifsfirst.endoff > endoff) {
  5221. while (ifsfirst.next) {
  5222. struct ifsregion *ifsp;
  5223. INT_OFF;
  5224. ifsp = ifsfirst.next->next;
  5225. free(ifsfirst.next);
  5226. ifsfirst.next = ifsp;
  5227. INT_ON;
  5228. }
  5229. if (ifsfirst.begoff > endoff) {
  5230. ifslastp = NULL;
  5231. } else {
  5232. ifslastp = &ifsfirst;
  5233. ifsfirst.endoff = endoff;
  5234. }
  5235. return;
  5236. }
  5237. ifslastp = &ifsfirst;
  5238. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5239. ifslastp = ifslastp->next;
  5240. while (ifslastp->next) {
  5241. struct ifsregion *ifsp;
  5242. INT_OFF;
  5243. ifsp = ifslastp->next->next;
  5244. free(ifslastp->next);
  5245. ifslastp->next = ifsp;
  5246. INT_ON;
  5247. }
  5248. if (ifslastp->endoff > endoff)
  5249. ifslastp->endoff = endoff;
  5250. }
  5251. static char *
  5252. exptilde(char *startp, char *p, int flags)
  5253. {
  5254. unsigned char c;
  5255. char *name;
  5256. struct passwd *pw;
  5257. const char *home;
  5258. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
  5259. int startloc;
  5260. name = p + 1;
  5261. while ((c = *++p) != '\0') {
  5262. switch (c) {
  5263. case CTLESC:
  5264. return startp;
  5265. case CTLQUOTEMARK:
  5266. return startp;
  5267. case ':':
  5268. if (flags & EXP_VARTILDE)
  5269. goto done;
  5270. break;
  5271. case '/':
  5272. case CTLENDVAR:
  5273. goto done;
  5274. }
  5275. }
  5276. done:
  5277. *p = '\0';
  5278. if (*name == '\0') {
  5279. home = lookupvar("HOME");
  5280. } else {
  5281. pw = getpwnam(name);
  5282. if (pw == NULL)
  5283. goto lose;
  5284. home = pw->pw_dir;
  5285. }
  5286. if (!home || !*home)
  5287. goto lose;
  5288. *p = c;
  5289. startloc = expdest - (char *)stackblock();
  5290. strtodest(home, SQSYNTAX, quotes);
  5291. recordregion(startloc, expdest - (char *)stackblock(), 0);
  5292. return p;
  5293. lose:
  5294. *p = c;
  5295. return startp;
  5296. }
  5297. /*
  5298. * Execute a command inside back quotes. If it's a builtin command, we
  5299. * want to save its output in a block obtained from malloc. Otherwise
  5300. * we fork off a subprocess and get the output of the command via a pipe.
  5301. * Should be called with interrupts off.
  5302. */
  5303. struct backcmd { /* result of evalbackcmd */
  5304. int fd; /* file descriptor to read from */
  5305. int nleft; /* number of chars in buffer */
  5306. char *buf; /* buffer */
  5307. struct job *jp; /* job structure for command */
  5308. };
  5309. /* These forward decls are needed to use "eval" code for backticks handling: */
  5310. static uint8_t back_exitstatus; /* exit status of backquoted command */
  5311. #define EV_EXIT 01 /* exit after evaluating tree */
  5312. static void evaltree(union node *, int);
  5313. static void FAST_FUNC
  5314. evalbackcmd(union node *n, struct backcmd *result)
  5315. {
  5316. int saveherefd;
  5317. result->fd = -1;
  5318. result->buf = NULL;
  5319. result->nleft = 0;
  5320. result->jp = NULL;
  5321. if (n == NULL)
  5322. goto out;
  5323. saveherefd = herefd;
  5324. herefd = -1;
  5325. {
  5326. int pip[2];
  5327. struct job *jp;
  5328. if (pipe(pip) < 0)
  5329. ash_msg_and_raise_error("pipe call failed");
  5330. jp = makejob(/*n,*/ 1);
  5331. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5332. FORCE_INT_ON;
  5333. close(pip[0]);
  5334. if (pip[1] != 1) {
  5335. /*close(1);*/
  5336. copyfd(pip[1], 1 | COPYFD_EXACT);
  5337. close(pip[1]);
  5338. }
  5339. eflag = 0;
  5340. evaltree(n, EV_EXIT); /* actually evaltreenr... */
  5341. /* NOTREACHED */
  5342. }
  5343. close(pip[1]);
  5344. result->fd = pip[0];
  5345. result->jp = jp;
  5346. }
  5347. herefd = saveherefd;
  5348. out:
  5349. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5350. result->fd, result->buf, result->nleft, result->jp));
  5351. }
  5352. /*
  5353. * Expand stuff in backwards quotes.
  5354. */
  5355. static void
  5356. expbackq(union node *cmd, int quoted, int quotes)
  5357. {
  5358. struct backcmd in;
  5359. int i;
  5360. char buf[128];
  5361. char *p;
  5362. char *dest;
  5363. int startloc;
  5364. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5365. struct stackmark smark;
  5366. INT_OFF;
  5367. setstackmark(&smark);
  5368. dest = expdest;
  5369. startloc = dest - (char *)stackblock();
  5370. grabstackstr(dest);
  5371. evalbackcmd(cmd, &in);
  5372. popstackmark(&smark);
  5373. p = in.buf;
  5374. i = in.nleft;
  5375. if (i == 0)
  5376. goto read;
  5377. for (;;) {
  5378. memtodest(p, i, syntax, quotes);
  5379. read:
  5380. if (in.fd < 0)
  5381. break;
  5382. i = nonblock_immune_read(in.fd, buf, sizeof(buf), /*loop_on_EINTR:*/ 1);
  5383. TRACE(("expbackq: read returns %d\n", i));
  5384. if (i <= 0)
  5385. break;
  5386. p = buf;
  5387. }
  5388. free(in.buf);
  5389. if (in.fd >= 0) {
  5390. close(in.fd);
  5391. back_exitstatus = waitforjob(in.jp);
  5392. }
  5393. INT_ON;
  5394. /* Eat all trailing newlines */
  5395. dest = expdest;
  5396. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5397. STUNPUTC(dest);
  5398. expdest = dest;
  5399. if (quoted == 0)
  5400. recordregion(startloc, dest - (char *)stackblock(), 0);
  5401. TRACE(("evalbackq: size:%d:'%.*s'\n",
  5402. (int)((dest - (char *)stackblock()) - startloc),
  5403. (int)((dest - (char *)stackblock()) - startloc),
  5404. stackblock() + startloc));
  5405. }
  5406. #if ENABLE_SH_MATH_SUPPORT
  5407. /*
  5408. * Expand arithmetic expression. Backup to start of expression,
  5409. * evaluate, place result in (backed up) result, adjust string position.
  5410. */
  5411. static void
  5412. expari(int quotes)
  5413. {
  5414. char *p, *start;
  5415. int begoff;
  5416. int flag;
  5417. int len;
  5418. /* ifsfree(); */
  5419. /*
  5420. * This routine is slightly over-complicated for
  5421. * efficiency. Next we scan backwards looking for the
  5422. * start of arithmetic.
  5423. */
  5424. start = stackblock();
  5425. p = expdest - 1;
  5426. *p = '\0';
  5427. p--;
  5428. while (1) {
  5429. int esc;
  5430. while ((unsigned char)*p != CTLARI) {
  5431. p--;
  5432. #if DEBUG
  5433. if (p < start) {
  5434. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5435. }
  5436. #endif
  5437. }
  5438. esc = esclen(start, p);
  5439. if (!(esc % 2)) {
  5440. break;
  5441. }
  5442. p -= esc + 1;
  5443. }
  5444. begoff = p - start;
  5445. removerecordregions(begoff);
  5446. flag = p[1];
  5447. expdest = p;
  5448. if (quotes)
  5449. rmescapes(p + 2, 0);
  5450. len = cvtnum(ash_arith(p + 2));
  5451. if (flag != '"')
  5452. recordregion(begoff, begoff + len, 0);
  5453. }
  5454. #endif
  5455. /* argstr needs it */
  5456. static char *evalvar(char *p, int flags, struct strlist *var_str_list);
  5457. /*
  5458. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5459. * characters to allow for further processing. Otherwise treat
  5460. * $@ like $* since no splitting will be performed.
  5461. *
  5462. * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
  5463. * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
  5464. * for correct expansion of "B=$A" word.
  5465. */
  5466. static void
  5467. argstr(char *p, int flags, struct strlist *var_str_list)
  5468. {
  5469. static const char spclchars[] ALIGN1 = {
  5470. '=',
  5471. ':',
  5472. CTLQUOTEMARK,
  5473. CTLENDVAR,
  5474. CTLESC,
  5475. CTLVAR,
  5476. CTLBACKQ,
  5477. CTLBACKQ | CTLQUOTE,
  5478. #if ENABLE_SH_MATH_SUPPORT
  5479. CTLENDARI,
  5480. #endif
  5481. '\0'
  5482. };
  5483. const char *reject = spclchars;
  5484. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
  5485. int breakall = flags & EXP_WORD;
  5486. int inquotes;
  5487. size_t length;
  5488. int startloc;
  5489. if (!(flags & EXP_VARTILDE)) {
  5490. reject += 2;
  5491. } else if (flags & EXP_VARTILDE2) {
  5492. reject++;
  5493. }
  5494. inquotes = 0;
  5495. length = 0;
  5496. if (flags & EXP_TILDE) {
  5497. char *q;
  5498. flags &= ~EXP_TILDE;
  5499. tilde:
  5500. q = p;
  5501. if ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
  5502. q++;
  5503. if (*q == '~')
  5504. p = exptilde(p, q, flags);
  5505. }
  5506. start:
  5507. startloc = expdest - (char *)stackblock();
  5508. for (;;) {
  5509. unsigned char c;
  5510. length += strcspn(p + length, reject);
  5511. c = p[length];
  5512. if (c) {
  5513. if (!(c & 0x80)
  5514. IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
  5515. ) {
  5516. /* c == '=' || c == ':' || c == CTLENDARI */
  5517. length++;
  5518. }
  5519. }
  5520. if (length > 0) {
  5521. int newloc;
  5522. expdest = stack_nputstr(p, length, expdest);
  5523. newloc = expdest - (char *)stackblock();
  5524. if (breakall && !inquotes && newloc > startloc) {
  5525. recordregion(startloc, newloc, 0);
  5526. }
  5527. startloc = newloc;
  5528. }
  5529. p += length + 1;
  5530. length = 0;
  5531. switch (c) {
  5532. case '\0':
  5533. goto breakloop;
  5534. case '=':
  5535. if (flags & EXP_VARTILDE2) {
  5536. p--;
  5537. continue;
  5538. }
  5539. flags |= EXP_VARTILDE2;
  5540. reject++;
  5541. /* fall through */
  5542. case ':':
  5543. /*
  5544. * sort of a hack - expand tildes in variable
  5545. * assignments (after the first '=' and after ':'s).
  5546. */
  5547. if (*--p == '~') {
  5548. goto tilde;
  5549. }
  5550. continue;
  5551. }
  5552. switch (c) {
  5553. case CTLENDVAR: /* ??? */
  5554. goto breakloop;
  5555. case CTLQUOTEMARK:
  5556. /* "$@" syntax adherence hack */
  5557. if (!inquotes
  5558. && memcmp(p, dolatstr, 4) == 0
  5559. && ( p[4] == (char)CTLQUOTEMARK
  5560. || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
  5561. )
  5562. ) {
  5563. p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
  5564. goto start;
  5565. }
  5566. inquotes = !inquotes;
  5567. addquote:
  5568. if (quotes) {
  5569. p--;
  5570. length++;
  5571. startloc++;
  5572. }
  5573. break;
  5574. case CTLESC:
  5575. startloc++;
  5576. length++;
  5577. goto addquote;
  5578. case CTLVAR:
  5579. p = evalvar(p, flags, var_str_list);
  5580. goto start;
  5581. case CTLBACKQ:
  5582. c = '\0';
  5583. case CTLBACKQ|CTLQUOTE:
  5584. expbackq(argbackq->n, c, quotes);
  5585. argbackq = argbackq->next;
  5586. goto start;
  5587. #if ENABLE_SH_MATH_SUPPORT
  5588. case CTLENDARI:
  5589. p--;
  5590. expari(quotes);
  5591. goto start;
  5592. #endif
  5593. }
  5594. }
  5595. breakloop: ;
  5596. }
  5597. static char *
  5598. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  5599. char *pattern, int quotes, int zero)
  5600. {
  5601. char *loc, *loc2;
  5602. char c;
  5603. loc = startp;
  5604. loc2 = rmesc;
  5605. do {
  5606. int match;
  5607. const char *s = loc2;
  5608. c = *loc2;
  5609. if (zero) {
  5610. *loc2 = '\0';
  5611. s = rmesc;
  5612. }
  5613. match = pmatch(pattern, s);
  5614. *loc2 = c;
  5615. if (match)
  5616. return loc;
  5617. if (quotes && (unsigned char)*loc == CTLESC)
  5618. loc++;
  5619. loc++;
  5620. loc2++;
  5621. } while (c);
  5622. return NULL;
  5623. }
  5624. static char *
  5625. scanright(char *startp, char *rmesc, char *rmescend,
  5626. char *pattern, int quotes, int match_at_start)
  5627. {
  5628. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5629. int try2optimize = match_at_start;
  5630. #endif
  5631. int esc = 0;
  5632. char *loc;
  5633. char *loc2;
  5634. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  5635. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  5636. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  5637. * Logic:
  5638. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  5639. * and on each iteration they go back two/one char until they reach the beginning.
  5640. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  5641. */
  5642. /* TODO: document in what other circumstances we are called. */
  5643. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  5644. int match;
  5645. char c = *loc2;
  5646. const char *s = loc2;
  5647. if (match_at_start) {
  5648. *loc2 = '\0';
  5649. s = rmesc;
  5650. }
  5651. match = pmatch(pattern, s);
  5652. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  5653. *loc2 = c;
  5654. if (match)
  5655. return loc;
  5656. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5657. if (try2optimize) {
  5658. /* Maybe we can optimize this:
  5659. * if pattern ends with unescaped *, we can avoid checking
  5660. * shorter strings: if "foo*" doesnt match "raw_value_of_v",
  5661. * it wont match truncated "raw_value_of_" strings too.
  5662. */
  5663. unsigned plen = strlen(pattern);
  5664. /* Does it end with "*"? */
  5665. if (plen != 0 && pattern[--plen] == '*') {
  5666. /* "xxxx*" is not escaped */
  5667. /* "xxx\*" is escaped */
  5668. /* "xx\\*" is not escaped */
  5669. /* "x\\\*" is escaped */
  5670. int slashes = 0;
  5671. while (plen != 0 && pattern[--plen] == '\\')
  5672. slashes++;
  5673. if (!(slashes & 1))
  5674. break; /* ends with unescaped "*" */
  5675. }
  5676. try2optimize = 0;
  5677. }
  5678. #endif
  5679. loc--;
  5680. if (quotes) {
  5681. if (--esc < 0) {
  5682. esc = esclen(startp, loc);
  5683. }
  5684. if (esc % 2) {
  5685. esc--;
  5686. loc--;
  5687. }
  5688. }
  5689. }
  5690. return NULL;
  5691. }
  5692. static void varunset(const char *, const char *, const char *, int) NORETURN;
  5693. static void
  5694. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5695. {
  5696. const char *msg;
  5697. const char *tail;
  5698. tail = nullstr;
  5699. msg = "parameter not set";
  5700. if (umsg) {
  5701. if ((unsigned char)*end == CTLENDVAR) {
  5702. if (varflags & VSNUL)
  5703. tail = " or null";
  5704. } else {
  5705. msg = umsg;
  5706. }
  5707. }
  5708. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  5709. }
  5710. #if ENABLE_ASH_BASH_COMPAT
  5711. static char *
  5712. parse_sub_pattern(char *arg, int varflags)
  5713. {
  5714. char *idx, *repl = NULL;
  5715. unsigned char c;
  5716. //char *org_arg = arg;
  5717. //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
  5718. idx = arg;
  5719. while (1) {
  5720. c = *arg;
  5721. if (!c)
  5722. break;
  5723. if (c == '/') {
  5724. /* Only the first '/' seen is our separator */
  5725. if (!repl) {
  5726. repl = idx + 1;
  5727. c = '\0';
  5728. }
  5729. }
  5730. *idx++ = c;
  5731. arg++;
  5732. /*
  5733. * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
  5734. * The result is a_\_z_c (not a\_\_z_c)!
  5735. *
  5736. * Enable debug prints in this function and you'll see:
  5737. * ash: arg:'\\b/_\\_z_' varflags:d
  5738. * ash: pattern:'\\b' repl:'_\_z_'
  5739. * That is, \\b is interpreted as \\b, but \\_ as \_!
  5740. * IOW: search pattern and replace string treat backslashes
  5741. * differently! That is the reason why we check repl below:
  5742. */
  5743. if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
  5744. arg++; /* skip both '\', not just first one */
  5745. }
  5746. *idx = c; /* NUL */
  5747. //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
  5748. return repl;
  5749. }
  5750. #endif /* ENABLE_ASH_BASH_COMPAT */
  5751. static const char *
  5752. subevalvar(char *p, char *varname, int strloc, int subtype,
  5753. int startloc, int varflags, int quotes, struct strlist *var_str_list)
  5754. {
  5755. struct nodelist *saveargbackq = argbackq;
  5756. char *startp;
  5757. char *loc;
  5758. char *rmesc, *rmescend;
  5759. char *str;
  5760. IF_ASH_BASH_COMPAT(const char *repl = NULL;)
  5761. IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
  5762. int saveherefd = herefd;
  5763. int amount, workloc, resetloc;
  5764. int zero;
  5765. char *(*scan)(char*, char*, char*, char*, int, int);
  5766. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  5767. // p, varname, strloc, subtype, startloc, varflags, quotes);
  5768. herefd = -1;
  5769. argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
  5770. var_str_list);
  5771. STPUTC('\0', expdest);
  5772. herefd = saveherefd;
  5773. argbackq = saveargbackq;
  5774. startp = (char *)stackblock() + startloc;
  5775. switch (subtype) {
  5776. case VSASSIGN:
  5777. setvar(varname, startp, 0);
  5778. amount = startp - expdest;
  5779. STADJUST(amount, expdest);
  5780. return startp;
  5781. case VSQUESTION:
  5782. varunset(p, varname, startp, varflags);
  5783. /* NOTREACHED */
  5784. #if ENABLE_ASH_BASH_COMPAT
  5785. case VSSUBSTR:
  5786. loc = str = stackblock() + strloc;
  5787. /* Read POS in ${var:POS:LEN} */
  5788. pos = atoi(loc); /* number(loc) errors out on "1:4" */
  5789. len = str - startp - 1;
  5790. /* *loc != '\0', guaranteed by parser */
  5791. if (quotes) {
  5792. char *ptr;
  5793. /* Adjust the length by the number of escapes */
  5794. for (ptr = startp; ptr < (str - 1); ptr++) {
  5795. if ((unsigned char)*ptr == CTLESC) {
  5796. len--;
  5797. ptr++;
  5798. }
  5799. }
  5800. }
  5801. orig_len = len;
  5802. if (*loc++ == ':') {
  5803. /* ${var::LEN} */
  5804. len = number(loc);
  5805. } else {
  5806. /* Skip POS in ${var:POS:LEN} */
  5807. len = orig_len;
  5808. while (*loc && *loc != ':') {
  5809. /* TODO?
  5810. * bash complains on: var=qwe; echo ${var:1a:123}
  5811. if (!isdigit(*loc))
  5812. ash_msg_and_raise_error(msg_illnum, str);
  5813. */
  5814. loc++;
  5815. }
  5816. if (*loc++ == ':') {
  5817. len = number(loc);
  5818. }
  5819. }
  5820. if (pos >= orig_len) {
  5821. pos = 0;
  5822. len = 0;
  5823. }
  5824. if (len > (orig_len - pos))
  5825. len = orig_len - pos;
  5826. for (str = startp; pos; str++, pos--) {
  5827. if (quotes && (unsigned char)*str == CTLESC)
  5828. str++;
  5829. }
  5830. for (loc = startp; len; len--) {
  5831. if (quotes && (unsigned char)*str == CTLESC)
  5832. *loc++ = *str++;
  5833. *loc++ = *str++;
  5834. }
  5835. *loc = '\0';
  5836. amount = loc - expdest;
  5837. STADJUST(amount, expdest);
  5838. return loc;
  5839. #endif
  5840. }
  5841. resetloc = expdest - (char *)stackblock();
  5842. /* We'll comeback here if we grow the stack while handling
  5843. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  5844. * stack will need rebasing, and we'll need to remove our work
  5845. * areas each time
  5846. */
  5847. IF_ASH_BASH_COMPAT(restart:)
  5848. amount = expdest - ((char *)stackblock() + resetloc);
  5849. STADJUST(-amount, expdest);
  5850. startp = (char *)stackblock() + startloc;
  5851. rmesc = startp;
  5852. rmescend = (char *)stackblock() + strloc;
  5853. if (quotes) {
  5854. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  5855. if (rmesc != startp) {
  5856. rmescend = expdest;
  5857. startp = (char *)stackblock() + startloc;
  5858. }
  5859. }
  5860. rmescend--;
  5861. str = (char *)stackblock() + strloc;
  5862. preglob(str, varflags & VSQUOTE, 0);
  5863. workloc = expdest - (char *)stackblock();
  5864. #if ENABLE_ASH_BASH_COMPAT
  5865. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  5866. char *idx, *end;
  5867. if (!repl) {
  5868. repl = parse_sub_pattern(str, varflags);
  5869. //bb_error_msg("repl:'%s'", repl);
  5870. if (!repl)
  5871. repl = nullstr;
  5872. }
  5873. /* If there's no pattern to match, return the expansion unmolested */
  5874. if (str[0] == '\0')
  5875. return NULL;
  5876. len = 0;
  5877. idx = startp;
  5878. end = str - 1;
  5879. while (idx < end) {
  5880. try_to_match:
  5881. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  5882. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  5883. if (!loc) {
  5884. /* No match, advance */
  5885. char *restart_detect = stackblock();
  5886. skip_matching:
  5887. STPUTC(*idx, expdest);
  5888. if (quotes && (unsigned char)*idx == CTLESC) {
  5889. idx++;
  5890. len++;
  5891. STPUTC(*idx, expdest);
  5892. }
  5893. if (stackblock() != restart_detect)
  5894. goto restart;
  5895. idx++;
  5896. len++;
  5897. rmesc++;
  5898. /* continue; - prone to quadratic behavior, smarter code: */
  5899. if (idx >= end)
  5900. break;
  5901. if (str[0] == '*') {
  5902. /* Pattern is "*foo". If "*foo" does not match "long_string",
  5903. * it would never match "ong_string" etc, no point in trying.
  5904. */
  5905. goto skip_matching;
  5906. }
  5907. goto try_to_match;
  5908. }
  5909. if (subtype == VSREPLACEALL) {
  5910. while (idx < loc) {
  5911. if (quotes && (unsigned char)*idx == CTLESC)
  5912. idx++;
  5913. idx++;
  5914. rmesc++;
  5915. }
  5916. } else {
  5917. idx = loc;
  5918. }
  5919. //bb_error_msg("repl:'%s'", repl);
  5920. for (loc = (char*)repl; *loc; loc++) {
  5921. char *restart_detect = stackblock();
  5922. if (quotes && *loc == '\\') {
  5923. STPUTC(CTLESC, expdest);
  5924. len++;
  5925. }
  5926. STPUTC(*loc, expdest);
  5927. if (stackblock() != restart_detect)
  5928. goto restart;
  5929. len++;
  5930. }
  5931. if (subtype == VSREPLACE) {
  5932. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  5933. while (*idx) {
  5934. char *restart_detect = stackblock();
  5935. STPUTC(*idx, expdest);
  5936. if (stackblock() != restart_detect)
  5937. goto restart;
  5938. len++;
  5939. idx++;
  5940. }
  5941. break;
  5942. }
  5943. }
  5944. /* We've put the replaced text into a buffer at workloc, now
  5945. * move it to the right place and adjust the stack.
  5946. */
  5947. STPUTC('\0', expdest);
  5948. startp = (char *)stackblock() + startloc;
  5949. memmove(startp, (char *)stackblock() + workloc, len + 1);
  5950. //bb_error_msg("startp:'%s'", startp);
  5951. amount = expdest - (startp + len);
  5952. STADJUST(-amount, expdest);
  5953. return startp;
  5954. }
  5955. #endif /* ENABLE_ASH_BASH_COMPAT */
  5956. subtype -= VSTRIMRIGHT;
  5957. #if DEBUG
  5958. if (subtype < 0 || subtype > 7)
  5959. abort();
  5960. #endif
  5961. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  5962. zero = subtype >> 1;
  5963. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  5964. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  5965. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  5966. if (loc) {
  5967. if (zero) {
  5968. memmove(startp, loc, str - loc);
  5969. loc = startp + (str - loc) - 1;
  5970. }
  5971. *loc = '\0';
  5972. amount = loc - expdest;
  5973. STADJUST(amount, expdest);
  5974. }
  5975. return loc;
  5976. }
  5977. /*
  5978. * Add the value of a specialized variable to the stack string.
  5979. * name parameter (examples):
  5980. * ash -c 'echo $1' name:'1='
  5981. * ash -c 'echo $qwe' name:'qwe='
  5982. * ash -c 'echo $$' name:'$='
  5983. * ash -c 'echo ${$}' name:'$='
  5984. * ash -c 'echo ${$##q}' name:'$=q'
  5985. * ash -c 'echo ${#$}' name:'$='
  5986. * note: examples with bad shell syntax:
  5987. * ash -c 'echo ${#$1}' name:'$=1'
  5988. * ash -c 'echo ${#1#}' name:'1=#'
  5989. */
  5990. static NOINLINE ssize_t
  5991. varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
  5992. {
  5993. const char *p;
  5994. int num;
  5995. int i;
  5996. int sepq = 0;
  5997. ssize_t len = 0;
  5998. int subtype = varflags & VSTYPE;
  5999. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
  6000. int quoted = varflags & VSQUOTE;
  6001. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  6002. switch (*name) {
  6003. case '$':
  6004. num = rootpid;
  6005. goto numvar;
  6006. case '?':
  6007. num = exitstatus;
  6008. goto numvar;
  6009. case '#':
  6010. num = shellparam.nparam;
  6011. goto numvar;
  6012. case '!':
  6013. num = backgndpid;
  6014. if (num == 0)
  6015. return -1;
  6016. numvar:
  6017. len = cvtnum(num);
  6018. goto check_1char_name;
  6019. case '-':
  6020. expdest = makestrspace(NOPTS, expdest);
  6021. for (i = NOPTS - 1; i >= 0; i--) {
  6022. if (optlist[i]) {
  6023. USTPUTC(optletters(i), expdest);
  6024. len++;
  6025. }
  6026. }
  6027. check_1char_name:
  6028. #if 0
  6029. /* handles cases similar to ${#$1} */
  6030. if (name[2] != '\0')
  6031. raise_error_syntax("bad substitution");
  6032. #endif
  6033. break;
  6034. case '@': {
  6035. char **ap;
  6036. int sep;
  6037. if (quoted && (flags & EXP_FULL)) {
  6038. /* note: this is not meant as PEOF value */
  6039. sep = 1 << CHAR_BIT;
  6040. goto param;
  6041. }
  6042. /* fall through */
  6043. case '*':
  6044. sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
  6045. i = SIT(sep, syntax);
  6046. if (quotes && (i == CCTL || i == CBACK))
  6047. sepq = 1;
  6048. param:
  6049. ap = shellparam.p;
  6050. if (!ap)
  6051. return -1;
  6052. while ((p = *ap++) != NULL) {
  6053. size_t partlen;
  6054. partlen = strlen(p);
  6055. len += partlen;
  6056. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  6057. memtodest(p, partlen, syntax, quotes);
  6058. if (*ap && sep) {
  6059. char *q;
  6060. len++;
  6061. if (subtype == VSPLUS || subtype == VSLENGTH) {
  6062. continue;
  6063. }
  6064. q = expdest;
  6065. if (sepq)
  6066. STPUTC(CTLESC, q);
  6067. /* note: may put NUL despite sep != 0
  6068. * (see sep = 1 << CHAR_BIT above) */
  6069. STPUTC(sep, q);
  6070. expdest = q;
  6071. }
  6072. }
  6073. return len;
  6074. } /* case '@' and '*' */
  6075. case '0':
  6076. case '1':
  6077. case '2':
  6078. case '3':
  6079. case '4':
  6080. case '5':
  6081. case '6':
  6082. case '7':
  6083. case '8':
  6084. case '9':
  6085. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6086. if (num < 0 || num > shellparam.nparam)
  6087. return -1;
  6088. p = num ? shellparam.p[num - 1] : arg0;
  6089. goto value;
  6090. default:
  6091. /* NB: name has form "VAR=..." */
  6092. /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
  6093. * which should be considered before we check variables. */
  6094. if (var_str_list) {
  6095. unsigned name_len = (strchrnul(name, '=') - name) + 1;
  6096. p = NULL;
  6097. do {
  6098. char *str, *eq;
  6099. str = var_str_list->text;
  6100. eq = strchr(str, '=');
  6101. if (!eq) /* stop at first non-assignment */
  6102. break;
  6103. eq++;
  6104. if (name_len == (unsigned)(eq - str)
  6105. && strncmp(str, name, name_len) == 0
  6106. ) {
  6107. p = eq;
  6108. /* goto value; - WRONG! */
  6109. /* think "A=1 A=2 B=$A" */
  6110. }
  6111. var_str_list = var_str_list->next;
  6112. } while (var_str_list);
  6113. if (p)
  6114. goto value;
  6115. }
  6116. p = lookupvar(name);
  6117. value:
  6118. if (!p)
  6119. return -1;
  6120. len = strlen(p);
  6121. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  6122. memtodest(p, len, syntax, quotes);
  6123. return len;
  6124. }
  6125. if (subtype == VSPLUS || subtype == VSLENGTH)
  6126. STADJUST(-len, expdest);
  6127. return len;
  6128. }
  6129. /*
  6130. * Expand a variable, and return a pointer to the next character in the
  6131. * input string.
  6132. */
  6133. static char *
  6134. evalvar(char *p, int flags, struct strlist *var_str_list)
  6135. {
  6136. char varflags;
  6137. char subtype;
  6138. char quoted;
  6139. char easy;
  6140. char *var;
  6141. int patloc;
  6142. int startloc;
  6143. ssize_t varlen;
  6144. varflags = (unsigned char) *p++;
  6145. subtype = varflags & VSTYPE;
  6146. quoted = varflags & VSQUOTE;
  6147. var = p;
  6148. easy = (!quoted || (*var == '@' && shellparam.nparam));
  6149. startloc = expdest - (char *)stackblock();
  6150. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6151. again:
  6152. varlen = varvalue(var, varflags, flags, var_str_list);
  6153. if (varflags & VSNUL)
  6154. varlen--;
  6155. if (subtype == VSPLUS) {
  6156. varlen = -1 - varlen;
  6157. goto vsplus;
  6158. }
  6159. if (subtype == VSMINUS) {
  6160. vsplus:
  6161. if (varlen < 0) {
  6162. argstr(
  6163. p,
  6164. flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
  6165. var_str_list
  6166. );
  6167. goto end;
  6168. }
  6169. if (easy)
  6170. goto record;
  6171. goto end;
  6172. }
  6173. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6174. if (varlen < 0) {
  6175. if (subevalvar(p, var, /* strloc: */ 0,
  6176. subtype, startloc, varflags,
  6177. /* quotes: */ 0,
  6178. var_str_list)
  6179. ) {
  6180. varflags &= ~VSNUL;
  6181. /*
  6182. * Remove any recorded regions beyond
  6183. * start of variable
  6184. */
  6185. removerecordregions(startloc);
  6186. goto again;
  6187. }
  6188. goto end;
  6189. }
  6190. if (easy)
  6191. goto record;
  6192. goto end;
  6193. }
  6194. if (varlen < 0 && uflag)
  6195. varunset(p, var, 0, 0);
  6196. if (subtype == VSLENGTH) {
  6197. cvtnum(varlen > 0 ? varlen : 0);
  6198. goto record;
  6199. }
  6200. if (subtype == VSNORMAL) {
  6201. if (easy)
  6202. goto record;
  6203. goto end;
  6204. }
  6205. #if DEBUG
  6206. switch (subtype) {
  6207. case VSTRIMLEFT:
  6208. case VSTRIMLEFTMAX:
  6209. case VSTRIMRIGHT:
  6210. case VSTRIMRIGHTMAX:
  6211. #if ENABLE_ASH_BASH_COMPAT
  6212. case VSSUBSTR:
  6213. case VSREPLACE:
  6214. case VSREPLACEALL:
  6215. #endif
  6216. break;
  6217. default:
  6218. abort();
  6219. }
  6220. #endif
  6221. if (varlen >= 0) {
  6222. /*
  6223. * Terminate the string and start recording the pattern
  6224. * right after it
  6225. */
  6226. STPUTC('\0', expdest);
  6227. patloc = expdest - (char *)stackblock();
  6228. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6229. startloc, varflags,
  6230. //TODO: | EXP_REDIR too? All other such places do it too
  6231. /* quotes: */ flags & (EXP_FULL | EXP_CASE),
  6232. var_str_list)
  6233. ) {
  6234. int amount = expdest - (
  6235. (char *)stackblock() + patloc - 1
  6236. );
  6237. STADJUST(-amount, expdest);
  6238. }
  6239. /* Remove any recorded regions beyond start of variable */
  6240. removerecordregions(startloc);
  6241. record:
  6242. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6243. }
  6244. end:
  6245. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6246. int nesting = 1;
  6247. for (;;) {
  6248. unsigned char c = *p++;
  6249. if (c == CTLESC)
  6250. p++;
  6251. else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
  6252. if (varlen >= 0)
  6253. argbackq = argbackq->next;
  6254. } else if (c == CTLVAR) {
  6255. if ((*p++ & VSTYPE) != VSNORMAL)
  6256. nesting++;
  6257. } else if (c == CTLENDVAR) {
  6258. if (--nesting == 0)
  6259. break;
  6260. }
  6261. }
  6262. }
  6263. return p;
  6264. }
  6265. /*
  6266. * Break the argument string into pieces based upon IFS and add the
  6267. * strings to the argument list. The regions of the string to be
  6268. * searched for IFS characters have been stored by recordregion.
  6269. */
  6270. static void
  6271. ifsbreakup(char *string, struct arglist *arglist)
  6272. {
  6273. struct ifsregion *ifsp;
  6274. struct strlist *sp;
  6275. char *start;
  6276. char *p;
  6277. char *q;
  6278. const char *ifs, *realifs;
  6279. int ifsspc;
  6280. int nulonly;
  6281. start = string;
  6282. if (ifslastp != NULL) {
  6283. ifsspc = 0;
  6284. nulonly = 0;
  6285. realifs = ifsset() ? ifsval() : defifs;
  6286. ifsp = &ifsfirst;
  6287. do {
  6288. p = string + ifsp->begoff;
  6289. nulonly = ifsp->nulonly;
  6290. ifs = nulonly ? nullstr : realifs;
  6291. ifsspc = 0;
  6292. while (p < string + ifsp->endoff) {
  6293. q = p;
  6294. if ((unsigned char)*p == CTLESC)
  6295. p++;
  6296. if (!strchr(ifs, *p)) {
  6297. p++;
  6298. continue;
  6299. }
  6300. if (!nulonly)
  6301. ifsspc = (strchr(defifs, *p) != NULL);
  6302. /* Ignore IFS whitespace at start */
  6303. if (q == start && ifsspc) {
  6304. p++;
  6305. start = p;
  6306. continue;
  6307. }
  6308. *q = '\0';
  6309. sp = stzalloc(sizeof(*sp));
  6310. sp->text = start;
  6311. *arglist->lastp = sp;
  6312. arglist->lastp = &sp->next;
  6313. p++;
  6314. if (!nulonly) {
  6315. for (;;) {
  6316. if (p >= string + ifsp->endoff) {
  6317. break;
  6318. }
  6319. q = p;
  6320. if ((unsigned char)*p == CTLESC)
  6321. p++;
  6322. if (strchr(ifs, *p) == NULL) {
  6323. p = q;
  6324. break;
  6325. }
  6326. if (strchr(defifs, *p) == NULL) {
  6327. if (ifsspc) {
  6328. p++;
  6329. ifsspc = 0;
  6330. } else {
  6331. p = q;
  6332. break;
  6333. }
  6334. } else
  6335. p++;
  6336. }
  6337. }
  6338. start = p;
  6339. } /* while */
  6340. ifsp = ifsp->next;
  6341. } while (ifsp != NULL);
  6342. if (nulonly)
  6343. goto add;
  6344. }
  6345. if (!*start)
  6346. return;
  6347. add:
  6348. sp = stzalloc(sizeof(*sp));
  6349. sp->text = start;
  6350. *arglist->lastp = sp;
  6351. arglist->lastp = &sp->next;
  6352. }
  6353. static void
  6354. ifsfree(void)
  6355. {
  6356. struct ifsregion *p;
  6357. INT_OFF;
  6358. p = ifsfirst.next;
  6359. do {
  6360. struct ifsregion *ifsp;
  6361. ifsp = p->next;
  6362. free(p);
  6363. p = ifsp;
  6364. } while (p);
  6365. ifslastp = NULL;
  6366. ifsfirst.next = NULL;
  6367. INT_ON;
  6368. }
  6369. /*
  6370. * Add a file name to the list.
  6371. */
  6372. static void
  6373. addfname(const char *name)
  6374. {
  6375. struct strlist *sp;
  6376. sp = stzalloc(sizeof(*sp));
  6377. sp->text = ststrdup(name);
  6378. *exparg.lastp = sp;
  6379. exparg.lastp = &sp->next;
  6380. }
  6381. /*
  6382. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6383. */
  6384. static void
  6385. expmeta(char *expdir, char *enddir, char *name)
  6386. {
  6387. char *p;
  6388. const char *cp;
  6389. char *start;
  6390. char *endname;
  6391. int metaflag;
  6392. struct stat statb;
  6393. DIR *dirp;
  6394. struct dirent *dp;
  6395. int atend;
  6396. int matchdot;
  6397. metaflag = 0;
  6398. start = name;
  6399. for (p = name; *p; p++) {
  6400. if (*p == '*' || *p == '?')
  6401. metaflag = 1;
  6402. else if (*p == '[') {
  6403. char *q = p + 1;
  6404. if (*q == '!')
  6405. q++;
  6406. for (;;) {
  6407. if (*q == '\\')
  6408. q++;
  6409. if (*q == '/' || *q == '\0')
  6410. break;
  6411. if (*++q == ']') {
  6412. metaflag = 1;
  6413. break;
  6414. }
  6415. }
  6416. } else if (*p == '\\')
  6417. p++;
  6418. else if (*p == '/') {
  6419. if (metaflag)
  6420. goto out;
  6421. start = p + 1;
  6422. }
  6423. }
  6424. out:
  6425. if (metaflag == 0) { /* we've reached the end of the file name */
  6426. if (enddir != expdir)
  6427. metaflag++;
  6428. p = name;
  6429. do {
  6430. if (*p == '\\')
  6431. p++;
  6432. *enddir++ = *p;
  6433. } while (*p++);
  6434. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6435. addfname(expdir);
  6436. return;
  6437. }
  6438. endname = p;
  6439. if (name < start) {
  6440. p = name;
  6441. do {
  6442. if (*p == '\\')
  6443. p++;
  6444. *enddir++ = *p++;
  6445. } while (p < start);
  6446. }
  6447. if (enddir == expdir) {
  6448. cp = ".";
  6449. } else if (enddir == expdir + 1 && *expdir == '/') {
  6450. cp = "/";
  6451. } else {
  6452. cp = expdir;
  6453. enddir[-1] = '\0';
  6454. }
  6455. dirp = opendir(cp);
  6456. if (dirp == NULL)
  6457. return;
  6458. if (enddir != expdir)
  6459. enddir[-1] = '/';
  6460. if (*endname == 0) {
  6461. atend = 1;
  6462. } else {
  6463. atend = 0;
  6464. *endname++ = '\0';
  6465. }
  6466. matchdot = 0;
  6467. p = start;
  6468. if (*p == '\\')
  6469. p++;
  6470. if (*p == '.')
  6471. matchdot++;
  6472. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  6473. if (dp->d_name[0] == '.' && !matchdot)
  6474. continue;
  6475. if (pmatch(start, dp->d_name)) {
  6476. if (atend) {
  6477. strcpy(enddir, dp->d_name);
  6478. addfname(expdir);
  6479. } else {
  6480. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6481. continue;
  6482. p[-1] = '/';
  6483. expmeta(expdir, p, endname);
  6484. }
  6485. }
  6486. }
  6487. closedir(dirp);
  6488. if (!atend)
  6489. endname[-1] = '/';
  6490. }
  6491. static struct strlist *
  6492. msort(struct strlist *list, int len)
  6493. {
  6494. struct strlist *p, *q = NULL;
  6495. struct strlist **lpp;
  6496. int half;
  6497. int n;
  6498. if (len <= 1)
  6499. return list;
  6500. half = len >> 1;
  6501. p = list;
  6502. for (n = half; --n >= 0;) {
  6503. q = p;
  6504. p = p->next;
  6505. }
  6506. q->next = NULL; /* terminate first half of list */
  6507. q = msort(list, half); /* sort first half of list */
  6508. p = msort(p, len - half); /* sort second half */
  6509. lpp = &list;
  6510. for (;;) {
  6511. #if ENABLE_LOCALE_SUPPORT
  6512. if (strcoll(p->text, q->text) < 0)
  6513. #else
  6514. if (strcmp(p->text, q->text) < 0)
  6515. #endif
  6516. {
  6517. *lpp = p;
  6518. lpp = &p->next;
  6519. p = *lpp;
  6520. if (p == NULL) {
  6521. *lpp = q;
  6522. break;
  6523. }
  6524. } else {
  6525. *lpp = q;
  6526. lpp = &q->next;
  6527. q = *lpp;
  6528. if (q == NULL) {
  6529. *lpp = p;
  6530. break;
  6531. }
  6532. }
  6533. }
  6534. return list;
  6535. }
  6536. /*
  6537. * Sort the results of file name expansion. It calculates the number of
  6538. * strings to sort and then calls msort (short for merge sort) to do the
  6539. * work.
  6540. */
  6541. static struct strlist *
  6542. expsort(struct strlist *str)
  6543. {
  6544. int len;
  6545. struct strlist *sp;
  6546. len = 0;
  6547. for (sp = str; sp; sp = sp->next)
  6548. len++;
  6549. return msort(str, len);
  6550. }
  6551. static void
  6552. expandmeta(struct strlist *str /*, int flag*/)
  6553. {
  6554. static const char metachars[] ALIGN1 = {
  6555. '*', '?', '[', 0
  6556. };
  6557. /* TODO - EXP_REDIR */
  6558. while (str) {
  6559. char *expdir;
  6560. struct strlist **savelastp;
  6561. struct strlist *sp;
  6562. char *p;
  6563. if (fflag)
  6564. goto nometa;
  6565. if (!strpbrk(str->text, metachars))
  6566. goto nometa;
  6567. savelastp = exparg.lastp;
  6568. INT_OFF;
  6569. p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6570. {
  6571. int i = strlen(str->text);
  6572. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  6573. }
  6574. expmeta(expdir, expdir, p);
  6575. free(expdir);
  6576. if (p != str->text)
  6577. free(p);
  6578. INT_ON;
  6579. if (exparg.lastp == savelastp) {
  6580. /*
  6581. * no matches
  6582. */
  6583. nometa:
  6584. *exparg.lastp = str;
  6585. rmescapes(str->text, 0);
  6586. exparg.lastp = &str->next;
  6587. } else {
  6588. *exparg.lastp = NULL;
  6589. *savelastp = sp = expsort(*savelastp);
  6590. while (sp->next != NULL)
  6591. sp = sp->next;
  6592. exparg.lastp = &sp->next;
  6593. }
  6594. str = str->next;
  6595. }
  6596. }
  6597. /*
  6598. * Perform variable substitution and command substitution on an argument,
  6599. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6600. * perform splitting and file name expansion. When arglist is NULL, perform
  6601. * here document expansion.
  6602. */
  6603. static void
  6604. expandarg(union node *arg, struct arglist *arglist, int flag)
  6605. {
  6606. struct strlist *sp;
  6607. char *p;
  6608. argbackq = arg->narg.backquote;
  6609. STARTSTACKSTR(expdest);
  6610. ifsfirst.next = NULL;
  6611. ifslastp = NULL;
  6612. argstr(arg->narg.text, flag,
  6613. /* var_str_list: */ arglist ? arglist->list : NULL);
  6614. p = _STPUTC('\0', expdest);
  6615. expdest = p - 1;
  6616. if (arglist == NULL) {
  6617. return; /* here document expanded */
  6618. }
  6619. p = grabstackstr(p);
  6620. exparg.lastp = &exparg.list;
  6621. /*
  6622. * TODO - EXP_REDIR
  6623. */
  6624. if (flag & EXP_FULL) {
  6625. ifsbreakup(p, &exparg);
  6626. *exparg.lastp = NULL;
  6627. exparg.lastp = &exparg.list;
  6628. expandmeta(exparg.list /*, flag*/);
  6629. } else {
  6630. if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
  6631. rmescapes(p, 0);
  6632. sp = stzalloc(sizeof(*sp));
  6633. sp->text = p;
  6634. *exparg.lastp = sp;
  6635. exparg.lastp = &sp->next;
  6636. }
  6637. if (ifsfirst.next)
  6638. ifsfree();
  6639. *exparg.lastp = NULL;
  6640. if (exparg.list) {
  6641. *arglist->lastp = exparg.list;
  6642. arglist->lastp = exparg.lastp;
  6643. }
  6644. }
  6645. /*
  6646. * Expand shell variables and backquotes inside a here document.
  6647. */
  6648. static void
  6649. expandhere(union node *arg, int fd)
  6650. {
  6651. herefd = fd;
  6652. expandarg(arg, (struct arglist *)NULL, 0);
  6653. full_write(fd, stackblock(), expdest - (char *)stackblock());
  6654. }
  6655. /*
  6656. * Returns true if the pattern matches the string.
  6657. */
  6658. static int
  6659. patmatch(char *pattern, const char *string)
  6660. {
  6661. return pmatch(preglob(pattern, 0, 0), string);
  6662. }
  6663. /*
  6664. * See if a pattern matches in a case statement.
  6665. */
  6666. static int
  6667. casematch(union node *pattern, char *val)
  6668. {
  6669. struct stackmark smark;
  6670. int result;
  6671. setstackmark(&smark);
  6672. argbackq = pattern->narg.backquote;
  6673. STARTSTACKSTR(expdest);
  6674. ifslastp = NULL;
  6675. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
  6676. /* var_str_list: */ NULL);
  6677. STACKSTRNUL(expdest);
  6678. result = patmatch(stackblock(), val);
  6679. popstackmark(&smark);
  6680. return result;
  6681. }
  6682. /* ============ find_command */
  6683. struct builtincmd {
  6684. const char *name;
  6685. int (*builtin)(int, char **) FAST_FUNC;
  6686. /* unsigned flags; */
  6687. };
  6688. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  6689. /* "regular" builtins always take precedence over commands,
  6690. * regardless of PATH=....%builtin... position */
  6691. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  6692. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  6693. struct cmdentry {
  6694. smallint cmdtype; /* CMDxxx */
  6695. union param {
  6696. int index;
  6697. /* index >= 0 for commands without path (slashes) */
  6698. /* (TODO: what exactly does the value mean? PATH position?) */
  6699. /* index == -1 for commands with slashes */
  6700. /* index == (-2 - applet_no) for NOFORK applets */
  6701. const struct builtincmd *cmd;
  6702. struct funcnode *func;
  6703. } u;
  6704. };
  6705. /* values of cmdtype */
  6706. #define CMDUNKNOWN -1 /* no entry in table for command */
  6707. #define CMDNORMAL 0 /* command is an executable program */
  6708. #define CMDFUNCTION 1 /* command is a shell function */
  6709. #define CMDBUILTIN 2 /* command is a shell builtin */
  6710. /* action to find_command() */
  6711. #define DO_ERR 0x01 /* prints errors */
  6712. #define DO_ABS 0x02 /* checks absolute paths */
  6713. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  6714. #define DO_ALTPATH 0x08 /* using alternate path */
  6715. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  6716. static void find_command(char *, struct cmdentry *, int, const char *);
  6717. /* ============ Hashing commands */
  6718. /*
  6719. * When commands are first encountered, they are entered in a hash table.
  6720. * This ensures that a full path search will not have to be done for them
  6721. * on each invocation.
  6722. *
  6723. * We should investigate converting to a linear search, even though that
  6724. * would make the command name "hash" a misnomer.
  6725. */
  6726. struct tblentry {
  6727. struct tblentry *next; /* next entry in hash chain */
  6728. union param param; /* definition of builtin function */
  6729. smallint cmdtype; /* CMDxxx */
  6730. char rehash; /* if set, cd done since entry created */
  6731. char cmdname[1]; /* name of command */
  6732. };
  6733. static struct tblentry **cmdtable;
  6734. #define INIT_G_cmdtable() do { \
  6735. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  6736. } while (0)
  6737. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  6738. static void
  6739. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
  6740. {
  6741. #if ENABLE_FEATURE_SH_STANDALONE
  6742. if (applet_no >= 0) {
  6743. if (APPLET_IS_NOEXEC(applet_no)) {
  6744. clearenv();
  6745. while (*envp)
  6746. putenv(*envp++);
  6747. run_applet_no_and_exit(applet_no, argv);
  6748. }
  6749. /* re-exec ourselves with the new arguments */
  6750. execve(bb_busybox_exec_path, argv, envp);
  6751. /* If they called chroot or otherwise made the binary no longer
  6752. * executable, fall through */
  6753. }
  6754. #endif
  6755. repeat:
  6756. #ifdef SYSV
  6757. do {
  6758. execve(cmd, argv, envp);
  6759. } while (errno == EINTR);
  6760. #else
  6761. execve(cmd, argv, envp);
  6762. #endif
  6763. if (cmd == (char*) bb_busybox_exec_path) {
  6764. /* We already visited ENOEXEC branch below, don't do it again */
  6765. //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
  6766. free(argv);
  6767. return;
  6768. }
  6769. if (errno == ENOEXEC) {
  6770. /* Run "cmd" as a shell script:
  6771. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  6772. * "If the execve() function fails with ENOEXEC, the shell
  6773. * shall execute a command equivalent to having a shell invoked
  6774. * with the command name as its first operand,
  6775. * with any remaining arguments passed to the new shell"
  6776. *
  6777. * That is, do not use $SHELL, user's shell, or /bin/sh;
  6778. * just call ourselves.
  6779. */
  6780. char **ap;
  6781. char **new;
  6782. for (ap = argv; *ap; ap++)
  6783. continue;
  6784. new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
  6785. new[0] = (char*) "ash";
  6786. new[1] = cmd;
  6787. ap = new + 2;
  6788. while ((*ap++ = *++argv) != NULL)
  6789. continue;
  6790. cmd = (char*) bb_busybox_exec_path;
  6791. argv = new;
  6792. goto repeat;
  6793. }
  6794. }
  6795. /*
  6796. * Exec a program. Never returns. If you change this routine, you may
  6797. * have to change the find_command routine as well.
  6798. */
  6799. static void shellexec(char **, const char *, int) NORETURN;
  6800. static void
  6801. shellexec(char **argv, const char *path, int idx)
  6802. {
  6803. char *cmdname;
  6804. int e;
  6805. char **envp;
  6806. int exerrno;
  6807. #if ENABLE_FEATURE_SH_STANDALONE
  6808. int applet_no = -1;
  6809. #endif
  6810. clearredir(/*drop:*/ 1);
  6811. envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
  6812. if (strchr(argv[0], '/') != NULL
  6813. #if ENABLE_FEATURE_SH_STANDALONE
  6814. || (applet_no = find_applet_by_name(argv[0])) >= 0
  6815. #endif
  6816. ) {
  6817. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
  6818. e = errno;
  6819. } else {
  6820. e = ENOENT;
  6821. while ((cmdname = path_advance(&path, argv[0])) != NULL) {
  6822. if (--idx < 0 && pathopt == NULL) {
  6823. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  6824. if (errno != ENOENT && errno != ENOTDIR)
  6825. e = errno;
  6826. }
  6827. stunalloc(cmdname);
  6828. }
  6829. }
  6830. /* Map to POSIX errors */
  6831. switch (e) {
  6832. case EACCES:
  6833. exerrno = 126;
  6834. break;
  6835. case ENOENT:
  6836. exerrno = 127;
  6837. break;
  6838. default:
  6839. exerrno = 2;
  6840. break;
  6841. }
  6842. exitstatus = exerrno;
  6843. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  6844. argv[0], e, suppress_int));
  6845. ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
  6846. /* NOTREACHED */
  6847. }
  6848. static void
  6849. printentry(struct tblentry *cmdp)
  6850. {
  6851. int idx;
  6852. const char *path;
  6853. char *name;
  6854. idx = cmdp->param.index;
  6855. path = pathval();
  6856. do {
  6857. name = path_advance(&path, cmdp->cmdname);
  6858. stunalloc(name);
  6859. } while (--idx >= 0);
  6860. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  6861. }
  6862. /*
  6863. * Clear out command entries. The argument specifies the first entry in
  6864. * PATH which has changed.
  6865. */
  6866. static void
  6867. clearcmdentry(int firstchange)
  6868. {
  6869. struct tblentry **tblp;
  6870. struct tblentry **pp;
  6871. struct tblentry *cmdp;
  6872. INT_OFF;
  6873. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  6874. pp = tblp;
  6875. while ((cmdp = *pp) != NULL) {
  6876. if ((cmdp->cmdtype == CMDNORMAL &&
  6877. cmdp->param.index >= firstchange)
  6878. || (cmdp->cmdtype == CMDBUILTIN &&
  6879. builtinloc >= firstchange)
  6880. ) {
  6881. *pp = cmdp->next;
  6882. free(cmdp);
  6883. } else {
  6884. pp = &cmdp->next;
  6885. }
  6886. }
  6887. }
  6888. INT_ON;
  6889. }
  6890. /*
  6891. * Locate a command in the command hash table. If "add" is nonzero,
  6892. * add the command to the table if it is not already present. The
  6893. * variable "lastcmdentry" is set to point to the address of the link
  6894. * pointing to the entry, so that delete_cmd_entry can delete the
  6895. * entry.
  6896. *
  6897. * Interrupts must be off if called with add != 0.
  6898. */
  6899. static struct tblentry **lastcmdentry;
  6900. static struct tblentry *
  6901. cmdlookup(const char *name, int add)
  6902. {
  6903. unsigned int hashval;
  6904. const char *p;
  6905. struct tblentry *cmdp;
  6906. struct tblentry **pp;
  6907. p = name;
  6908. hashval = (unsigned char)*p << 4;
  6909. while (*p)
  6910. hashval += (unsigned char)*p++;
  6911. hashval &= 0x7FFF;
  6912. pp = &cmdtable[hashval % CMDTABLESIZE];
  6913. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6914. if (strcmp(cmdp->cmdname, name) == 0)
  6915. break;
  6916. pp = &cmdp->next;
  6917. }
  6918. if (add && cmdp == NULL) {
  6919. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  6920. + strlen(name)
  6921. /* + 1 - already done because
  6922. * tblentry::cmdname is char[1] */);
  6923. /*cmdp->next = NULL; - ckzalloc did it */
  6924. cmdp->cmdtype = CMDUNKNOWN;
  6925. strcpy(cmdp->cmdname, name);
  6926. }
  6927. lastcmdentry = pp;
  6928. return cmdp;
  6929. }
  6930. /*
  6931. * Delete the command entry returned on the last lookup.
  6932. */
  6933. static void
  6934. delete_cmd_entry(void)
  6935. {
  6936. struct tblentry *cmdp;
  6937. INT_OFF;
  6938. cmdp = *lastcmdentry;
  6939. *lastcmdentry = cmdp->next;
  6940. if (cmdp->cmdtype == CMDFUNCTION)
  6941. freefunc(cmdp->param.func);
  6942. free(cmdp);
  6943. INT_ON;
  6944. }
  6945. /*
  6946. * Add a new command entry, replacing any existing command entry for
  6947. * the same name - except special builtins.
  6948. */
  6949. static void
  6950. addcmdentry(char *name, struct cmdentry *entry)
  6951. {
  6952. struct tblentry *cmdp;
  6953. cmdp = cmdlookup(name, 1);
  6954. if (cmdp->cmdtype == CMDFUNCTION) {
  6955. freefunc(cmdp->param.func);
  6956. }
  6957. cmdp->cmdtype = entry->cmdtype;
  6958. cmdp->param = entry->u;
  6959. cmdp->rehash = 0;
  6960. }
  6961. static int FAST_FUNC
  6962. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6963. {
  6964. struct tblentry **pp;
  6965. struct tblentry *cmdp;
  6966. int c;
  6967. struct cmdentry entry;
  6968. char *name;
  6969. if (nextopt("r") != '\0') {
  6970. clearcmdentry(0);
  6971. return 0;
  6972. }
  6973. if (*argptr == NULL) {
  6974. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6975. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6976. if (cmdp->cmdtype == CMDNORMAL)
  6977. printentry(cmdp);
  6978. }
  6979. }
  6980. return 0;
  6981. }
  6982. c = 0;
  6983. while ((name = *argptr) != NULL) {
  6984. cmdp = cmdlookup(name, 0);
  6985. if (cmdp != NULL
  6986. && (cmdp->cmdtype == CMDNORMAL
  6987. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  6988. ) {
  6989. delete_cmd_entry();
  6990. }
  6991. find_command(name, &entry, DO_ERR, pathval());
  6992. if (entry.cmdtype == CMDUNKNOWN)
  6993. c = 1;
  6994. argptr++;
  6995. }
  6996. return c;
  6997. }
  6998. /*
  6999. * Called when a cd is done. Marks all commands so the next time they
  7000. * are executed they will be rehashed.
  7001. */
  7002. static void
  7003. hashcd(void)
  7004. {
  7005. struct tblentry **pp;
  7006. struct tblentry *cmdp;
  7007. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7008. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7009. if (cmdp->cmdtype == CMDNORMAL
  7010. || (cmdp->cmdtype == CMDBUILTIN
  7011. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7012. && builtinloc > 0)
  7013. ) {
  7014. cmdp->rehash = 1;
  7015. }
  7016. }
  7017. }
  7018. }
  7019. /*
  7020. * Fix command hash table when PATH changed.
  7021. * Called before PATH is changed. The argument is the new value of PATH;
  7022. * pathval() still returns the old value at this point.
  7023. * Called with interrupts off.
  7024. */
  7025. static void FAST_FUNC
  7026. changepath(const char *new)
  7027. {
  7028. const char *old;
  7029. int firstchange;
  7030. int idx;
  7031. int idx_bltin;
  7032. old = pathval();
  7033. firstchange = 9999; /* assume no change */
  7034. idx = 0;
  7035. idx_bltin = -1;
  7036. for (;;) {
  7037. if (*old != *new) {
  7038. firstchange = idx;
  7039. if ((*old == '\0' && *new == ':')
  7040. || (*old == ':' && *new == '\0')
  7041. ) {
  7042. firstchange++;
  7043. }
  7044. old = new; /* ignore subsequent differences */
  7045. }
  7046. if (*new == '\0')
  7047. break;
  7048. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7049. idx_bltin = idx;
  7050. if (*new == ':')
  7051. idx++;
  7052. new++;
  7053. old++;
  7054. }
  7055. if (builtinloc < 0 && idx_bltin >= 0)
  7056. builtinloc = idx_bltin; /* zap builtins */
  7057. if (builtinloc >= 0 && idx_bltin < 0)
  7058. firstchange = 0;
  7059. clearcmdentry(firstchange);
  7060. builtinloc = idx_bltin;
  7061. }
  7062. #define TEOF 0
  7063. #define TNL 1
  7064. #define TREDIR 2
  7065. #define TWORD 3
  7066. #define TSEMI 4
  7067. #define TBACKGND 5
  7068. #define TAND 6
  7069. #define TOR 7
  7070. #define TPIPE 8
  7071. #define TLP 9
  7072. #define TRP 10
  7073. #define TENDCASE 11
  7074. #define TENDBQUOTE 12
  7075. #define TNOT 13
  7076. #define TCASE 14
  7077. #define TDO 15
  7078. #define TDONE 16
  7079. #define TELIF 17
  7080. #define TELSE 18
  7081. #define TESAC 19
  7082. #define TFI 20
  7083. #define TFOR 21
  7084. #define TIF 22
  7085. #define TIN 23
  7086. #define TTHEN 24
  7087. #define TUNTIL 25
  7088. #define TWHILE 26
  7089. #define TBEGIN 27
  7090. #define TEND 28
  7091. typedef smallint token_id_t;
  7092. /* first char is indicating which tokens mark the end of a list */
  7093. static const char *const tokname_array[] = {
  7094. "\1end of file",
  7095. "\0newline",
  7096. "\0redirection",
  7097. "\0word",
  7098. "\0;",
  7099. "\0&",
  7100. "\0&&",
  7101. "\0||",
  7102. "\0|",
  7103. "\0(",
  7104. "\1)",
  7105. "\1;;",
  7106. "\1`",
  7107. #define KWDOFFSET 13
  7108. /* the following are keywords */
  7109. "\0!",
  7110. "\0case",
  7111. "\1do",
  7112. "\1done",
  7113. "\1elif",
  7114. "\1else",
  7115. "\1esac",
  7116. "\1fi",
  7117. "\0for",
  7118. "\0if",
  7119. "\0in",
  7120. "\1then",
  7121. "\0until",
  7122. "\0while",
  7123. "\0{",
  7124. "\1}",
  7125. };
  7126. /* Wrapper around strcmp for qsort/bsearch/... */
  7127. static int
  7128. pstrcmp(const void *a, const void *b)
  7129. {
  7130. return strcmp((char*) a, (*(char**) b) + 1);
  7131. }
  7132. static const char *const *
  7133. findkwd(const char *s)
  7134. {
  7135. return bsearch(s, tokname_array + KWDOFFSET,
  7136. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7137. sizeof(tokname_array[0]), pstrcmp);
  7138. }
  7139. /*
  7140. * Locate and print what a word is...
  7141. */
  7142. static int
  7143. describe_command(char *command, int describe_command_verbose)
  7144. {
  7145. struct cmdentry entry;
  7146. struct tblentry *cmdp;
  7147. #if ENABLE_ASH_ALIAS
  7148. const struct alias *ap;
  7149. #endif
  7150. const char *path = pathval();
  7151. if (describe_command_verbose) {
  7152. out1str(command);
  7153. }
  7154. /* First look at the keywords */
  7155. if (findkwd(command)) {
  7156. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7157. goto out;
  7158. }
  7159. #if ENABLE_ASH_ALIAS
  7160. /* Then look at the aliases */
  7161. ap = lookupalias(command, 0);
  7162. if (ap != NULL) {
  7163. if (!describe_command_verbose) {
  7164. out1str("alias ");
  7165. printalias(ap);
  7166. return 0;
  7167. }
  7168. out1fmt(" is an alias for %s", ap->val);
  7169. goto out;
  7170. }
  7171. #endif
  7172. /* Then check if it is a tracked alias */
  7173. cmdp = cmdlookup(command, 0);
  7174. if (cmdp != NULL) {
  7175. entry.cmdtype = cmdp->cmdtype;
  7176. entry.u = cmdp->param;
  7177. } else {
  7178. /* Finally use brute force */
  7179. find_command(command, &entry, DO_ABS, path);
  7180. }
  7181. switch (entry.cmdtype) {
  7182. case CMDNORMAL: {
  7183. int j = entry.u.index;
  7184. char *p;
  7185. if (j < 0) {
  7186. p = command;
  7187. } else {
  7188. do {
  7189. p = path_advance(&path, command);
  7190. stunalloc(p);
  7191. } while (--j >= 0);
  7192. }
  7193. if (describe_command_verbose) {
  7194. out1fmt(" is%s %s",
  7195. (cmdp ? " a tracked alias for" : nullstr), p
  7196. );
  7197. } else {
  7198. out1str(p);
  7199. }
  7200. break;
  7201. }
  7202. case CMDFUNCTION:
  7203. if (describe_command_verbose) {
  7204. out1str(" is a shell function");
  7205. } else {
  7206. out1str(command);
  7207. }
  7208. break;
  7209. case CMDBUILTIN:
  7210. if (describe_command_verbose) {
  7211. out1fmt(" is a %sshell builtin",
  7212. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7213. "special " : nullstr
  7214. );
  7215. } else {
  7216. out1str(command);
  7217. }
  7218. break;
  7219. default:
  7220. if (describe_command_verbose) {
  7221. out1str(": not found\n");
  7222. }
  7223. return 127;
  7224. }
  7225. out:
  7226. out1str("\n");
  7227. return 0;
  7228. }
  7229. static int FAST_FUNC
  7230. typecmd(int argc UNUSED_PARAM, char **argv)
  7231. {
  7232. int i = 1;
  7233. int err = 0;
  7234. int verbose = 1;
  7235. /* type -p ... ? (we don't bother checking for 'p') */
  7236. if (argv[1] && argv[1][0] == '-') {
  7237. i++;
  7238. verbose = 0;
  7239. }
  7240. while (argv[i]) {
  7241. err |= describe_command(argv[i++], verbose);
  7242. }
  7243. return err;
  7244. }
  7245. #if ENABLE_ASH_CMDCMD
  7246. static int FAST_FUNC
  7247. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7248. {
  7249. int c;
  7250. enum {
  7251. VERIFY_BRIEF = 1,
  7252. VERIFY_VERBOSE = 2,
  7253. } verify = 0;
  7254. while ((c = nextopt("pvV")) != '\0')
  7255. if (c == 'V')
  7256. verify |= VERIFY_VERBOSE;
  7257. else if (c == 'v')
  7258. verify |= VERIFY_BRIEF;
  7259. #if DEBUG
  7260. else if (c != 'p')
  7261. abort();
  7262. #endif
  7263. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7264. if (verify && (*argptr != NULL)) {
  7265. return describe_command(*argptr, verify - VERIFY_BRIEF);
  7266. }
  7267. return 0;
  7268. }
  7269. #endif
  7270. /* ============ eval.c */
  7271. static int funcblocksize; /* size of structures in function */
  7272. static int funcstringsize; /* size of strings in node */
  7273. static void *funcblock; /* block to allocate function from */
  7274. static char *funcstring; /* block to allocate strings from */
  7275. /* flags in argument to evaltree */
  7276. #define EV_EXIT 01 /* exit after evaluating tree */
  7277. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  7278. #define EV_BACKCMD 04 /* command executing within back quotes */
  7279. static const uint8_t nodesize[N_NUMBER] = {
  7280. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7281. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7282. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7283. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7284. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7285. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7286. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7287. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7288. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7289. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7290. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7291. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7292. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7293. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7294. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7295. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7296. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7297. #if ENABLE_ASH_BASH_COMPAT
  7298. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7299. #endif
  7300. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7301. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7302. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7303. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7304. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7305. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7306. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7307. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7308. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7309. };
  7310. static void calcsize(union node *n);
  7311. static void
  7312. sizenodelist(struct nodelist *lp)
  7313. {
  7314. while (lp) {
  7315. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7316. calcsize(lp->n);
  7317. lp = lp->next;
  7318. }
  7319. }
  7320. static void
  7321. calcsize(union node *n)
  7322. {
  7323. if (n == NULL)
  7324. return;
  7325. funcblocksize += nodesize[n->type];
  7326. switch (n->type) {
  7327. case NCMD:
  7328. calcsize(n->ncmd.redirect);
  7329. calcsize(n->ncmd.args);
  7330. calcsize(n->ncmd.assign);
  7331. break;
  7332. case NPIPE:
  7333. sizenodelist(n->npipe.cmdlist);
  7334. break;
  7335. case NREDIR:
  7336. case NBACKGND:
  7337. case NSUBSHELL:
  7338. calcsize(n->nredir.redirect);
  7339. calcsize(n->nredir.n);
  7340. break;
  7341. case NAND:
  7342. case NOR:
  7343. case NSEMI:
  7344. case NWHILE:
  7345. case NUNTIL:
  7346. calcsize(n->nbinary.ch2);
  7347. calcsize(n->nbinary.ch1);
  7348. break;
  7349. case NIF:
  7350. calcsize(n->nif.elsepart);
  7351. calcsize(n->nif.ifpart);
  7352. calcsize(n->nif.test);
  7353. break;
  7354. case NFOR:
  7355. funcstringsize += strlen(n->nfor.var) + 1;
  7356. calcsize(n->nfor.body);
  7357. calcsize(n->nfor.args);
  7358. break;
  7359. case NCASE:
  7360. calcsize(n->ncase.cases);
  7361. calcsize(n->ncase.expr);
  7362. break;
  7363. case NCLIST:
  7364. calcsize(n->nclist.body);
  7365. calcsize(n->nclist.pattern);
  7366. calcsize(n->nclist.next);
  7367. break;
  7368. case NDEFUN:
  7369. case NARG:
  7370. sizenodelist(n->narg.backquote);
  7371. funcstringsize += strlen(n->narg.text) + 1;
  7372. calcsize(n->narg.next);
  7373. break;
  7374. case NTO:
  7375. #if ENABLE_ASH_BASH_COMPAT
  7376. case NTO2:
  7377. #endif
  7378. case NCLOBBER:
  7379. case NFROM:
  7380. case NFROMTO:
  7381. case NAPPEND:
  7382. calcsize(n->nfile.fname);
  7383. calcsize(n->nfile.next);
  7384. break;
  7385. case NTOFD:
  7386. case NFROMFD:
  7387. calcsize(n->ndup.vname);
  7388. calcsize(n->ndup.next);
  7389. break;
  7390. case NHERE:
  7391. case NXHERE:
  7392. calcsize(n->nhere.doc);
  7393. calcsize(n->nhere.next);
  7394. break;
  7395. case NNOT:
  7396. calcsize(n->nnot.com);
  7397. break;
  7398. };
  7399. }
  7400. static char *
  7401. nodeckstrdup(char *s)
  7402. {
  7403. char *rtn = funcstring;
  7404. strcpy(funcstring, s);
  7405. funcstring += strlen(s) + 1;
  7406. return rtn;
  7407. }
  7408. static union node *copynode(union node *);
  7409. static struct nodelist *
  7410. copynodelist(struct nodelist *lp)
  7411. {
  7412. struct nodelist *start;
  7413. struct nodelist **lpp;
  7414. lpp = &start;
  7415. while (lp) {
  7416. *lpp = funcblock;
  7417. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  7418. (*lpp)->n = copynode(lp->n);
  7419. lp = lp->next;
  7420. lpp = &(*lpp)->next;
  7421. }
  7422. *lpp = NULL;
  7423. return start;
  7424. }
  7425. static union node *
  7426. copynode(union node *n)
  7427. {
  7428. union node *new;
  7429. if (n == NULL)
  7430. return NULL;
  7431. new = funcblock;
  7432. funcblock = (char *) funcblock + nodesize[n->type];
  7433. switch (n->type) {
  7434. case NCMD:
  7435. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7436. new->ncmd.args = copynode(n->ncmd.args);
  7437. new->ncmd.assign = copynode(n->ncmd.assign);
  7438. break;
  7439. case NPIPE:
  7440. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7441. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7442. break;
  7443. case NREDIR:
  7444. case NBACKGND:
  7445. case NSUBSHELL:
  7446. new->nredir.redirect = copynode(n->nredir.redirect);
  7447. new->nredir.n = copynode(n->nredir.n);
  7448. break;
  7449. case NAND:
  7450. case NOR:
  7451. case NSEMI:
  7452. case NWHILE:
  7453. case NUNTIL:
  7454. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7455. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7456. break;
  7457. case NIF:
  7458. new->nif.elsepart = copynode(n->nif.elsepart);
  7459. new->nif.ifpart = copynode(n->nif.ifpart);
  7460. new->nif.test = copynode(n->nif.test);
  7461. break;
  7462. case NFOR:
  7463. new->nfor.var = nodeckstrdup(n->nfor.var);
  7464. new->nfor.body = copynode(n->nfor.body);
  7465. new->nfor.args = copynode(n->nfor.args);
  7466. break;
  7467. case NCASE:
  7468. new->ncase.cases = copynode(n->ncase.cases);
  7469. new->ncase.expr = copynode(n->ncase.expr);
  7470. break;
  7471. case NCLIST:
  7472. new->nclist.body = copynode(n->nclist.body);
  7473. new->nclist.pattern = copynode(n->nclist.pattern);
  7474. new->nclist.next = copynode(n->nclist.next);
  7475. break;
  7476. case NDEFUN:
  7477. case NARG:
  7478. new->narg.backquote = copynodelist(n->narg.backquote);
  7479. new->narg.text = nodeckstrdup(n->narg.text);
  7480. new->narg.next = copynode(n->narg.next);
  7481. break;
  7482. case NTO:
  7483. #if ENABLE_ASH_BASH_COMPAT
  7484. case NTO2:
  7485. #endif
  7486. case NCLOBBER:
  7487. case NFROM:
  7488. case NFROMTO:
  7489. case NAPPEND:
  7490. new->nfile.fname = copynode(n->nfile.fname);
  7491. new->nfile.fd = n->nfile.fd;
  7492. new->nfile.next = copynode(n->nfile.next);
  7493. break;
  7494. case NTOFD:
  7495. case NFROMFD:
  7496. new->ndup.vname = copynode(n->ndup.vname);
  7497. new->ndup.dupfd = n->ndup.dupfd;
  7498. new->ndup.fd = n->ndup.fd;
  7499. new->ndup.next = copynode(n->ndup.next);
  7500. break;
  7501. case NHERE:
  7502. case NXHERE:
  7503. new->nhere.doc = copynode(n->nhere.doc);
  7504. new->nhere.fd = n->nhere.fd;
  7505. new->nhere.next = copynode(n->nhere.next);
  7506. break;
  7507. case NNOT:
  7508. new->nnot.com = copynode(n->nnot.com);
  7509. break;
  7510. };
  7511. new->type = n->type;
  7512. return new;
  7513. }
  7514. /*
  7515. * Make a copy of a parse tree.
  7516. */
  7517. static struct funcnode *
  7518. copyfunc(union node *n)
  7519. {
  7520. struct funcnode *f;
  7521. size_t blocksize;
  7522. funcblocksize = offsetof(struct funcnode, n);
  7523. funcstringsize = 0;
  7524. calcsize(n);
  7525. blocksize = funcblocksize;
  7526. f = ckmalloc(blocksize + funcstringsize);
  7527. funcblock = (char *) f + offsetof(struct funcnode, n);
  7528. funcstring = (char *) f + blocksize;
  7529. copynode(n);
  7530. f->count = 0;
  7531. return f;
  7532. }
  7533. /*
  7534. * Define a shell function.
  7535. */
  7536. static void
  7537. defun(char *name, union node *func)
  7538. {
  7539. struct cmdentry entry;
  7540. INT_OFF;
  7541. entry.cmdtype = CMDFUNCTION;
  7542. entry.u.func = copyfunc(func);
  7543. addcmdentry(name, &entry);
  7544. INT_ON;
  7545. }
  7546. /* Reasons for skipping commands (see comment on breakcmd routine) */
  7547. #define SKIPBREAK (1 << 0)
  7548. #define SKIPCONT (1 << 1)
  7549. #define SKIPFUNC (1 << 2)
  7550. #define SKIPFILE (1 << 3)
  7551. #define SKIPEVAL (1 << 4)
  7552. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  7553. static int skipcount; /* number of levels to skip */
  7554. static int funcnest; /* depth of function calls */
  7555. static int loopnest; /* current loop nesting level */
  7556. /* Forward decl way out to parsing code - dotrap needs it */
  7557. static int evalstring(char *s, int mask);
  7558. /* Called to execute a trap.
  7559. * Single callsite - at the end of evaltree().
  7560. * If we return non-zero, evaltree raises EXEXIT exception.
  7561. *
  7562. * Perhaps we should avoid entering new trap handlers
  7563. * while we are executing a trap handler. [is it a TODO?]
  7564. */
  7565. static int
  7566. dotrap(void)
  7567. {
  7568. uint8_t *g;
  7569. int sig;
  7570. uint8_t savestatus;
  7571. savestatus = exitstatus;
  7572. pending_sig = 0;
  7573. xbarrier();
  7574. TRACE(("dotrap entered\n"));
  7575. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  7576. int want_exexit;
  7577. char *t;
  7578. if (*g == 0)
  7579. continue;
  7580. t = trap[sig];
  7581. /* non-trapped SIGINT is handled separately by raise_interrupt,
  7582. * don't upset it by resetting gotsig[SIGINT-1] */
  7583. if (sig == SIGINT && !t)
  7584. continue;
  7585. TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
  7586. *g = 0;
  7587. if (!t)
  7588. continue;
  7589. want_exexit = evalstring(t, SKIPEVAL);
  7590. exitstatus = savestatus;
  7591. if (want_exexit) {
  7592. TRACE(("dotrap returns %d\n", want_exexit));
  7593. return want_exexit;
  7594. }
  7595. }
  7596. TRACE(("dotrap returns 0\n"));
  7597. return 0;
  7598. }
  7599. /* forward declarations - evaluation is fairly recursive business... */
  7600. static void evalloop(union node *, int);
  7601. static void evalfor(union node *, int);
  7602. static void evalcase(union node *, int);
  7603. static void evalsubshell(union node *, int);
  7604. static void expredir(union node *);
  7605. static void evalpipe(union node *, int);
  7606. static void evalcommand(union node *, int);
  7607. static int evalbltin(const struct builtincmd *, int, char **);
  7608. static void prehash(union node *);
  7609. /*
  7610. * Evaluate a parse tree. The value is left in the global variable
  7611. * exitstatus.
  7612. */
  7613. static void
  7614. evaltree(union node *n, int flags)
  7615. {
  7616. struct jmploc *volatile savehandler = exception_handler;
  7617. struct jmploc jmploc;
  7618. int checkexit = 0;
  7619. void (*evalfn)(union node *, int);
  7620. int status;
  7621. int int_level;
  7622. SAVE_INT(int_level);
  7623. if (n == NULL) {
  7624. TRACE(("evaltree(NULL) called\n"));
  7625. goto out1;
  7626. }
  7627. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  7628. exception_handler = &jmploc;
  7629. {
  7630. int err = setjmp(jmploc.loc);
  7631. if (err) {
  7632. /* if it was a signal, check for trap handlers */
  7633. if (exception_type == EXSIG) {
  7634. TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
  7635. exception_type, err));
  7636. goto out;
  7637. }
  7638. /* continue on the way out */
  7639. TRACE(("exception %d in evaltree, propagating err=%d\n",
  7640. exception_type, err));
  7641. exception_handler = savehandler;
  7642. longjmp(exception_handler->loc, err);
  7643. }
  7644. }
  7645. switch (n->type) {
  7646. default:
  7647. #if DEBUG
  7648. out1fmt("Node type = %d\n", n->type);
  7649. fflush_all();
  7650. break;
  7651. #endif
  7652. case NNOT:
  7653. evaltree(n->nnot.com, EV_TESTED);
  7654. status = !exitstatus;
  7655. goto setstatus;
  7656. case NREDIR:
  7657. expredir(n->nredir.redirect);
  7658. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  7659. if (!status) {
  7660. evaltree(n->nredir.n, flags & EV_TESTED);
  7661. status = exitstatus;
  7662. }
  7663. popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
  7664. goto setstatus;
  7665. case NCMD:
  7666. evalfn = evalcommand;
  7667. checkexit:
  7668. if (eflag && !(flags & EV_TESTED))
  7669. checkexit = ~0;
  7670. goto calleval;
  7671. case NFOR:
  7672. evalfn = evalfor;
  7673. goto calleval;
  7674. case NWHILE:
  7675. case NUNTIL:
  7676. evalfn = evalloop;
  7677. goto calleval;
  7678. case NSUBSHELL:
  7679. case NBACKGND:
  7680. evalfn = evalsubshell;
  7681. goto calleval;
  7682. case NPIPE:
  7683. evalfn = evalpipe;
  7684. goto checkexit;
  7685. case NCASE:
  7686. evalfn = evalcase;
  7687. goto calleval;
  7688. case NAND:
  7689. case NOR:
  7690. case NSEMI: {
  7691. #if NAND + 1 != NOR
  7692. #error NAND + 1 != NOR
  7693. #endif
  7694. #if NOR + 1 != NSEMI
  7695. #error NOR + 1 != NSEMI
  7696. #endif
  7697. unsigned is_or = n->type - NAND;
  7698. evaltree(
  7699. n->nbinary.ch1,
  7700. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  7701. );
  7702. if (!exitstatus == is_or)
  7703. break;
  7704. if (!evalskip) {
  7705. n = n->nbinary.ch2;
  7706. evaln:
  7707. evalfn = evaltree;
  7708. calleval:
  7709. evalfn(n, flags);
  7710. break;
  7711. }
  7712. break;
  7713. }
  7714. case NIF:
  7715. evaltree(n->nif.test, EV_TESTED);
  7716. if (evalskip)
  7717. break;
  7718. if (exitstatus == 0) {
  7719. n = n->nif.ifpart;
  7720. goto evaln;
  7721. }
  7722. if (n->nif.elsepart) {
  7723. n = n->nif.elsepart;
  7724. goto evaln;
  7725. }
  7726. goto success;
  7727. case NDEFUN:
  7728. defun(n->narg.text, n->narg.next);
  7729. success:
  7730. status = 0;
  7731. setstatus:
  7732. exitstatus = status;
  7733. break;
  7734. }
  7735. out:
  7736. exception_handler = savehandler;
  7737. out1:
  7738. /* Order of checks below is important:
  7739. * signal handlers trigger before exit caused by "set -e".
  7740. */
  7741. if (pending_sig && dotrap())
  7742. goto exexit;
  7743. if (checkexit & exitstatus)
  7744. evalskip |= SKIPEVAL;
  7745. if (flags & EV_EXIT) {
  7746. exexit:
  7747. raise_exception(EXEXIT);
  7748. }
  7749. RESTORE_INT(int_level);
  7750. TRACE(("leaving evaltree (no interrupts)\n"));
  7751. }
  7752. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  7753. static
  7754. #endif
  7755. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  7756. static void
  7757. evalloop(union node *n, int flags)
  7758. {
  7759. int status;
  7760. loopnest++;
  7761. status = 0;
  7762. flags &= EV_TESTED;
  7763. for (;;) {
  7764. int i;
  7765. evaltree(n->nbinary.ch1, EV_TESTED);
  7766. if (evalskip) {
  7767. skipping:
  7768. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7769. evalskip = 0;
  7770. continue;
  7771. }
  7772. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7773. evalskip = 0;
  7774. break;
  7775. }
  7776. i = exitstatus;
  7777. if (n->type != NWHILE)
  7778. i = !i;
  7779. if (i != 0)
  7780. break;
  7781. evaltree(n->nbinary.ch2, flags);
  7782. status = exitstatus;
  7783. if (evalskip)
  7784. goto skipping;
  7785. }
  7786. loopnest--;
  7787. exitstatus = status;
  7788. }
  7789. static void
  7790. evalfor(union node *n, int flags)
  7791. {
  7792. struct arglist arglist;
  7793. union node *argp;
  7794. struct strlist *sp;
  7795. struct stackmark smark;
  7796. setstackmark(&smark);
  7797. arglist.list = NULL;
  7798. arglist.lastp = &arglist.list;
  7799. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  7800. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
  7801. /* XXX */
  7802. if (evalskip)
  7803. goto out;
  7804. }
  7805. *arglist.lastp = NULL;
  7806. exitstatus = 0;
  7807. loopnest++;
  7808. flags &= EV_TESTED;
  7809. for (sp = arglist.list; sp; sp = sp->next) {
  7810. setvar(n->nfor.var, sp->text, 0);
  7811. evaltree(n->nfor.body, flags);
  7812. if (evalskip) {
  7813. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7814. evalskip = 0;
  7815. continue;
  7816. }
  7817. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7818. evalskip = 0;
  7819. break;
  7820. }
  7821. }
  7822. loopnest--;
  7823. out:
  7824. popstackmark(&smark);
  7825. }
  7826. static void
  7827. evalcase(union node *n, int flags)
  7828. {
  7829. union node *cp;
  7830. union node *patp;
  7831. struct arglist arglist;
  7832. struct stackmark smark;
  7833. setstackmark(&smark);
  7834. arglist.list = NULL;
  7835. arglist.lastp = &arglist.list;
  7836. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  7837. exitstatus = 0;
  7838. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  7839. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  7840. if (casematch(patp, arglist.list->text)) {
  7841. if (evalskip == 0) {
  7842. evaltree(cp->nclist.body, flags);
  7843. }
  7844. goto out;
  7845. }
  7846. }
  7847. }
  7848. out:
  7849. popstackmark(&smark);
  7850. }
  7851. /*
  7852. * Kick off a subshell to evaluate a tree.
  7853. */
  7854. static void
  7855. evalsubshell(union node *n, int flags)
  7856. {
  7857. struct job *jp;
  7858. int backgnd = (n->type == NBACKGND);
  7859. int status;
  7860. expredir(n->nredir.redirect);
  7861. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  7862. goto nofork;
  7863. INT_OFF;
  7864. jp = makejob(/*n,*/ 1);
  7865. if (forkshell(jp, n, backgnd) == 0) {
  7866. /* child */
  7867. INT_ON;
  7868. flags |= EV_EXIT;
  7869. if (backgnd)
  7870. flags &= ~EV_TESTED;
  7871. nofork:
  7872. redirect(n->nredir.redirect, 0);
  7873. evaltreenr(n->nredir.n, flags);
  7874. /* never returns */
  7875. }
  7876. status = 0;
  7877. if (!backgnd)
  7878. status = waitforjob(jp);
  7879. exitstatus = status;
  7880. INT_ON;
  7881. }
  7882. /*
  7883. * Compute the names of the files in a redirection list.
  7884. */
  7885. static void fixredir(union node *, const char *, int);
  7886. static void
  7887. expredir(union node *n)
  7888. {
  7889. union node *redir;
  7890. for (redir = n; redir; redir = redir->nfile.next) {
  7891. struct arglist fn;
  7892. fn.list = NULL;
  7893. fn.lastp = &fn.list;
  7894. switch (redir->type) {
  7895. case NFROMTO:
  7896. case NFROM:
  7897. case NTO:
  7898. #if ENABLE_ASH_BASH_COMPAT
  7899. case NTO2:
  7900. #endif
  7901. case NCLOBBER:
  7902. case NAPPEND:
  7903. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  7904. #if ENABLE_ASH_BASH_COMPAT
  7905. store_expfname:
  7906. #endif
  7907. redir->nfile.expfname = fn.list->text;
  7908. break;
  7909. case NFROMFD:
  7910. case NTOFD: /* >& */
  7911. if (redir->ndup.vname) {
  7912. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  7913. if (fn.list == NULL)
  7914. ash_msg_and_raise_error("redir error");
  7915. #if ENABLE_ASH_BASH_COMPAT
  7916. //FIXME: we used expandarg with different args!
  7917. if (!isdigit_str9(fn.list->text)) {
  7918. /* >&file, not >&fd */
  7919. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  7920. ash_msg_and_raise_error("redir error");
  7921. redir->type = NTO2;
  7922. goto store_expfname;
  7923. }
  7924. #endif
  7925. fixredir(redir, fn.list->text, 1);
  7926. }
  7927. break;
  7928. }
  7929. }
  7930. }
  7931. /*
  7932. * Evaluate a pipeline. All the processes in the pipeline are children
  7933. * of the process creating the pipeline. (This differs from some versions
  7934. * of the shell, which make the last process in a pipeline the parent
  7935. * of all the rest.)
  7936. */
  7937. static void
  7938. evalpipe(union node *n, int flags)
  7939. {
  7940. struct job *jp;
  7941. struct nodelist *lp;
  7942. int pipelen;
  7943. int prevfd;
  7944. int pip[2];
  7945. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  7946. pipelen = 0;
  7947. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  7948. pipelen++;
  7949. flags |= EV_EXIT;
  7950. INT_OFF;
  7951. jp = makejob(/*n,*/ pipelen);
  7952. prevfd = -1;
  7953. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  7954. prehash(lp->n);
  7955. pip[1] = -1;
  7956. if (lp->next) {
  7957. if (pipe(pip) < 0) {
  7958. close(prevfd);
  7959. ash_msg_and_raise_error("pipe call failed");
  7960. }
  7961. }
  7962. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  7963. INT_ON;
  7964. if (pip[1] >= 0) {
  7965. close(pip[0]);
  7966. }
  7967. if (prevfd > 0) {
  7968. dup2(prevfd, 0);
  7969. close(prevfd);
  7970. }
  7971. if (pip[1] > 1) {
  7972. dup2(pip[1], 1);
  7973. close(pip[1]);
  7974. }
  7975. evaltreenr(lp->n, flags);
  7976. /* never returns */
  7977. }
  7978. if (prevfd >= 0)
  7979. close(prevfd);
  7980. prevfd = pip[0];
  7981. /* Don't want to trigger debugging */
  7982. if (pip[1] != -1)
  7983. close(pip[1]);
  7984. }
  7985. if (n->npipe.pipe_backgnd == 0) {
  7986. exitstatus = waitforjob(jp);
  7987. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  7988. }
  7989. INT_ON;
  7990. }
  7991. /*
  7992. * Controls whether the shell is interactive or not.
  7993. */
  7994. static void
  7995. setinteractive(int on)
  7996. {
  7997. static smallint is_interactive;
  7998. if (++on == is_interactive)
  7999. return;
  8000. is_interactive = on;
  8001. setsignal(SIGINT);
  8002. setsignal(SIGQUIT);
  8003. setsignal(SIGTERM);
  8004. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8005. if (is_interactive > 1) {
  8006. /* Looks like they want an interactive shell */
  8007. static smallint did_banner;
  8008. if (!did_banner) {
  8009. /* note: ash and hush share this string */
  8010. out1fmt("\n\n%s %s\n"
  8011. "Enter 'help' for a list of built-in commands."
  8012. "\n\n",
  8013. bb_banner,
  8014. "built-in shell (ash)"
  8015. );
  8016. did_banner = 1;
  8017. }
  8018. }
  8019. #endif
  8020. }
  8021. static void
  8022. optschanged(void)
  8023. {
  8024. #if DEBUG
  8025. opentrace();
  8026. #endif
  8027. setinteractive(iflag);
  8028. setjobctl(mflag);
  8029. #if ENABLE_FEATURE_EDITING_VI
  8030. if (viflag)
  8031. line_input_state->flags |= VI_MODE;
  8032. else
  8033. line_input_state->flags &= ~VI_MODE;
  8034. #else
  8035. viflag = 0; /* forcibly keep the option off */
  8036. #endif
  8037. }
  8038. static struct localvar *localvars;
  8039. /*
  8040. * Called after a function returns.
  8041. * Interrupts must be off.
  8042. */
  8043. static void
  8044. poplocalvars(void)
  8045. {
  8046. struct localvar *lvp;
  8047. struct var *vp;
  8048. while ((lvp = localvars) != NULL) {
  8049. localvars = lvp->next;
  8050. vp = lvp->vp;
  8051. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8052. if (vp == NULL) { /* $- saved */
  8053. memcpy(optlist, lvp->text, sizeof(optlist));
  8054. free((char*)lvp->text);
  8055. optschanged();
  8056. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  8057. unsetvar(vp->var_text);
  8058. } else {
  8059. if (vp->var_func)
  8060. vp->var_func(var_end(lvp->text));
  8061. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8062. free((char*)vp->var_text);
  8063. vp->flags = lvp->flags;
  8064. vp->var_text = lvp->text;
  8065. }
  8066. free(lvp);
  8067. }
  8068. }
  8069. static int
  8070. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8071. {
  8072. volatile struct shparam saveparam;
  8073. struct localvar *volatile savelocalvars;
  8074. struct jmploc *volatile savehandler;
  8075. struct jmploc jmploc;
  8076. int e;
  8077. saveparam = shellparam;
  8078. savelocalvars = localvars;
  8079. e = setjmp(jmploc.loc);
  8080. if (e) {
  8081. goto funcdone;
  8082. }
  8083. INT_OFF;
  8084. savehandler = exception_handler;
  8085. exception_handler = &jmploc;
  8086. localvars = NULL;
  8087. shellparam.malloced = 0;
  8088. func->count++;
  8089. funcnest++;
  8090. INT_ON;
  8091. shellparam.nparam = argc - 1;
  8092. shellparam.p = argv + 1;
  8093. #if ENABLE_ASH_GETOPTS
  8094. shellparam.optind = 1;
  8095. shellparam.optoff = -1;
  8096. #endif
  8097. evaltree(&func->n, flags & EV_TESTED);
  8098. funcdone:
  8099. INT_OFF;
  8100. funcnest--;
  8101. freefunc(func);
  8102. poplocalvars();
  8103. localvars = savelocalvars;
  8104. freeparam(&shellparam);
  8105. shellparam = saveparam;
  8106. exception_handler = savehandler;
  8107. INT_ON;
  8108. evalskip &= ~SKIPFUNC;
  8109. return e;
  8110. }
  8111. #if ENABLE_ASH_CMDCMD
  8112. static char **
  8113. parse_command_args(char **argv, const char **path)
  8114. {
  8115. char *cp, c;
  8116. for (;;) {
  8117. cp = *++argv;
  8118. if (!cp)
  8119. return 0;
  8120. if (*cp++ != '-')
  8121. break;
  8122. c = *cp++;
  8123. if (!c)
  8124. break;
  8125. if (c == '-' && !*cp) {
  8126. argv++;
  8127. break;
  8128. }
  8129. do {
  8130. switch (c) {
  8131. case 'p':
  8132. *path = bb_default_path;
  8133. break;
  8134. default:
  8135. /* run 'typecmd' for other options */
  8136. return 0;
  8137. }
  8138. c = *cp++;
  8139. } while (c);
  8140. }
  8141. return argv;
  8142. }
  8143. #endif
  8144. /*
  8145. * Make a variable a local variable. When a variable is made local, it's
  8146. * value and flags are saved in a localvar structure. The saved values
  8147. * will be restored when the shell function returns. We handle the name
  8148. * "-" as a special case.
  8149. */
  8150. static void
  8151. mklocal(char *name)
  8152. {
  8153. struct localvar *lvp;
  8154. struct var **vpp;
  8155. struct var *vp;
  8156. INT_OFF;
  8157. lvp = ckzalloc(sizeof(struct localvar));
  8158. if (LONE_DASH(name)) {
  8159. char *p;
  8160. p = ckmalloc(sizeof(optlist));
  8161. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8162. vp = NULL;
  8163. } else {
  8164. char *eq;
  8165. vpp = hashvar(name);
  8166. vp = *findvar(vpp, name);
  8167. eq = strchr(name, '=');
  8168. if (vp == NULL) {
  8169. if (eq)
  8170. setvareq(name, VSTRFIXED);
  8171. else
  8172. setvar(name, NULL, VSTRFIXED);
  8173. vp = *vpp; /* the new variable */
  8174. lvp->flags = VUNSET;
  8175. } else {
  8176. lvp->text = vp->var_text;
  8177. lvp->flags = vp->flags;
  8178. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8179. if (eq)
  8180. setvareq(name, 0);
  8181. }
  8182. }
  8183. lvp->vp = vp;
  8184. lvp->next = localvars;
  8185. localvars = lvp;
  8186. INT_ON;
  8187. }
  8188. /*
  8189. * The "local" command.
  8190. */
  8191. static int FAST_FUNC
  8192. localcmd(int argc UNUSED_PARAM, char **argv)
  8193. {
  8194. char *name;
  8195. argv = argptr;
  8196. while ((name = *argv++) != NULL) {
  8197. mklocal(name);
  8198. }
  8199. return 0;
  8200. }
  8201. static int FAST_FUNC
  8202. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8203. {
  8204. return 1;
  8205. }
  8206. static int FAST_FUNC
  8207. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8208. {
  8209. return 0;
  8210. }
  8211. static int FAST_FUNC
  8212. execcmd(int argc UNUSED_PARAM, char **argv)
  8213. {
  8214. if (argv[1]) {
  8215. iflag = 0; /* exit on error */
  8216. mflag = 0;
  8217. optschanged();
  8218. shellexec(argv + 1, pathval(), 0);
  8219. }
  8220. return 0;
  8221. }
  8222. /*
  8223. * The return command.
  8224. */
  8225. static int FAST_FUNC
  8226. returncmd(int argc UNUSED_PARAM, char **argv)
  8227. {
  8228. /*
  8229. * If called outside a function, do what ksh does;
  8230. * skip the rest of the file.
  8231. */
  8232. evalskip = funcnest ? SKIPFUNC : SKIPFILE;
  8233. return argv[1] ? number(argv[1]) : exitstatus;
  8234. }
  8235. /* Forward declarations for builtintab[] */
  8236. static int breakcmd(int, char **) FAST_FUNC;
  8237. static int dotcmd(int, char **) FAST_FUNC;
  8238. static int evalcmd(int, char **) FAST_FUNC;
  8239. static int exitcmd(int, char **) FAST_FUNC;
  8240. static int exportcmd(int, char **) FAST_FUNC;
  8241. #if ENABLE_ASH_GETOPTS
  8242. static int getoptscmd(int, char **) FAST_FUNC;
  8243. #endif
  8244. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8245. static int helpcmd(int, char **) FAST_FUNC;
  8246. #endif
  8247. #if ENABLE_SH_MATH_SUPPORT
  8248. static int letcmd(int, char **) FAST_FUNC;
  8249. #endif
  8250. static int readcmd(int, char **) FAST_FUNC;
  8251. static int setcmd(int, char **) FAST_FUNC;
  8252. static int shiftcmd(int, char **) FAST_FUNC;
  8253. static int timescmd(int, char **) FAST_FUNC;
  8254. static int trapcmd(int, char **) FAST_FUNC;
  8255. static int umaskcmd(int, char **) FAST_FUNC;
  8256. static int unsetcmd(int, char **) FAST_FUNC;
  8257. static int ulimitcmd(int, char **) FAST_FUNC;
  8258. #define BUILTIN_NOSPEC "0"
  8259. #define BUILTIN_SPECIAL "1"
  8260. #define BUILTIN_REGULAR "2"
  8261. #define BUILTIN_SPEC_REG "3"
  8262. #define BUILTIN_ASSIGN "4"
  8263. #define BUILTIN_SPEC_ASSG "5"
  8264. #define BUILTIN_REG_ASSG "6"
  8265. #define BUILTIN_SPEC_REG_ASSG "7"
  8266. /* Stubs for calling non-FAST_FUNC's */
  8267. #if ENABLE_ASH_BUILTIN_ECHO
  8268. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8269. #endif
  8270. #if ENABLE_ASH_BUILTIN_PRINTF
  8271. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8272. #endif
  8273. #if ENABLE_ASH_BUILTIN_TEST
  8274. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8275. #endif
  8276. /* Keep these in proper order since it is searched via bsearch() */
  8277. static const struct builtincmd builtintab[] = {
  8278. { BUILTIN_SPEC_REG "." , dotcmd },
  8279. { BUILTIN_SPEC_REG ":" , truecmd },
  8280. #if ENABLE_ASH_BUILTIN_TEST
  8281. { BUILTIN_REGULAR "[" , testcmd },
  8282. #if ENABLE_ASH_BASH_COMPAT
  8283. { BUILTIN_REGULAR "[[" , testcmd },
  8284. #endif
  8285. #endif
  8286. #if ENABLE_ASH_ALIAS
  8287. { BUILTIN_REG_ASSG "alias" , aliascmd },
  8288. #endif
  8289. #if JOBS
  8290. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  8291. #endif
  8292. { BUILTIN_SPEC_REG "break" , breakcmd },
  8293. { BUILTIN_REGULAR "cd" , cdcmd },
  8294. { BUILTIN_NOSPEC "chdir" , cdcmd },
  8295. #if ENABLE_ASH_CMDCMD
  8296. { BUILTIN_REGULAR "command" , commandcmd },
  8297. #endif
  8298. { BUILTIN_SPEC_REG "continue", breakcmd },
  8299. #if ENABLE_ASH_BUILTIN_ECHO
  8300. { BUILTIN_REGULAR "echo" , echocmd },
  8301. #endif
  8302. { BUILTIN_SPEC_REG "eval" , evalcmd },
  8303. { BUILTIN_SPEC_REG "exec" , execcmd },
  8304. { BUILTIN_SPEC_REG "exit" , exitcmd },
  8305. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  8306. { BUILTIN_REGULAR "false" , falsecmd },
  8307. #if JOBS
  8308. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  8309. #endif
  8310. #if ENABLE_ASH_GETOPTS
  8311. { BUILTIN_REGULAR "getopts" , getoptscmd },
  8312. #endif
  8313. { BUILTIN_NOSPEC "hash" , hashcmd },
  8314. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8315. { BUILTIN_NOSPEC "help" , helpcmd },
  8316. #endif
  8317. #if JOBS
  8318. { BUILTIN_REGULAR "jobs" , jobscmd },
  8319. { BUILTIN_REGULAR "kill" , killcmd },
  8320. #endif
  8321. #if ENABLE_SH_MATH_SUPPORT
  8322. { BUILTIN_NOSPEC "let" , letcmd },
  8323. #endif
  8324. { BUILTIN_ASSIGN "local" , localcmd },
  8325. #if ENABLE_ASH_BUILTIN_PRINTF
  8326. { BUILTIN_REGULAR "printf" , printfcmd },
  8327. #endif
  8328. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  8329. { BUILTIN_REGULAR "read" , readcmd },
  8330. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  8331. { BUILTIN_SPEC_REG "return" , returncmd },
  8332. { BUILTIN_SPEC_REG "set" , setcmd },
  8333. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  8334. #if ENABLE_ASH_BASH_COMPAT
  8335. { BUILTIN_SPEC_REG "source" , dotcmd },
  8336. #endif
  8337. #if ENABLE_ASH_BUILTIN_TEST
  8338. { BUILTIN_REGULAR "test" , testcmd },
  8339. #endif
  8340. { BUILTIN_SPEC_REG "times" , timescmd },
  8341. { BUILTIN_SPEC_REG "trap" , trapcmd },
  8342. { BUILTIN_REGULAR "true" , truecmd },
  8343. { BUILTIN_NOSPEC "type" , typecmd },
  8344. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  8345. { BUILTIN_REGULAR "umask" , umaskcmd },
  8346. #if ENABLE_ASH_ALIAS
  8347. { BUILTIN_REGULAR "unalias" , unaliascmd },
  8348. #endif
  8349. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  8350. { BUILTIN_REGULAR "wait" , waitcmd },
  8351. };
  8352. /* Should match the above table! */
  8353. #define COMMANDCMD (builtintab + \
  8354. 2 + \
  8355. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8356. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8357. 1 * ENABLE_ASH_ALIAS + \
  8358. 1 * ENABLE_ASH_JOB_CONTROL + \
  8359. 3)
  8360. #define EXECCMD (builtintab + \
  8361. 2 + \
  8362. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8363. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8364. 1 * ENABLE_ASH_ALIAS + \
  8365. 1 * ENABLE_ASH_JOB_CONTROL + \
  8366. 3 + \
  8367. 1 * ENABLE_ASH_CMDCMD + \
  8368. 1 + \
  8369. ENABLE_ASH_BUILTIN_ECHO + \
  8370. 1)
  8371. /*
  8372. * Search the table of builtin commands.
  8373. */
  8374. static struct builtincmd *
  8375. find_builtin(const char *name)
  8376. {
  8377. struct builtincmd *bp;
  8378. bp = bsearch(
  8379. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  8380. pstrcmp
  8381. );
  8382. return bp;
  8383. }
  8384. /*
  8385. * Execute a simple command.
  8386. */
  8387. static int
  8388. isassignment(const char *p)
  8389. {
  8390. const char *q = endofname(p);
  8391. if (p == q)
  8392. return 0;
  8393. return *q == '=';
  8394. }
  8395. static int FAST_FUNC
  8396. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8397. {
  8398. /* Preserve exitstatus of a previous possible redirection
  8399. * as POSIX mandates */
  8400. return back_exitstatus;
  8401. }
  8402. static void
  8403. evalcommand(union node *cmd, int flags)
  8404. {
  8405. static const struct builtincmd null_bltin = {
  8406. "\0\0", bltincmd /* why three NULs? */
  8407. };
  8408. struct stackmark smark;
  8409. union node *argp;
  8410. struct arglist arglist;
  8411. struct arglist varlist;
  8412. char **argv;
  8413. int argc;
  8414. const struct strlist *sp;
  8415. struct cmdentry cmdentry;
  8416. struct job *jp;
  8417. char *lastarg;
  8418. const char *path;
  8419. int spclbltin;
  8420. int status;
  8421. char **nargv;
  8422. struct builtincmd *bcmd;
  8423. smallint cmd_is_exec;
  8424. smallint pseudovarflag = 0;
  8425. /* First expand the arguments. */
  8426. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  8427. setstackmark(&smark);
  8428. back_exitstatus = 0;
  8429. cmdentry.cmdtype = CMDBUILTIN;
  8430. cmdentry.u.cmd = &null_bltin;
  8431. varlist.lastp = &varlist.list;
  8432. *varlist.lastp = NULL;
  8433. arglist.lastp = &arglist.list;
  8434. *arglist.lastp = NULL;
  8435. argc = 0;
  8436. if (cmd->ncmd.args) {
  8437. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  8438. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  8439. }
  8440. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  8441. struct strlist **spp;
  8442. spp = arglist.lastp;
  8443. if (pseudovarflag && isassignment(argp->narg.text))
  8444. expandarg(argp, &arglist, EXP_VARTILDE);
  8445. else
  8446. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8447. for (sp = *spp; sp; sp = sp->next)
  8448. argc++;
  8449. }
  8450. argv = nargv = stalloc(sizeof(char *) * (argc + 1));
  8451. for (sp = arglist.list; sp; sp = sp->next) {
  8452. TRACE(("evalcommand arg: %s\n", sp->text));
  8453. *nargv++ = sp->text;
  8454. }
  8455. *nargv = NULL;
  8456. lastarg = NULL;
  8457. if (iflag && funcnest == 0 && argc > 0)
  8458. lastarg = nargv[-1];
  8459. preverrout_fd = 2;
  8460. expredir(cmd->ncmd.redirect);
  8461. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  8462. path = vpath.var_text;
  8463. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  8464. struct strlist **spp;
  8465. char *p;
  8466. spp = varlist.lastp;
  8467. expandarg(argp, &varlist, EXP_VARTILDE);
  8468. /*
  8469. * Modify the command lookup path, if a PATH= assignment
  8470. * is present
  8471. */
  8472. p = (*spp)->text;
  8473. if (varcmp(p, path) == 0)
  8474. path = p;
  8475. }
  8476. /* Print the command if xflag is set. */
  8477. if (xflag) {
  8478. int n;
  8479. const char *p = " %s" + 1;
  8480. fdprintf(preverrout_fd, p, expandstr(ps4val()));
  8481. sp = varlist.list;
  8482. for (n = 0; n < 2; n++) {
  8483. while (sp) {
  8484. fdprintf(preverrout_fd, p, sp->text);
  8485. sp = sp->next;
  8486. p = " %s";
  8487. }
  8488. sp = arglist.list;
  8489. }
  8490. safe_write(preverrout_fd, "\n", 1);
  8491. }
  8492. cmd_is_exec = 0;
  8493. spclbltin = -1;
  8494. /* Now locate the command. */
  8495. if (argc) {
  8496. const char *oldpath;
  8497. int cmd_flag = DO_ERR;
  8498. path += 5;
  8499. oldpath = path;
  8500. for (;;) {
  8501. find_command(argv[0], &cmdentry, cmd_flag, path);
  8502. if (cmdentry.cmdtype == CMDUNKNOWN) {
  8503. flush_stdout_stderr();
  8504. status = 127;
  8505. goto bail;
  8506. }
  8507. /* implement bltin and command here */
  8508. if (cmdentry.cmdtype != CMDBUILTIN)
  8509. break;
  8510. if (spclbltin < 0)
  8511. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  8512. if (cmdentry.u.cmd == EXECCMD)
  8513. cmd_is_exec = 1;
  8514. #if ENABLE_ASH_CMDCMD
  8515. if (cmdentry.u.cmd == COMMANDCMD) {
  8516. path = oldpath;
  8517. nargv = parse_command_args(argv, &path);
  8518. if (!nargv)
  8519. break;
  8520. argc -= nargv - argv;
  8521. argv = nargv;
  8522. cmd_flag |= DO_NOFUNC;
  8523. } else
  8524. #endif
  8525. break;
  8526. }
  8527. }
  8528. if (status) {
  8529. /* We have a redirection error. */
  8530. if (spclbltin > 0)
  8531. raise_exception(EXERROR);
  8532. bail:
  8533. exitstatus = status;
  8534. goto out;
  8535. }
  8536. /* Execute the command. */
  8537. switch (cmdentry.cmdtype) {
  8538. default: {
  8539. #if ENABLE_FEATURE_SH_NOFORK
  8540. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  8541. * around run_nofork_applet() call.
  8542. * (2) Should this check also be done in forkshell()?
  8543. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  8544. */
  8545. /* find_command() encodes applet_no as (-2 - applet_no) */
  8546. int applet_no = (- cmdentry.u.index - 2);
  8547. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  8548. listsetvar(varlist.list, VEXPORT|VSTACK);
  8549. /* run <applet>_main() */
  8550. exitstatus = run_nofork_applet(applet_no, argv);
  8551. break;
  8552. }
  8553. #endif
  8554. /* Can we avoid forking off? For example, very last command
  8555. * in a script or a subshell does not need forking,
  8556. * we can just exec it.
  8557. */
  8558. if (!(flags & EV_EXIT) || may_have_traps) {
  8559. /* No, forking off a child is necessary */
  8560. INT_OFF;
  8561. jp = makejob(/*cmd,*/ 1);
  8562. if (forkshell(jp, cmd, FORK_FG) != 0) {
  8563. /* parent */
  8564. exitstatus = waitforjob(jp);
  8565. INT_ON;
  8566. TRACE(("forked child exited with %d\n", exitstatus));
  8567. break;
  8568. }
  8569. /* child */
  8570. FORCE_INT_ON;
  8571. /* fall through to exec'ing external program */
  8572. }
  8573. listsetvar(varlist.list, VEXPORT|VSTACK);
  8574. shellexec(argv, path, cmdentry.u.index);
  8575. /* NOTREACHED */
  8576. } /* default */
  8577. case CMDBUILTIN:
  8578. cmdenviron = varlist.list;
  8579. if (cmdenviron) {
  8580. struct strlist *list = cmdenviron;
  8581. int i = VNOSET;
  8582. if (spclbltin > 0 || argc == 0) {
  8583. i = 0;
  8584. if (cmd_is_exec && argc > 1)
  8585. i = VEXPORT;
  8586. }
  8587. listsetvar(list, i);
  8588. }
  8589. /* Tight loop with builtins only:
  8590. * "while kill -0 $child; do true; done"
  8591. * will never exit even if $child died, unless we do this
  8592. * to reap the zombie and make kill detect that it's gone: */
  8593. dowait(DOWAIT_NONBLOCK, NULL);
  8594. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  8595. int exit_status;
  8596. int i = exception_type;
  8597. if (i == EXEXIT)
  8598. goto raise;
  8599. exit_status = 2;
  8600. if (i == EXINT)
  8601. exit_status = 128 + SIGINT;
  8602. if (i == EXSIG)
  8603. exit_status = 128 + pending_sig;
  8604. exitstatus = exit_status;
  8605. if (i == EXINT || spclbltin > 0) {
  8606. raise:
  8607. longjmp(exception_handler->loc, 1);
  8608. }
  8609. FORCE_INT_ON;
  8610. }
  8611. break;
  8612. case CMDFUNCTION:
  8613. listsetvar(varlist.list, 0);
  8614. /* See above for the rationale */
  8615. dowait(DOWAIT_NONBLOCK, NULL);
  8616. if (evalfun(cmdentry.u.func, argc, argv, flags))
  8617. goto raise;
  8618. break;
  8619. } /* switch */
  8620. out:
  8621. popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
  8622. if (lastarg) {
  8623. /* dsl: I think this is intended to be used to support
  8624. * '_' in 'vi' command mode during line editing...
  8625. * However I implemented that within libedit itself.
  8626. */
  8627. setvar("_", lastarg, 0);
  8628. }
  8629. popstackmark(&smark);
  8630. }
  8631. static int
  8632. evalbltin(const struct builtincmd *cmd, int argc, char **argv)
  8633. {
  8634. char *volatile savecmdname;
  8635. struct jmploc *volatile savehandler;
  8636. struct jmploc jmploc;
  8637. int i;
  8638. savecmdname = commandname;
  8639. i = setjmp(jmploc.loc);
  8640. if (i)
  8641. goto cmddone;
  8642. savehandler = exception_handler;
  8643. exception_handler = &jmploc;
  8644. commandname = argv[0];
  8645. argptr = argv + 1;
  8646. optptr = NULL; /* initialize nextopt */
  8647. exitstatus = (*cmd->builtin)(argc, argv);
  8648. flush_stdout_stderr();
  8649. cmddone:
  8650. exitstatus |= ferror(stdout);
  8651. clearerr(stdout);
  8652. commandname = savecmdname;
  8653. exception_handler = savehandler;
  8654. return i;
  8655. }
  8656. static int
  8657. goodname(const char *p)
  8658. {
  8659. return endofname(p)[0] == '\0';
  8660. }
  8661. /*
  8662. * Search for a command. This is called before we fork so that the
  8663. * location of the command will be available in the parent as well as
  8664. * the child. The check for "goodname" is an overly conservative
  8665. * check that the name will not be subject to expansion.
  8666. */
  8667. static void
  8668. prehash(union node *n)
  8669. {
  8670. struct cmdentry entry;
  8671. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  8672. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  8673. }
  8674. /* ============ Builtin commands
  8675. *
  8676. * Builtin commands whose functions are closely tied to evaluation
  8677. * are implemented here.
  8678. */
  8679. /*
  8680. * Handle break and continue commands. Break, continue, and return are
  8681. * all handled by setting the evalskip flag. The evaluation routines
  8682. * above all check this flag, and if it is set they start skipping
  8683. * commands rather than executing them. The variable skipcount is
  8684. * the number of loops to break/continue, or the number of function
  8685. * levels to return. (The latter is always 1.) It should probably
  8686. * be an error to break out of more loops than exist, but it isn't
  8687. * in the standard shell so we don't make it one here.
  8688. */
  8689. static int FAST_FUNC
  8690. breakcmd(int argc UNUSED_PARAM, char **argv)
  8691. {
  8692. int n = argv[1] ? number(argv[1]) : 1;
  8693. if (n <= 0)
  8694. ash_msg_and_raise_error(msg_illnum, argv[1]);
  8695. if (n > loopnest)
  8696. n = loopnest;
  8697. if (n > 0) {
  8698. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  8699. skipcount = n;
  8700. }
  8701. return 0;
  8702. }
  8703. /* ============ input.c
  8704. *
  8705. * This implements the input routines used by the parser.
  8706. */
  8707. enum {
  8708. INPUT_PUSH_FILE = 1,
  8709. INPUT_NOFILE_OK = 2,
  8710. };
  8711. static smallint checkkwd;
  8712. /* values of checkkwd variable */
  8713. #define CHKALIAS 0x1
  8714. #define CHKKWD 0x2
  8715. #define CHKNL 0x4
  8716. /*
  8717. * Push a string back onto the input at this current parsefile level.
  8718. * We handle aliases this way.
  8719. */
  8720. #if !ENABLE_ASH_ALIAS
  8721. #define pushstring(s, ap) pushstring(s)
  8722. #endif
  8723. static void
  8724. pushstring(char *s, struct alias *ap)
  8725. {
  8726. struct strpush *sp;
  8727. int len;
  8728. len = strlen(s);
  8729. INT_OFF;
  8730. if (g_parsefile->strpush) {
  8731. sp = ckzalloc(sizeof(*sp));
  8732. sp->prev = g_parsefile->strpush;
  8733. } else {
  8734. sp = &(g_parsefile->basestrpush);
  8735. }
  8736. g_parsefile->strpush = sp;
  8737. sp->prev_string = g_parsefile->next_to_pgetc;
  8738. sp->prev_left_in_line = g_parsefile->left_in_line;
  8739. #if ENABLE_ASH_ALIAS
  8740. sp->ap = ap;
  8741. if (ap) {
  8742. ap->flag |= ALIASINUSE;
  8743. sp->string = s;
  8744. }
  8745. #endif
  8746. g_parsefile->next_to_pgetc = s;
  8747. g_parsefile->left_in_line = len;
  8748. INT_ON;
  8749. }
  8750. static void
  8751. popstring(void)
  8752. {
  8753. struct strpush *sp = g_parsefile->strpush;
  8754. INT_OFF;
  8755. #if ENABLE_ASH_ALIAS
  8756. if (sp->ap) {
  8757. if (g_parsefile->next_to_pgetc[-1] == ' '
  8758. || g_parsefile->next_to_pgetc[-1] == '\t'
  8759. ) {
  8760. checkkwd |= CHKALIAS;
  8761. }
  8762. if (sp->string != sp->ap->val) {
  8763. free(sp->string);
  8764. }
  8765. sp->ap->flag &= ~ALIASINUSE;
  8766. if (sp->ap->flag & ALIASDEAD) {
  8767. unalias(sp->ap->name);
  8768. }
  8769. }
  8770. #endif
  8771. g_parsefile->next_to_pgetc = sp->prev_string;
  8772. g_parsefile->left_in_line = sp->prev_left_in_line;
  8773. g_parsefile->strpush = sp->prev;
  8774. if (sp != &(g_parsefile->basestrpush))
  8775. free(sp);
  8776. INT_ON;
  8777. }
  8778. //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
  8779. //it peeks whether it is &>, and then pushes back both chars.
  8780. //This function needs to save last *next_to_pgetc to buf[0]
  8781. //to make two pungetc() reliable. Currently,
  8782. // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
  8783. static int
  8784. preadfd(void)
  8785. {
  8786. int nr;
  8787. char *buf = g_parsefile->buf;
  8788. g_parsefile->next_to_pgetc = buf;
  8789. #if ENABLE_FEATURE_EDITING
  8790. retry:
  8791. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  8792. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1, /*loop_on_EINTR:*/ 1);
  8793. else {
  8794. int timeout = -1;
  8795. # if ENABLE_ASH_IDLE_TIMEOUT
  8796. if (iflag) {
  8797. const char *tmout_var = lookupvar("TMOUT");
  8798. if (tmout_var) {
  8799. timeout = atoi(tmout_var) * 1000;
  8800. if (timeout <= 0)
  8801. timeout = -1;
  8802. }
  8803. }
  8804. # endif
  8805. # if ENABLE_FEATURE_TAB_COMPLETION
  8806. line_input_state->path_lookup = pathval();
  8807. # endif
  8808. /* Unicode support should be activated even if LANG is set
  8809. * _during_ shell execution, not only if it was set when
  8810. * shell was started. Therefore, re-check LANG every time:
  8811. */
  8812. reinit_unicode(lookupvar("LANG"));
  8813. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
  8814. if (nr == 0) {
  8815. /* Ctrl+C pressed */
  8816. if (trap[SIGINT]) {
  8817. buf[0] = '\n';
  8818. buf[1] = '\0';
  8819. raise(SIGINT);
  8820. return 1;
  8821. }
  8822. goto retry;
  8823. }
  8824. if (nr < 0) {
  8825. if (errno == 0) {
  8826. /* Ctrl+D pressed */
  8827. nr = 0;
  8828. }
  8829. # if ENABLE_ASH_IDLE_TIMEOUT
  8830. else if (errno == EAGAIN && timeout > 0) {
  8831. printf("\007timed out waiting for input: auto-logout\n");
  8832. exitshell();
  8833. }
  8834. # endif
  8835. }
  8836. }
  8837. #else
  8838. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1, /*loop_on_EINTR:*/ 1);
  8839. #endif
  8840. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  8841. if (nr < 0) {
  8842. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  8843. int flags = fcntl(0, F_GETFL);
  8844. if (flags >= 0 && (flags & O_NONBLOCK)) {
  8845. flags &= ~O_NONBLOCK;
  8846. if (fcntl(0, F_SETFL, flags) >= 0) {
  8847. out2str("sh: turning off NDELAY mode\n");
  8848. goto retry;
  8849. }
  8850. }
  8851. }
  8852. }
  8853. #endif
  8854. return nr;
  8855. }
  8856. /*
  8857. * Refill the input buffer and return the next input character:
  8858. *
  8859. * 1) If a string was pushed back on the input, pop it;
  8860. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  8861. * or we are reading from a string so we can't refill the buffer,
  8862. * return EOF.
  8863. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  8864. * 4) Process input up to the next newline, deleting nul characters.
  8865. */
  8866. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  8867. #define pgetc_debug(...) ((void)0)
  8868. static int
  8869. preadbuffer(void)
  8870. {
  8871. char *q;
  8872. int more;
  8873. while (g_parsefile->strpush) {
  8874. #if ENABLE_ASH_ALIAS
  8875. if (g_parsefile->left_in_line == -1
  8876. && g_parsefile->strpush->ap
  8877. && g_parsefile->next_to_pgetc[-1] != ' '
  8878. && g_parsefile->next_to_pgetc[-1] != '\t'
  8879. ) {
  8880. pgetc_debug("preadbuffer PEOA");
  8881. return PEOA;
  8882. }
  8883. #endif
  8884. popstring();
  8885. /* try "pgetc" now: */
  8886. pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
  8887. g_parsefile->left_in_line,
  8888. g_parsefile->next_to_pgetc,
  8889. g_parsefile->next_to_pgetc);
  8890. if (--g_parsefile->left_in_line >= 0)
  8891. return (unsigned char)(*g_parsefile->next_to_pgetc++);
  8892. }
  8893. /* on both branches above g_parsefile->left_in_line < 0.
  8894. * "pgetc" needs refilling.
  8895. */
  8896. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  8897. * pungetc() may increment it a few times.
  8898. * Assuming it won't increment it to less than -90.
  8899. */
  8900. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  8901. pgetc_debug("preadbuffer PEOF1");
  8902. /* even in failure keep left_in_line and next_to_pgetc
  8903. * in lock step, for correct multi-layer pungetc.
  8904. * left_in_line was decremented before preadbuffer(),
  8905. * must inc next_to_pgetc: */
  8906. g_parsefile->next_to_pgetc++;
  8907. return PEOF;
  8908. }
  8909. more = g_parsefile->left_in_buffer;
  8910. if (more <= 0) {
  8911. flush_stdout_stderr();
  8912. again:
  8913. more = preadfd();
  8914. if (more <= 0) {
  8915. /* don't try reading again */
  8916. g_parsefile->left_in_line = -99;
  8917. pgetc_debug("preadbuffer PEOF2");
  8918. g_parsefile->next_to_pgetc++;
  8919. return PEOF;
  8920. }
  8921. }
  8922. /* Find out where's the end of line.
  8923. * Set g_parsefile->left_in_line
  8924. * and g_parsefile->left_in_buffer acordingly.
  8925. * NUL chars are deleted.
  8926. */
  8927. q = g_parsefile->next_to_pgetc;
  8928. for (;;) {
  8929. char c;
  8930. more--;
  8931. c = *q;
  8932. if (c == '\0') {
  8933. memmove(q, q + 1, more);
  8934. } else {
  8935. q++;
  8936. if (c == '\n') {
  8937. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8938. break;
  8939. }
  8940. }
  8941. if (more <= 0) {
  8942. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8943. if (g_parsefile->left_in_line < 0)
  8944. goto again;
  8945. break;
  8946. }
  8947. }
  8948. g_parsefile->left_in_buffer = more;
  8949. if (vflag) {
  8950. char save = *q;
  8951. *q = '\0';
  8952. out2str(g_parsefile->next_to_pgetc);
  8953. *q = save;
  8954. }
  8955. pgetc_debug("preadbuffer at %d:%p'%s'",
  8956. g_parsefile->left_in_line,
  8957. g_parsefile->next_to_pgetc,
  8958. g_parsefile->next_to_pgetc);
  8959. return (unsigned char)*g_parsefile->next_to_pgetc++;
  8960. }
  8961. #define pgetc_as_macro() \
  8962. (--g_parsefile->left_in_line >= 0 \
  8963. ? (unsigned char)*g_parsefile->next_to_pgetc++ \
  8964. : preadbuffer() \
  8965. )
  8966. static int
  8967. pgetc(void)
  8968. {
  8969. pgetc_debug("pgetc_fast at %d:%p'%s'",
  8970. g_parsefile->left_in_line,
  8971. g_parsefile->next_to_pgetc,
  8972. g_parsefile->next_to_pgetc);
  8973. return pgetc_as_macro();
  8974. }
  8975. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  8976. # define pgetc_fast() pgetc()
  8977. #else
  8978. # define pgetc_fast() pgetc_as_macro()
  8979. #endif
  8980. #if ENABLE_ASH_ALIAS
  8981. static int
  8982. pgetc_without_PEOA(void)
  8983. {
  8984. int c;
  8985. do {
  8986. pgetc_debug("pgetc_fast at %d:%p'%s'",
  8987. g_parsefile->left_in_line,
  8988. g_parsefile->next_to_pgetc,
  8989. g_parsefile->next_to_pgetc);
  8990. c = pgetc_fast();
  8991. } while (c == PEOA);
  8992. return c;
  8993. }
  8994. #else
  8995. # define pgetc_without_PEOA() pgetc()
  8996. #endif
  8997. /*
  8998. * Read a line from the script.
  8999. */
  9000. static char *
  9001. pfgets(char *line, int len)
  9002. {
  9003. char *p = line;
  9004. int nleft = len;
  9005. int c;
  9006. while (--nleft > 0) {
  9007. c = pgetc_without_PEOA();
  9008. if (c == PEOF) {
  9009. if (p == line)
  9010. return NULL;
  9011. break;
  9012. }
  9013. *p++ = c;
  9014. if (c == '\n')
  9015. break;
  9016. }
  9017. *p = '\0';
  9018. return line;
  9019. }
  9020. /*
  9021. * Undo the last call to pgetc. Only one character may be pushed back.
  9022. * PEOF may be pushed back.
  9023. */
  9024. static void
  9025. pungetc(void)
  9026. {
  9027. g_parsefile->left_in_line++;
  9028. g_parsefile->next_to_pgetc--;
  9029. pgetc_debug("pushed back to %d:%p'%s'",
  9030. g_parsefile->left_in_line,
  9031. g_parsefile->next_to_pgetc,
  9032. g_parsefile->next_to_pgetc);
  9033. }
  9034. /*
  9035. * To handle the "." command, a stack of input files is used. Pushfile
  9036. * adds a new entry to the stack and popfile restores the previous level.
  9037. */
  9038. static void
  9039. pushfile(void)
  9040. {
  9041. struct parsefile *pf;
  9042. pf = ckzalloc(sizeof(*pf));
  9043. pf->prev = g_parsefile;
  9044. pf->pf_fd = -1;
  9045. /*pf->strpush = NULL; - ckzalloc did it */
  9046. /*pf->basestrpush.prev = NULL;*/
  9047. g_parsefile = pf;
  9048. }
  9049. static void
  9050. popfile(void)
  9051. {
  9052. struct parsefile *pf = g_parsefile;
  9053. INT_OFF;
  9054. if (pf->pf_fd >= 0)
  9055. close(pf->pf_fd);
  9056. free(pf->buf);
  9057. while (pf->strpush)
  9058. popstring();
  9059. g_parsefile = pf->prev;
  9060. free(pf);
  9061. INT_ON;
  9062. }
  9063. /*
  9064. * Return to top level.
  9065. */
  9066. static void
  9067. popallfiles(void)
  9068. {
  9069. while (g_parsefile != &basepf)
  9070. popfile();
  9071. }
  9072. /*
  9073. * Close the file(s) that the shell is reading commands from. Called
  9074. * after a fork is done.
  9075. */
  9076. static void
  9077. closescript(void)
  9078. {
  9079. popallfiles();
  9080. if (g_parsefile->pf_fd > 0) {
  9081. close(g_parsefile->pf_fd);
  9082. g_parsefile->pf_fd = 0;
  9083. }
  9084. }
  9085. /*
  9086. * Like setinputfile, but takes an open file descriptor. Call this with
  9087. * interrupts off.
  9088. */
  9089. static void
  9090. setinputfd(int fd, int push)
  9091. {
  9092. close_on_exec_on(fd);
  9093. if (push) {
  9094. pushfile();
  9095. g_parsefile->buf = NULL;
  9096. }
  9097. g_parsefile->pf_fd = fd;
  9098. if (g_parsefile->buf == NULL)
  9099. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9100. g_parsefile->left_in_buffer = 0;
  9101. g_parsefile->left_in_line = 0;
  9102. g_parsefile->linno = 1;
  9103. }
  9104. /*
  9105. * Set the input to take input from a file. If push is set, push the
  9106. * old input onto the stack first.
  9107. */
  9108. static int
  9109. setinputfile(const char *fname, int flags)
  9110. {
  9111. int fd;
  9112. int fd2;
  9113. INT_OFF;
  9114. fd = open(fname, O_RDONLY);
  9115. if (fd < 0) {
  9116. if (flags & INPUT_NOFILE_OK)
  9117. goto out;
  9118. ash_msg_and_raise_error("can't open '%s'", fname);
  9119. }
  9120. if (fd < 10) {
  9121. fd2 = copyfd(fd, 10);
  9122. close(fd);
  9123. if (fd2 < 0)
  9124. ash_msg_and_raise_error("out of file descriptors");
  9125. fd = fd2;
  9126. }
  9127. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9128. out:
  9129. INT_ON;
  9130. return fd;
  9131. }
  9132. /*
  9133. * Like setinputfile, but takes input from a string.
  9134. */
  9135. static void
  9136. setinputstring(char *string)
  9137. {
  9138. INT_OFF;
  9139. pushfile();
  9140. g_parsefile->next_to_pgetc = string;
  9141. g_parsefile->left_in_line = strlen(string);
  9142. g_parsefile->buf = NULL;
  9143. g_parsefile->linno = 1;
  9144. INT_ON;
  9145. }
  9146. /* ============ mail.c
  9147. *
  9148. * Routines to check for mail.
  9149. */
  9150. #if ENABLE_ASH_MAIL
  9151. #define MAXMBOXES 10
  9152. /* times of mailboxes */
  9153. static time_t mailtime[MAXMBOXES];
  9154. /* Set if MAIL or MAILPATH is changed. */
  9155. static smallint mail_var_path_changed;
  9156. /*
  9157. * Print appropriate message(s) if mail has arrived.
  9158. * If mail_var_path_changed is set,
  9159. * then the value of MAIL has mail_var_path_changed,
  9160. * so we just update the values.
  9161. */
  9162. static void
  9163. chkmail(void)
  9164. {
  9165. const char *mpath;
  9166. char *p;
  9167. char *q;
  9168. time_t *mtp;
  9169. struct stackmark smark;
  9170. struct stat statb;
  9171. setstackmark(&smark);
  9172. mpath = mpathset() ? mpathval() : mailval();
  9173. for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
  9174. p = path_advance(&mpath, nullstr);
  9175. if (p == NULL)
  9176. break;
  9177. if (*p == '\0')
  9178. continue;
  9179. for (q = p; *q; q++)
  9180. continue;
  9181. #if DEBUG
  9182. if (q[-1] != '/')
  9183. abort();
  9184. #endif
  9185. q[-1] = '\0'; /* delete trailing '/' */
  9186. if (stat(p, &statb) < 0) {
  9187. *mtp = 0;
  9188. continue;
  9189. }
  9190. if (!mail_var_path_changed && statb.st_mtime != *mtp) {
  9191. fprintf(
  9192. stderr, "%s\n",
  9193. pathopt ? pathopt : "you have mail"
  9194. );
  9195. }
  9196. *mtp = statb.st_mtime;
  9197. }
  9198. mail_var_path_changed = 0;
  9199. popstackmark(&smark);
  9200. }
  9201. static void FAST_FUNC
  9202. changemail(const char *val UNUSED_PARAM)
  9203. {
  9204. mail_var_path_changed = 1;
  9205. }
  9206. #endif /* ASH_MAIL */
  9207. /* ============ ??? */
  9208. /*
  9209. * Set the shell parameters.
  9210. */
  9211. static void
  9212. setparam(char **argv)
  9213. {
  9214. char **newparam;
  9215. char **ap;
  9216. int nparam;
  9217. for (nparam = 0; argv[nparam]; nparam++)
  9218. continue;
  9219. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  9220. while (*argv) {
  9221. *ap++ = ckstrdup(*argv++);
  9222. }
  9223. *ap = NULL;
  9224. freeparam(&shellparam);
  9225. shellparam.malloced = 1;
  9226. shellparam.nparam = nparam;
  9227. shellparam.p = newparam;
  9228. #if ENABLE_ASH_GETOPTS
  9229. shellparam.optind = 1;
  9230. shellparam.optoff = -1;
  9231. #endif
  9232. }
  9233. /*
  9234. * Process shell options. The global variable argptr contains a pointer
  9235. * to the argument list; we advance it past the options.
  9236. *
  9237. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  9238. * For a non-interactive shell, an error condition encountered
  9239. * by a special built-in ... shall cause the shell to write a diagnostic message
  9240. * to standard error and exit as shown in the following table:
  9241. * Error Special Built-In
  9242. * ...
  9243. * Utility syntax error (option or operand error) Shall exit
  9244. * ...
  9245. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  9246. * we see that bash does not do that (set "finishes" with error code 1 instead,
  9247. * and shell continues), and people rely on this behavior!
  9248. * Testcase:
  9249. * set -o barfoo 2>/dev/null
  9250. * echo $?
  9251. *
  9252. * Oh well. Let's mimic that.
  9253. */
  9254. static int
  9255. plus_minus_o(char *name, int val)
  9256. {
  9257. int i;
  9258. if (name) {
  9259. for (i = 0; i < NOPTS; i++) {
  9260. if (strcmp(name, optnames(i)) == 0) {
  9261. optlist[i] = val;
  9262. return 0;
  9263. }
  9264. }
  9265. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  9266. return 1;
  9267. }
  9268. for (i = 0; i < NOPTS; i++) {
  9269. if (val) {
  9270. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  9271. } else {
  9272. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  9273. }
  9274. }
  9275. return 0;
  9276. }
  9277. static void
  9278. setoption(int flag, int val)
  9279. {
  9280. int i;
  9281. for (i = 0; i < NOPTS; i++) {
  9282. if (optletters(i) == flag) {
  9283. optlist[i] = val;
  9284. return;
  9285. }
  9286. }
  9287. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  9288. /* NOTREACHED */
  9289. }
  9290. static int
  9291. options(int cmdline)
  9292. {
  9293. char *p;
  9294. int val;
  9295. int c;
  9296. if (cmdline)
  9297. minusc = NULL;
  9298. while ((p = *argptr) != NULL) {
  9299. c = *p++;
  9300. if (c != '-' && c != '+')
  9301. break;
  9302. argptr++;
  9303. val = 0; /* val = 0 if c == '+' */
  9304. if (c == '-') {
  9305. val = 1;
  9306. if (p[0] == '\0' || LONE_DASH(p)) {
  9307. if (!cmdline) {
  9308. /* "-" means turn off -x and -v */
  9309. if (p[0] == '\0')
  9310. xflag = vflag = 0;
  9311. /* "--" means reset params */
  9312. else if (*argptr == NULL)
  9313. setparam(argptr);
  9314. }
  9315. break; /* "-" or "--" terminates options */
  9316. }
  9317. }
  9318. /* first char was + or - */
  9319. while ((c = *p++) != '\0') {
  9320. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  9321. if (c == 'c' && cmdline) {
  9322. minusc = p; /* command is after shell args */
  9323. } else if (c == 'o') {
  9324. if (plus_minus_o(*argptr, val)) {
  9325. /* it already printed err message */
  9326. return 1; /* error */
  9327. }
  9328. if (*argptr)
  9329. argptr++;
  9330. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  9331. isloginsh = 1;
  9332. /* bash does not accept +-login, we also won't */
  9333. } else if (cmdline && val && (c == '-')) { /* long options */
  9334. if (strcmp(p, "login") == 0)
  9335. isloginsh = 1;
  9336. break;
  9337. } else {
  9338. setoption(c, val);
  9339. }
  9340. }
  9341. }
  9342. return 0;
  9343. }
  9344. /*
  9345. * The shift builtin command.
  9346. */
  9347. static int FAST_FUNC
  9348. shiftcmd(int argc UNUSED_PARAM, char **argv)
  9349. {
  9350. int n;
  9351. char **ap1, **ap2;
  9352. n = 1;
  9353. if (argv[1])
  9354. n = number(argv[1]);
  9355. if (n > shellparam.nparam)
  9356. n = 0; /* bash compat, was = shellparam.nparam; */
  9357. INT_OFF;
  9358. shellparam.nparam -= n;
  9359. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  9360. if (shellparam.malloced)
  9361. free(*ap1);
  9362. }
  9363. ap2 = shellparam.p;
  9364. while ((*ap2++ = *ap1++) != NULL)
  9365. continue;
  9366. #if ENABLE_ASH_GETOPTS
  9367. shellparam.optind = 1;
  9368. shellparam.optoff = -1;
  9369. #endif
  9370. INT_ON;
  9371. return 0;
  9372. }
  9373. /*
  9374. * POSIX requires that 'set' (but not export or readonly) output the
  9375. * variables in lexicographic order - by the locale's collating order (sigh).
  9376. * Maybe we could keep them in an ordered balanced binary tree
  9377. * instead of hashed lists.
  9378. * For now just roll 'em through qsort for printing...
  9379. */
  9380. static int
  9381. showvars(const char *sep_prefix, int on, int off)
  9382. {
  9383. const char *sep;
  9384. char **ep, **epend;
  9385. ep = listvars(on, off, &epend);
  9386. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  9387. sep = *sep_prefix ? " " : sep_prefix;
  9388. for (; ep < epend; ep++) {
  9389. const char *p;
  9390. const char *q;
  9391. p = strchrnul(*ep, '=');
  9392. q = nullstr;
  9393. if (*p)
  9394. q = single_quote(++p);
  9395. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  9396. }
  9397. return 0;
  9398. }
  9399. /*
  9400. * The set command builtin.
  9401. */
  9402. static int FAST_FUNC
  9403. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9404. {
  9405. int retval;
  9406. if (!argv[1])
  9407. return showvars(nullstr, 0, VUNSET);
  9408. INT_OFF;
  9409. retval = options(/*cmdline:*/ 0);
  9410. if (retval == 0) { /* if no parse error... */
  9411. optschanged();
  9412. if (*argptr != NULL) {
  9413. setparam(argptr);
  9414. }
  9415. }
  9416. INT_ON;
  9417. return retval;
  9418. }
  9419. #if ENABLE_ASH_RANDOM_SUPPORT
  9420. static void FAST_FUNC
  9421. change_random(const char *value)
  9422. {
  9423. uint32_t t;
  9424. if (value == NULL) {
  9425. /* "get", generate */
  9426. t = next_random(&random_gen);
  9427. /* set without recursion */
  9428. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  9429. vrandom.flags &= ~VNOFUNC;
  9430. } else {
  9431. /* set/reset */
  9432. t = strtoul(value, NULL, 10);
  9433. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  9434. }
  9435. }
  9436. #endif
  9437. #if ENABLE_ASH_GETOPTS
  9438. static int
  9439. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  9440. {
  9441. char *p, *q;
  9442. char c = '?';
  9443. int done = 0;
  9444. int err = 0;
  9445. char s[12];
  9446. char **optnext;
  9447. if (*param_optind < 1)
  9448. return 1;
  9449. optnext = optfirst + *param_optind - 1;
  9450. if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
  9451. p = NULL;
  9452. else
  9453. p = optnext[-1] + *optoff;
  9454. if (p == NULL || *p == '\0') {
  9455. /* Current word is done, advance */
  9456. p = *optnext;
  9457. if (p == NULL || *p != '-' || *++p == '\0') {
  9458. atend:
  9459. p = NULL;
  9460. done = 1;
  9461. goto out;
  9462. }
  9463. optnext++;
  9464. if (LONE_DASH(p)) /* check for "--" */
  9465. goto atend;
  9466. }
  9467. c = *p++;
  9468. for (q = optstr; *q != c;) {
  9469. if (*q == '\0') {
  9470. if (optstr[0] == ':') {
  9471. s[0] = c;
  9472. s[1] = '\0';
  9473. err |= setvarsafe("OPTARG", s, 0);
  9474. } else {
  9475. fprintf(stderr, "Illegal option -%c\n", c);
  9476. unsetvar("OPTARG");
  9477. }
  9478. c = '?';
  9479. goto out;
  9480. }
  9481. if (*++q == ':')
  9482. q++;
  9483. }
  9484. if (*++q == ':') {
  9485. if (*p == '\0' && (p = *optnext) == NULL) {
  9486. if (optstr[0] == ':') {
  9487. s[0] = c;
  9488. s[1] = '\0';
  9489. err |= setvarsafe("OPTARG", s, 0);
  9490. c = ':';
  9491. } else {
  9492. fprintf(stderr, "No arg for -%c option\n", c);
  9493. unsetvar("OPTARG");
  9494. c = '?';
  9495. }
  9496. goto out;
  9497. }
  9498. if (p == *optnext)
  9499. optnext++;
  9500. err |= setvarsafe("OPTARG", p, 0);
  9501. p = NULL;
  9502. } else
  9503. err |= setvarsafe("OPTARG", nullstr, 0);
  9504. out:
  9505. *optoff = p ? p - *(optnext - 1) : -1;
  9506. *param_optind = optnext - optfirst + 1;
  9507. fmtstr(s, sizeof(s), "%d", *param_optind);
  9508. err |= setvarsafe("OPTIND", s, VNOFUNC);
  9509. s[0] = c;
  9510. s[1] = '\0';
  9511. err |= setvarsafe(optvar, s, 0);
  9512. if (err) {
  9513. *param_optind = 1;
  9514. *optoff = -1;
  9515. flush_stdout_stderr();
  9516. raise_exception(EXERROR);
  9517. }
  9518. return done;
  9519. }
  9520. /*
  9521. * The getopts builtin. Shellparam.optnext points to the next argument
  9522. * to be processed. Shellparam.optptr points to the next character to
  9523. * be processed in the current argument. If shellparam.optnext is NULL,
  9524. * then it's the first time getopts has been called.
  9525. */
  9526. static int FAST_FUNC
  9527. getoptscmd(int argc, char **argv)
  9528. {
  9529. char **optbase;
  9530. if (argc < 3)
  9531. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  9532. if (argc == 3) {
  9533. optbase = shellparam.p;
  9534. if (shellparam.optind > shellparam.nparam + 1) {
  9535. shellparam.optind = 1;
  9536. shellparam.optoff = -1;
  9537. }
  9538. } else {
  9539. optbase = &argv[3];
  9540. if (shellparam.optind > argc - 2) {
  9541. shellparam.optind = 1;
  9542. shellparam.optoff = -1;
  9543. }
  9544. }
  9545. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  9546. &shellparam.optoff);
  9547. }
  9548. #endif /* ASH_GETOPTS */
  9549. /* ============ Shell parser */
  9550. struct heredoc {
  9551. struct heredoc *next; /* next here document in list */
  9552. union node *here; /* redirection node */
  9553. char *eofmark; /* string indicating end of input */
  9554. smallint striptabs; /* if set, strip leading tabs */
  9555. };
  9556. static smallint tokpushback; /* last token pushed back */
  9557. static smallint parsebackquote; /* nonzero if we are inside backquotes */
  9558. static smallint quoteflag; /* set if (part of) last token was quoted */
  9559. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  9560. static struct heredoc *heredoclist; /* list of here documents to read */
  9561. static char *wordtext; /* text of last word returned by readtoken */
  9562. static struct nodelist *backquotelist;
  9563. static union node *redirnode;
  9564. static struct heredoc *heredoc;
  9565. static const char *
  9566. tokname(char *buf, int tok)
  9567. {
  9568. if (tok < TSEMI)
  9569. return tokname_array[tok] + 1;
  9570. sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
  9571. return buf;
  9572. }
  9573. /* raise_error_unexpected_syntax:
  9574. * Called when an unexpected token is read during the parse. The argument
  9575. * is the token that is expected, or -1 if more than one type of token can
  9576. * occur at this point.
  9577. */
  9578. static void raise_error_unexpected_syntax(int) NORETURN;
  9579. static void
  9580. raise_error_unexpected_syntax(int token)
  9581. {
  9582. char msg[64];
  9583. char buf[16];
  9584. int l;
  9585. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  9586. if (token >= 0)
  9587. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  9588. raise_error_syntax(msg);
  9589. /* NOTREACHED */
  9590. }
  9591. #define EOFMARKLEN 79
  9592. /* parsing is heavily cross-recursive, need these forward decls */
  9593. static union node *andor(void);
  9594. static union node *pipeline(void);
  9595. static union node *parse_command(void);
  9596. static void parseheredoc(void);
  9597. static char peektoken(void);
  9598. static int readtoken(void);
  9599. static union node *
  9600. list(int nlflag)
  9601. {
  9602. union node *n1, *n2, *n3;
  9603. int tok;
  9604. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9605. if (nlflag == 2 && peektoken())
  9606. return NULL;
  9607. n1 = NULL;
  9608. for (;;) {
  9609. n2 = andor();
  9610. tok = readtoken();
  9611. if (tok == TBACKGND) {
  9612. if (n2->type == NPIPE) {
  9613. n2->npipe.pipe_backgnd = 1;
  9614. } else {
  9615. if (n2->type != NREDIR) {
  9616. n3 = stzalloc(sizeof(struct nredir));
  9617. n3->nredir.n = n2;
  9618. /*n3->nredir.redirect = NULL; - stzalloc did it */
  9619. n2 = n3;
  9620. }
  9621. n2->type = NBACKGND;
  9622. }
  9623. }
  9624. if (n1 == NULL) {
  9625. n1 = n2;
  9626. } else {
  9627. n3 = stzalloc(sizeof(struct nbinary));
  9628. n3->type = NSEMI;
  9629. n3->nbinary.ch1 = n1;
  9630. n3->nbinary.ch2 = n2;
  9631. n1 = n3;
  9632. }
  9633. switch (tok) {
  9634. case TBACKGND:
  9635. case TSEMI:
  9636. tok = readtoken();
  9637. /* fall through */
  9638. case TNL:
  9639. if (tok == TNL) {
  9640. parseheredoc();
  9641. if (nlflag == 1)
  9642. return n1;
  9643. } else {
  9644. tokpushback = 1;
  9645. }
  9646. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9647. if (peektoken())
  9648. return n1;
  9649. break;
  9650. case TEOF:
  9651. if (heredoclist)
  9652. parseheredoc();
  9653. else
  9654. pungetc(); /* push back EOF on input */
  9655. return n1;
  9656. default:
  9657. if (nlflag == 1)
  9658. raise_error_unexpected_syntax(-1);
  9659. tokpushback = 1;
  9660. return n1;
  9661. }
  9662. }
  9663. }
  9664. static union node *
  9665. andor(void)
  9666. {
  9667. union node *n1, *n2, *n3;
  9668. int t;
  9669. n1 = pipeline();
  9670. for (;;) {
  9671. t = readtoken();
  9672. if (t == TAND) {
  9673. t = NAND;
  9674. } else if (t == TOR) {
  9675. t = NOR;
  9676. } else {
  9677. tokpushback = 1;
  9678. return n1;
  9679. }
  9680. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9681. n2 = pipeline();
  9682. n3 = stzalloc(sizeof(struct nbinary));
  9683. n3->type = t;
  9684. n3->nbinary.ch1 = n1;
  9685. n3->nbinary.ch2 = n2;
  9686. n1 = n3;
  9687. }
  9688. }
  9689. static union node *
  9690. pipeline(void)
  9691. {
  9692. union node *n1, *n2, *pipenode;
  9693. struct nodelist *lp, *prev;
  9694. int negate;
  9695. negate = 0;
  9696. TRACE(("pipeline: entered\n"));
  9697. if (readtoken() == TNOT) {
  9698. negate = !negate;
  9699. checkkwd = CHKKWD | CHKALIAS;
  9700. } else
  9701. tokpushback = 1;
  9702. n1 = parse_command();
  9703. if (readtoken() == TPIPE) {
  9704. pipenode = stzalloc(sizeof(struct npipe));
  9705. pipenode->type = NPIPE;
  9706. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  9707. lp = stzalloc(sizeof(struct nodelist));
  9708. pipenode->npipe.cmdlist = lp;
  9709. lp->n = n1;
  9710. do {
  9711. prev = lp;
  9712. lp = stzalloc(sizeof(struct nodelist));
  9713. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9714. lp->n = parse_command();
  9715. prev->next = lp;
  9716. } while (readtoken() == TPIPE);
  9717. lp->next = NULL;
  9718. n1 = pipenode;
  9719. }
  9720. tokpushback = 1;
  9721. if (negate) {
  9722. n2 = stzalloc(sizeof(struct nnot));
  9723. n2->type = NNOT;
  9724. n2->nnot.com = n1;
  9725. return n2;
  9726. }
  9727. return n1;
  9728. }
  9729. static union node *
  9730. makename(void)
  9731. {
  9732. union node *n;
  9733. n = stzalloc(sizeof(struct narg));
  9734. n->type = NARG;
  9735. /*n->narg.next = NULL; - stzalloc did it */
  9736. n->narg.text = wordtext;
  9737. n->narg.backquote = backquotelist;
  9738. return n;
  9739. }
  9740. static void
  9741. fixredir(union node *n, const char *text, int err)
  9742. {
  9743. int fd;
  9744. TRACE(("Fix redir %s %d\n", text, err));
  9745. if (!err)
  9746. n->ndup.vname = NULL;
  9747. fd = bb_strtou(text, NULL, 10);
  9748. if (!errno && fd >= 0)
  9749. n->ndup.dupfd = fd;
  9750. else if (LONE_DASH(text))
  9751. n->ndup.dupfd = -1;
  9752. else {
  9753. if (err)
  9754. raise_error_syntax("bad fd number");
  9755. n->ndup.vname = makename();
  9756. }
  9757. }
  9758. /*
  9759. * Returns true if the text contains nothing to expand (no dollar signs
  9760. * or backquotes).
  9761. */
  9762. static int
  9763. noexpand(const char *text)
  9764. {
  9765. unsigned char c;
  9766. while ((c = *text++) != '\0') {
  9767. if (c == CTLQUOTEMARK)
  9768. continue;
  9769. if (c == CTLESC)
  9770. text++;
  9771. else if (SIT(c, BASESYNTAX) == CCTL)
  9772. return 0;
  9773. }
  9774. return 1;
  9775. }
  9776. static void
  9777. parsefname(void)
  9778. {
  9779. union node *n = redirnode;
  9780. if (readtoken() != TWORD)
  9781. raise_error_unexpected_syntax(-1);
  9782. if (n->type == NHERE) {
  9783. struct heredoc *here = heredoc;
  9784. struct heredoc *p;
  9785. int i;
  9786. if (quoteflag == 0)
  9787. n->type = NXHERE;
  9788. TRACE(("Here document %d\n", n->type));
  9789. if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  9790. raise_error_syntax("illegal eof marker for << redirection");
  9791. rmescapes(wordtext, 0);
  9792. here->eofmark = wordtext;
  9793. here->next = NULL;
  9794. if (heredoclist == NULL)
  9795. heredoclist = here;
  9796. else {
  9797. for (p = heredoclist; p->next; p = p->next)
  9798. continue;
  9799. p->next = here;
  9800. }
  9801. } else if (n->type == NTOFD || n->type == NFROMFD) {
  9802. fixredir(n, wordtext, 0);
  9803. } else {
  9804. n->nfile.fname = makename();
  9805. }
  9806. }
  9807. static union node *
  9808. simplecmd(void)
  9809. {
  9810. union node *args, **app;
  9811. union node *n = NULL;
  9812. union node *vars, **vpp;
  9813. union node **rpp, *redir;
  9814. int savecheckkwd;
  9815. #if ENABLE_ASH_BASH_COMPAT
  9816. smallint double_brackets_flag = 0;
  9817. #endif
  9818. args = NULL;
  9819. app = &args;
  9820. vars = NULL;
  9821. vpp = &vars;
  9822. redir = NULL;
  9823. rpp = &redir;
  9824. savecheckkwd = CHKALIAS;
  9825. for (;;) {
  9826. int t;
  9827. checkkwd = savecheckkwd;
  9828. t = readtoken();
  9829. switch (t) {
  9830. #if ENABLE_ASH_BASH_COMPAT
  9831. case TAND: /* "&&" */
  9832. case TOR: /* "||" */
  9833. if (!double_brackets_flag) {
  9834. tokpushback = 1;
  9835. goto out;
  9836. }
  9837. wordtext = (char *) (t == TAND ? "-a" : "-o");
  9838. #endif
  9839. case TWORD:
  9840. n = stzalloc(sizeof(struct narg));
  9841. n->type = NARG;
  9842. /*n->narg.next = NULL; - stzalloc did it */
  9843. n->narg.text = wordtext;
  9844. #if ENABLE_ASH_BASH_COMPAT
  9845. if (strcmp("[[", wordtext) == 0)
  9846. double_brackets_flag = 1;
  9847. else if (strcmp("]]", wordtext) == 0)
  9848. double_brackets_flag = 0;
  9849. #endif
  9850. n->narg.backquote = backquotelist;
  9851. if (savecheckkwd && isassignment(wordtext)) {
  9852. *vpp = n;
  9853. vpp = &n->narg.next;
  9854. } else {
  9855. *app = n;
  9856. app = &n->narg.next;
  9857. savecheckkwd = 0;
  9858. }
  9859. break;
  9860. case TREDIR:
  9861. *rpp = n = redirnode;
  9862. rpp = &n->nfile.next;
  9863. parsefname(); /* read name of redirection file */
  9864. break;
  9865. case TLP:
  9866. if (args && app == &args->narg.next
  9867. && !vars && !redir
  9868. ) {
  9869. struct builtincmd *bcmd;
  9870. const char *name;
  9871. /* We have a function */
  9872. if (readtoken() != TRP)
  9873. raise_error_unexpected_syntax(TRP);
  9874. name = n->narg.text;
  9875. if (!goodname(name)
  9876. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  9877. ) {
  9878. raise_error_syntax("bad function name");
  9879. }
  9880. n->type = NDEFUN;
  9881. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9882. n->narg.next = parse_command();
  9883. return n;
  9884. }
  9885. /* fall through */
  9886. default:
  9887. tokpushback = 1;
  9888. goto out;
  9889. }
  9890. }
  9891. out:
  9892. *app = NULL;
  9893. *vpp = NULL;
  9894. *rpp = NULL;
  9895. n = stzalloc(sizeof(struct ncmd));
  9896. n->type = NCMD;
  9897. n->ncmd.args = args;
  9898. n->ncmd.assign = vars;
  9899. n->ncmd.redirect = redir;
  9900. return n;
  9901. }
  9902. static union node *
  9903. parse_command(void)
  9904. {
  9905. union node *n1, *n2;
  9906. union node *ap, **app;
  9907. union node *cp, **cpp;
  9908. union node *redir, **rpp;
  9909. union node **rpp2;
  9910. int t;
  9911. redir = NULL;
  9912. rpp2 = &redir;
  9913. switch (readtoken()) {
  9914. default:
  9915. raise_error_unexpected_syntax(-1);
  9916. /* NOTREACHED */
  9917. case TIF:
  9918. n1 = stzalloc(sizeof(struct nif));
  9919. n1->type = NIF;
  9920. n1->nif.test = list(0);
  9921. if (readtoken() != TTHEN)
  9922. raise_error_unexpected_syntax(TTHEN);
  9923. n1->nif.ifpart = list(0);
  9924. n2 = n1;
  9925. while (readtoken() == TELIF) {
  9926. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  9927. n2 = n2->nif.elsepart;
  9928. n2->type = NIF;
  9929. n2->nif.test = list(0);
  9930. if (readtoken() != TTHEN)
  9931. raise_error_unexpected_syntax(TTHEN);
  9932. n2->nif.ifpart = list(0);
  9933. }
  9934. if (lasttoken == TELSE)
  9935. n2->nif.elsepart = list(0);
  9936. else {
  9937. n2->nif.elsepart = NULL;
  9938. tokpushback = 1;
  9939. }
  9940. t = TFI;
  9941. break;
  9942. case TWHILE:
  9943. case TUNTIL: {
  9944. int got;
  9945. n1 = stzalloc(sizeof(struct nbinary));
  9946. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  9947. n1->nbinary.ch1 = list(0);
  9948. got = readtoken();
  9949. if (got != TDO) {
  9950. TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
  9951. got == TWORD ? wordtext : ""));
  9952. raise_error_unexpected_syntax(TDO);
  9953. }
  9954. n1->nbinary.ch2 = list(0);
  9955. t = TDONE;
  9956. break;
  9957. }
  9958. case TFOR:
  9959. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  9960. raise_error_syntax("bad for loop variable");
  9961. n1 = stzalloc(sizeof(struct nfor));
  9962. n1->type = NFOR;
  9963. n1->nfor.var = wordtext;
  9964. checkkwd = CHKKWD | CHKALIAS;
  9965. if (readtoken() == TIN) {
  9966. app = &ap;
  9967. while (readtoken() == TWORD) {
  9968. n2 = stzalloc(sizeof(struct narg));
  9969. n2->type = NARG;
  9970. /*n2->narg.next = NULL; - stzalloc did it */
  9971. n2->narg.text = wordtext;
  9972. n2->narg.backquote = backquotelist;
  9973. *app = n2;
  9974. app = &n2->narg.next;
  9975. }
  9976. *app = NULL;
  9977. n1->nfor.args = ap;
  9978. if (lasttoken != TNL && lasttoken != TSEMI)
  9979. raise_error_unexpected_syntax(-1);
  9980. } else {
  9981. n2 = stzalloc(sizeof(struct narg));
  9982. n2->type = NARG;
  9983. /*n2->narg.next = NULL; - stzalloc did it */
  9984. n2->narg.text = (char *)dolatstr;
  9985. /*n2->narg.backquote = NULL;*/
  9986. n1->nfor.args = n2;
  9987. /*
  9988. * Newline or semicolon here is optional (but note
  9989. * that the original Bourne shell only allowed NL).
  9990. */
  9991. if (lasttoken != TNL && lasttoken != TSEMI)
  9992. tokpushback = 1;
  9993. }
  9994. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9995. if (readtoken() != TDO)
  9996. raise_error_unexpected_syntax(TDO);
  9997. n1->nfor.body = list(0);
  9998. t = TDONE;
  9999. break;
  10000. case TCASE:
  10001. n1 = stzalloc(sizeof(struct ncase));
  10002. n1->type = NCASE;
  10003. if (readtoken() != TWORD)
  10004. raise_error_unexpected_syntax(TWORD);
  10005. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10006. n2->type = NARG;
  10007. /*n2->narg.next = NULL; - stzalloc did it */
  10008. n2->narg.text = wordtext;
  10009. n2->narg.backquote = backquotelist;
  10010. do {
  10011. checkkwd = CHKKWD | CHKALIAS;
  10012. } while (readtoken() == TNL);
  10013. if (lasttoken != TIN)
  10014. raise_error_unexpected_syntax(TIN);
  10015. cpp = &n1->ncase.cases;
  10016. next_case:
  10017. checkkwd = CHKNL | CHKKWD;
  10018. t = readtoken();
  10019. while (t != TESAC) {
  10020. if (lasttoken == TLP)
  10021. readtoken();
  10022. *cpp = cp = stzalloc(sizeof(struct nclist));
  10023. cp->type = NCLIST;
  10024. app = &cp->nclist.pattern;
  10025. for (;;) {
  10026. *app = ap = stzalloc(sizeof(struct narg));
  10027. ap->type = NARG;
  10028. /*ap->narg.next = NULL; - stzalloc did it */
  10029. ap->narg.text = wordtext;
  10030. ap->narg.backquote = backquotelist;
  10031. if (readtoken() != TPIPE)
  10032. break;
  10033. app = &ap->narg.next;
  10034. readtoken();
  10035. }
  10036. //ap->narg.next = NULL;
  10037. if (lasttoken != TRP)
  10038. raise_error_unexpected_syntax(TRP);
  10039. cp->nclist.body = list(2);
  10040. cpp = &cp->nclist.next;
  10041. checkkwd = CHKNL | CHKKWD;
  10042. t = readtoken();
  10043. if (t != TESAC) {
  10044. if (t != TENDCASE)
  10045. raise_error_unexpected_syntax(TENDCASE);
  10046. goto next_case;
  10047. }
  10048. }
  10049. *cpp = NULL;
  10050. goto redir;
  10051. case TLP:
  10052. n1 = stzalloc(sizeof(struct nredir));
  10053. n1->type = NSUBSHELL;
  10054. n1->nredir.n = list(0);
  10055. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10056. t = TRP;
  10057. break;
  10058. case TBEGIN:
  10059. n1 = list(0);
  10060. t = TEND;
  10061. break;
  10062. case TWORD:
  10063. case TREDIR:
  10064. tokpushback = 1;
  10065. return simplecmd();
  10066. }
  10067. if (readtoken() != t)
  10068. raise_error_unexpected_syntax(t);
  10069. redir:
  10070. /* Now check for redirection which may follow command */
  10071. checkkwd = CHKKWD | CHKALIAS;
  10072. rpp = rpp2;
  10073. while (readtoken() == TREDIR) {
  10074. *rpp = n2 = redirnode;
  10075. rpp = &n2->nfile.next;
  10076. parsefname();
  10077. }
  10078. tokpushback = 1;
  10079. *rpp = NULL;
  10080. if (redir) {
  10081. if (n1->type != NSUBSHELL) {
  10082. n2 = stzalloc(sizeof(struct nredir));
  10083. n2->type = NREDIR;
  10084. n2->nredir.n = n1;
  10085. n1 = n2;
  10086. }
  10087. n1->nredir.redirect = redir;
  10088. }
  10089. return n1;
  10090. }
  10091. #if ENABLE_ASH_BASH_COMPAT
  10092. static int decode_dollar_squote(void)
  10093. {
  10094. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  10095. int c, cnt;
  10096. char *p;
  10097. char buf[4];
  10098. c = pgetc();
  10099. p = strchr(C_escapes, c);
  10100. if (p) {
  10101. buf[0] = c;
  10102. p = buf;
  10103. cnt = 3;
  10104. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  10105. do {
  10106. c = pgetc();
  10107. *++p = c;
  10108. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  10109. pungetc();
  10110. } else if (c == 'x') { /* \xHH */
  10111. do {
  10112. c = pgetc();
  10113. *++p = c;
  10114. } while (isxdigit(c) && --cnt);
  10115. pungetc();
  10116. if (cnt == 3) { /* \x but next char is "bad" */
  10117. c = 'x';
  10118. goto unrecognized;
  10119. }
  10120. } else { /* simple seq like \\ or \t */
  10121. p++;
  10122. }
  10123. *p = '\0';
  10124. p = buf;
  10125. c = bb_process_escape_sequence((void*)&p);
  10126. } else { /* unrecognized "\z": print both chars unless ' or " */
  10127. if (c != '\'' && c != '"') {
  10128. unrecognized:
  10129. c |= 0x100; /* "please encode \, then me" */
  10130. }
  10131. }
  10132. return c;
  10133. }
  10134. #endif
  10135. /*
  10136. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  10137. * is not NULL, read a here document. In the latter case, eofmark is the
  10138. * word which marks the end of the document and striptabs is true if
  10139. * leading tabs should be stripped from the document. The argument c
  10140. * is the first character of the input token or document.
  10141. *
  10142. * Because C does not have internal subroutines, I have simulated them
  10143. * using goto's to implement the subroutine linkage. The following macros
  10144. * will run code that appears at the end of readtoken1.
  10145. */
  10146. #define CHECKEND() {goto checkend; checkend_return:;}
  10147. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  10148. #define PARSESUB() {goto parsesub; parsesub_return:;}
  10149. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  10150. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  10151. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  10152. static int
  10153. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  10154. {
  10155. /* NB: syntax parameter fits into smallint */
  10156. /* c parameter is an unsigned char or PEOF or PEOA */
  10157. char *out;
  10158. int len;
  10159. char line[EOFMARKLEN + 1];
  10160. struct nodelist *bqlist;
  10161. smallint quotef;
  10162. smallint dblquote;
  10163. smallint oldstyle;
  10164. smallint prevsyntax; /* syntax before arithmetic */
  10165. #if ENABLE_ASH_EXPAND_PRMT
  10166. smallint pssyntax; /* we are expanding a prompt string */
  10167. #endif
  10168. int varnest; /* levels of variables expansion */
  10169. int arinest; /* levels of arithmetic expansion */
  10170. int parenlevel; /* levels of parens in arithmetic */
  10171. int dqvarnest; /* levels of variables expansion within double quotes */
  10172. IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
  10173. #if __GNUC__
  10174. /* Avoid longjmp clobbering */
  10175. (void) &out;
  10176. (void) &quotef;
  10177. (void) &dblquote;
  10178. (void) &varnest;
  10179. (void) &arinest;
  10180. (void) &parenlevel;
  10181. (void) &dqvarnest;
  10182. (void) &oldstyle;
  10183. (void) &prevsyntax;
  10184. (void) &syntax;
  10185. #endif
  10186. startlinno = g_parsefile->linno;
  10187. bqlist = NULL;
  10188. quotef = 0;
  10189. prevsyntax = 0;
  10190. #if ENABLE_ASH_EXPAND_PRMT
  10191. pssyntax = (syntax == PSSYNTAX);
  10192. if (pssyntax)
  10193. syntax = DQSYNTAX;
  10194. #endif
  10195. dblquote = (syntax == DQSYNTAX);
  10196. varnest = 0;
  10197. arinest = 0;
  10198. parenlevel = 0;
  10199. dqvarnest = 0;
  10200. STARTSTACKSTR(out);
  10201. loop:
  10202. /* For each line, until end of word */
  10203. CHECKEND(); /* set c to PEOF if at end of here document */
  10204. for (;;) { /* until end of line or end of word */
  10205. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  10206. switch (SIT(c, syntax)) {
  10207. case CNL: /* '\n' */
  10208. if (syntax == BASESYNTAX)
  10209. goto endword; /* exit outer loop */
  10210. USTPUTC(c, out);
  10211. g_parsefile->linno++;
  10212. setprompt_if(doprompt, 2);
  10213. c = pgetc();
  10214. goto loop; /* continue outer loop */
  10215. case CWORD:
  10216. USTPUTC(c, out);
  10217. break;
  10218. case CCTL:
  10219. if (eofmark == NULL || dblquote)
  10220. USTPUTC(CTLESC, out);
  10221. #if ENABLE_ASH_BASH_COMPAT
  10222. if (c == '\\' && bash_dollar_squote) {
  10223. c = decode_dollar_squote();
  10224. if (c & 0x100) {
  10225. USTPUTC('\\', out);
  10226. c = (unsigned char)c;
  10227. }
  10228. }
  10229. #endif
  10230. USTPUTC(c, out);
  10231. break;
  10232. case CBACK: /* backslash */
  10233. c = pgetc_without_PEOA();
  10234. if (c == PEOF) {
  10235. USTPUTC(CTLESC, out);
  10236. USTPUTC('\\', out);
  10237. pungetc();
  10238. } else if (c == '\n') {
  10239. setprompt_if(doprompt, 2);
  10240. } else {
  10241. #if ENABLE_ASH_EXPAND_PRMT
  10242. if (c == '$' && pssyntax) {
  10243. USTPUTC(CTLESC, out);
  10244. USTPUTC('\\', out);
  10245. }
  10246. #endif
  10247. /* Backslash is retained if we are in "str" and next char isn't special */
  10248. if (dblquote
  10249. && c != '\\'
  10250. && c != '`'
  10251. && c != '$'
  10252. && (c != '"' || eofmark != NULL)
  10253. ) {
  10254. USTPUTC(CTLESC, out);
  10255. USTPUTC('\\', out);
  10256. }
  10257. if (SIT(c, SQSYNTAX) == CCTL)
  10258. USTPUTC(CTLESC, out);
  10259. USTPUTC(c, out);
  10260. quotef = 1;
  10261. }
  10262. break;
  10263. case CSQUOTE:
  10264. syntax = SQSYNTAX;
  10265. quotemark:
  10266. if (eofmark == NULL) {
  10267. USTPUTC(CTLQUOTEMARK, out);
  10268. }
  10269. break;
  10270. case CDQUOTE:
  10271. syntax = DQSYNTAX;
  10272. dblquote = 1;
  10273. goto quotemark;
  10274. case CENDQUOTE:
  10275. IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
  10276. if (eofmark != NULL && arinest == 0
  10277. && varnest == 0
  10278. ) {
  10279. USTPUTC(c, out);
  10280. } else {
  10281. if (dqvarnest == 0) {
  10282. syntax = BASESYNTAX;
  10283. dblquote = 0;
  10284. }
  10285. quotef = 1;
  10286. goto quotemark;
  10287. }
  10288. break;
  10289. case CVAR: /* '$' */
  10290. PARSESUB(); /* parse substitution */
  10291. break;
  10292. case CENDVAR: /* '}' */
  10293. if (varnest > 0) {
  10294. varnest--;
  10295. if (dqvarnest > 0) {
  10296. dqvarnest--;
  10297. }
  10298. c = CTLENDVAR;
  10299. }
  10300. USTPUTC(c, out);
  10301. break;
  10302. #if ENABLE_SH_MATH_SUPPORT
  10303. case CLP: /* '(' in arithmetic */
  10304. parenlevel++;
  10305. USTPUTC(c, out);
  10306. break;
  10307. case CRP: /* ')' in arithmetic */
  10308. if (parenlevel > 0) {
  10309. parenlevel--;
  10310. } else {
  10311. if (pgetc() == ')') {
  10312. if (--arinest == 0) {
  10313. syntax = prevsyntax;
  10314. dblquote = (syntax == DQSYNTAX);
  10315. c = CTLENDARI;
  10316. }
  10317. } else {
  10318. /*
  10319. * unbalanced parens
  10320. * (don't 2nd guess - no error)
  10321. */
  10322. pungetc();
  10323. }
  10324. }
  10325. USTPUTC(c, out);
  10326. break;
  10327. #endif
  10328. case CBQUOTE: /* '`' */
  10329. PARSEBACKQOLD();
  10330. break;
  10331. case CENDFILE:
  10332. goto endword; /* exit outer loop */
  10333. case CIGN:
  10334. break;
  10335. default:
  10336. if (varnest == 0) {
  10337. #if ENABLE_ASH_BASH_COMPAT
  10338. if (c == '&') {
  10339. if (pgetc() == '>')
  10340. c = 0x100 + '>'; /* flag &> */
  10341. pungetc();
  10342. }
  10343. #endif
  10344. goto endword; /* exit outer loop */
  10345. }
  10346. IF_ASH_ALIAS(if (c != PEOA))
  10347. USTPUTC(c, out);
  10348. }
  10349. c = pgetc_fast();
  10350. } /* for (;;) */
  10351. endword:
  10352. #if ENABLE_SH_MATH_SUPPORT
  10353. if (syntax == ARISYNTAX)
  10354. raise_error_syntax("missing '))'");
  10355. #endif
  10356. if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
  10357. raise_error_syntax("unterminated quoted string");
  10358. if (varnest != 0) {
  10359. startlinno = g_parsefile->linno;
  10360. /* { */
  10361. raise_error_syntax("missing '}'");
  10362. }
  10363. USTPUTC('\0', out);
  10364. len = out - (char *)stackblock();
  10365. out = stackblock();
  10366. if (eofmark == NULL) {
  10367. if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
  10368. && quotef == 0
  10369. ) {
  10370. if (isdigit_str9(out)) {
  10371. PARSEREDIR(); /* passed as params: out, c */
  10372. lasttoken = TREDIR;
  10373. return lasttoken;
  10374. }
  10375. /* else: non-number X seen, interpret it
  10376. * as "NNNX>file" = "NNNX >file" */
  10377. }
  10378. pungetc();
  10379. }
  10380. quoteflag = quotef;
  10381. backquotelist = bqlist;
  10382. grabstackblock(len);
  10383. wordtext = out;
  10384. lasttoken = TWORD;
  10385. return lasttoken;
  10386. /* end of readtoken routine */
  10387. /*
  10388. * Check to see whether we are at the end of the here document. When this
  10389. * is called, c is set to the first character of the next input line. If
  10390. * we are at the end of the here document, this routine sets the c to PEOF.
  10391. */
  10392. checkend: {
  10393. if (eofmark) {
  10394. #if ENABLE_ASH_ALIAS
  10395. if (c == PEOA)
  10396. c = pgetc_without_PEOA();
  10397. #endif
  10398. if (striptabs) {
  10399. while (c == '\t') {
  10400. c = pgetc_without_PEOA();
  10401. }
  10402. }
  10403. if (c == *eofmark) {
  10404. if (pfgets(line, sizeof(line)) != NULL) {
  10405. char *p, *q;
  10406. p = line;
  10407. for (q = eofmark + 1; *q && *p == *q; p++, q++)
  10408. continue;
  10409. if (*p == '\n' && *q == '\0') {
  10410. c = PEOF;
  10411. g_parsefile->linno++;
  10412. needprompt = doprompt;
  10413. } else {
  10414. pushstring(line, NULL);
  10415. }
  10416. }
  10417. }
  10418. }
  10419. goto checkend_return;
  10420. }
  10421. /*
  10422. * Parse a redirection operator. The variable "out" points to a string
  10423. * specifying the fd to be redirected. The variable "c" contains the
  10424. * first character of the redirection operator.
  10425. */
  10426. parseredir: {
  10427. /* out is already checked to be a valid number or "" */
  10428. int fd = (*out == '\0' ? -1 : atoi(out));
  10429. union node *np;
  10430. np = stzalloc(sizeof(struct nfile));
  10431. if (c == '>') {
  10432. np->nfile.fd = 1;
  10433. c = pgetc();
  10434. if (c == '>')
  10435. np->type = NAPPEND;
  10436. else if (c == '|')
  10437. np->type = NCLOBBER;
  10438. else if (c == '&')
  10439. np->type = NTOFD;
  10440. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  10441. else {
  10442. np->type = NTO;
  10443. pungetc();
  10444. }
  10445. }
  10446. #if ENABLE_ASH_BASH_COMPAT
  10447. else if (c == 0x100 + '>') { /* this flags &> redirection */
  10448. np->nfile.fd = 1;
  10449. pgetc(); /* this is '>', no need to check */
  10450. np->type = NTO2;
  10451. }
  10452. #endif
  10453. else { /* c == '<' */
  10454. /*np->nfile.fd = 0; - stzalloc did it */
  10455. c = pgetc();
  10456. switch (c) {
  10457. case '<':
  10458. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  10459. np = stzalloc(sizeof(struct nhere));
  10460. /*np->nfile.fd = 0; - stzalloc did it */
  10461. }
  10462. np->type = NHERE;
  10463. heredoc = stzalloc(sizeof(struct heredoc));
  10464. heredoc->here = np;
  10465. c = pgetc();
  10466. if (c == '-') {
  10467. heredoc->striptabs = 1;
  10468. } else {
  10469. /*heredoc->striptabs = 0; - stzalloc did it */
  10470. pungetc();
  10471. }
  10472. break;
  10473. case '&':
  10474. np->type = NFROMFD;
  10475. break;
  10476. case '>':
  10477. np->type = NFROMTO;
  10478. break;
  10479. default:
  10480. np->type = NFROM;
  10481. pungetc();
  10482. break;
  10483. }
  10484. }
  10485. if (fd >= 0)
  10486. np->nfile.fd = fd;
  10487. redirnode = np;
  10488. goto parseredir_return;
  10489. }
  10490. /*
  10491. * Parse a substitution. At this point, we have read the dollar sign
  10492. * and nothing else.
  10493. */
  10494. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  10495. * (assuming ascii char codes, as the original implementation did) */
  10496. #define is_special(c) \
  10497. (((unsigned)(c) - 33 < 32) \
  10498. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  10499. parsesub: {
  10500. unsigned char subtype;
  10501. int typeloc;
  10502. int flags;
  10503. c = pgetc();
  10504. if (c > 255 /* PEOA or PEOF */
  10505. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  10506. ) {
  10507. #if ENABLE_ASH_BASH_COMPAT
  10508. if (c == '\'')
  10509. bash_dollar_squote = 1;
  10510. else
  10511. #endif
  10512. USTPUTC('$', out);
  10513. pungetc();
  10514. } else if (c == '(') {
  10515. /* $(command) or $((arith)) */
  10516. if (pgetc() == '(') {
  10517. #if ENABLE_SH_MATH_SUPPORT
  10518. PARSEARITH();
  10519. #else
  10520. raise_error_syntax("you disabled math support for $((arith)) syntax");
  10521. #endif
  10522. } else {
  10523. pungetc();
  10524. PARSEBACKQNEW();
  10525. }
  10526. } else {
  10527. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  10528. USTPUTC(CTLVAR, out);
  10529. typeloc = out - (char *)stackblock();
  10530. USTPUTC(VSNORMAL, out);
  10531. subtype = VSNORMAL;
  10532. if (c == '{') {
  10533. c = pgetc();
  10534. if (c == '#') {
  10535. c = pgetc();
  10536. if (c == '}')
  10537. c = '#'; /* ${#} - same as $# */
  10538. else
  10539. subtype = VSLENGTH; /* ${#VAR} */
  10540. } else {
  10541. subtype = 0;
  10542. }
  10543. }
  10544. if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
  10545. /* $[{[#]]NAME[}] */
  10546. do {
  10547. STPUTC(c, out);
  10548. c = pgetc();
  10549. } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
  10550. } else if (isdigit(c)) {
  10551. /* $[{[#]]NUM[}] */
  10552. do {
  10553. STPUTC(c, out);
  10554. c = pgetc();
  10555. } while (isdigit(c));
  10556. } else if (is_special(c)) {
  10557. /* $[{[#]]<specialchar>[}] */
  10558. USTPUTC(c, out);
  10559. c = pgetc();
  10560. } else {
  10561. badsub:
  10562. raise_error_syntax("bad substitution");
  10563. }
  10564. if (c != '}' && subtype == VSLENGTH) {
  10565. /* ${#VAR didn't end with } */
  10566. goto badsub;
  10567. }
  10568. STPUTC('=', out);
  10569. flags = 0;
  10570. if (subtype == 0) {
  10571. /* ${VAR...} but not $VAR or ${#VAR} */
  10572. /* c == first char after VAR */
  10573. switch (c) {
  10574. case ':':
  10575. c = pgetc();
  10576. #if ENABLE_ASH_BASH_COMPAT
  10577. if (c == ':' || c == '$' || isdigit(c)) {
  10578. //TODO: support more general format ${v:EXPR:EXPR},
  10579. // where EXPR follows $(()) rules
  10580. subtype = VSSUBSTR;
  10581. pungetc();
  10582. break; /* "goto do_pungetc" is bigger (!) */
  10583. }
  10584. #endif
  10585. flags = VSNUL;
  10586. /*FALLTHROUGH*/
  10587. default: {
  10588. static const char types[] ALIGN1 = "}-+?=";
  10589. const char *p = strchr(types, c);
  10590. if (p == NULL)
  10591. goto badsub;
  10592. subtype = p - types + VSNORMAL;
  10593. break;
  10594. }
  10595. case '%':
  10596. case '#': {
  10597. int cc = c;
  10598. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  10599. c = pgetc();
  10600. if (c != cc)
  10601. goto do_pungetc;
  10602. subtype++;
  10603. break;
  10604. }
  10605. #if ENABLE_ASH_BASH_COMPAT
  10606. case '/':
  10607. /* ${v/[/]pattern/repl} */
  10608. //TODO: encode pattern and repl separately.
  10609. // Currently ${v/$var_with_slash/repl} is horribly broken
  10610. subtype = VSREPLACE;
  10611. c = pgetc();
  10612. if (c != '/')
  10613. goto do_pungetc;
  10614. subtype++; /* VSREPLACEALL */
  10615. break;
  10616. #endif
  10617. }
  10618. } else {
  10619. do_pungetc:
  10620. pungetc();
  10621. }
  10622. if (dblquote || arinest)
  10623. flags |= VSQUOTE;
  10624. ((unsigned char *)stackblock())[typeloc] = subtype | flags;
  10625. if (subtype != VSNORMAL) {
  10626. varnest++;
  10627. if (dblquote || arinest) {
  10628. dqvarnest++;
  10629. }
  10630. }
  10631. }
  10632. goto parsesub_return;
  10633. }
  10634. /*
  10635. * Called to parse command substitutions. Newstyle is set if the command
  10636. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  10637. * list of commands (passed by reference), and savelen is the number of
  10638. * characters on the top of the stack which must be preserved.
  10639. */
  10640. parsebackq: {
  10641. struct nodelist **nlpp;
  10642. smallint savepbq;
  10643. union node *n;
  10644. char *volatile str;
  10645. struct jmploc jmploc;
  10646. struct jmploc *volatile savehandler;
  10647. size_t savelen;
  10648. smallint saveprompt = 0;
  10649. #ifdef __GNUC__
  10650. (void) &saveprompt;
  10651. #endif
  10652. savepbq = parsebackquote;
  10653. if (setjmp(jmploc.loc)) {
  10654. free(str);
  10655. parsebackquote = 0;
  10656. exception_handler = savehandler;
  10657. longjmp(exception_handler->loc, 1);
  10658. }
  10659. INT_OFF;
  10660. str = NULL;
  10661. savelen = out - (char *)stackblock();
  10662. if (savelen > 0) {
  10663. str = ckmalloc(savelen);
  10664. memcpy(str, stackblock(), savelen);
  10665. }
  10666. savehandler = exception_handler;
  10667. exception_handler = &jmploc;
  10668. INT_ON;
  10669. if (oldstyle) {
  10670. /* We must read until the closing backquote, giving special
  10671. treatment to some slashes, and then push the string and
  10672. reread it as input, interpreting it normally. */
  10673. char *pout;
  10674. size_t psavelen;
  10675. char *pstr;
  10676. STARTSTACKSTR(pout);
  10677. for (;;) {
  10678. int pc;
  10679. setprompt_if(needprompt, 2);
  10680. pc = pgetc();
  10681. switch (pc) {
  10682. case '`':
  10683. goto done;
  10684. case '\\':
  10685. pc = pgetc();
  10686. if (pc == '\n') {
  10687. g_parsefile->linno++;
  10688. setprompt_if(doprompt, 2);
  10689. /*
  10690. * If eating a newline, avoid putting
  10691. * the newline into the new character
  10692. * stream (via the STPUTC after the
  10693. * switch).
  10694. */
  10695. continue;
  10696. }
  10697. if (pc != '\\' && pc != '`' && pc != '$'
  10698. && (!dblquote || pc != '"')
  10699. ) {
  10700. STPUTC('\\', pout);
  10701. }
  10702. if (pc <= 255 /* not PEOA or PEOF */) {
  10703. break;
  10704. }
  10705. /* fall through */
  10706. case PEOF:
  10707. IF_ASH_ALIAS(case PEOA:)
  10708. startlinno = g_parsefile->linno;
  10709. raise_error_syntax("EOF in backquote substitution");
  10710. case '\n':
  10711. g_parsefile->linno++;
  10712. needprompt = doprompt;
  10713. break;
  10714. default:
  10715. break;
  10716. }
  10717. STPUTC(pc, pout);
  10718. }
  10719. done:
  10720. STPUTC('\0', pout);
  10721. psavelen = pout - (char *)stackblock();
  10722. if (psavelen > 0) {
  10723. pstr = grabstackstr(pout);
  10724. setinputstring(pstr);
  10725. }
  10726. }
  10727. nlpp = &bqlist;
  10728. while (*nlpp)
  10729. nlpp = &(*nlpp)->next;
  10730. *nlpp = stzalloc(sizeof(**nlpp));
  10731. /* (*nlpp)->next = NULL; - stzalloc did it */
  10732. parsebackquote = oldstyle;
  10733. if (oldstyle) {
  10734. saveprompt = doprompt;
  10735. doprompt = 0;
  10736. }
  10737. n = list(2);
  10738. if (oldstyle)
  10739. doprompt = saveprompt;
  10740. else if (readtoken() != TRP)
  10741. raise_error_unexpected_syntax(TRP);
  10742. (*nlpp)->n = n;
  10743. if (oldstyle) {
  10744. /*
  10745. * Start reading from old file again, ignoring any pushed back
  10746. * tokens left from the backquote parsing
  10747. */
  10748. popfile();
  10749. tokpushback = 0;
  10750. }
  10751. while (stackblocksize() <= savelen)
  10752. growstackblock();
  10753. STARTSTACKSTR(out);
  10754. if (str) {
  10755. memcpy(out, str, savelen);
  10756. STADJUST(savelen, out);
  10757. INT_OFF;
  10758. free(str);
  10759. str = NULL;
  10760. INT_ON;
  10761. }
  10762. parsebackquote = savepbq;
  10763. exception_handler = savehandler;
  10764. if (arinest || dblquote)
  10765. USTPUTC(CTLBACKQ | CTLQUOTE, out);
  10766. else
  10767. USTPUTC(CTLBACKQ, out);
  10768. if (oldstyle)
  10769. goto parsebackq_oldreturn;
  10770. goto parsebackq_newreturn;
  10771. }
  10772. #if ENABLE_SH_MATH_SUPPORT
  10773. /*
  10774. * Parse an arithmetic expansion (indicate start of one and set state)
  10775. */
  10776. parsearith: {
  10777. if (++arinest == 1) {
  10778. prevsyntax = syntax;
  10779. syntax = ARISYNTAX;
  10780. USTPUTC(CTLARI, out);
  10781. if (dblquote)
  10782. USTPUTC('"', out);
  10783. else
  10784. USTPUTC(' ', out);
  10785. } else {
  10786. /*
  10787. * we collapse embedded arithmetic expansion to
  10788. * parenthesis, which should be equivalent
  10789. */
  10790. USTPUTC('(', out);
  10791. }
  10792. goto parsearith_return;
  10793. }
  10794. #endif
  10795. } /* end of readtoken */
  10796. /*
  10797. * Read the next input token.
  10798. * If the token is a word, we set backquotelist to the list of cmds in
  10799. * backquotes. We set quoteflag to true if any part of the word was
  10800. * quoted.
  10801. * If the token is TREDIR, then we set redirnode to a structure containing
  10802. * the redirection.
  10803. * In all cases, the variable startlinno is set to the number of the line
  10804. * on which the token starts.
  10805. *
  10806. * [Change comment: here documents and internal procedures]
  10807. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  10808. * word parsing code into a separate routine. In this case, readtoken
  10809. * doesn't need to have any internal procedures, but parseword does.
  10810. * We could also make parseoperator in essence the main routine, and
  10811. * have parseword (readtoken1?) handle both words and redirection.]
  10812. */
  10813. #define NEW_xxreadtoken
  10814. #ifdef NEW_xxreadtoken
  10815. /* singles must be first! */
  10816. static const char xxreadtoken_chars[7] ALIGN1 = {
  10817. '\n', '(', ')', /* singles */
  10818. '&', '|', ';', /* doubles */
  10819. 0
  10820. };
  10821. #define xxreadtoken_singles 3
  10822. #define xxreadtoken_doubles 3
  10823. static const char xxreadtoken_tokens[] ALIGN1 = {
  10824. TNL, TLP, TRP, /* only single occurrence allowed */
  10825. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  10826. TEOF, /* corresponds to trailing nul */
  10827. TAND, TOR, TENDCASE /* if double occurrence */
  10828. };
  10829. static int
  10830. xxreadtoken(void)
  10831. {
  10832. int c;
  10833. if (tokpushback) {
  10834. tokpushback = 0;
  10835. return lasttoken;
  10836. }
  10837. setprompt_if(needprompt, 2);
  10838. startlinno = g_parsefile->linno;
  10839. for (;;) { /* until token or start of word found */
  10840. c = pgetc_fast();
  10841. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  10842. continue;
  10843. if (c == '#') {
  10844. while ((c = pgetc()) != '\n' && c != PEOF)
  10845. continue;
  10846. pungetc();
  10847. } else if (c == '\\') {
  10848. if (pgetc() != '\n') {
  10849. pungetc();
  10850. break; /* return readtoken1(...) */
  10851. }
  10852. startlinno = ++g_parsefile->linno;
  10853. setprompt_if(doprompt, 2);
  10854. } else {
  10855. const char *p;
  10856. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  10857. if (c != PEOF) {
  10858. if (c == '\n') {
  10859. g_parsefile->linno++;
  10860. needprompt = doprompt;
  10861. }
  10862. p = strchr(xxreadtoken_chars, c);
  10863. if (p == NULL)
  10864. break; /* return readtoken1(...) */
  10865. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  10866. int cc = pgetc();
  10867. if (cc == c) { /* double occurrence? */
  10868. p += xxreadtoken_doubles + 1;
  10869. } else {
  10870. pungetc();
  10871. #if ENABLE_ASH_BASH_COMPAT
  10872. if (c == '&' && cc == '>') /* &> */
  10873. break; /* return readtoken1(...) */
  10874. #endif
  10875. }
  10876. }
  10877. }
  10878. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  10879. return lasttoken;
  10880. }
  10881. } /* for (;;) */
  10882. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  10883. }
  10884. #else /* old xxreadtoken */
  10885. #define RETURN(token) return lasttoken = token
  10886. static int
  10887. xxreadtoken(void)
  10888. {
  10889. int c;
  10890. if (tokpushback) {
  10891. tokpushback = 0;
  10892. return lasttoken;
  10893. }
  10894. setprompt_if(needprompt, 2);
  10895. startlinno = g_parsefile->linno;
  10896. for (;;) { /* until token or start of word found */
  10897. c = pgetc_fast();
  10898. switch (c) {
  10899. case ' ': case '\t':
  10900. IF_ASH_ALIAS(case PEOA:)
  10901. continue;
  10902. case '#':
  10903. while ((c = pgetc()) != '\n' && c != PEOF)
  10904. continue;
  10905. pungetc();
  10906. continue;
  10907. case '\\':
  10908. if (pgetc() == '\n') {
  10909. startlinno = ++g_parsefile->linno;
  10910. setprompt_if(doprompt, 2);
  10911. continue;
  10912. }
  10913. pungetc();
  10914. goto breakloop;
  10915. case '\n':
  10916. g_parsefile->linno++;
  10917. needprompt = doprompt;
  10918. RETURN(TNL);
  10919. case PEOF:
  10920. RETURN(TEOF);
  10921. case '&':
  10922. if (pgetc() == '&')
  10923. RETURN(TAND);
  10924. pungetc();
  10925. RETURN(TBACKGND);
  10926. case '|':
  10927. if (pgetc() == '|')
  10928. RETURN(TOR);
  10929. pungetc();
  10930. RETURN(TPIPE);
  10931. case ';':
  10932. if (pgetc() == ';')
  10933. RETURN(TENDCASE);
  10934. pungetc();
  10935. RETURN(TSEMI);
  10936. case '(':
  10937. RETURN(TLP);
  10938. case ')':
  10939. RETURN(TRP);
  10940. default:
  10941. goto breakloop;
  10942. }
  10943. }
  10944. breakloop:
  10945. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  10946. #undef RETURN
  10947. }
  10948. #endif /* old xxreadtoken */
  10949. static int
  10950. readtoken(void)
  10951. {
  10952. int t;
  10953. #if DEBUG
  10954. smallint alreadyseen = tokpushback;
  10955. #endif
  10956. #if ENABLE_ASH_ALIAS
  10957. top:
  10958. #endif
  10959. t = xxreadtoken();
  10960. /*
  10961. * eat newlines
  10962. */
  10963. if (checkkwd & CHKNL) {
  10964. while (t == TNL) {
  10965. parseheredoc();
  10966. t = xxreadtoken();
  10967. }
  10968. }
  10969. if (t != TWORD || quoteflag) {
  10970. goto out;
  10971. }
  10972. /*
  10973. * check for keywords
  10974. */
  10975. if (checkkwd & CHKKWD) {
  10976. const char *const *pp;
  10977. pp = findkwd(wordtext);
  10978. if (pp) {
  10979. lasttoken = t = pp - tokname_array;
  10980. TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
  10981. goto out;
  10982. }
  10983. }
  10984. if (checkkwd & CHKALIAS) {
  10985. #if ENABLE_ASH_ALIAS
  10986. struct alias *ap;
  10987. ap = lookupalias(wordtext, 1);
  10988. if (ap != NULL) {
  10989. if (*ap->val) {
  10990. pushstring(ap->val, ap);
  10991. }
  10992. goto top;
  10993. }
  10994. #endif
  10995. }
  10996. out:
  10997. checkkwd = 0;
  10998. #if DEBUG
  10999. if (!alreadyseen)
  11000. TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
  11001. else
  11002. TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
  11003. #endif
  11004. return t;
  11005. }
  11006. static char
  11007. peektoken(void)
  11008. {
  11009. int t;
  11010. t = readtoken();
  11011. tokpushback = 1;
  11012. return tokname_array[t][0];
  11013. }
  11014. /*
  11015. * Read and parse a command. Returns NODE_EOF on end of file.
  11016. * (NULL is a valid parse tree indicating a blank line.)
  11017. */
  11018. static union node *
  11019. parsecmd(int interact)
  11020. {
  11021. int t;
  11022. tokpushback = 0;
  11023. doprompt = interact;
  11024. setprompt_if(doprompt, doprompt);
  11025. needprompt = 0;
  11026. t = readtoken();
  11027. if (t == TEOF)
  11028. return NODE_EOF;
  11029. if (t == TNL)
  11030. return NULL;
  11031. tokpushback = 1;
  11032. return list(1);
  11033. }
  11034. /*
  11035. * Input any here documents.
  11036. */
  11037. static void
  11038. parseheredoc(void)
  11039. {
  11040. struct heredoc *here;
  11041. union node *n;
  11042. here = heredoclist;
  11043. heredoclist = NULL;
  11044. while (here) {
  11045. setprompt_if(needprompt, 2);
  11046. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11047. here->eofmark, here->striptabs);
  11048. n = stzalloc(sizeof(struct narg));
  11049. n->narg.type = NARG;
  11050. /*n->narg.next = NULL; - stzalloc did it */
  11051. n->narg.text = wordtext;
  11052. n->narg.backquote = backquotelist;
  11053. here->here->nhere.doc = n;
  11054. here = here->next;
  11055. }
  11056. }
  11057. /*
  11058. * called by editline -- any expansions to the prompt should be added here.
  11059. */
  11060. #if ENABLE_ASH_EXPAND_PRMT
  11061. static const char *
  11062. expandstr(const char *ps)
  11063. {
  11064. union node n;
  11065. /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
  11066. * and token processing _can_ alter it (delete NULs etc). */
  11067. setinputstring((char *)ps);
  11068. readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
  11069. popfile();
  11070. n.narg.type = NARG;
  11071. n.narg.next = NULL;
  11072. n.narg.text = wordtext;
  11073. n.narg.backquote = backquotelist;
  11074. expandarg(&n, NULL, 0);
  11075. return stackblock();
  11076. }
  11077. #endif
  11078. /*
  11079. * Execute a command or commands contained in a string.
  11080. */
  11081. static int
  11082. evalstring(char *s, int mask)
  11083. {
  11084. union node *n;
  11085. struct stackmark smark;
  11086. int skip;
  11087. setinputstring(s);
  11088. setstackmark(&smark);
  11089. skip = 0;
  11090. while ((n = parsecmd(0)) != NODE_EOF) {
  11091. evaltree(n, 0);
  11092. popstackmark(&smark);
  11093. skip = evalskip;
  11094. if (skip)
  11095. break;
  11096. }
  11097. popfile();
  11098. skip &= mask;
  11099. evalskip = skip;
  11100. return skip;
  11101. }
  11102. /*
  11103. * The eval command.
  11104. */
  11105. static int FAST_FUNC
  11106. evalcmd(int argc UNUSED_PARAM, char **argv)
  11107. {
  11108. char *p;
  11109. char *concat;
  11110. if (argv[1]) {
  11111. p = argv[1];
  11112. argv += 2;
  11113. if (argv[0]) {
  11114. STARTSTACKSTR(concat);
  11115. for (;;) {
  11116. concat = stack_putstr(p, concat);
  11117. p = *argv++;
  11118. if (p == NULL)
  11119. break;
  11120. STPUTC(' ', concat);
  11121. }
  11122. STPUTC('\0', concat);
  11123. p = grabstackstr(concat);
  11124. }
  11125. evalstring(p, ~SKIPEVAL);
  11126. }
  11127. return exitstatus;
  11128. }
  11129. /*
  11130. * Read and execute commands.
  11131. * "Top" is nonzero for the top level command loop;
  11132. * it turns on prompting if the shell is interactive.
  11133. */
  11134. static int
  11135. cmdloop(int top)
  11136. {
  11137. union node *n;
  11138. struct stackmark smark;
  11139. int inter;
  11140. int numeof = 0;
  11141. TRACE(("cmdloop(%d) called\n", top));
  11142. for (;;) {
  11143. int skip;
  11144. setstackmark(&smark);
  11145. #if JOBS
  11146. if (doing_jobctl)
  11147. showjobs(stderr, SHOW_CHANGED);
  11148. #endif
  11149. inter = 0;
  11150. if (iflag && top) {
  11151. inter++;
  11152. chkmail();
  11153. }
  11154. n = parsecmd(inter);
  11155. #if DEBUG
  11156. if (DEBUG > 2 && debug && (n != NODE_EOF))
  11157. showtree(n);
  11158. #endif
  11159. if (n == NODE_EOF) {
  11160. if (!top || numeof >= 50)
  11161. break;
  11162. if (!stoppedjobs()) {
  11163. if (!Iflag)
  11164. break;
  11165. out2str("\nUse \"exit\" to leave shell.\n");
  11166. }
  11167. numeof++;
  11168. } else if (nflag == 0) {
  11169. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  11170. job_warning >>= 1;
  11171. numeof = 0;
  11172. evaltree(n, 0);
  11173. }
  11174. popstackmark(&smark);
  11175. skip = evalskip;
  11176. if (skip) {
  11177. evalskip = 0;
  11178. return skip & SKIPEVAL;
  11179. }
  11180. }
  11181. return 0;
  11182. }
  11183. /*
  11184. * Take commands from a file. To be compatible we should do a path
  11185. * search for the file, which is necessary to find sub-commands.
  11186. */
  11187. static char *
  11188. find_dot_file(char *name)
  11189. {
  11190. char *fullname;
  11191. const char *path = pathval();
  11192. struct stat statb;
  11193. /* don't try this for absolute or relative paths */
  11194. if (strchr(name, '/'))
  11195. return name;
  11196. /* IIRC standards do not say whether . is to be searched.
  11197. * And it is even smaller this way, making it unconditional for now:
  11198. */
  11199. if (1) { /* ENABLE_ASH_BASH_COMPAT */
  11200. fullname = name;
  11201. goto try_cur_dir;
  11202. }
  11203. while ((fullname = path_advance(&path, name)) != NULL) {
  11204. try_cur_dir:
  11205. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  11206. /*
  11207. * Don't bother freeing here, since it will
  11208. * be freed by the caller.
  11209. */
  11210. return fullname;
  11211. }
  11212. if (fullname != name)
  11213. stunalloc(fullname);
  11214. }
  11215. /* not found in the PATH */
  11216. ash_msg_and_raise_error("%s: not found", name);
  11217. /* NOTREACHED */
  11218. }
  11219. static int FAST_FUNC
  11220. dotcmd(int argc, char **argv)
  11221. {
  11222. char *fullname;
  11223. struct strlist *sp;
  11224. volatile struct shparam saveparam;
  11225. for (sp = cmdenviron; sp; sp = sp->next)
  11226. setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  11227. if (!argv[1]) {
  11228. /* bash says: "bash: .: filename argument required" */
  11229. return 2; /* bash compat */
  11230. }
  11231. /* "false; . empty_file; echo $?" should print 0, not 1: */
  11232. exitstatus = 0;
  11233. fullname = find_dot_file(argv[1]);
  11234. argv += 2;
  11235. argc -= 2;
  11236. if (argc) { /* argc > 0, argv[0] != NULL */
  11237. saveparam = shellparam;
  11238. shellparam.malloced = 0;
  11239. shellparam.nparam = argc;
  11240. shellparam.p = argv;
  11241. };
  11242. setinputfile(fullname, INPUT_PUSH_FILE);
  11243. commandname = fullname;
  11244. cmdloop(0);
  11245. popfile();
  11246. if (argc) {
  11247. freeparam(&shellparam);
  11248. shellparam = saveparam;
  11249. };
  11250. return exitstatus;
  11251. }
  11252. static int FAST_FUNC
  11253. exitcmd(int argc UNUSED_PARAM, char **argv)
  11254. {
  11255. if (stoppedjobs())
  11256. return 0;
  11257. if (argv[1])
  11258. exitstatus = number(argv[1]);
  11259. raise_exception(EXEXIT);
  11260. /* NOTREACHED */
  11261. }
  11262. /*
  11263. * Read a file containing shell functions.
  11264. */
  11265. static void
  11266. readcmdfile(char *name)
  11267. {
  11268. setinputfile(name, INPUT_PUSH_FILE);
  11269. cmdloop(0);
  11270. popfile();
  11271. }
  11272. /* ============ find_command inplementation */
  11273. /*
  11274. * Resolve a command name. If you change this routine, you may have to
  11275. * change the shellexec routine as well.
  11276. */
  11277. static void
  11278. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  11279. {
  11280. struct tblentry *cmdp;
  11281. int idx;
  11282. int prev;
  11283. char *fullname;
  11284. struct stat statb;
  11285. int e;
  11286. int updatetbl;
  11287. struct builtincmd *bcmd;
  11288. /* If name contains a slash, don't use PATH or hash table */
  11289. if (strchr(name, '/') != NULL) {
  11290. entry->u.index = -1;
  11291. if (act & DO_ABS) {
  11292. while (stat(name, &statb) < 0) {
  11293. #ifdef SYSV
  11294. if (errno == EINTR)
  11295. continue;
  11296. #endif
  11297. entry->cmdtype = CMDUNKNOWN;
  11298. return;
  11299. }
  11300. }
  11301. entry->cmdtype = CMDNORMAL;
  11302. return;
  11303. }
  11304. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  11305. updatetbl = (path == pathval());
  11306. if (!updatetbl) {
  11307. act |= DO_ALTPATH;
  11308. if (strstr(path, "%builtin") != NULL)
  11309. act |= DO_ALTBLTIN;
  11310. }
  11311. /* If name is in the table, check answer will be ok */
  11312. cmdp = cmdlookup(name, 0);
  11313. if (cmdp != NULL) {
  11314. int bit;
  11315. switch (cmdp->cmdtype) {
  11316. default:
  11317. #if DEBUG
  11318. abort();
  11319. #endif
  11320. case CMDNORMAL:
  11321. bit = DO_ALTPATH;
  11322. break;
  11323. case CMDFUNCTION:
  11324. bit = DO_NOFUNC;
  11325. break;
  11326. case CMDBUILTIN:
  11327. bit = DO_ALTBLTIN;
  11328. break;
  11329. }
  11330. if (act & bit) {
  11331. updatetbl = 0;
  11332. cmdp = NULL;
  11333. } else if (cmdp->rehash == 0)
  11334. /* if not invalidated by cd, we're done */
  11335. goto success;
  11336. }
  11337. /* If %builtin not in path, check for builtin next */
  11338. bcmd = find_builtin(name);
  11339. if (bcmd) {
  11340. if (IS_BUILTIN_REGULAR(bcmd))
  11341. goto builtin_success;
  11342. if (act & DO_ALTPATH) {
  11343. if (!(act & DO_ALTBLTIN))
  11344. goto builtin_success;
  11345. } else if (builtinloc <= 0) {
  11346. goto builtin_success;
  11347. }
  11348. }
  11349. #if ENABLE_FEATURE_SH_STANDALONE
  11350. {
  11351. int applet_no = find_applet_by_name(name);
  11352. if (applet_no >= 0) {
  11353. entry->cmdtype = CMDNORMAL;
  11354. entry->u.index = -2 - applet_no;
  11355. return;
  11356. }
  11357. }
  11358. #endif
  11359. /* We have to search path. */
  11360. prev = -1; /* where to start */
  11361. if (cmdp && cmdp->rehash) { /* doing a rehash */
  11362. if (cmdp->cmdtype == CMDBUILTIN)
  11363. prev = builtinloc;
  11364. else
  11365. prev = cmdp->param.index;
  11366. }
  11367. e = ENOENT;
  11368. idx = -1;
  11369. loop:
  11370. while ((fullname = path_advance(&path, name)) != NULL) {
  11371. stunalloc(fullname);
  11372. /* NB: code below will still use fullname
  11373. * despite it being "unallocated" */
  11374. idx++;
  11375. if (pathopt) {
  11376. if (prefix(pathopt, "builtin")) {
  11377. if (bcmd)
  11378. goto builtin_success;
  11379. continue;
  11380. }
  11381. if ((act & DO_NOFUNC)
  11382. || !prefix(pathopt, "func")
  11383. ) { /* ignore unimplemented options */
  11384. continue;
  11385. }
  11386. }
  11387. /* if rehash, don't redo absolute path names */
  11388. if (fullname[0] == '/' && idx <= prev) {
  11389. if (idx < prev)
  11390. continue;
  11391. TRACE(("searchexec \"%s\": no change\n", name));
  11392. goto success;
  11393. }
  11394. while (stat(fullname, &statb) < 0) {
  11395. #ifdef SYSV
  11396. if (errno == EINTR)
  11397. continue;
  11398. #endif
  11399. if (errno != ENOENT && errno != ENOTDIR)
  11400. e = errno;
  11401. goto loop;
  11402. }
  11403. e = EACCES; /* if we fail, this will be the error */
  11404. if (!S_ISREG(statb.st_mode))
  11405. continue;
  11406. if (pathopt) { /* this is a %func directory */
  11407. stalloc(strlen(fullname) + 1);
  11408. /* NB: stalloc will return space pointed by fullname
  11409. * (because we don't have any intervening allocations
  11410. * between stunalloc above and this stalloc) */
  11411. readcmdfile(fullname);
  11412. cmdp = cmdlookup(name, 0);
  11413. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  11414. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  11415. stunalloc(fullname);
  11416. goto success;
  11417. }
  11418. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  11419. if (!updatetbl) {
  11420. entry->cmdtype = CMDNORMAL;
  11421. entry->u.index = idx;
  11422. return;
  11423. }
  11424. INT_OFF;
  11425. cmdp = cmdlookup(name, 1);
  11426. cmdp->cmdtype = CMDNORMAL;
  11427. cmdp->param.index = idx;
  11428. INT_ON;
  11429. goto success;
  11430. }
  11431. /* We failed. If there was an entry for this command, delete it */
  11432. if (cmdp && updatetbl)
  11433. delete_cmd_entry();
  11434. if (act & DO_ERR)
  11435. ash_msg("%s: %s", name, errmsg(e, "not found"));
  11436. entry->cmdtype = CMDUNKNOWN;
  11437. return;
  11438. builtin_success:
  11439. if (!updatetbl) {
  11440. entry->cmdtype = CMDBUILTIN;
  11441. entry->u.cmd = bcmd;
  11442. return;
  11443. }
  11444. INT_OFF;
  11445. cmdp = cmdlookup(name, 1);
  11446. cmdp->cmdtype = CMDBUILTIN;
  11447. cmdp->param.cmd = bcmd;
  11448. INT_ON;
  11449. success:
  11450. cmdp->rehash = 0;
  11451. entry->cmdtype = cmdp->cmdtype;
  11452. entry->u = cmdp->param;
  11453. }
  11454. /* ============ trap.c */
  11455. /*
  11456. * The trap builtin.
  11457. */
  11458. static int FAST_FUNC
  11459. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11460. {
  11461. char *action;
  11462. char **ap;
  11463. int signo, exitcode;
  11464. nextopt(nullstr);
  11465. ap = argptr;
  11466. if (!*ap) {
  11467. for (signo = 0; signo < NSIG; signo++) {
  11468. char *tr = trap_ptr[signo];
  11469. if (tr) {
  11470. /* note: bash adds "SIG", but only if invoked
  11471. * as "bash". If called as "sh", or if set -o posix,
  11472. * then it prints short signal names.
  11473. * We are printing short names: */
  11474. out1fmt("trap -- %s %s\n",
  11475. single_quote(tr),
  11476. get_signame(signo));
  11477. /* trap_ptr != trap only if we are in special-cased `trap` code.
  11478. * In this case, we will exit very soon, no need to free(). */
  11479. /* if (trap_ptr != trap && tp[0]) */
  11480. /* free(tr); */
  11481. }
  11482. }
  11483. /*
  11484. if (trap_ptr != trap) {
  11485. free(trap_ptr);
  11486. trap_ptr = trap;
  11487. }
  11488. */
  11489. return 0;
  11490. }
  11491. action = NULL;
  11492. if (ap[1])
  11493. action = *ap++;
  11494. exitcode = 0;
  11495. while (*ap) {
  11496. signo = get_signum(*ap);
  11497. if (signo < 0) {
  11498. /* Mimic bash message exactly */
  11499. ash_msg("%s: invalid signal specification", *ap);
  11500. exitcode = 1;
  11501. goto next;
  11502. }
  11503. INT_OFF;
  11504. if (action) {
  11505. if (LONE_DASH(action))
  11506. action = NULL;
  11507. else
  11508. action = ckstrdup(action);
  11509. }
  11510. free(trap[signo]);
  11511. if (action)
  11512. may_have_traps = 1;
  11513. trap[signo] = action;
  11514. if (signo != 0)
  11515. setsignal(signo);
  11516. INT_ON;
  11517. next:
  11518. ap++;
  11519. }
  11520. return exitcode;
  11521. }
  11522. /* ============ Builtins */
  11523. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  11524. /*
  11525. * Lists available builtins
  11526. */
  11527. static int FAST_FUNC
  11528. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11529. {
  11530. unsigned col;
  11531. unsigned i;
  11532. out1fmt(
  11533. "Built-in commands:\n"
  11534. "------------------\n");
  11535. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  11536. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  11537. builtintab[i].name + 1);
  11538. if (col > 60) {
  11539. out1fmt("\n");
  11540. col = 0;
  11541. }
  11542. }
  11543. #if ENABLE_FEATURE_SH_STANDALONE
  11544. {
  11545. const char *a = applet_names;
  11546. while (*a) {
  11547. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  11548. if (col > 60) {
  11549. out1fmt("\n");
  11550. col = 0;
  11551. }
  11552. a += strlen(a) + 1;
  11553. }
  11554. }
  11555. #endif
  11556. out1fmt("\n\n");
  11557. return EXIT_SUCCESS;
  11558. }
  11559. #endif /* FEATURE_SH_EXTRA_QUIET */
  11560. /*
  11561. * The export and readonly commands.
  11562. */
  11563. static int FAST_FUNC
  11564. exportcmd(int argc UNUSED_PARAM, char **argv)
  11565. {
  11566. struct var *vp;
  11567. char *name;
  11568. const char *p;
  11569. char **aptr;
  11570. int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
  11571. if (nextopt("p") != 'p') {
  11572. aptr = argptr;
  11573. name = *aptr;
  11574. if (name) {
  11575. do {
  11576. p = strchr(name, '=');
  11577. if (p != NULL) {
  11578. p++;
  11579. } else {
  11580. vp = *findvar(hashvar(name), name);
  11581. if (vp) {
  11582. vp->flags |= flag;
  11583. continue;
  11584. }
  11585. }
  11586. setvar(name, p, flag);
  11587. } while ((name = *++aptr) != NULL);
  11588. return 0;
  11589. }
  11590. }
  11591. showvars(argv[0], flag, 0);
  11592. return 0;
  11593. }
  11594. /*
  11595. * Delete a function if it exists.
  11596. */
  11597. static void
  11598. unsetfunc(const char *name)
  11599. {
  11600. struct tblentry *cmdp;
  11601. cmdp = cmdlookup(name, 0);
  11602. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  11603. delete_cmd_entry();
  11604. }
  11605. /*
  11606. * The unset builtin command. We unset the function before we unset the
  11607. * variable to allow a function to be unset when there is a readonly variable
  11608. * with the same name.
  11609. */
  11610. static int FAST_FUNC
  11611. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11612. {
  11613. char **ap;
  11614. int i;
  11615. int flag = 0;
  11616. int ret = 0;
  11617. while ((i = nextopt("vf")) != 0) {
  11618. flag = i;
  11619. }
  11620. for (ap = argptr; *ap; ap++) {
  11621. if (flag != 'f') {
  11622. i = unsetvar(*ap);
  11623. ret |= i;
  11624. if (!(i & 2))
  11625. continue;
  11626. }
  11627. if (flag != 'v')
  11628. unsetfunc(*ap);
  11629. }
  11630. return ret & 1;
  11631. }
  11632. static const unsigned char timescmd_str[] ALIGN1 = {
  11633. ' ', offsetof(struct tms, tms_utime),
  11634. '\n', offsetof(struct tms, tms_stime),
  11635. ' ', offsetof(struct tms, tms_cutime),
  11636. '\n', offsetof(struct tms, tms_cstime),
  11637. 0
  11638. };
  11639. static int FAST_FUNC
  11640. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11641. {
  11642. unsigned long clk_tck, s, t;
  11643. const unsigned char *p;
  11644. struct tms buf;
  11645. clk_tck = sysconf(_SC_CLK_TCK);
  11646. times(&buf);
  11647. p = timescmd_str;
  11648. do {
  11649. t = *(clock_t *)(((char *) &buf) + p[1]);
  11650. s = t / clk_tck;
  11651. t = t % clk_tck;
  11652. out1fmt("%lum%lu.%03lus%c",
  11653. s / 60, s % 60,
  11654. (t * 1000) / clk_tck,
  11655. p[0]);
  11656. p += 2;
  11657. } while (*p);
  11658. return 0;
  11659. }
  11660. #if ENABLE_SH_MATH_SUPPORT
  11661. /*
  11662. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  11663. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  11664. *
  11665. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11666. */
  11667. static int FAST_FUNC
  11668. letcmd(int argc UNUSED_PARAM, char **argv)
  11669. {
  11670. arith_t i;
  11671. argv++;
  11672. if (!*argv)
  11673. ash_msg_and_raise_error("expression expected");
  11674. do {
  11675. i = ash_arith(*argv);
  11676. } while (*++argv);
  11677. return !i;
  11678. }
  11679. #endif
  11680. /*
  11681. * The read builtin. Options:
  11682. * -r Do not interpret '\' specially
  11683. * -s Turn off echo (tty only)
  11684. * -n NCHARS Read NCHARS max
  11685. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  11686. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  11687. * -u FD Read from given FD instead of fd 0
  11688. * This uses unbuffered input, which may be avoidable in some cases.
  11689. * TODO: bash also has:
  11690. * -a ARRAY Read into array[0],[1],etc
  11691. * -d DELIM End on DELIM char, not newline
  11692. * -e Use line editing (tty only)
  11693. */
  11694. static int FAST_FUNC
  11695. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11696. {
  11697. char *opt_n = NULL;
  11698. char *opt_p = NULL;
  11699. char *opt_t = NULL;
  11700. char *opt_u = NULL;
  11701. int read_flags = 0;
  11702. const char *r;
  11703. int i;
  11704. while ((i = nextopt("p:u:rt:n:s")) != '\0') {
  11705. switch (i) {
  11706. case 'p':
  11707. opt_p = optionarg;
  11708. break;
  11709. case 'n':
  11710. opt_n = optionarg;
  11711. break;
  11712. case 's':
  11713. read_flags |= BUILTIN_READ_SILENT;
  11714. break;
  11715. case 't':
  11716. opt_t = optionarg;
  11717. break;
  11718. case 'r':
  11719. read_flags |= BUILTIN_READ_RAW;
  11720. break;
  11721. case 'u':
  11722. opt_u = optionarg;
  11723. break;
  11724. default:
  11725. break;
  11726. }
  11727. }
  11728. r = shell_builtin_read(setvar2,
  11729. argptr,
  11730. bltinlookup("IFS"), /* can be NULL */
  11731. read_flags,
  11732. opt_n,
  11733. opt_p,
  11734. opt_t,
  11735. opt_u
  11736. );
  11737. if ((uintptr_t)r > 1)
  11738. ash_msg_and_raise_error(r);
  11739. return (uintptr_t)r;
  11740. }
  11741. static int FAST_FUNC
  11742. umaskcmd(int argc UNUSED_PARAM, char **argv)
  11743. {
  11744. static const char permuser[3] ALIGN1 = "ugo";
  11745. static const char permmode[3] ALIGN1 = "rwx";
  11746. static const short permmask[] ALIGN2 = {
  11747. S_IRUSR, S_IWUSR, S_IXUSR,
  11748. S_IRGRP, S_IWGRP, S_IXGRP,
  11749. S_IROTH, S_IWOTH, S_IXOTH
  11750. };
  11751. /* TODO: use bb_parse_mode() instead */
  11752. char *ap;
  11753. mode_t mask;
  11754. int i;
  11755. int symbolic_mode = 0;
  11756. while (nextopt("S") != '\0') {
  11757. symbolic_mode = 1;
  11758. }
  11759. INT_OFF;
  11760. mask = umask(0);
  11761. umask(mask);
  11762. INT_ON;
  11763. ap = *argptr;
  11764. if (ap == NULL) {
  11765. if (symbolic_mode) {
  11766. char buf[18];
  11767. char *p = buf;
  11768. for (i = 0; i < 3; i++) {
  11769. int j;
  11770. *p++ = permuser[i];
  11771. *p++ = '=';
  11772. for (j = 0; j < 3; j++) {
  11773. if ((mask & permmask[3 * i + j]) == 0) {
  11774. *p++ = permmode[j];
  11775. }
  11776. }
  11777. *p++ = ',';
  11778. }
  11779. *--p = 0;
  11780. puts(buf);
  11781. } else {
  11782. out1fmt("%.4o\n", mask);
  11783. }
  11784. } else {
  11785. if (isdigit((unsigned char) *ap)) {
  11786. mask = 0;
  11787. do {
  11788. if (*ap >= '8' || *ap < '0')
  11789. ash_msg_and_raise_error(msg_illnum, argv[1]);
  11790. mask = (mask << 3) + (*ap - '0');
  11791. } while (*++ap != '\0');
  11792. umask(mask);
  11793. } else {
  11794. mask = ~mask & 0777;
  11795. if (!bb_parse_mode(ap, &mask)) {
  11796. ash_msg_and_raise_error("illegal mode: %s", ap);
  11797. }
  11798. umask(~mask & 0777);
  11799. }
  11800. }
  11801. return 0;
  11802. }
  11803. static int FAST_FUNC
  11804. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  11805. {
  11806. return shell_builtin_ulimit(argv);
  11807. }
  11808. /* ============ main() and helpers */
  11809. /*
  11810. * Called to exit the shell.
  11811. */
  11812. static void
  11813. exitshell(void)
  11814. {
  11815. struct jmploc loc;
  11816. char *p;
  11817. int status;
  11818. status = exitstatus;
  11819. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  11820. if (setjmp(loc.loc)) {
  11821. if (exception_type == EXEXIT)
  11822. /* dash bug: it just does _exit(exitstatus) here
  11823. * but we have to do setjobctl(0) first!
  11824. * (bug is still not fixed in dash-0.5.3 - if you run dash
  11825. * under Midnight Commander, on exit from dash MC is backgrounded) */
  11826. status = exitstatus;
  11827. goto out;
  11828. }
  11829. exception_handler = &loc;
  11830. p = trap[0];
  11831. if (p) {
  11832. trap[0] = NULL;
  11833. evalstring(p, 0);
  11834. free(p);
  11835. }
  11836. flush_stdout_stderr();
  11837. out:
  11838. setjobctl(0);
  11839. _exit(status);
  11840. /* NOTREACHED */
  11841. }
  11842. static void
  11843. init(void)
  11844. {
  11845. /* from input.c: */
  11846. /* we will never free this */
  11847. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  11848. /* from trap.c: */
  11849. signal(SIGCHLD, SIG_DFL);
  11850. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  11851. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  11852. */
  11853. signal(SIGHUP, SIG_DFL);
  11854. /* from var.c: */
  11855. {
  11856. char **envp;
  11857. const char *p;
  11858. struct stat st1, st2;
  11859. initvar();
  11860. for (envp = environ; envp && *envp; envp++) {
  11861. if (strchr(*envp, '=')) {
  11862. setvareq(*envp, VEXPORT|VTEXTFIXED);
  11863. }
  11864. }
  11865. setvar("PPID", utoa(getppid()), 0);
  11866. p = lookupvar("PWD");
  11867. if (p) {
  11868. if (*p != '/' || stat(p, &st1) || stat(".", &st2)
  11869. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  11870. ) {
  11871. p = '\0';
  11872. }
  11873. }
  11874. setpwd(p, 0);
  11875. }
  11876. }
  11877. //usage:#define ash_trivial_usage
  11878. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
  11879. //usage:#define ash_full_usage "\n\n"
  11880. //usage: "Unix shell interpreter"
  11881. //usage:#if ENABLE_FEATURE_SH_IS_ASH
  11882. //usage:# define sh_trivial_usage ash_trivial_usage
  11883. //usage:# define sh_full_usage ash_full_usage
  11884. //usage:#endif
  11885. //usage:#if ENABLE_FEATURE_BASH_IS_ASH
  11886. //usage:# define bash_trivial_usage ash_trivial_usage
  11887. //usage:# define bash_full_usage ash_full_usage
  11888. //usage:#endif
  11889. /*
  11890. * Process the shell command line arguments.
  11891. */
  11892. static void
  11893. procargs(char **argv)
  11894. {
  11895. int i;
  11896. const char *xminusc;
  11897. char **xargv;
  11898. xargv = argv;
  11899. arg0 = xargv[0];
  11900. /* if (xargv[0]) - mmm, this is always true! */
  11901. xargv++;
  11902. for (i = 0; i < NOPTS; i++)
  11903. optlist[i] = 2;
  11904. argptr = xargv;
  11905. if (options(/*cmdline:*/ 1)) {
  11906. /* it already printed err message */
  11907. raise_exception(EXERROR);
  11908. }
  11909. xargv = argptr;
  11910. xminusc = minusc;
  11911. if (*xargv == NULL) {
  11912. if (xminusc)
  11913. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  11914. sflag = 1;
  11915. }
  11916. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  11917. iflag = 1;
  11918. if (mflag == 2)
  11919. mflag = iflag;
  11920. for (i = 0; i < NOPTS; i++)
  11921. if (optlist[i] == 2)
  11922. optlist[i] = 0;
  11923. #if DEBUG == 2
  11924. debug = 1;
  11925. #endif
  11926. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  11927. if (xminusc) {
  11928. minusc = *xargv++;
  11929. if (*xargv)
  11930. goto setarg0;
  11931. } else if (!sflag) {
  11932. setinputfile(*xargv, 0);
  11933. setarg0:
  11934. arg0 = *xargv++;
  11935. commandname = arg0;
  11936. }
  11937. shellparam.p = xargv;
  11938. #if ENABLE_ASH_GETOPTS
  11939. shellparam.optind = 1;
  11940. shellparam.optoff = -1;
  11941. #endif
  11942. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  11943. while (*xargv) {
  11944. shellparam.nparam++;
  11945. xargv++;
  11946. }
  11947. optschanged();
  11948. }
  11949. /*
  11950. * Read /etc/profile or .profile.
  11951. */
  11952. static void
  11953. read_profile(const char *name)
  11954. {
  11955. int skip;
  11956. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  11957. return;
  11958. skip = cmdloop(0);
  11959. popfile();
  11960. if (skip)
  11961. exitshell();
  11962. }
  11963. /*
  11964. * This routine is called when an error or an interrupt occurs in an
  11965. * interactive shell and control is returned to the main command loop.
  11966. */
  11967. static void
  11968. reset(void)
  11969. {
  11970. /* from eval.c: */
  11971. evalskip = 0;
  11972. loopnest = 0;
  11973. /* from input.c: */
  11974. g_parsefile->left_in_buffer = 0;
  11975. g_parsefile->left_in_line = 0; /* clear input buffer */
  11976. popallfiles();
  11977. /* from parser.c: */
  11978. tokpushback = 0;
  11979. checkkwd = 0;
  11980. /* from redir.c: */
  11981. clearredir(/*drop:*/ 0);
  11982. }
  11983. #if PROFILE
  11984. static short profile_buf[16384];
  11985. extern int etext();
  11986. #endif
  11987. /*
  11988. * Main routine. We initialize things, parse the arguments, execute
  11989. * profiles if we're a login shell, and then call cmdloop to execute
  11990. * commands. The setjmp call sets up the location to jump to when an
  11991. * exception occurs. When an exception occurs the variable "state"
  11992. * is used to figure out how far we had gotten.
  11993. */
  11994. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  11995. int ash_main(int argc UNUSED_PARAM, char **argv)
  11996. {
  11997. const char *shinit;
  11998. volatile smallint state;
  11999. struct jmploc jmploc;
  12000. struct stackmark smark;
  12001. /* Initialize global data */
  12002. INIT_G_misc();
  12003. INIT_G_memstack();
  12004. INIT_G_var();
  12005. #if ENABLE_ASH_ALIAS
  12006. INIT_G_alias();
  12007. #endif
  12008. INIT_G_cmdtable();
  12009. #if PROFILE
  12010. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12011. #endif
  12012. #if ENABLE_FEATURE_EDITING
  12013. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12014. #endif
  12015. state = 0;
  12016. if (setjmp(jmploc.loc)) {
  12017. smallint e;
  12018. smallint s;
  12019. reset();
  12020. e = exception_type;
  12021. if (e == EXERROR)
  12022. exitstatus = 2;
  12023. s = state;
  12024. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  12025. exitshell();
  12026. }
  12027. if (e == EXINT) {
  12028. outcslow('\n', stderr);
  12029. }
  12030. popstackmark(&smark);
  12031. FORCE_INT_ON; /* enable interrupts */
  12032. if (s == 1)
  12033. goto state1;
  12034. if (s == 2)
  12035. goto state2;
  12036. if (s == 3)
  12037. goto state3;
  12038. goto state4;
  12039. }
  12040. exception_handler = &jmploc;
  12041. #if DEBUG
  12042. opentrace();
  12043. TRACE(("Shell args: "));
  12044. trace_puts_args(argv);
  12045. #endif
  12046. rootpid = getpid();
  12047. init();
  12048. setstackmark(&smark);
  12049. procargs(argv);
  12050. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  12051. if (iflag) {
  12052. const char *hp = lookupvar("HISTFILE");
  12053. if (!hp) {
  12054. hp = lookupvar("HOME");
  12055. if (hp) {
  12056. char *defhp = concat_path_file(hp, ".ash_history");
  12057. setvar("HISTFILE", defhp, 0);
  12058. free(defhp);
  12059. }
  12060. }
  12061. }
  12062. #endif
  12063. if (argv[0] && argv[0][0] == '-')
  12064. isloginsh = 1;
  12065. if (isloginsh) {
  12066. state = 1;
  12067. read_profile("/etc/profile");
  12068. state1:
  12069. state = 2;
  12070. read_profile(".profile");
  12071. }
  12072. state2:
  12073. state = 3;
  12074. if (
  12075. #ifndef linux
  12076. getuid() == geteuid() && getgid() == getegid() &&
  12077. #endif
  12078. iflag
  12079. ) {
  12080. shinit = lookupvar("ENV");
  12081. if (shinit != NULL && *shinit != '\0') {
  12082. read_profile(shinit);
  12083. }
  12084. }
  12085. state3:
  12086. state = 4;
  12087. if (minusc) {
  12088. /* evalstring pushes parsefile stack.
  12089. * Ensure we don't falsely claim that 0 (stdin)
  12090. * is one of stacked source fds.
  12091. * Testcase: ash -c 'exec 1>&0' must not complain. */
  12092. // if (!sflag) g_parsefile->pf_fd = -1;
  12093. // ^^ not necessary since now we special-case fd 0
  12094. // in is_hidden_fd() to not be considered "hidden fd"
  12095. evalstring(minusc, 0);
  12096. }
  12097. if (sflag || minusc == NULL) {
  12098. #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  12099. if (iflag) {
  12100. const char *hp = lookupvar("HISTFILE");
  12101. if (hp)
  12102. line_input_state->hist_file = hp;
  12103. # if ENABLE_FEATURE_SH_HISTFILESIZE
  12104. hp = lookupvar("HISTFILESIZE");
  12105. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  12106. # endif
  12107. }
  12108. #endif
  12109. state4: /* XXX ??? - why isn't this before the "if" statement */
  12110. cmdloop(1);
  12111. }
  12112. #if PROFILE
  12113. monitor(0);
  12114. #endif
  12115. #ifdef GPROF
  12116. {
  12117. extern void _mcleanup(void);
  12118. _mcleanup();
  12119. }
  12120. #endif
  12121. TRACE(("End of main reached\n"));
  12122. exitshell();
  12123. /* NOTREACHED */
  12124. }
  12125. /*-
  12126. * Copyright (c) 1989, 1991, 1993, 1994
  12127. * The Regents of the University of California. All rights reserved.
  12128. *
  12129. * This code is derived from software contributed to Berkeley by
  12130. * Kenneth Almquist.
  12131. *
  12132. * Redistribution and use in source and binary forms, with or without
  12133. * modification, are permitted provided that the following conditions
  12134. * are met:
  12135. * 1. Redistributions of source code must retain the above copyright
  12136. * notice, this list of conditions and the following disclaimer.
  12137. * 2. Redistributions in binary form must reproduce the above copyright
  12138. * notice, this list of conditions and the following disclaimer in the
  12139. * documentation and/or other materials provided with the distribution.
  12140. * 3. Neither the name of the University nor the names of its contributors
  12141. * may be used to endorse or promote products derived from this software
  12142. * without specific prior written permission.
  12143. *
  12144. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  12145. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12146. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12147. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12148. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12149. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12150. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12151. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12152. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12153. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12154. * SUCH DAMAGE.
  12155. */