ash.c 321 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * This code is derived from software contributed to Berkeley by
  6. * Kenneth Almquist.
  7. *
  8. * Original BSD copyright notice is retained at the end of this file.
  9. *
  10. * Copyright (c) 1989, 1991, 1993, 1994
  11. * The Regents of the University of California. All rights reserved.
  12. *
  13. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  14. * was re-ported from NetBSD and debianized.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  17. */
  18. //config:config ASH
  19. //config: bool "ash (77 kb)"
  20. //config: default y
  21. //config: depends on !NOMMU
  22. //config: help
  23. //config: The most complete and most pedantically correct shell included with
  24. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  25. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  26. //config: (written by Kenneth Almquist) from NetBSD.
  27. //config:
  28. //config:# ash options
  29. //config:# note: Don't remove !NOMMU part in the next line; it would break
  30. //config:# menuconfig's indenting.
  31. //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
  32. //config:
  33. //config:config ASH_OPTIMIZE_FOR_SIZE
  34. //config: bool "Optimize for size instead of speed"
  35. //config: default y
  36. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  37. //config:
  38. //config:config ASH_INTERNAL_GLOB
  39. //config: bool "Use internal glob() implementation"
  40. //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
  41. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  42. //config: help
  43. //config: Do not use glob() function from libc, use internal implementation.
  44. //config: Use this if you are getting "glob.h: No such file or directory"
  45. //config: or similar build errors.
  46. //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
  47. //config: which would break ash if you select N here.
  48. //config:
  49. //config:config ASH_BASH_COMPAT
  50. //config: bool "bash-compatible extensions"
  51. //config: default y
  52. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  53. //config:
  54. //config:config ASH_BASH_SOURCE_CURDIR
  55. //config: bool "'source' and '.' builtins search current directory after $PATH"
  56. //config: default n # do not encourage non-standard behavior
  57. //config: depends on ASH_BASH_COMPAT
  58. //config: help
  59. //config: This is not compliant with standards. Avoid if possible.
  60. //config:
  61. //config:config ASH_BASH_NOT_FOUND_HOOK
  62. //config: bool "command_not_found_handle hook support"
  63. //config: default y
  64. //config: depends on ASH_BASH_COMPAT
  65. //config: help
  66. //config: Enable support for the 'command_not_found_handle' hook function,
  67. //config: from GNU bash, which allows for alternative command not found
  68. //config: handling.
  69. //config:
  70. //config:config ASH_JOB_CONTROL
  71. //config: bool "Job control"
  72. //config: default y
  73. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  74. //config:
  75. //config:config ASH_ALIAS
  76. //config: bool "Alias support"
  77. //config: default y
  78. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  79. //config:
  80. //config:config ASH_RANDOM_SUPPORT
  81. //config: bool "Pseudorandom generator and $RANDOM variable"
  82. //config: default y
  83. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  84. //config: help
  85. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  86. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  87. //config: You can reset the generator by using a specified start value.
  88. //config: After "unset RANDOM" the generator will switch off and this
  89. //config: variable will no longer have special treatment.
  90. //config:
  91. //config:config ASH_EXPAND_PRMT
  92. //config: bool "Expand prompt string"
  93. //config: default y
  94. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  95. //config: help
  96. //config: $PS# may contain volatile content, such as backquote commands.
  97. //config: This option recreates the prompt string from the environment
  98. //config: variable each time it is displayed.
  99. //config:
  100. //config:config ASH_IDLE_TIMEOUT
  101. //config: bool "Idle timeout variable $TMOUT"
  102. //config: default y
  103. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  104. //config: help
  105. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  106. //config:
  107. //config:config ASH_MAIL
  108. //config: bool "Check for new mail in interactive shell"
  109. //config: default y
  110. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  111. //config: help
  112. //config: Enable "check for new mail" function:
  113. //config: if set, $MAIL file and $MAILPATH list of files
  114. //config: are checked for mtime changes, and "you have mail"
  115. //config: message is printed if change is detected.
  116. //config:
  117. //config:config ASH_ECHO
  118. //config: bool "echo builtin"
  119. //config: default y
  120. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  121. //config:
  122. //config:config ASH_PRINTF
  123. //config: bool "printf builtin"
  124. //config: default y
  125. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  126. //config:
  127. //config:config ASH_TEST
  128. //config: bool "test builtin"
  129. //config: default y
  130. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  131. //config:
  132. //config:config ASH_HELP
  133. //config: bool "help builtin"
  134. //config: default y
  135. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  136. //config:
  137. //config:config ASH_GETOPTS
  138. //config: bool "getopts builtin"
  139. //config: default y
  140. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  141. //config:
  142. //config:config ASH_CMDCMD
  143. //config: bool "command builtin"
  144. //config: default y
  145. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  146. //config: help
  147. //config: Enable support for the 'command' builtin, which allows
  148. //config: you to run the specified command or builtin,
  149. //config: even when there is a function with the same name.
  150. //config:
  151. //config:endif # ash options
  152. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  153. // APPLET_ODDNAME:name main location suid_type help
  154. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  155. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  156. //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
  157. //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  158. //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  159. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  160. /*
  161. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  162. * DEBUG=2 to compile in and turn on debugging.
  163. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  164. * debugging info is written to ./trace, quit signal generates core dump.
  165. */
  166. #define DEBUG 0
  167. /* Tweak debug output verbosity here */
  168. #define DEBUG_TIME 0
  169. #define DEBUG_PID 1
  170. #define DEBUG_SIG 1
  171. #define DEBUG_INTONOFF 0
  172. #define PROFILE 0
  173. #define JOBS ENABLE_ASH_JOB_CONTROL
  174. #include <fnmatch.h>
  175. #include <sys/times.h>
  176. #include <sys/utsname.h> /* for setting $HOSTNAME */
  177. #include "busybox.h" /* for applet_names */
  178. /* So far, all bash compat is controlled by one config option */
  179. /* Separate defines document which part of code implements what */
  180. /* function keyword */
  181. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  182. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  183. /* &>file */
  184. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  185. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  186. /* $'...' */
  187. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  188. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  189. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  190. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  191. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  192. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  193. /* BASH_TEST2: [[ EXPR ]]
  194. * Status of [[ support:
  195. * We replace && and || with -a and -o
  196. * TODO:
  197. * singleword+noglob expansion:
  198. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  199. * [[ /bin/n* ]]; echo 0:$?
  200. * -a/-o are not AND/OR ops! (they are just strings)
  201. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  202. * = is glob match operator, not equality operator: STR = GLOB
  203. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  204. * == same as =
  205. * add =~ regex match operator: STR =~ REGEX
  206. */
  207. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  208. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  209. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  210. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  211. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  212. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  213. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  214. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  215. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  216. /* Bionic at least up to version 24 has no glob() */
  217. # undef ENABLE_ASH_INTERNAL_GLOB
  218. # define ENABLE_ASH_INTERNAL_GLOB 1
  219. #endif
  220. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  221. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  222. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  223. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  224. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  225. # error fails to match dirname, subsequently not expanding <pattern> in it.
  226. // Testcase:
  227. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  228. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  229. #endif
  230. #if !ENABLE_ASH_INTERNAL_GLOB
  231. # include <glob.h>
  232. #endif
  233. #include "unicode.h"
  234. #include "shell_common.h"
  235. #if ENABLE_FEATURE_SH_MATH
  236. # include "math.h"
  237. #else
  238. typedef long arith_t;
  239. # define ARITH_FMT "%ld"
  240. #endif
  241. #if ENABLE_ASH_RANDOM_SUPPORT
  242. # include "random.h"
  243. #else
  244. # define CLEAR_RANDOM_T(rnd) ((void)0)
  245. #endif
  246. #include "NUM_APPLETS.h"
  247. #if NUM_APPLETS == 1
  248. /* STANDALONE does not make sense, and won't compile */
  249. # undef CONFIG_FEATURE_SH_STANDALONE
  250. # undef ENABLE_FEATURE_SH_STANDALONE
  251. # undef IF_FEATURE_SH_STANDALONE
  252. # undef IF_NOT_FEATURE_SH_STANDALONE
  253. # define ENABLE_FEATURE_SH_STANDALONE 0
  254. # define IF_FEATURE_SH_STANDALONE(...)
  255. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  256. #endif
  257. #ifndef F_DUPFD_CLOEXEC
  258. # define F_DUPFD_CLOEXEC F_DUPFD
  259. #endif
  260. #ifndef O_CLOEXEC
  261. # define O_CLOEXEC 0
  262. #endif
  263. #ifndef PIPE_BUF
  264. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  265. #endif
  266. #if !BB_MMU
  267. # error "Do not even bother, ash will not run on NOMMU machine"
  268. #endif
  269. /* We use a trick to have more optimized code (fewer pointer reloads):
  270. * ash.c: extern struct globals *const ash_ptr_to_globals;
  271. * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
  272. * This way, compiler in ash.c knows the pointer can not change.
  273. *
  274. * However, this may break on weird arches or toolchains. In this case,
  275. * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
  276. * this optimization.
  277. */
  278. #ifndef BB_GLOBAL_CONST
  279. # define BB_GLOBAL_CONST const
  280. #endif
  281. /* ============ Hash table sizes. Configurable. */
  282. #define VTABSIZE 39
  283. #define ATABSIZE 39
  284. #define CMDTABLESIZE 31 /* should be prime */
  285. /* ============ Shell options */
  286. static const char *const optletters_optnames[] = {
  287. "e" "errexit",
  288. "f" "noglob",
  289. "I" "ignoreeof",
  290. "i" "interactive",
  291. "m" "monitor",
  292. "n" "noexec",
  293. "s" "stdin",
  294. "x" "xtrace",
  295. "v" "verbose",
  296. "C" "noclobber",
  297. "a" "allexport",
  298. "b" "notify",
  299. "u" "nounset",
  300. "\0" "vi"
  301. #if BASH_PIPEFAIL
  302. ,"\0" "pipefail"
  303. #endif
  304. #if DEBUG
  305. ,"\0" "nolog"
  306. ,"\0" "debug"
  307. #endif
  308. };
  309. #define optletters(n) optletters_optnames[n][0]
  310. #define optnames(n) (optletters_optnames[n] + 1)
  311. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  312. /* ============ Misc data */
  313. #define msg_illnum "Illegal number: %s"
  314. /*
  315. * We enclose jmp_buf in a structure so that we can declare pointers to
  316. * jump locations. The global variable handler contains the location to
  317. * jump to when an exception occurs, and the global variable exception_type
  318. * contains a code identifying the exception. To implement nested
  319. * exception handlers, the user should save the value of handler on entry
  320. * to an inner scope, set handler to point to a jmploc structure for the
  321. * inner scope, and restore handler on exit from the scope.
  322. */
  323. struct jmploc {
  324. jmp_buf loc;
  325. };
  326. struct globals_misc {
  327. uint8_t exitstatus; /* exit status of last command */
  328. uint8_t back_exitstatus;/* exit status of backquoted command */
  329. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  330. int rootpid; /* pid of main shell */
  331. /* shell level: 0 for the main shell, 1 for its children, and so on */
  332. int shlvl;
  333. #define rootshell (!shlvl)
  334. int errlinno;
  335. char *minusc; /* argument to -c option */
  336. char *curdir; // = nullstr; /* current working directory */
  337. char *physdir; // = nullstr; /* physical working directory */
  338. char *arg0; /* value of $0 */
  339. struct jmploc *exception_handler;
  340. volatile int suppress_int; /* counter */
  341. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  342. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  343. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  344. smallint exception_type; /* kind of exception (0..5) */
  345. /* exceptions */
  346. #define EXINT 0 /* SIGINT received */
  347. #define EXERROR 1 /* a generic error */
  348. #define EXEXIT 4 /* exit the shell */
  349. char nullstr[1]; /* zero length string */
  350. char optlist[NOPTS];
  351. #define eflag optlist[0]
  352. #define fflag optlist[1]
  353. #define Iflag optlist[2]
  354. #define iflag optlist[3]
  355. #define mflag optlist[4]
  356. #define nflag optlist[5]
  357. #define sflag optlist[6]
  358. #define xflag optlist[7]
  359. #define vflag optlist[8]
  360. #define Cflag optlist[9]
  361. #define aflag optlist[10]
  362. #define bflag optlist[11]
  363. #define uflag optlist[12]
  364. #define viflag optlist[13]
  365. #if BASH_PIPEFAIL
  366. # define pipefail optlist[14]
  367. #else
  368. # define pipefail 0
  369. #endif
  370. #if DEBUG
  371. # define nolog optlist[14 + BASH_PIPEFAIL]
  372. # define debug optlist[15 + BASH_PIPEFAIL]
  373. #endif
  374. /* trap handler commands */
  375. /*
  376. * Sigmode records the current value of the signal handlers for the various
  377. * modes. A value of zero means that the current handler is not known.
  378. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  379. */
  380. char sigmode[NSIG - 1];
  381. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  382. #define S_CATCH 2 /* signal is caught */
  383. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  384. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  385. /* indicates specified signal received */
  386. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  387. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  388. char *trap[NSIG];
  389. char **trap_ptr; /* used only by "trap hack" */
  390. /* Rarely referenced stuff */
  391. #if ENABLE_ASH_RANDOM_SUPPORT
  392. random_t random_gen;
  393. #endif
  394. pid_t backgndpid; /* pid of last background process */
  395. };
  396. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  397. #define G_misc (*ash_ptr_to_globals_misc)
  398. #define exitstatus (G_misc.exitstatus )
  399. #define back_exitstatus (G_misc.back_exitstatus )
  400. #define job_warning (G_misc.job_warning)
  401. #define rootpid (G_misc.rootpid )
  402. #define shlvl (G_misc.shlvl )
  403. #define errlinno (G_misc.errlinno )
  404. #define minusc (G_misc.minusc )
  405. #define curdir (G_misc.curdir )
  406. #define physdir (G_misc.physdir )
  407. #define arg0 (G_misc.arg0 )
  408. #define exception_handler (G_misc.exception_handler)
  409. #define exception_type (G_misc.exception_type )
  410. #define suppress_int (G_misc.suppress_int )
  411. #define pending_int (G_misc.pending_int )
  412. #define got_sigchld (G_misc.got_sigchld )
  413. #define pending_sig (G_misc.pending_sig )
  414. #define nullstr (G_misc.nullstr )
  415. #define optlist (G_misc.optlist )
  416. #define sigmode (G_misc.sigmode )
  417. #define gotsig (G_misc.gotsig )
  418. #define may_have_traps (G_misc.may_have_traps )
  419. #define trap (G_misc.trap )
  420. #define trap_ptr (G_misc.trap_ptr )
  421. #define random_gen (G_misc.random_gen )
  422. #define backgndpid (G_misc.backgndpid )
  423. #define INIT_G_misc() do { \
  424. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  425. barrier(); \
  426. curdir = nullstr; \
  427. physdir = nullstr; \
  428. trap_ptr = trap; \
  429. } while (0)
  430. /* ============ DEBUG */
  431. #if DEBUG
  432. static void trace_printf(const char *fmt, ...);
  433. static void trace_vprintf(const char *fmt, va_list va);
  434. # define TRACE(param) trace_printf param
  435. # define TRACEV(param) trace_vprintf param
  436. # define close(fd) do { \
  437. int dfd = (fd); \
  438. if (close(dfd) < 0) \
  439. bb_error_msg("bug on %d: closing %d(0x%x)", \
  440. __LINE__, dfd, dfd); \
  441. } while (0)
  442. #else
  443. # define TRACE(param)
  444. # define TRACEV(param)
  445. #endif
  446. /* ============ Utility functions */
  447. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  448. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  449. static int
  450. isdigit_str9(const char *str)
  451. {
  452. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  453. while (--maxlen && isdigit(*str))
  454. str++;
  455. return (*str == '\0');
  456. }
  457. static const char *
  458. var_end(const char *var)
  459. {
  460. while (*var)
  461. if (*var++ == '=')
  462. break;
  463. return var;
  464. }
  465. /* ============ Interrupts / exceptions */
  466. static void exitshell(void) NORETURN;
  467. /*
  468. * These macros allow the user to suspend the handling of interrupt signals
  469. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  470. * much more efficient and portable. (But hacking the kernel is so much
  471. * more fun than worrying about efficiency and portability. :-))
  472. */
  473. #if DEBUG_INTONOFF
  474. # define INT_OFF do { \
  475. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  476. suppress_int++; \
  477. barrier(); \
  478. } while (0)
  479. #else
  480. # define INT_OFF do { \
  481. suppress_int++; \
  482. barrier(); \
  483. } while (0)
  484. #endif
  485. /*
  486. * Called to raise an exception. Since C doesn't include exceptions, we
  487. * just do a longjmp to the exception handler. The type of exception is
  488. * stored in the global variable "exception_type".
  489. */
  490. static void raise_exception(int) NORETURN;
  491. static void
  492. raise_exception(int e)
  493. {
  494. #if DEBUG
  495. if (exception_handler == NULL)
  496. abort();
  497. #endif
  498. INT_OFF;
  499. exception_type = e;
  500. longjmp(exception_handler->loc, 1);
  501. }
  502. #if DEBUG
  503. #define raise_exception(e) do { \
  504. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  505. raise_exception(e); \
  506. } while (0)
  507. #endif
  508. /*
  509. * Called when a SIGINT is received. (If the user specifies
  510. * that SIGINT is to be trapped or ignored using the trap builtin, then
  511. * this routine is not called.) Suppressint is nonzero when interrupts
  512. * are held using the INT_OFF macro. (The test for iflag is just
  513. * defensive programming.)
  514. */
  515. static void raise_interrupt(void) NORETURN;
  516. static void
  517. raise_interrupt(void)
  518. {
  519. pending_int = 0;
  520. /* Signal is not automatically unmasked after it is raised,
  521. * do it ourself - unmask all signals */
  522. sigprocmask_allsigs(SIG_UNBLOCK);
  523. /* pending_sig = 0; - now done in signal_handler() */
  524. if (!(rootshell && iflag)) {
  525. /* Kill ourself with SIGINT */
  526. signal(SIGINT, SIG_DFL);
  527. raise(SIGINT);
  528. }
  529. /* bash: ^C even on empty command line sets $? */
  530. exitstatus = SIGINT + 128;
  531. raise_exception(EXINT);
  532. /* NOTREACHED */
  533. }
  534. #if DEBUG
  535. #define raise_interrupt() do { \
  536. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  537. raise_interrupt(); \
  538. } while (0)
  539. #endif
  540. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  541. int_on(void)
  542. {
  543. barrier();
  544. if (--suppress_int == 0 && pending_int) {
  545. raise_interrupt();
  546. }
  547. }
  548. #if DEBUG_INTONOFF
  549. # define INT_ON do { \
  550. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  551. int_on(); \
  552. } while (0)
  553. #else
  554. # define INT_ON int_on()
  555. #endif
  556. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  557. force_int_on(void)
  558. {
  559. barrier();
  560. suppress_int = 0;
  561. if (pending_int)
  562. raise_interrupt();
  563. }
  564. #define FORCE_INT_ON force_int_on()
  565. #define SAVE_INT(v) ((v) = suppress_int)
  566. #define RESTORE_INT(v) do { \
  567. barrier(); \
  568. suppress_int = (v); \
  569. if (suppress_int == 0 && pending_int) \
  570. raise_interrupt(); \
  571. } while (0)
  572. /* ============ Stdout/stderr output */
  573. static void
  574. outstr(const char *p, FILE *file)
  575. {
  576. INT_OFF;
  577. fputs(p, file);
  578. INT_ON;
  579. }
  580. static void
  581. flush_stdout_stderr(void)
  582. {
  583. INT_OFF;
  584. fflush_all();
  585. INT_ON;
  586. }
  587. /* Was called outcslow(c,FILE*), but c was always '\n' */
  588. static void
  589. newline_and_flush(FILE *dest)
  590. {
  591. INT_OFF;
  592. putc('\n', dest);
  593. fflush(dest);
  594. INT_ON;
  595. }
  596. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  597. static int
  598. out1fmt(const char *fmt, ...)
  599. {
  600. va_list ap;
  601. int r;
  602. INT_OFF;
  603. va_start(ap, fmt);
  604. r = vprintf(fmt, ap);
  605. va_end(ap);
  606. INT_ON;
  607. return r;
  608. }
  609. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  610. static int
  611. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  612. {
  613. va_list ap;
  614. int ret;
  615. INT_OFF;
  616. va_start(ap, fmt);
  617. ret = vsnprintf(outbuf, length, fmt, ap);
  618. va_end(ap);
  619. INT_ON;
  620. return ret;
  621. }
  622. static void
  623. out1str(const char *p)
  624. {
  625. outstr(p, stdout);
  626. }
  627. static void
  628. out2str(const char *p)
  629. {
  630. outstr(p, stderr);
  631. flush_stdout_stderr();
  632. }
  633. /* ============ Parser structures */
  634. /* control characters in argument strings */
  635. #define CTL_FIRST CTLESC
  636. #define CTLESC ((unsigned char)'\201') /* escape next character */
  637. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  638. #define CTLENDVAR ((unsigned char)'\203')
  639. #define CTLBACKQ ((unsigned char)'\204')
  640. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  641. #define CTLENDARI ((unsigned char)'\207')
  642. #define CTLQUOTEMARK ((unsigned char)'\210')
  643. #define CTL_LAST CTLQUOTEMARK
  644. /* variable substitution byte (follows CTLVAR) */
  645. #define VSTYPE 0x0f /* type of variable substitution */
  646. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  647. /* values of VSTYPE field */
  648. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  649. #define VSMINUS 0x2 /* ${var-text} */
  650. #define VSPLUS 0x3 /* ${var+text} */
  651. #define VSQUESTION 0x4 /* ${var?message} */
  652. #define VSASSIGN 0x5 /* ${var=text} */
  653. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  654. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  655. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  656. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  657. #define VSLENGTH 0xa /* ${#var} */
  658. #if BASH_SUBSTR
  659. #define VSSUBSTR 0xc /* ${var:position:length} */
  660. #endif
  661. #if BASH_PATTERN_SUBST
  662. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  663. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  664. #endif
  665. static const char dolatstr[] ALIGN1 = {
  666. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  667. };
  668. #define DOLATSTRLEN 6
  669. #define NCMD 0
  670. #define NPIPE 1
  671. #define NREDIR 2
  672. #define NBACKGND 3
  673. #define NSUBSHELL 4
  674. #define NAND 5
  675. #define NOR 6
  676. #define NSEMI 7
  677. #define NIF 8
  678. #define NWHILE 9
  679. #define NUNTIL 10
  680. #define NFOR 11
  681. #define NCASE 12
  682. #define NCLIST 13
  683. #define NDEFUN 14
  684. #define NARG 15
  685. #define NTO 16
  686. #if BASH_REDIR_OUTPUT
  687. #define NTO2 17
  688. #endif
  689. #define NCLOBBER 18
  690. #define NFROM 19
  691. #define NFROMTO 20
  692. #define NAPPEND 21
  693. #define NTOFD 22
  694. #define NFROMFD 23
  695. #define NHERE 24
  696. #define NXHERE 25
  697. #define NNOT 26
  698. #define N_NUMBER 27
  699. union node;
  700. struct ncmd {
  701. smallint type; /* Nxxxx */
  702. int linno;
  703. union node *assign;
  704. union node *args;
  705. union node *redirect;
  706. };
  707. struct npipe {
  708. smallint type;
  709. smallint pipe_backgnd;
  710. struct nodelist *cmdlist;
  711. };
  712. struct nredir {
  713. smallint type;
  714. int linno;
  715. union node *n;
  716. union node *redirect;
  717. };
  718. struct nbinary {
  719. smallint type;
  720. union node *ch1;
  721. union node *ch2;
  722. };
  723. struct nif {
  724. smallint type;
  725. union node *test;
  726. union node *ifpart;
  727. union node *elsepart;
  728. };
  729. struct nfor {
  730. smallint type;
  731. int linno;
  732. union node *args;
  733. union node *body;
  734. char *var;
  735. };
  736. struct ncase {
  737. smallint type;
  738. int linno;
  739. union node *expr;
  740. union node *cases;
  741. };
  742. struct nclist {
  743. smallint type;
  744. union node *next;
  745. union node *pattern;
  746. union node *body;
  747. };
  748. struct ndefun {
  749. smallint type;
  750. int linno;
  751. char *text;
  752. union node *body;
  753. };
  754. struct narg {
  755. smallint type;
  756. union node *next;
  757. char *text;
  758. struct nodelist *backquote;
  759. };
  760. /* nfile and ndup layout must match!
  761. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  762. * that it is actually NTO2 (>&file), and change its type.
  763. */
  764. struct nfile {
  765. smallint type;
  766. union node *next;
  767. int fd;
  768. int _unused_dupfd;
  769. union node *fname;
  770. char *expfname;
  771. };
  772. struct ndup {
  773. smallint type;
  774. union node *next;
  775. int fd;
  776. int dupfd;
  777. union node *vname;
  778. char *_unused_expfname;
  779. };
  780. struct nhere {
  781. smallint type;
  782. union node *next;
  783. int fd;
  784. union node *doc;
  785. };
  786. struct nnot {
  787. smallint type;
  788. union node *com;
  789. };
  790. union node {
  791. smallint type;
  792. struct ncmd ncmd;
  793. struct npipe npipe;
  794. struct nredir nredir;
  795. struct nbinary nbinary;
  796. struct nif nif;
  797. struct nfor nfor;
  798. struct ncase ncase;
  799. struct nclist nclist;
  800. struct ndefun ndefun;
  801. struct narg narg;
  802. struct nfile nfile;
  803. struct ndup ndup;
  804. struct nhere nhere;
  805. struct nnot nnot;
  806. };
  807. /*
  808. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  809. * It must be distinct from NULL.
  810. */
  811. #define NODE_EOF ((union node *) -1L)
  812. struct nodelist {
  813. struct nodelist *next;
  814. union node *n;
  815. };
  816. struct funcnode {
  817. int count;
  818. union node n;
  819. };
  820. /*
  821. * Free a parse tree.
  822. */
  823. static void
  824. freefunc(struct funcnode *f)
  825. {
  826. if (f && --f->count < 0)
  827. free(f);
  828. }
  829. /* ============ Debugging output */
  830. #if DEBUG
  831. static FILE *tracefile;
  832. static void
  833. trace_printf(const char *fmt, ...)
  834. {
  835. va_list va;
  836. if (debug != 1)
  837. return;
  838. if (DEBUG_TIME)
  839. fprintf(tracefile, "%u ", (int) time(NULL));
  840. if (DEBUG_PID)
  841. fprintf(tracefile, "[%u] ", (int) getpid());
  842. if (DEBUG_SIG)
  843. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  844. va_start(va, fmt);
  845. vfprintf(tracefile, fmt, va);
  846. va_end(va);
  847. }
  848. static void
  849. trace_vprintf(const char *fmt, va_list va)
  850. {
  851. if (debug != 1)
  852. return;
  853. vfprintf(tracefile, fmt, va);
  854. fprintf(tracefile, "\n");
  855. }
  856. static void
  857. trace_puts(const char *s)
  858. {
  859. if (debug != 1)
  860. return;
  861. fputs(s, tracefile);
  862. }
  863. static void
  864. trace_puts_quoted(char *s)
  865. {
  866. char *p;
  867. char c;
  868. if (debug != 1)
  869. return;
  870. putc('"', tracefile);
  871. for (p = s; *p; p++) {
  872. switch ((unsigned char)*p) {
  873. case '\n': c = 'n'; goto backslash;
  874. case '\t': c = 't'; goto backslash;
  875. case '\r': c = 'r'; goto backslash;
  876. case '\"': c = '\"'; goto backslash;
  877. case '\\': c = '\\'; goto backslash;
  878. case CTLESC: c = 'e'; goto backslash;
  879. case CTLVAR: c = 'v'; goto backslash;
  880. case CTLBACKQ: c = 'q'; goto backslash;
  881. backslash:
  882. putc('\\', tracefile);
  883. putc(c, tracefile);
  884. break;
  885. default:
  886. if (*p >= ' ' && *p <= '~')
  887. putc(*p, tracefile);
  888. else {
  889. putc('\\', tracefile);
  890. putc((*p >> 6) & 03, tracefile);
  891. putc((*p >> 3) & 07, tracefile);
  892. putc(*p & 07, tracefile);
  893. }
  894. break;
  895. }
  896. }
  897. putc('"', tracefile);
  898. }
  899. static void
  900. trace_puts_args(char **ap)
  901. {
  902. if (debug != 1)
  903. return;
  904. if (!*ap)
  905. return;
  906. while (1) {
  907. trace_puts_quoted(*ap);
  908. if (!*++ap) {
  909. putc('\n', tracefile);
  910. break;
  911. }
  912. putc(' ', tracefile);
  913. }
  914. }
  915. static void
  916. opentrace(void)
  917. {
  918. char s[100];
  919. #ifdef O_APPEND
  920. int flags;
  921. #endif
  922. if (debug != 1) {
  923. if (tracefile)
  924. fflush(tracefile);
  925. /* leave open because libedit might be using it */
  926. return;
  927. }
  928. strcpy(s, "./trace");
  929. if (tracefile) {
  930. if (!freopen(s, "a", tracefile)) {
  931. fprintf(stderr, "Can't re-open %s\n", s);
  932. debug = 0;
  933. return;
  934. }
  935. } else {
  936. tracefile = fopen(s, "a");
  937. if (tracefile == NULL) {
  938. fprintf(stderr, "Can't open %s\n", s);
  939. debug = 0;
  940. return;
  941. }
  942. }
  943. #ifdef O_APPEND
  944. flags = fcntl(fileno(tracefile), F_GETFL);
  945. if (flags >= 0)
  946. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  947. #endif
  948. setlinebuf(tracefile);
  949. fputs("\nTracing started.\n", tracefile);
  950. }
  951. static void
  952. indent(int amount, char *pfx, FILE *fp)
  953. {
  954. int i;
  955. for (i = 0; i < amount; i++) {
  956. if (pfx && i == amount - 1)
  957. fputs(pfx, fp);
  958. putc('\t', fp);
  959. }
  960. }
  961. /* little circular references here... */
  962. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  963. static void
  964. sharg(union node *arg, FILE *fp)
  965. {
  966. char *p;
  967. struct nodelist *bqlist;
  968. unsigned char subtype;
  969. if (arg->type != NARG) {
  970. out1fmt("<node type %d>\n", arg->type);
  971. abort();
  972. }
  973. bqlist = arg->narg.backquote;
  974. for (p = arg->narg.text; *p; p++) {
  975. switch ((unsigned char)*p) {
  976. case CTLESC:
  977. p++;
  978. putc(*p, fp);
  979. break;
  980. case CTLVAR:
  981. putc('$', fp);
  982. putc('{', fp);
  983. subtype = *++p;
  984. if (subtype == VSLENGTH)
  985. putc('#', fp);
  986. while (*p != '=') {
  987. putc(*p, fp);
  988. p++;
  989. }
  990. if (subtype & VSNUL)
  991. putc(':', fp);
  992. switch (subtype & VSTYPE) {
  993. case VSNORMAL:
  994. putc('}', fp);
  995. break;
  996. case VSMINUS:
  997. putc('-', fp);
  998. break;
  999. case VSPLUS:
  1000. putc('+', fp);
  1001. break;
  1002. case VSQUESTION:
  1003. putc('?', fp);
  1004. break;
  1005. case VSASSIGN:
  1006. putc('=', fp);
  1007. break;
  1008. case VSTRIMLEFT:
  1009. putc('#', fp);
  1010. break;
  1011. case VSTRIMLEFTMAX:
  1012. putc('#', fp);
  1013. putc('#', fp);
  1014. break;
  1015. case VSTRIMRIGHT:
  1016. putc('%', fp);
  1017. break;
  1018. case VSTRIMRIGHTMAX:
  1019. putc('%', fp);
  1020. putc('%', fp);
  1021. break;
  1022. case VSLENGTH:
  1023. break;
  1024. default:
  1025. out1fmt("<subtype %d>", subtype);
  1026. }
  1027. break;
  1028. case CTLENDVAR:
  1029. putc('}', fp);
  1030. break;
  1031. case CTLBACKQ:
  1032. putc('$', fp);
  1033. putc('(', fp);
  1034. shtree(bqlist->n, -1, NULL, fp);
  1035. putc(')', fp);
  1036. break;
  1037. default:
  1038. putc(*p, fp);
  1039. break;
  1040. }
  1041. }
  1042. }
  1043. static void
  1044. shcmd(union node *cmd, FILE *fp)
  1045. {
  1046. union node *np;
  1047. int first;
  1048. const char *s;
  1049. int dftfd;
  1050. first = 1;
  1051. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1052. if (!first)
  1053. putc(' ', fp);
  1054. sharg(np, fp);
  1055. first = 0;
  1056. }
  1057. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1058. if (!first)
  1059. putc(' ', fp);
  1060. dftfd = 0;
  1061. switch (np->nfile.type) {
  1062. case NTO: s = ">>"+1; dftfd = 1; break;
  1063. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1064. case NAPPEND: s = ">>"; dftfd = 1; break;
  1065. #if BASH_REDIR_OUTPUT
  1066. case NTO2:
  1067. #endif
  1068. case NTOFD: s = ">&"; dftfd = 1; break;
  1069. case NFROM: s = "<"; break;
  1070. case NFROMFD: s = "<&"; break;
  1071. case NFROMTO: s = "<>"; break;
  1072. default: s = "*error*"; break;
  1073. }
  1074. if (np->nfile.fd != dftfd)
  1075. fprintf(fp, "%d", np->nfile.fd);
  1076. fputs(s, fp);
  1077. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1078. fprintf(fp, "%d", np->ndup.dupfd);
  1079. } else {
  1080. sharg(np->nfile.fname, fp);
  1081. }
  1082. first = 0;
  1083. }
  1084. }
  1085. static void
  1086. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1087. {
  1088. struct nodelist *lp;
  1089. const char *s;
  1090. if (n == NULL)
  1091. return;
  1092. indent(ind, pfx, fp);
  1093. if (n == NODE_EOF) {
  1094. fputs("<EOF>", fp);
  1095. return;
  1096. }
  1097. switch (n->type) {
  1098. case NSEMI:
  1099. s = "; ";
  1100. goto binop;
  1101. case NAND:
  1102. s = " && ";
  1103. goto binop;
  1104. case NOR:
  1105. s = " || ";
  1106. binop:
  1107. shtree(n->nbinary.ch1, ind, NULL, fp);
  1108. /* if (ind < 0) */
  1109. fputs(s, fp);
  1110. shtree(n->nbinary.ch2, ind, NULL, fp);
  1111. break;
  1112. case NCMD:
  1113. shcmd(n, fp);
  1114. if (ind >= 0)
  1115. putc('\n', fp);
  1116. break;
  1117. case NPIPE:
  1118. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1119. shtree(lp->n, 0, NULL, fp);
  1120. if (lp->next)
  1121. fputs(" | ", fp);
  1122. }
  1123. if (n->npipe.pipe_backgnd)
  1124. fputs(" &", fp);
  1125. if (ind >= 0)
  1126. putc('\n', fp);
  1127. break;
  1128. default:
  1129. fprintf(fp, "<node type %d>", n->type);
  1130. if (ind >= 0)
  1131. putc('\n', fp);
  1132. break;
  1133. }
  1134. }
  1135. static void
  1136. showtree(union node *n)
  1137. {
  1138. trace_puts("showtree called\n");
  1139. shtree(n, 1, NULL, stderr);
  1140. }
  1141. #endif /* DEBUG */
  1142. /* ============ Parser data */
  1143. /*
  1144. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1145. */
  1146. struct strlist {
  1147. struct strlist *next;
  1148. char *text;
  1149. };
  1150. struct alias;
  1151. struct strpush {
  1152. struct strpush *prev; /* preceding string on stack */
  1153. char *prev_string;
  1154. int prev_left_in_line;
  1155. #if ENABLE_ASH_ALIAS
  1156. struct alias *ap; /* if push was associated with an alias */
  1157. #endif
  1158. char *string; /* remember the string since it may change */
  1159. /* Remember last two characters for pungetc. */
  1160. int lastc[2];
  1161. /* Number of outstanding calls to pungetc. */
  1162. int unget;
  1163. };
  1164. /*
  1165. * The parsefile structure pointed to by the global variable parsefile
  1166. * contains information about the current file being read.
  1167. */
  1168. struct parsefile {
  1169. struct parsefile *prev; /* preceding file on stack */
  1170. int linno; /* current line */
  1171. int pf_fd; /* file descriptor (or -1 if string) */
  1172. int left_in_line; /* number of chars left in this line */
  1173. int left_in_buffer; /* number of chars left in this buffer past the line */
  1174. char *next_to_pgetc; /* next char in buffer */
  1175. char *buf; /* input buffer */
  1176. struct strpush *strpush; /* for pushing strings at this level */
  1177. struct strpush basestrpush; /* so pushing one is fast */
  1178. /* Remember last two characters for pungetc. */
  1179. int lastc[2];
  1180. /* Number of outstanding calls to pungetc. */
  1181. int unget;
  1182. };
  1183. static struct parsefile basepf; /* top level input file */
  1184. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1185. static char *commandname; /* currently executing command */
  1186. /* ============ Message printing */
  1187. static void
  1188. ash_vmsg(const char *msg, va_list ap)
  1189. {
  1190. fprintf(stderr, "%s: ", arg0);
  1191. if (commandname) {
  1192. if (strcmp(arg0, commandname))
  1193. fprintf(stderr, "%s: ", commandname);
  1194. if (!iflag || g_parsefile->pf_fd > 0)
  1195. fprintf(stderr, "line %d: ", errlinno);
  1196. }
  1197. vfprintf(stderr, msg, ap);
  1198. newline_and_flush(stderr);
  1199. }
  1200. /*
  1201. * Exverror is called to raise the error exception. If the second argument
  1202. * is not NULL then error prints an error message using printf style
  1203. * formatting. It then raises the error exception.
  1204. */
  1205. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1206. static void
  1207. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1208. {
  1209. #if DEBUG
  1210. if (msg) {
  1211. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1212. TRACEV((msg, ap));
  1213. } else
  1214. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1215. if (msg)
  1216. #endif
  1217. ash_vmsg(msg, ap);
  1218. flush_stdout_stderr();
  1219. raise_exception(cond);
  1220. /* NOTREACHED */
  1221. }
  1222. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1223. static void
  1224. ash_msg_and_raise_error(const char *msg, ...)
  1225. {
  1226. va_list ap;
  1227. exitstatus = 2;
  1228. va_start(ap, msg);
  1229. ash_vmsg_and_raise(EXERROR, msg, ap);
  1230. /* NOTREACHED */
  1231. va_end(ap);
  1232. }
  1233. /*
  1234. * 'fmt' must be a string literal.
  1235. */
  1236. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1237. static void raise_error_syntax(const char *) NORETURN;
  1238. static void
  1239. raise_error_syntax(const char *msg)
  1240. {
  1241. errlinno = g_parsefile->linno;
  1242. ash_msg_and_raise_error("syntax error: %s", msg);
  1243. /* NOTREACHED */
  1244. }
  1245. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1246. static void
  1247. ash_msg_and_raise(int cond, const char *msg, ...)
  1248. {
  1249. va_list ap;
  1250. va_start(ap, msg);
  1251. ash_vmsg_and_raise(cond, msg, ap);
  1252. /* NOTREACHED */
  1253. va_end(ap);
  1254. }
  1255. /*
  1256. * error/warning routines for external builtins
  1257. */
  1258. static void
  1259. ash_msg(const char *fmt, ...)
  1260. {
  1261. va_list ap;
  1262. va_start(ap, fmt);
  1263. ash_vmsg(fmt, ap);
  1264. va_end(ap);
  1265. }
  1266. /*
  1267. * Return a string describing an error. The returned string may be a
  1268. * pointer to a static buffer that will be overwritten on the next call.
  1269. * Action describes the operation that got the error.
  1270. */
  1271. static const char *
  1272. errmsg(int e, const char *em)
  1273. {
  1274. if (e == ENOENT || e == ENOTDIR) {
  1275. return em;
  1276. }
  1277. return strerror(e);
  1278. }
  1279. /* ============ Memory allocation */
  1280. #if 0
  1281. /* I consider these wrappers nearly useless:
  1282. * ok, they return you to nearest exception handler, but
  1283. * how much memory do you leak in the process, making
  1284. * memory starvation worse?
  1285. */
  1286. static void *
  1287. ckrealloc(void * p, size_t nbytes)
  1288. {
  1289. p = realloc(p, nbytes);
  1290. if (!p)
  1291. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1292. return p;
  1293. }
  1294. static void *
  1295. ckmalloc(size_t nbytes)
  1296. {
  1297. return ckrealloc(NULL, nbytes);
  1298. }
  1299. static void *
  1300. ckzalloc(size_t nbytes)
  1301. {
  1302. return memset(ckmalloc(nbytes), 0, nbytes);
  1303. }
  1304. static char *
  1305. ckstrdup(const char *s)
  1306. {
  1307. char *p = strdup(s);
  1308. if (!p)
  1309. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1310. return p;
  1311. }
  1312. #else
  1313. /* Using bbox equivalents. They exit if out of memory */
  1314. # define ckrealloc xrealloc
  1315. # define ckmalloc xmalloc
  1316. # define ckzalloc xzalloc
  1317. # define ckstrdup xstrdup
  1318. #endif
  1319. /*
  1320. * It appears that grabstackstr() will barf with such alignments
  1321. * because stalloc() will return a string allocated in a new stackblock.
  1322. */
  1323. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1324. enum {
  1325. /* Most machines require the value returned from malloc to be aligned
  1326. * in some way. The following macro will get this right
  1327. * on many machines. */
  1328. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1329. /* Minimum size of a block */
  1330. MINSIZE = SHELL_ALIGN(504),
  1331. };
  1332. struct stack_block {
  1333. struct stack_block *prev;
  1334. char space[MINSIZE];
  1335. };
  1336. struct stackmark {
  1337. struct stack_block *stackp;
  1338. char *stacknxt;
  1339. size_t stacknleft;
  1340. };
  1341. struct globals_memstack {
  1342. struct stack_block *g_stackp; // = &stackbase;
  1343. char *g_stacknxt; // = stackbase.space;
  1344. char *sstrend; // = stackbase.space + MINSIZE;
  1345. size_t g_stacknleft; // = MINSIZE;
  1346. struct stack_block stackbase;
  1347. };
  1348. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1349. #define G_memstack (*ash_ptr_to_globals_memstack)
  1350. #define g_stackp (G_memstack.g_stackp )
  1351. #define g_stacknxt (G_memstack.g_stacknxt )
  1352. #define sstrend (G_memstack.sstrend )
  1353. #define g_stacknleft (G_memstack.g_stacknleft)
  1354. #define stackbase (G_memstack.stackbase )
  1355. #define INIT_G_memstack() do { \
  1356. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1357. barrier(); \
  1358. g_stackp = &stackbase; \
  1359. g_stacknxt = stackbase.space; \
  1360. g_stacknleft = MINSIZE; \
  1361. sstrend = stackbase.space + MINSIZE; \
  1362. } while (0)
  1363. #define stackblock() ((void *)g_stacknxt)
  1364. #define stackblocksize() g_stacknleft
  1365. /*
  1366. * Parse trees for commands are allocated in lifo order, so we use a stack
  1367. * to make this more efficient, and also to avoid all sorts of exception
  1368. * handling code to handle interrupts in the middle of a parse.
  1369. *
  1370. * The size 504 was chosen because the Ultrix malloc handles that size
  1371. * well.
  1372. */
  1373. static void *
  1374. stalloc(size_t nbytes)
  1375. {
  1376. char *p;
  1377. size_t aligned;
  1378. aligned = SHELL_ALIGN(nbytes);
  1379. if (aligned > g_stacknleft) {
  1380. size_t len;
  1381. size_t blocksize;
  1382. struct stack_block *sp;
  1383. blocksize = aligned;
  1384. if (blocksize < MINSIZE)
  1385. blocksize = MINSIZE;
  1386. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1387. if (len < blocksize)
  1388. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1389. INT_OFF;
  1390. sp = ckmalloc(len);
  1391. sp->prev = g_stackp;
  1392. g_stacknxt = sp->space;
  1393. g_stacknleft = blocksize;
  1394. sstrend = g_stacknxt + blocksize;
  1395. g_stackp = sp;
  1396. INT_ON;
  1397. }
  1398. p = g_stacknxt;
  1399. g_stacknxt += aligned;
  1400. g_stacknleft -= aligned;
  1401. return p;
  1402. }
  1403. static void *
  1404. stzalloc(size_t nbytes)
  1405. {
  1406. return memset(stalloc(nbytes), 0, nbytes);
  1407. }
  1408. static void
  1409. stunalloc(void *p)
  1410. {
  1411. #if DEBUG
  1412. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1413. write(STDERR_FILENO, "stunalloc\n", 10);
  1414. abort();
  1415. }
  1416. #endif
  1417. g_stacknleft += g_stacknxt - (char *)p;
  1418. g_stacknxt = p;
  1419. }
  1420. /*
  1421. * Like strdup but works with the ash stack.
  1422. */
  1423. static char *
  1424. sstrdup(const char *p)
  1425. {
  1426. size_t len = strlen(p) + 1;
  1427. return memcpy(stalloc(len), p, len);
  1428. }
  1429. static ALWAYS_INLINE void
  1430. grabstackblock(size_t len)
  1431. {
  1432. stalloc(len);
  1433. }
  1434. static void
  1435. pushstackmark(struct stackmark *mark, size_t len)
  1436. {
  1437. mark->stackp = g_stackp;
  1438. mark->stacknxt = g_stacknxt;
  1439. mark->stacknleft = g_stacknleft;
  1440. grabstackblock(len);
  1441. }
  1442. static void
  1443. setstackmark(struct stackmark *mark)
  1444. {
  1445. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1446. }
  1447. static void
  1448. popstackmark(struct stackmark *mark)
  1449. {
  1450. struct stack_block *sp;
  1451. if (!mark->stackp)
  1452. return;
  1453. INT_OFF;
  1454. while (g_stackp != mark->stackp) {
  1455. sp = g_stackp;
  1456. g_stackp = sp->prev;
  1457. free(sp);
  1458. }
  1459. g_stacknxt = mark->stacknxt;
  1460. g_stacknleft = mark->stacknleft;
  1461. sstrend = mark->stacknxt + mark->stacknleft;
  1462. INT_ON;
  1463. }
  1464. /*
  1465. * When the parser reads in a string, it wants to stick the string on the
  1466. * stack and only adjust the stack pointer when it knows how big the
  1467. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1468. * of space on top of the stack and stackblocklen returns the length of
  1469. * this block. Growstackblock will grow this space by at least one byte,
  1470. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1471. * part of the block that has been used.
  1472. */
  1473. static void
  1474. growstackblock(void)
  1475. {
  1476. size_t newlen;
  1477. newlen = g_stacknleft * 2;
  1478. if (newlen < g_stacknleft)
  1479. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1480. if (newlen < 128)
  1481. newlen += 128;
  1482. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1483. struct stack_block *sp;
  1484. struct stack_block *prevstackp;
  1485. size_t grosslen;
  1486. INT_OFF;
  1487. sp = g_stackp;
  1488. prevstackp = sp->prev;
  1489. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1490. sp = ckrealloc(sp, grosslen);
  1491. sp->prev = prevstackp;
  1492. g_stackp = sp;
  1493. g_stacknxt = sp->space;
  1494. g_stacknleft = newlen;
  1495. sstrend = sp->space + newlen;
  1496. INT_ON;
  1497. } else {
  1498. char *oldspace = g_stacknxt;
  1499. size_t oldlen = g_stacknleft;
  1500. char *p = stalloc(newlen);
  1501. /* free the space we just allocated */
  1502. g_stacknxt = memcpy(p, oldspace, oldlen);
  1503. g_stacknleft += newlen;
  1504. }
  1505. }
  1506. /*
  1507. * The following routines are somewhat easier to use than the above.
  1508. * The user declares a variable of type STACKSTR, which may be declared
  1509. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1510. * the user uses the macro STPUTC to add characters to the string. In
  1511. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1512. * grown as necessary. When the user is done, she can just leave the
  1513. * string there and refer to it using stackblock(). Or she can allocate
  1514. * the space for it using grabstackstr(). If it is necessary to allow
  1515. * someone else to use the stack temporarily and then continue to grow
  1516. * the string, the user should use grabstack to allocate the space, and
  1517. * then call ungrabstr(p) to return to the previous mode of operation.
  1518. *
  1519. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1520. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1521. * is space for at least one character.
  1522. */
  1523. static void *
  1524. growstackstr(void)
  1525. {
  1526. size_t len = stackblocksize();
  1527. growstackblock();
  1528. return (char *)stackblock() + len;
  1529. }
  1530. /*
  1531. * Called from CHECKSTRSPACE.
  1532. */
  1533. static char *
  1534. makestrspace(size_t newlen, char *p)
  1535. {
  1536. size_t len = p - g_stacknxt;
  1537. size_t size;
  1538. for (;;) {
  1539. size_t nleft;
  1540. size = stackblocksize();
  1541. nleft = size - len;
  1542. if (nleft >= newlen)
  1543. break;
  1544. growstackblock();
  1545. }
  1546. return (char *)stackblock() + len;
  1547. }
  1548. static char *
  1549. stack_nputstr(const char *s, size_t n, char *p)
  1550. {
  1551. p = makestrspace(n, p);
  1552. p = (char *)mempcpy(p, s, n);
  1553. return p;
  1554. }
  1555. static char *
  1556. stack_putstr(const char *s, char *p)
  1557. {
  1558. return stack_nputstr(s, strlen(s), p);
  1559. }
  1560. static char *
  1561. _STPUTC(int c, char *p)
  1562. {
  1563. if (p == sstrend)
  1564. p = growstackstr();
  1565. *p++ = c;
  1566. return p;
  1567. }
  1568. #define STARTSTACKSTR(p) ((p) = stackblock())
  1569. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1570. #define CHECKSTRSPACE(n, p) do { \
  1571. char *q = (p); \
  1572. size_t l = (n); \
  1573. size_t m = sstrend - q; \
  1574. if (l > m) \
  1575. (p) = makestrspace(l, q); \
  1576. } while (0)
  1577. #define USTPUTC(c, p) (*(p)++ = (c))
  1578. #define STACKSTRNUL(p) do { \
  1579. if ((p) == sstrend) \
  1580. (p) = growstackstr(); \
  1581. *(p) = '\0'; \
  1582. } while (0)
  1583. #define STUNPUTC(p) (--(p))
  1584. #define STTOPC(p) ((p)[-1])
  1585. #define STADJUST(amount, p) ((p) += (amount))
  1586. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1587. #define ungrabstackstr(s, p) stunalloc(s)
  1588. #define stackstrend() ((void *)sstrend)
  1589. /* ============ String helpers */
  1590. /*
  1591. * prefix -- see if pfx is a prefix of string.
  1592. */
  1593. static char *
  1594. prefix(const char *string, const char *pfx)
  1595. {
  1596. while (*pfx) {
  1597. if (*pfx++ != *string++)
  1598. return NULL;
  1599. }
  1600. return (char *) string;
  1601. }
  1602. /*
  1603. * Check for a valid number. This should be elsewhere.
  1604. */
  1605. static int
  1606. is_number(const char *p)
  1607. {
  1608. do {
  1609. if (!isdigit(*p))
  1610. return 0;
  1611. } while (*++p != '\0');
  1612. return 1;
  1613. }
  1614. /*
  1615. * Convert a string of digits to an integer, printing an error message on
  1616. * failure.
  1617. */
  1618. static int
  1619. number(const char *s)
  1620. {
  1621. if (!is_number(s))
  1622. ash_msg_and_raise_error(msg_illnum, s);
  1623. return atoi(s);
  1624. }
  1625. /*
  1626. * Produce a single quoted string suitable as input to the shell.
  1627. * The return string is allocated on the stack.
  1628. */
  1629. static char *
  1630. single_quote(const char *s)
  1631. {
  1632. char *p;
  1633. STARTSTACKSTR(p);
  1634. do {
  1635. char *q;
  1636. size_t len;
  1637. len = strchrnul(s, '\'') - s;
  1638. q = p = makestrspace(len + 3, p);
  1639. *q++ = '\'';
  1640. q = (char *)mempcpy(q, s, len);
  1641. *q++ = '\'';
  1642. s += len;
  1643. STADJUST(q - p, p);
  1644. if (*s != '\'')
  1645. break;
  1646. len = 0;
  1647. do len++; while (*++s == '\'');
  1648. q = p = makestrspace(len + 3, p);
  1649. *q++ = '"';
  1650. q = (char *)mempcpy(q, s - len, len);
  1651. *q++ = '"';
  1652. STADJUST(q - p, p);
  1653. } while (*s);
  1654. USTPUTC('\0', p);
  1655. return stackblock();
  1656. }
  1657. /*
  1658. * Produce a possibly single quoted string suitable as input to the shell.
  1659. * If quoting was done, the return string is allocated on the stack,
  1660. * otherwise a pointer to the original string is returned.
  1661. */
  1662. static const char *
  1663. maybe_single_quote(const char *s)
  1664. {
  1665. const char *p = s;
  1666. while (*p) {
  1667. /* Assuming ACSII */
  1668. /* quote ctrl_chars space !"#$%&'()* */
  1669. if (*p < '+')
  1670. goto need_quoting;
  1671. /* quote ;<=>? */
  1672. if (*p >= ';' && *p <= '?')
  1673. goto need_quoting;
  1674. /* quote `[\ */
  1675. if (*p == '`')
  1676. goto need_quoting;
  1677. if (*p == '[')
  1678. goto need_quoting;
  1679. if (*p == '\\')
  1680. goto need_quoting;
  1681. /* quote {|}~ DEL and high bytes */
  1682. if (*p > 'z')
  1683. goto need_quoting;
  1684. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1685. /* TODO: maybe avoid quoting % */
  1686. p++;
  1687. }
  1688. return s;
  1689. need_quoting:
  1690. return single_quote(s);
  1691. }
  1692. /* ============ nextopt */
  1693. static char **argptr; /* argument list for builtin commands */
  1694. static char *optionarg; /* set by nextopt (like getopt) */
  1695. static char *optptr; /* used by nextopt */
  1696. /*
  1697. * XXX - should get rid of. Have all builtins use getopt(3).
  1698. * The library getopt must have the BSD extension static variable
  1699. * "optreset", otherwise it can't be used within the shell safely.
  1700. *
  1701. * Standard option processing (a la getopt) for builtin routines.
  1702. * The only argument that is passed to nextopt is the option string;
  1703. * the other arguments are unnecessary. It returns the character,
  1704. * or '\0' on end of input.
  1705. */
  1706. static int
  1707. nextopt(const char *optstring)
  1708. {
  1709. char *p;
  1710. const char *q;
  1711. char c;
  1712. p = optptr;
  1713. if (p == NULL || *p == '\0') {
  1714. /* We ate entire "-param", take next one */
  1715. p = *argptr;
  1716. if (p == NULL)
  1717. return '\0';
  1718. if (*p != '-')
  1719. return '\0';
  1720. if (*++p == '\0') /* just "-" ? */
  1721. return '\0';
  1722. argptr++;
  1723. if (LONE_DASH(p)) /* "--" ? */
  1724. return '\0';
  1725. /* p => next "-param" */
  1726. }
  1727. /* p => some option char in the middle of a "-param" */
  1728. c = *p++;
  1729. for (q = optstring; *q != c;) {
  1730. if (*q == '\0')
  1731. ash_msg_and_raise_error("illegal option -%c", c);
  1732. if (*++q == ':')
  1733. q++;
  1734. }
  1735. if (*++q == ':') {
  1736. if (*p == '\0') {
  1737. p = *argptr++;
  1738. if (p == NULL)
  1739. ash_msg_and_raise_error("no arg for -%c option", c);
  1740. }
  1741. optionarg = p;
  1742. p = NULL;
  1743. }
  1744. optptr = p;
  1745. return c;
  1746. }
  1747. /* ============ Shell variables */
  1748. struct shparam {
  1749. int nparam; /* # of positional parameters (without $0) */
  1750. #if ENABLE_ASH_GETOPTS
  1751. int optind; /* next parameter to be processed by getopts */
  1752. int optoff; /* used by getopts */
  1753. #endif
  1754. unsigned char malloced; /* if parameter list dynamically allocated */
  1755. char **p; /* parameter list */
  1756. };
  1757. /*
  1758. * Free the list of positional parameters.
  1759. */
  1760. static void
  1761. freeparam(volatile struct shparam *param)
  1762. {
  1763. if (param->malloced) {
  1764. char **ap, **ap1;
  1765. ap = ap1 = param->p;
  1766. while (*ap)
  1767. free(*ap++);
  1768. free(ap1);
  1769. }
  1770. }
  1771. #if ENABLE_ASH_GETOPTS
  1772. static void FAST_FUNC getoptsreset(const char *value);
  1773. #endif
  1774. struct var {
  1775. struct var *next; /* next entry in hash list */
  1776. int flags; /* flags are defined above */
  1777. const char *var_text; /* name=value */
  1778. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1779. /* the variable gets set/unset */
  1780. };
  1781. struct localvar {
  1782. struct localvar *next; /* next local variable in list */
  1783. struct var *vp; /* the variable that was made local */
  1784. int flags; /* saved flags */
  1785. const char *text; /* saved text */
  1786. };
  1787. /* flags */
  1788. #define VEXPORT 0x01 /* variable is exported */
  1789. #define VREADONLY 0x02 /* variable cannot be modified */
  1790. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1791. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1792. #define VSTACK 0x10 /* text is allocated on the stack */
  1793. #define VUNSET 0x20 /* the variable is not set */
  1794. #define VNOFUNC 0x40 /* don't call the callback function */
  1795. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1796. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1797. #if ENABLE_ASH_RANDOM_SUPPORT
  1798. # define VDYNAMIC 0x200 /* dynamic variable */
  1799. #else
  1800. # define VDYNAMIC 0
  1801. #endif
  1802. /* Need to be before varinit_data[] */
  1803. #if ENABLE_LOCALE_SUPPORT
  1804. static void FAST_FUNC
  1805. change_lc_all(const char *value)
  1806. {
  1807. if (value && *value != '\0')
  1808. setlocale(LC_ALL, value);
  1809. }
  1810. static void FAST_FUNC
  1811. change_lc_ctype(const char *value)
  1812. {
  1813. if (value && *value != '\0')
  1814. setlocale(LC_CTYPE, value);
  1815. }
  1816. #endif
  1817. #if ENABLE_ASH_MAIL
  1818. static void chkmail(void);
  1819. static void changemail(const char *var_value) FAST_FUNC;
  1820. #else
  1821. # define chkmail() ((void)0)
  1822. #endif
  1823. static void changepath(const char *) FAST_FUNC;
  1824. #if ENABLE_ASH_RANDOM_SUPPORT
  1825. static void change_random(const char *) FAST_FUNC;
  1826. #endif
  1827. static const struct {
  1828. int flags;
  1829. const char *var_text;
  1830. void (*var_func)(const char *) FAST_FUNC;
  1831. } varinit_data[] = {
  1832. /*
  1833. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1834. * some environment strings may be constant.
  1835. */
  1836. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1837. #if ENABLE_ASH_MAIL
  1838. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1839. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1840. #endif
  1841. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1842. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1843. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1844. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1845. #if ENABLE_ASH_GETOPTS
  1846. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1847. #endif
  1848. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1849. #if ENABLE_ASH_RANDOM_SUPPORT
  1850. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1851. #endif
  1852. #if ENABLE_LOCALE_SUPPORT
  1853. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1854. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1855. #endif
  1856. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1857. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1858. #endif
  1859. };
  1860. struct redirtab;
  1861. struct globals_var {
  1862. struct shparam shellparam; /* $@ current positional parameters */
  1863. struct redirtab *redirlist;
  1864. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1865. struct var *vartab[VTABSIZE];
  1866. struct var varinit[ARRAY_SIZE(varinit_data)];
  1867. int lineno;
  1868. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1869. };
  1870. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1871. #define G_var (*ash_ptr_to_globals_var)
  1872. #define shellparam (G_var.shellparam )
  1873. //#define redirlist (G_var.redirlist )
  1874. #define preverrout_fd (G_var.preverrout_fd)
  1875. #define vartab (G_var.vartab )
  1876. #define varinit (G_var.varinit )
  1877. #define lineno (G_var.lineno )
  1878. #define linenovar (G_var.linenovar )
  1879. #define vifs varinit[0]
  1880. #if ENABLE_ASH_MAIL
  1881. # define vmail (&vifs)[1]
  1882. # define vmpath (&vmail)[1]
  1883. # define vpath (&vmpath)[1]
  1884. #else
  1885. # define vpath (&vifs)[1]
  1886. #endif
  1887. #define vps1 (&vpath)[1]
  1888. #define vps2 (&vps1)[1]
  1889. #define vps4 (&vps2)[1]
  1890. #if ENABLE_ASH_GETOPTS
  1891. # define voptind (&vps4)[1]
  1892. # define vlineno (&voptind)[1]
  1893. # if ENABLE_ASH_RANDOM_SUPPORT
  1894. # define vrandom (&vlineno)[1]
  1895. # endif
  1896. #else
  1897. # define vlineno (&vps4)[1]
  1898. # if ENABLE_ASH_RANDOM_SUPPORT
  1899. # define vrandom (&vlineno)[1]
  1900. # endif
  1901. #endif
  1902. #define INIT_G_var() do { \
  1903. unsigned i; \
  1904. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1905. barrier(); \
  1906. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1907. varinit[i].flags = varinit_data[i].flags; \
  1908. varinit[i].var_text = varinit_data[i].var_text; \
  1909. varinit[i].var_func = varinit_data[i].var_func; \
  1910. } \
  1911. strcpy(linenovar, "LINENO="); \
  1912. vlineno.var_text = linenovar; \
  1913. } while (0)
  1914. /*
  1915. * The following macros access the values of the above variables.
  1916. * They have to skip over the name. They return the null string
  1917. * for unset variables.
  1918. */
  1919. #define ifsval() (vifs.var_text + 4)
  1920. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1921. #if ENABLE_ASH_MAIL
  1922. # define mailval() (vmail.var_text + 5)
  1923. # define mpathval() (vmpath.var_text + 9)
  1924. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1925. #endif
  1926. #define pathval() (vpath.var_text + 5)
  1927. #define ps1val() (vps1.var_text + 4)
  1928. #define ps2val() (vps2.var_text + 4)
  1929. #define ps4val() (vps4.var_text + 4)
  1930. #if ENABLE_ASH_GETOPTS
  1931. # define optindval() (voptind.var_text + 7)
  1932. #endif
  1933. #if ENABLE_ASH_GETOPTS
  1934. static void FAST_FUNC
  1935. getoptsreset(const char *value)
  1936. {
  1937. shellparam.optind = 1;
  1938. if (is_number(value))
  1939. shellparam.optind = number(value) ?: 1;
  1940. shellparam.optoff = -1;
  1941. }
  1942. #endif
  1943. /*
  1944. * Compares two strings up to the first = or '\0'. The first
  1945. * string must be terminated by '='; the second may be terminated by
  1946. * either '=' or '\0'.
  1947. */
  1948. static int
  1949. varcmp(const char *p, const char *q)
  1950. {
  1951. int c, d;
  1952. while ((c = *p) == (d = *q)) {
  1953. if (c == '\0' || c == '=')
  1954. goto out;
  1955. p++;
  1956. q++;
  1957. }
  1958. if (c == '=')
  1959. c = '\0';
  1960. if (d == '=')
  1961. d = '\0';
  1962. out:
  1963. return c - d;
  1964. }
  1965. /*
  1966. * Find the appropriate entry in the hash table from the name.
  1967. */
  1968. static struct var **
  1969. hashvar(const char *p)
  1970. {
  1971. unsigned hashval;
  1972. hashval = ((unsigned char) *p) << 4;
  1973. while (*p && *p != '=')
  1974. hashval += (unsigned char) *p++;
  1975. return &vartab[hashval % VTABSIZE];
  1976. }
  1977. static int
  1978. vpcmp(const void *a, const void *b)
  1979. {
  1980. return varcmp(*(const char **)a, *(const char **)b);
  1981. }
  1982. /*
  1983. * This routine initializes the builtin variables.
  1984. */
  1985. static void
  1986. initvar(void)
  1987. {
  1988. struct var *vp;
  1989. struct var *end;
  1990. struct var **vpp;
  1991. /*
  1992. * PS1 depends on uid
  1993. */
  1994. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1995. vps1.var_text = "PS1=\\w \\$ ";
  1996. #else
  1997. if (!geteuid())
  1998. vps1.var_text = "PS1=# ";
  1999. #endif
  2000. vp = varinit;
  2001. end = vp + ARRAY_SIZE(varinit);
  2002. do {
  2003. vpp = hashvar(vp->var_text);
  2004. vp->next = *vpp;
  2005. *vpp = vp;
  2006. } while (++vp < end);
  2007. }
  2008. static struct var **
  2009. findvar(struct var **vpp, const char *name)
  2010. {
  2011. for (; *vpp; vpp = &(*vpp)->next) {
  2012. if (varcmp((*vpp)->var_text, name) == 0) {
  2013. break;
  2014. }
  2015. }
  2016. return vpp;
  2017. }
  2018. /*
  2019. * Find the value of a variable. Returns NULL if not set.
  2020. */
  2021. static const char* FAST_FUNC
  2022. lookupvar(const char *name)
  2023. {
  2024. struct var *v;
  2025. v = *findvar(hashvar(name), name);
  2026. if (v) {
  2027. #if ENABLE_ASH_RANDOM_SUPPORT
  2028. /*
  2029. * Dynamic variables are implemented roughly the same way they are
  2030. * in bash. Namely, they're "special" so long as they aren't unset.
  2031. * As soon as they're unset, they're no longer dynamic, and dynamic
  2032. * lookup will no longer happen at that point. -- PFM.
  2033. */
  2034. if (v->flags & VDYNAMIC)
  2035. v->var_func(NULL);
  2036. #endif
  2037. if (!(v->flags & VUNSET)) {
  2038. if (v == &vlineno && v->var_text == linenovar) {
  2039. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2040. }
  2041. return var_end(v->var_text);
  2042. }
  2043. }
  2044. return NULL;
  2045. }
  2046. #if ENABLE_UNICODE_SUPPORT
  2047. static void
  2048. reinit_unicode_for_ash(void)
  2049. {
  2050. /* Unicode support should be activated even if LANG is set
  2051. * _during_ shell execution, not only if it was set when
  2052. * shell was started. Therefore, re-check LANG every time:
  2053. */
  2054. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2055. || ENABLE_UNICODE_USING_LOCALE
  2056. ) {
  2057. const char *s = lookupvar("LC_ALL");
  2058. if (!s) s = lookupvar("LC_CTYPE");
  2059. if (!s) s = lookupvar("LANG");
  2060. reinit_unicode(s);
  2061. }
  2062. }
  2063. #else
  2064. # define reinit_unicode_for_ash() ((void)0)
  2065. #endif
  2066. /*
  2067. * Search the environment of a builtin command.
  2068. */
  2069. static ALWAYS_INLINE const char *
  2070. bltinlookup(const char *name)
  2071. {
  2072. return lookupvar(name);
  2073. }
  2074. /*
  2075. * Same as setvar except that the variable and value are passed in
  2076. * the first argument as name=value. Since the first argument will
  2077. * be actually stored in the table, it should not be a string that
  2078. * will go away.
  2079. * Called with interrupts off.
  2080. */
  2081. static struct var *
  2082. setvareq(char *s, int flags)
  2083. {
  2084. struct var *vp, **vpp;
  2085. vpp = hashvar(s);
  2086. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2087. vpp = findvar(vpp, s);
  2088. vp = *vpp;
  2089. if (vp) {
  2090. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2091. const char *n;
  2092. if (flags & VNOSAVE)
  2093. free(s);
  2094. n = vp->var_text;
  2095. exitstatus = 1;
  2096. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2097. }
  2098. if (flags & VNOSET)
  2099. goto out;
  2100. if (vp->var_func && !(flags & VNOFUNC))
  2101. vp->var_func(var_end(s));
  2102. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2103. free((char*)vp->var_text);
  2104. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2105. *vpp = vp->next;
  2106. free(vp);
  2107. out_free:
  2108. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2109. free(s);
  2110. goto out;
  2111. }
  2112. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2113. } else {
  2114. /* variable s is not found */
  2115. if (flags & VNOSET)
  2116. goto out;
  2117. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2118. goto out_free;
  2119. vp = ckzalloc(sizeof(*vp));
  2120. vp->next = *vpp;
  2121. /*vp->func = NULL; - ckzalloc did it */
  2122. *vpp = vp;
  2123. }
  2124. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2125. s = ckstrdup(s);
  2126. vp->var_text = s;
  2127. vp->flags = flags;
  2128. out:
  2129. return vp;
  2130. }
  2131. /*
  2132. * Set the value of a variable. The flags argument is ored with the
  2133. * flags of the variable. If val is NULL, the variable is unset.
  2134. */
  2135. static struct var *
  2136. setvar(const char *name, const char *val, int flags)
  2137. {
  2138. const char *q;
  2139. char *p;
  2140. char *nameeq;
  2141. size_t namelen;
  2142. size_t vallen;
  2143. struct var *vp;
  2144. q = endofname(name);
  2145. p = strchrnul(q, '=');
  2146. namelen = p - name;
  2147. if (!namelen || p != q)
  2148. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2149. vallen = 0;
  2150. if (val == NULL) {
  2151. flags |= VUNSET;
  2152. } else {
  2153. vallen = strlen(val);
  2154. }
  2155. INT_OFF;
  2156. nameeq = ckmalloc(namelen + vallen + 2);
  2157. p = mempcpy(nameeq, name, namelen);
  2158. if (val) {
  2159. *p++ = '=';
  2160. p = mempcpy(p, val, vallen);
  2161. }
  2162. *p = '\0';
  2163. vp = setvareq(nameeq, flags | VNOSAVE);
  2164. INT_ON;
  2165. return vp;
  2166. }
  2167. static void FAST_FUNC
  2168. setvar0(const char *name, const char *val)
  2169. {
  2170. setvar(name, val, 0);
  2171. }
  2172. /*
  2173. * Unset the specified variable.
  2174. */
  2175. static void
  2176. unsetvar(const char *s)
  2177. {
  2178. setvar(s, NULL, 0);
  2179. }
  2180. /*
  2181. * Process a linked list of variable assignments.
  2182. */
  2183. static void
  2184. listsetvar(struct strlist *list_set_var, int flags)
  2185. {
  2186. struct strlist *lp = list_set_var;
  2187. if (!lp)
  2188. return;
  2189. INT_OFF;
  2190. do {
  2191. setvareq(lp->text, flags);
  2192. lp = lp->next;
  2193. } while (lp);
  2194. INT_ON;
  2195. }
  2196. /*
  2197. * Generate a list of variables satisfying the given conditions.
  2198. */
  2199. #if !ENABLE_FEATURE_SH_NOFORK
  2200. # define listvars(on, off, lp, end) listvars(on, off, end)
  2201. #endif
  2202. static char **
  2203. listvars(int on, int off, struct strlist *lp, char ***end)
  2204. {
  2205. struct var **vpp;
  2206. struct var *vp;
  2207. char **ep;
  2208. int mask;
  2209. STARTSTACKSTR(ep);
  2210. vpp = vartab;
  2211. mask = on | off;
  2212. do {
  2213. for (vp = *vpp; vp; vp = vp->next) {
  2214. if ((vp->flags & mask) == on) {
  2215. #if ENABLE_FEATURE_SH_NOFORK
  2216. /* If variable with the same name is both
  2217. * exported and temporarily set for a command:
  2218. * export ZVAR=5
  2219. * ZVAR=6 printenv
  2220. * then "ZVAR=6" will be both in vartab and
  2221. * lp lists. Do not pass it twice to printenv.
  2222. */
  2223. struct strlist *lp1 = lp;
  2224. while (lp1) {
  2225. if (strcmp(lp1->text, vp->var_text) == 0)
  2226. goto skip;
  2227. lp1 = lp1->next;
  2228. }
  2229. #endif
  2230. if (ep == stackstrend())
  2231. ep = growstackstr();
  2232. *ep++ = (char*)vp->var_text;
  2233. #if ENABLE_FEATURE_SH_NOFORK
  2234. skip: ;
  2235. #endif
  2236. }
  2237. }
  2238. } while (++vpp < vartab + VTABSIZE);
  2239. #if ENABLE_FEATURE_SH_NOFORK
  2240. while (lp) {
  2241. if (ep == stackstrend())
  2242. ep = growstackstr();
  2243. *ep++ = lp->text;
  2244. lp = lp->next;
  2245. }
  2246. #endif
  2247. if (ep == stackstrend())
  2248. ep = growstackstr();
  2249. if (end)
  2250. *end = ep;
  2251. *ep++ = NULL;
  2252. return grabstackstr(ep);
  2253. }
  2254. /* ============ Path search helper
  2255. *
  2256. * The variable path (passed by reference) should be set to the start
  2257. * of the path before the first call; path_advance will update
  2258. * this value as it proceeds. Successive calls to path_advance will return
  2259. * the possible path expansions in sequence. If an option (indicated by
  2260. * a percent sign) appears in the path entry then the global variable
  2261. * pathopt will be set to point to it; otherwise pathopt will be set to
  2262. * NULL.
  2263. */
  2264. static const char *pathopt; /* set by path_advance */
  2265. static char *
  2266. path_advance(const char **path, const char *name)
  2267. {
  2268. const char *p;
  2269. char *q;
  2270. const char *start;
  2271. size_t len;
  2272. if (*path == NULL)
  2273. return NULL;
  2274. start = *path;
  2275. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2276. continue;
  2277. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2278. while (stackblocksize() < len)
  2279. growstackblock();
  2280. q = stackblock();
  2281. if (p != start) {
  2282. q = mempcpy(q, start, p - start);
  2283. *q++ = '/';
  2284. }
  2285. strcpy(q, name);
  2286. pathopt = NULL;
  2287. if (*p == '%') {
  2288. pathopt = ++p;
  2289. while (*p && *p != ':')
  2290. p++;
  2291. }
  2292. if (*p == ':')
  2293. *path = p + 1;
  2294. else
  2295. *path = NULL;
  2296. return stalloc(len);
  2297. }
  2298. /* ============ Prompt */
  2299. static smallint doprompt; /* if set, prompt the user */
  2300. static smallint needprompt; /* true if interactive and at start of line */
  2301. #if ENABLE_FEATURE_EDITING
  2302. static line_input_t *line_input_state;
  2303. static const char *cmdedit_prompt;
  2304. static void
  2305. putprompt(const char *s)
  2306. {
  2307. if (ENABLE_ASH_EXPAND_PRMT) {
  2308. free((char*)cmdedit_prompt);
  2309. cmdedit_prompt = ckstrdup(s);
  2310. return;
  2311. }
  2312. cmdedit_prompt = s;
  2313. }
  2314. #else
  2315. static void
  2316. putprompt(const char *s)
  2317. {
  2318. out2str(s);
  2319. }
  2320. #endif
  2321. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2322. static const char *expandstr(const char *ps, int syntax_type);
  2323. /* Values for syntax param */
  2324. #define BASESYNTAX 0 /* not in quotes */
  2325. #define DQSYNTAX 1 /* in double quotes */
  2326. #define SQSYNTAX 2 /* in single quotes */
  2327. #define ARISYNTAX 3 /* in arithmetic */
  2328. #if ENABLE_ASH_EXPAND_PRMT
  2329. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2330. #endif
  2331. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2332. /*
  2333. * called by editline -- any expansions to the prompt should be added here.
  2334. */
  2335. static void
  2336. setprompt_if(smallint do_set, int whichprompt)
  2337. {
  2338. const char *prompt;
  2339. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2340. if (!do_set)
  2341. return;
  2342. needprompt = 0;
  2343. switch (whichprompt) {
  2344. case 1:
  2345. prompt = ps1val();
  2346. break;
  2347. case 2:
  2348. prompt = ps2val();
  2349. break;
  2350. default: /* 0 */
  2351. prompt = nullstr;
  2352. }
  2353. #if ENABLE_ASH_EXPAND_PRMT
  2354. pushstackmark(&smark, stackblocksize());
  2355. putprompt(expandstr(prompt, PSSYNTAX));
  2356. popstackmark(&smark);
  2357. #else
  2358. putprompt(prompt);
  2359. #endif
  2360. }
  2361. /* ============ The cd and pwd commands */
  2362. #define CD_PHYSICAL 1
  2363. #define CD_PRINT 2
  2364. static int
  2365. cdopt(void)
  2366. {
  2367. int flags = 0;
  2368. int i, j;
  2369. j = 'L';
  2370. while ((i = nextopt("LP")) != '\0') {
  2371. if (i != j) {
  2372. flags ^= CD_PHYSICAL;
  2373. j = i;
  2374. }
  2375. }
  2376. return flags;
  2377. }
  2378. /*
  2379. * Update curdir (the name of the current directory) in response to a
  2380. * cd command.
  2381. */
  2382. static const char *
  2383. updatepwd(const char *dir)
  2384. {
  2385. char *new;
  2386. char *p;
  2387. char *cdcomppath;
  2388. const char *lim;
  2389. cdcomppath = sstrdup(dir);
  2390. STARTSTACKSTR(new);
  2391. if (*dir != '/') {
  2392. if (curdir == nullstr)
  2393. return 0;
  2394. new = stack_putstr(curdir, new);
  2395. }
  2396. new = makestrspace(strlen(dir) + 2, new);
  2397. lim = (char *)stackblock() + 1;
  2398. if (*dir != '/') {
  2399. if (new[-1] != '/')
  2400. USTPUTC('/', new);
  2401. if (new > lim && *lim == '/')
  2402. lim++;
  2403. } else {
  2404. USTPUTC('/', new);
  2405. cdcomppath++;
  2406. if (dir[1] == '/' && dir[2] != '/') {
  2407. USTPUTC('/', new);
  2408. cdcomppath++;
  2409. lim++;
  2410. }
  2411. }
  2412. p = strtok(cdcomppath, "/");
  2413. while (p) {
  2414. switch (*p) {
  2415. case '.':
  2416. if (p[1] == '.' && p[2] == '\0') {
  2417. while (new > lim) {
  2418. STUNPUTC(new);
  2419. if (new[-1] == '/')
  2420. break;
  2421. }
  2422. break;
  2423. }
  2424. if (p[1] == '\0')
  2425. break;
  2426. /* fall through */
  2427. default:
  2428. new = stack_putstr(p, new);
  2429. USTPUTC('/', new);
  2430. }
  2431. p = strtok(NULL, "/");
  2432. }
  2433. if (new > lim)
  2434. STUNPUTC(new);
  2435. *new = 0;
  2436. return stackblock();
  2437. }
  2438. /*
  2439. * Find out what the current directory is. If we already know the current
  2440. * directory, this routine returns immediately.
  2441. */
  2442. static char *
  2443. getpwd(void)
  2444. {
  2445. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2446. return dir ? dir : nullstr;
  2447. }
  2448. static void
  2449. setpwd(const char *val, int setold)
  2450. {
  2451. char *oldcur, *dir;
  2452. oldcur = dir = curdir;
  2453. if (setold) {
  2454. setvar("OLDPWD", oldcur, VEXPORT);
  2455. }
  2456. INT_OFF;
  2457. if (physdir != nullstr) {
  2458. if (physdir != oldcur)
  2459. free(physdir);
  2460. physdir = nullstr;
  2461. }
  2462. if (oldcur == val || !val) {
  2463. char *s = getpwd();
  2464. physdir = s;
  2465. if (!val)
  2466. dir = s;
  2467. } else
  2468. dir = ckstrdup(val);
  2469. if (oldcur != dir && oldcur != nullstr) {
  2470. free(oldcur);
  2471. }
  2472. curdir = dir;
  2473. INT_ON;
  2474. setvar("PWD", dir, VEXPORT);
  2475. }
  2476. static void hashcd(void);
  2477. /*
  2478. * Actually do the chdir. We also call hashcd to let other routines
  2479. * know that the current directory has changed.
  2480. */
  2481. static int
  2482. docd(const char *dest, int flags)
  2483. {
  2484. const char *dir = NULL;
  2485. int err;
  2486. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2487. INT_OFF;
  2488. if (!(flags & CD_PHYSICAL)) {
  2489. dir = updatepwd(dest);
  2490. if (dir)
  2491. dest = dir;
  2492. }
  2493. err = chdir(dest);
  2494. if (err)
  2495. goto out;
  2496. setpwd(dir, 1);
  2497. hashcd();
  2498. out:
  2499. INT_ON;
  2500. return err;
  2501. }
  2502. static int FAST_FUNC
  2503. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2504. {
  2505. const char *dest;
  2506. const char *path;
  2507. const char *p;
  2508. char c;
  2509. struct stat statb;
  2510. int flags;
  2511. flags = cdopt();
  2512. dest = *argptr;
  2513. if (!dest)
  2514. dest = bltinlookup("HOME");
  2515. else if (LONE_DASH(dest)) {
  2516. dest = bltinlookup("OLDPWD");
  2517. flags |= CD_PRINT;
  2518. }
  2519. if (!dest)
  2520. dest = nullstr;
  2521. if (*dest == '/')
  2522. goto step6;
  2523. if (*dest == '.') {
  2524. c = dest[1];
  2525. dotdot:
  2526. switch (c) {
  2527. case '\0':
  2528. case '/':
  2529. goto step6;
  2530. case '.':
  2531. c = dest[2];
  2532. if (c != '.')
  2533. goto dotdot;
  2534. }
  2535. }
  2536. if (!*dest)
  2537. dest = ".";
  2538. path = bltinlookup("CDPATH");
  2539. while (path) {
  2540. c = *path;
  2541. p = path_advance(&path, dest);
  2542. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2543. if (c && c != ':')
  2544. flags |= CD_PRINT;
  2545. docd:
  2546. if (!docd(p, flags))
  2547. goto out;
  2548. goto err;
  2549. }
  2550. }
  2551. step6:
  2552. p = dest;
  2553. goto docd;
  2554. err:
  2555. ash_msg_and_raise_perror("can't cd to %s", dest);
  2556. /* NOTREACHED */
  2557. out:
  2558. if (flags & CD_PRINT)
  2559. out1fmt("%s\n", curdir);
  2560. return 0;
  2561. }
  2562. static int FAST_FUNC
  2563. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2564. {
  2565. int flags;
  2566. const char *dir = curdir;
  2567. flags = cdopt();
  2568. if (flags) {
  2569. if (physdir == nullstr)
  2570. setpwd(dir, 0);
  2571. dir = physdir;
  2572. }
  2573. out1fmt("%s\n", dir);
  2574. return 0;
  2575. }
  2576. /* ============ ... */
  2577. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2578. /* Syntax classes */
  2579. #define CWORD 0 /* character is nothing special */
  2580. #define CNL 1 /* newline character */
  2581. #define CBACK 2 /* a backslash character */
  2582. #define CSQUOTE 3 /* single quote */
  2583. #define CDQUOTE 4 /* double quote */
  2584. #define CENDQUOTE 5 /* a terminating quote */
  2585. #define CBQUOTE 6 /* backwards single quote */
  2586. #define CVAR 7 /* a dollar sign */
  2587. #define CENDVAR 8 /* a '}' character */
  2588. #define CLP 9 /* a left paren in arithmetic */
  2589. #define CRP 10 /* a right paren in arithmetic */
  2590. #define CENDFILE 11 /* end of file */
  2591. #define CCTL 12 /* like CWORD, except it must be escaped */
  2592. #define CSPCL 13 /* these terminate a word */
  2593. #define CIGN 14 /* character should be ignored */
  2594. #define PEOF 256
  2595. #if ENABLE_ASH_ALIAS
  2596. # define PEOA 257
  2597. #endif
  2598. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2599. #if ENABLE_FEATURE_SH_MATH
  2600. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2601. #else
  2602. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2603. #endif
  2604. static const uint16_t S_I_T[] ALIGN2 = {
  2605. #if ENABLE_ASH_ALIAS
  2606. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2607. #endif
  2608. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2609. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2610. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2611. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2612. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2613. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2614. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2615. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2616. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2617. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2618. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2619. #if !USE_SIT_FUNCTION
  2620. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2621. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2622. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2623. #endif
  2624. #undef SIT_ITEM
  2625. };
  2626. /* Constants below must match table above */
  2627. enum {
  2628. #if ENABLE_ASH_ALIAS
  2629. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2630. #endif
  2631. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2632. CNL_CNL_CNL_CNL , /* 2 */
  2633. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2634. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2635. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2636. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2637. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2638. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2639. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2640. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2641. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2642. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2643. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2644. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2645. };
  2646. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2647. * caller must ensure proper cast on it if c is *char_ptr!
  2648. */
  2649. #if USE_SIT_FUNCTION
  2650. static int
  2651. SIT(int c, int syntax)
  2652. {
  2653. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2654. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2655. /*
  2656. * This causes '/' to be prepended with CTLESC in dquoted string,
  2657. * making "./file"* treated incorrectly because we feed
  2658. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2659. * The "homegrown" glob implementation is okay with that,
  2660. * but glibc one isn't. With '/' always treated as CWORD,
  2661. * both work fine.
  2662. */
  2663. # if ENABLE_ASH_ALIAS
  2664. static const uint8_t syntax_index_table[] ALIGN1 = {
  2665. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2666. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2667. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2668. 11, 3 /* "}~" */
  2669. };
  2670. # else
  2671. static const uint8_t syntax_index_table[] ALIGN1 = {
  2672. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2673. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2674. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2675. 10, 2 /* "}~" */
  2676. };
  2677. # endif
  2678. const char *s;
  2679. int indx;
  2680. if (c == PEOF)
  2681. return CENDFILE;
  2682. # if ENABLE_ASH_ALIAS
  2683. if (c == PEOA)
  2684. indx = 0;
  2685. else
  2686. # endif
  2687. {
  2688. /* Cast is purely for paranoia here,
  2689. * just in case someone passed signed char to us */
  2690. if ((unsigned char)c >= CTL_FIRST
  2691. && (unsigned char)c <= CTL_LAST
  2692. ) {
  2693. return CCTL;
  2694. }
  2695. s = strchrnul(spec_symbls, c);
  2696. if (*s == '\0')
  2697. return CWORD;
  2698. indx = syntax_index_table[s - spec_symbls];
  2699. }
  2700. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2701. }
  2702. #else /* !USE_SIT_FUNCTION */
  2703. static const uint8_t syntax_index_table[] ALIGN1 = {
  2704. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2705. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2706. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2707. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2708. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2709. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2710. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2711. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2712. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2713. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2714. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2715. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2716. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2717. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2718. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2719. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2720. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2721. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2722. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2723. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2724. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2725. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2726. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2727. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2728. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2729. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2730. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2731. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2732. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2733. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2734. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2735. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2736. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2737. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2738. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2739. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2740. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2741. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2742. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2743. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2744. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2745. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2746. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2747. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2748. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2749. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2750. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2751. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2752. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2753. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2755. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2756. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2757. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2758. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2759. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2760. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2761. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2762. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2763. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2764. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2765. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2766. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2767. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2768. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2769. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2770. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2771. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2781. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2798. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2799. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2800. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2803. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2831. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2832. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2833. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2835. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2836. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2837. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2838. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2839. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2840. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2841. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2842. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2843. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2844. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2897. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2899. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2902. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2903. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2904. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2905. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2906. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2922. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2923. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2924. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2925. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2926. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2927. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2928. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2929. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2930. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2931. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2932. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2933. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2934. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2935. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2936. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2937. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2963. # if ENABLE_ASH_ALIAS
  2964. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2965. # endif
  2966. };
  2967. #if 1
  2968. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2969. #else /* debug version, caught one signed char bug */
  2970. # define SIT(c, syntax) \
  2971. ({ \
  2972. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  2973. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2974. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  2975. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2976. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  2977. })
  2978. #endif
  2979. #endif /* !USE_SIT_FUNCTION */
  2980. /* ============ Alias handling */
  2981. #if ENABLE_ASH_ALIAS
  2982. #define ALIASINUSE 1
  2983. #define ALIASDEAD 2
  2984. struct alias {
  2985. struct alias *next;
  2986. char *name;
  2987. char *val;
  2988. int flag;
  2989. };
  2990. static struct alias **atab; // [ATABSIZE];
  2991. #define INIT_G_alias() do { \
  2992. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2993. } while (0)
  2994. static struct alias **
  2995. __lookupalias(const char *name)
  2996. {
  2997. unsigned int hashval;
  2998. struct alias **app;
  2999. const char *p;
  3000. unsigned int ch;
  3001. p = name;
  3002. ch = (unsigned char)*p;
  3003. hashval = ch << 4;
  3004. while (ch) {
  3005. hashval += ch;
  3006. ch = (unsigned char)*++p;
  3007. }
  3008. app = &atab[hashval % ATABSIZE];
  3009. for (; *app; app = &(*app)->next) {
  3010. if (strcmp(name, (*app)->name) == 0) {
  3011. break;
  3012. }
  3013. }
  3014. return app;
  3015. }
  3016. static struct alias *
  3017. lookupalias(const char *name, int check)
  3018. {
  3019. struct alias *ap = *__lookupalias(name);
  3020. if (check && ap && (ap->flag & ALIASINUSE))
  3021. return NULL;
  3022. return ap;
  3023. }
  3024. static struct alias *
  3025. freealias(struct alias *ap)
  3026. {
  3027. struct alias *next;
  3028. if (ap->flag & ALIASINUSE) {
  3029. ap->flag |= ALIASDEAD;
  3030. return ap;
  3031. }
  3032. next = ap->next;
  3033. free(ap->name);
  3034. free(ap->val);
  3035. free(ap);
  3036. return next;
  3037. }
  3038. static void
  3039. setalias(const char *name, const char *val)
  3040. {
  3041. struct alias *ap, **app;
  3042. app = __lookupalias(name);
  3043. ap = *app;
  3044. INT_OFF;
  3045. if (ap) {
  3046. if (!(ap->flag & ALIASINUSE)) {
  3047. free(ap->val);
  3048. }
  3049. ap->val = ckstrdup(val);
  3050. ap->flag &= ~ALIASDEAD;
  3051. } else {
  3052. /* not found */
  3053. ap = ckzalloc(sizeof(struct alias));
  3054. ap->name = ckstrdup(name);
  3055. ap->val = ckstrdup(val);
  3056. /*ap->flag = 0; - ckzalloc did it */
  3057. /*ap->next = NULL;*/
  3058. *app = ap;
  3059. }
  3060. INT_ON;
  3061. }
  3062. static int
  3063. unalias(const char *name)
  3064. {
  3065. struct alias **app;
  3066. app = __lookupalias(name);
  3067. if (*app) {
  3068. INT_OFF;
  3069. *app = freealias(*app);
  3070. INT_ON;
  3071. return 0;
  3072. }
  3073. return 1;
  3074. }
  3075. static void
  3076. rmaliases(void)
  3077. {
  3078. struct alias *ap, **app;
  3079. int i;
  3080. INT_OFF;
  3081. for (i = 0; i < ATABSIZE; i++) {
  3082. app = &atab[i];
  3083. for (ap = *app; ap; ap = *app) {
  3084. *app = freealias(*app);
  3085. if (ap == *app) {
  3086. app = &ap->next;
  3087. }
  3088. }
  3089. }
  3090. INT_ON;
  3091. }
  3092. static void
  3093. printalias(const struct alias *ap)
  3094. {
  3095. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3096. }
  3097. /*
  3098. * TODO - sort output
  3099. */
  3100. static int FAST_FUNC
  3101. aliascmd(int argc UNUSED_PARAM, char **argv)
  3102. {
  3103. char *n, *v;
  3104. int ret = 0;
  3105. struct alias *ap;
  3106. if (!argv[1]) {
  3107. int i;
  3108. for (i = 0; i < ATABSIZE; i++) {
  3109. for (ap = atab[i]; ap; ap = ap->next) {
  3110. printalias(ap);
  3111. }
  3112. }
  3113. return 0;
  3114. }
  3115. while ((n = *++argv) != NULL) {
  3116. v = strchr(n+1, '=');
  3117. if (v == NULL) { /* n+1: funny ksh stuff */
  3118. ap = *__lookupalias(n);
  3119. if (ap == NULL) {
  3120. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3121. ret = 1;
  3122. } else
  3123. printalias(ap);
  3124. } else {
  3125. *v++ = '\0';
  3126. setalias(n, v);
  3127. }
  3128. }
  3129. return ret;
  3130. }
  3131. static int FAST_FUNC
  3132. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3133. {
  3134. int i;
  3135. while (nextopt("a") != '\0') {
  3136. rmaliases();
  3137. return 0;
  3138. }
  3139. for (i = 0; *argptr; argptr++) {
  3140. if (unalias(*argptr)) {
  3141. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3142. i = 1;
  3143. }
  3144. }
  3145. return i;
  3146. }
  3147. #endif /* ASH_ALIAS */
  3148. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3149. #define FORK_FG 0
  3150. #define FORK_BG 1
  3151. #define FORK_NOJOB 2
  3152. /* mode flags for showjob(s) */
  3153. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3154. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3155. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3156. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3157. /*
  3158. * A job structure contains information about a job. A job is either a
  3159. * single process or a set of processes contained in a pipeline. In the
  3160. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3161. * array of pids.
  3162. */
  3163. struct procstat {
  3164. pid_t ps_pid; /* process id */
  3165. int ps_status; /* last process status from wait() */
  3166. char *ps_cmd; /* text of command being run */
  3167. };
  3168. struct job {
  3169. struct procstat ps0; /* status of process */
  3170. struct procstat *ps; /* status or processes when more than one */
  3171. #if JOBS
  3172. int stopstatus; /* status of a stopped job */
  3173. #endif
  3174. unsigned nprocs; /* number of processes */
  3175. #define JOBRUNNING 0 /* at least one proc running */
  3176. #define JOBSTOPPED 1 /* all procs are stopped */
  3177. #define JOBDONE 2 /* all procs are completed */
  3178. unsigned
  3179. state: 8,
  3180. #if JOBS
  3181. sigint: 1, /* job was killed by SIGINT */
  3182. jobctl: 1, /* job running under job control */
  3183. #endif
  3184. waited: 1, /* true if this entry has been waited for */
  3185. used: 1, /* true if this entry is in used */
  3186. changed: 1; /* true if status has changed */
  3187. struct job *prev_job; /* previous job */
  3188. };
  3189. static struct job *makejob(/*union node *,*/ int);
  3190. static int forkshell(struct job *, union node *, int);
  3191. static int waitforjob(struct job *);
  3192. #if !JOBS
  3193. enum { doing_jobctl = 0 };
  3194. #define setjobctl(on) do {} while (0)
  3195. #else
  3196. static smallint doing_jobctl; //references:8
  3197. static void setjobctl(int);
  3198. #endif
  3199. /*
  3200. * Ignore a signal.
  3201. */
  3202. static void
  3203. ignoresig(int signo)
  3204. {
  3205. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3206. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3207. /* No, need to do it */
  3208. signal(signo, SIG_IGN);
  3209. }
  3210. sigmode[signo - 1] = S_HARD_IGN;
  3211. }
  3212. /*
  3213. * Only one usage site - in setsignal()
  3214. */
  3215. static void
  3216. signal_handler(int signo)
  3217. {
  3218. if (signo == SIGCHLD) {
  3219. got_sigchld = 1;
  3220. if (!trap[SIGCHLD])
  3221. return;
  3222. }
  3223. gotsig[signo - 1] = 1;
  3224. pending_sig = signo;
  3225. if (signo == SIGINT && !trap[SIGINT]) {
  3226. if (!suppress_int) {
  3227. pending_sig = 0;
  3228. raise_interrupt(); /* does not return */
  3229. }
  3230. pending_int = 1;
  3231. }
  3232. }
  3233. /*
  3234. * Set the signal handler for the specified signal. The routine figures
  3235. * out what it should be set to.
  3236. */
  3237. static void
  3238. setsignal(int signo)
  3239. {
  3240. char *t;
  3241. char cur_act, new_act;
  3242. struct sigaction act;
  3243. t = trap[signo];
  3244. new_act = S_DFL;
  3245. if (t != NULL) { /* trap for this sig is set */
  3246. new_act = S_CATCH;
  3247. if (t[0] == '\0') /* trap is "": ignore this sig */
  3248. new_act = S_IGN;
  3249. }
  3250. if (rootshell && new_act == S_DFL) {
  3251. switch (signo) {
  3252. case SIGINT:
  3253. if (iflag || minusc || sflag == 0)
  3254. new_act = S_CATCH;
  3255. break;
  3256. case SIGQUIT:
  3257. #if DEBUG
  3258. if (debug)
  3259. break;
  3260. #endif
  3261. /* man bash:
  3262. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3263. * commands run by bash have signal handlers
  3264. * set to the values inherited by the shell
  3265. * from its parent". */
  3266. new_act = S_IGN;
  3267. break;
  3268. case SIGTERM:
  3269. if (iflag)
  3270. new_act = S_IGN;
  3271. break;
  3272. #if JOBS
  3273. case SIGTSTP:
  3274. case SIGTTOU:
  3275. if (mflag)
  3276. new_act = S_IGN;
  3277. break;
  3278. #endif
  3279. }
  3280. }
  3281. /* if !rootshell, we reset SIGQUIT to DFL,
  3282. * whereas we have to restore it to what shell got on entry.
  3283. * This is handled by the fact that if signal was IGNored on entry,
  3284. * then cur_act is S_HARD_IGN and we never change its sigaction
  3285. * (see code below).
  3286. */
  3287. if (signo == SIGCHLD)
  3288. new_act = S_CATCH;
  3289. t = &sigmode[signo - 1];
  3290. cur_act = *t;
  3291. if (cur_act == 0) {
  3292. /* current setting is not yet known */
  3293. if (sigaction(signo, NULL, &act)) {
  3294. /* pretend it worked; maybe we should give a warning,
  3295. * but other shells don't. We don't alter sigmode,
  3296. * so we retry every time.
  3297. * btw, in Linux it never fails. --vda */
  3298. return;
  3299. }
  3300. if (act.sa_handler == SIG_IGN) {
  3301. cur_act = S_HARD_IGN;
  3302. if (mflag
  3303. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3304. ) {
  3305. cur_act = S_IGN; /* don't hard ignore these */
  3306. }
  3307. }
  3308. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3309. /* installing SIG_DFL over SIG_DFL is a no-op */
  3310. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3311. *t = S_DFL;
  3312. return;
  3313. }
  3314. }
  3315. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3316. return;
  3317. *t = new_act;
  3318. act.sa_handler = SIG_DFL;
  3319. switch (new_act) {
  3320. case S_CATCH:
  3321. act.sa_handler = signal_handler;
  3322. break;
  3323. case S_IGN:
  3324. act.sa_handler = SIG_IGN;
  3325. break;
  3326. }
  3327. /* flags and mask matter only if !DFL and !IGN, but we do it
  3328. * for all cases for more deterministic behavior:
  3329. */
  3330. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3331. sigfillset(&act.sa_mask);
  3332. sigaction_set(signo, &act);
  3333. }
  3334. /* mode flags for set_curjob */
  3335. #define CUR_DELETE 2
  3336. #define CUR_RUNNING 1
  3337. #define CUR_STOPPED 0
  3338. #if JOBS
  3339. /* pgrp of shell on invocation */
  3340. static int initialpgrp; //references:2
  3341. static int ttyfd = -1; //5
  3342. #endif
  3343. /* array of jobs */
  3344. static struct job *jobtab; //5
  3345. /* size of array */
  3346. static unsigned njobs; //4
  3347. /* current job */
  3348. static struct job *curjob; //lots
  3349. /* number of presumed living untracked jobs */
  3350. static int jobless; //4
  3351. #if 0
  3352. /* Bash has a feature: it restores termios after a successful wait for
  3353. * a foreground job which had at least one stopped or sigkilled member.
  3354. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3355. * properly restoring tty state. Should we do this too?
  3356. * A reproducer: ^Z an interactive python:
  3357. *
  3358. * # python
  3359. * Python 2.7.12 (...)
  3360. * >>> ^Z
  3361. * { python leaves tty in -icanon -echo state. We do survive that... }
  3362. * [1]+ Stopped python
  3363. * { ...however, next program (python #2) does not survive it well: }
  3364. * # python
  3365. * Python 2.7.12 (...)
  3366. * >>> Traceback (most recent call last):
  3367. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3368. * File "<stdin>", line 1, in <module>
  3369. * NameError: name 'qwerty' is not defined
  3370. *
  3371. * The implementation below is modeled on bash code and seems to work.
  3372. * However, I'm not sure we should do this. For one: what if I'd fg
  3373. * the stopped python instead? It'll be confused by "restored" tty state.
  3374. */
  3375. static struct termios shell_tty_info;
  3376. static void
  3377. get_tty_state(void)
  3378. {
  3379. if (rootshell && ttyfd >= 0)
  3380. tcgetattr(ttyfd, &shell_tty_info);
  3381. }
  3382. static void
  3383. set_tty_state(void)
  3384. {
  3385. /* if (rootshell) - caller ensures this */
  3386. if (ttyfd >= 0)
  3387. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3388. }
  3389. static int
  3390. job_signal_status(struct job *jp)
  3391. {
  3392. int status;
  3393. unsigned i;
  3394. struct procstat *ps = jp->ps;
  3395. for (i = 0; i < jp->nprocs; i++) {
  3396. status = ps[i].ps_status;
  3397. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3398. return status;
  3399. }
  3400. return 0;
  3401. }
  3402. static void
  3403. restore_tty_if_stopped_or_signaled(struct job *jp)
  3404. {
  3405. //TODO: check what happens if we come from waitforjob() in expbackq()
  3406. if (rootshell) {
  3407. int s = job_signal_status(jp);
  3408. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3409. set_tty_state();
  3410. }
  3411. }
  3412. #else
  3413. # define get_tty_state() ((void)0)
  3414. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3415. #endif
  3416. static void
  3417. set_curjob(struct job *jp, unsigned mode)
  3418. {
  3419. struct job *jp1;
  3420. struct job **jpp, **curp;
  3421. /* first remove from list */
  3422. jpp = curp = &curjob;
  3423. while (1) {
  3424. jp1 = *jpp;
  3425. if (jp1 == jp)
  3426. break;
  3427. jpp = &jp1->prev_job;
  3428. }
  3429. *jpp = jp1->prev_job;
  3430. /* Then re-insert in correct position */
  3431. jpp = curp;
  3432. switch (mode) {
  3433. default:
  3434. #if DEBUG
  3435. abort();
  3436. #endif
  3437. case CUR_DELETE:
  3438. /* job being deleted */
  3439. break;
  3440. case CUR_RUNNING:
  3441. /* newly created job or backgrounded job,
  3442. * put after all stopped jobs.
  3443. */
  3444. while (1) {
  3445. jp1 = *jpp;
  3446. #if JOBS
  3447. if (!jp1 || jp1->state != JOBSTOPPED)
  3448. #endif
  3449. break;
  3450. jpp = &jp1->prev_job;
  3451. }
  3452. /* FALLTHROUGH */
  3453. #if JOBS
  3454. case CUR_STOPPED:
  3455. #endif
  3456. /* newly stopped job - becomes curjob */
  3457. jp->prev_job = *jpp;
  3458. *jpp = jp;
  3459. break;
  3460. }
  3461. }
  3462. #if JOBS || DEBUG
  3463. static int
  3464. jobno(const struct job *jp)
  3465. {
  3466. return jp - jobtab + 1;
  3467. }
  3468. #endif
  3469. /*
  3470. * Convert a job name to a job structure.
  3471. */
  3472. #if !JOBS
  3473. #define getjob(name, getctl) getjob(name)
  3474. #endif
  3475. static struct job *
  3476. getjob(const char *name, int getctl)
  3477. {
  3478. struct job *jp;
  3479. struct job *found;
  3480. const char *err_msg = "%s: no such job";
  3481. unsigned num;
  3482. int c;
  3483. const char *p;
  3484. char *(*match)(const char *, const char *);
  3485. jp = curjob;
  3486. p = name;
  3487. if (!p)
  3488. goto currentjob;
  3489. if (*p != '%')
  3490. goto err;
  3491. c = *++p;
  3492. if (!c)
  3493. goto currentjob;
  3494. if (!p[1]) {
  3495. if (c == '+' || c == '%') {
  3496. currentjob:
  3497. err_msg = "No current job";
  3498. goto check;
  3499. }
  3500. if (c == '-') {
  3501. if (jp)
  3502. jp = jp->prev_job;
  3503. err_msg = "No previous job";
  3504. check:
  3505. if (!jp)
  3506. goto err;
  3507. goto gotit;
  3508. }
  3509. }
  3510. if (is_number(p)) {
  3511. num = atoi(p);
  3512. if (num > 0 && num <= njobs) {
  3513. jp = jobtab + num - 1;
  3514. if (jp->used)
  3515. goto gotit;
  3516. goto err;
  3517. }
  3518. }
  3519. match = prefix;
  3520. if (*p == '?') {
  3521. match = strstr;
  3522. p++;
  3523. }
  3524. found = NULL;
  3525. while (jp) {
  3526. if (match(jp->ps[0].ps_cmd, p)) {
  3527. if (found)
  3528. goto err;
  3529. found = jp;
  3530. err_msg = "%s: ambiguous";
  3531. }
  3532. jp = jp->prev_job;
  3533. }
  3534. if (!found)
  3535. goto err;
  3536. jp = found;
  3537. gotit:
  3538. #if JOBS
  3539. err_msg = "job %s not created under job control";
  3540. if (getctl && jp->jobctl == 0)
  3541. goto err;
  3542. #endif
  3543. return jp;
  3544. err:
  3545. ash_msg_and_raise_error(err_msg, name);
  3546. }
  3547. /*
  3548. * Mark a job structure as unused.
  3549. */
  3550. static void
  3551. freejob(struct job *jp)
  3552. {
  3553. struct procstat *ps;
  3554. int i;
  3555. INT_OFF;
  3556. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3557. if (ps->ps_cmd != nullstr)
  3558. free(ps->ps_cmd);
  3559. }
  3560. if (jp->ps != &jp->ps0)
  3561. free(jp->ps);
  3562. jp->used = 0;
  3563. set_curjob(jp, CUR_DELETE);
  3564. INT_ON;
  3565. }
  3566. #if JOBS
  3567. static void
  3568. xtcsetpgrp(int fd, pid_t pgrp)
  3569. {
  3570. if (tcsetpgrp(fd, pgrp))
  3571. ash_msg_and_raise_perror("can't set tty process group");
  3572. }
  3573. /*
  3574. * Turn job control on and off.
  3575. *
  3576. * Note: This code assumes that the third arg to ioctl is a character
  3577. * pointer, which is true on Berkeley systems but not System V. Since
  3578. * System V doesn't have job control yet, this isn't a problem now.
  3579. *
  3580. * Called with interrupts off.
  3581. */
  3582. static void
  3583. setjobctl(int on)
  3584. {
  3585. int fd;
  3586. int pgrp;
  3587. if (on == doing_jobctl || rootshell == 0)
  3588. return;
  3589. if (on) {
  3590. int ofd;
  3591. ofd = fd = open(_PATH_TTY, O_RDWR);
  3592. if (fd < 0) {
  3593. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3594. * That sometimes helps to acquire controlling tty.
  3595. * Obviously, a workaround for bugs when someone
  3596. * failed to provide a controlling tty to bash! :) */
  3597. fd = 2;
  3598. while (!isatty(fd))
  3599. if (--fd < 0)
  3600. goto out;
  3601. }
  3602. /* fd is a tty at this point */
  3603. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3604. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3605. close(ofd);
  3606. if (fd < 0)
  3607. goto out; /* F_DUPFD failed */
  3608. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3609. close_on_exec_on(fd);
  3610. while (1) { /* while we are in the background */
  3611. pgrp = tcgetpgrp(fd);
  3612. if (pgrp < 0) {
  3613. out:
  3614. ash_msg("can't access tty; job control turned off");
  3615. mflag = on = 0;
  3616. goto close;
  3617. }
  3618. if (pgrp == getpgrp())
  3619. break;
  3620. killpg(0, SIGTTIN);
  3621. }
  3622. initialpgrp = pgrp;
  3623. setsignal(SIGTSTP);
  3624. setsignal(SIGTTOU);
  3625. setsignal(SIGTTIN);
  3626. pgrp = rootpid;
  3627. setpgid(0, pgrp);
  3628. xtcsetpgrp(fd, pgrp);
  3629. } else {
  3630. /* turning job control off */
  3631. fd = ttyfd;
  3632. pgrp = initialpgrp;
  3633. /* was xtcsetpgrp, but this can make exiting ash
  3634. * loop forever if pty is already deleted */
  3635. tcsetpgrp(fd, pgrp);
  3636. setpgid(0, pgrp);
  3637. setsignal(SIGTSTP);
  3638. setsignal(SIGTTOU);
  3639. setsignal(SIGTTIN);
  3640. close:
  3641. if (fd >= 0)
  3642. close(fd);
  3643. fd = -1;
  3644. }
  3645. ttyfd = fd;
  3646. doing_jobctl = on;
  3647. }
  3648. static int FAST_FUNC
  3649. killcmd(int argc, char **argv)
  3650. {
  3651. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3652. int i = 1;
  3653. do {
  3654. if (argv[i][0] == '%') {
  3655. /*
  3656. * "kill %N" - job kill
  3657. * Converting to pgrp / pid kill
  3658. */
  3659. struct job *jp;
  3660. char *dst;
  3661. int j, n;
  3662. jp = getjob(argv[i], 0);
  3663. /*
  3664. * In jobs started under job control, we signal
  3665. * entire process group by kill -PGRP_ID.
  3666. * This happens, f.e., in interactive shell.
  3667. *
  3668. * Otherwise, we signal each child via
  3669. * kill PID1 PID2 PID3.
  3670. * Testcases:
  3671. * sh -c 'sleep 1|sleep 1 & kill %1'
  3672. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3673. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3674. */
  3675. n = jp->nprocs; /* can't be 0 (I hope) */
  3676. if (jp->jobctl)
  3677. n = 1;
  3678. dst = alloca(n * sizeof(int)*4);
  3679. argv[i] = dst;
  3680. for (j = 0; j < n; j++) {
  3681. struct procstat *ps = &jp->ps[j];
  3682. /* Skip non-running and not-stopped members
  3683. * (i.e. dead members) of the job
  3684. */
  3685. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3686. continue;
  3687. /*
  3688. * kill_main has matching code to expect
  3689. * leading space. Needed to not confuse
  3690. * negative pids with "kill -SIGNAL_NO" syntax
  3691. */
  3692. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3693. }
  3694. *dst = '\0';
  3695. }
  3696. } while (argv[++i]);
  3697. }
  3698. return kill_main(argc, argv);
  3699. }
  3700. static void
  3701. showpipe(struct job *jp /*, FILE *out*/)
  3702. {
  3703. struct procstat *ps;
  3704. struct procstat *psend;
  3705. psend = jp->ps + jp->nprocs;
  3706. for (ps = jp->ps + 1; ps < psend; ps++)
  3707. printf(" | %s", ps->ps_cmd);
  3708. newline_and_flush(stdout);
  3709. flush_stdout_stderr();
  3710. }
  3711. static int
  3712. restartjob(struct job *jp, int mode)
  3713. {
  3714. struct procstat *ps;
  3715. int i;
  3716. int status;
  3717. pid_t pgid;
  3718. INT_OFF;
  3719. if (jp->state == JOBDONE)
  3720. goto out;
  3721. jp->state = JOBRUNNING;
  3722. pgid = jp->ps[0].ps_pid;
  3723. if (mode == FORK_FG) {
  3724. get_tty_state();
  3725. xtcsetpgrp(ttyfd, pgid);
  3726. }
  3727. killpg(pgid, SIGCONT);
  3728. ps = jp->ps;
  3729. i = jp->nprocs;
  3730. do {
  3731. if (WIFSTOPPED(ps->ps_status)) {
  3732. ps->ps_status = -1;
  3733. }
  3734. ps++;
  3735. } while (--i);
  3736. out:
  3737. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3738. INT_ON;
  3739. return status;
  3740. }
  3741. static int FAST_FUNC
  3742. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3743. {
  3744. struct job *jp;
  3745. int mode;
  3746. int retval;
  3747. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3748. nextopt(nullstr);
  3749. argv = argptr;
  3750. do {
  3751. jp = getjob(*argv, 1);
  3752. if (mode == FORK_BG) {
  3753. set_curjob(jp, CUR_RUNNING);
  3754. printf("[%d] ", jobno(jp));
  3755. }
  3756. out1str(jp->ps[0].ps_cmd);
  3757. showpipe(jp /*, stdout*/);
  3758. retval = restartjob(jp, mode);
  3759. } while (*argv && *++argv);
  3760. return retval;
  3761. }
  3762. #endif
  3763. static int
  3764. sprint_status48(char *s, int status, int sigonly)
  3765. {
  3766. int col;
  3767. int st;
  3768. col = 0;
  3769. if (!WIFEXITED(status)) {
  3770. #if JOBS
  3771. if (WIFSTOPPED(status))
  3772. st = WSTOPSIG(status);
  3773. else
  3774. #endif
  3775. st = WTERMSIG(status);
  3776. if (sigonly) {
  3777. if (st == SIGINT || st == SIGPIPE)
  3778. goto out;
  3779. #if JOBS
  3780. if (WIFSTOPPED(status))
  3781. goto out;
  3782. #endif
  3783. }
  3784. st &= 0x7f;
  3785. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3786. col = fmtstr(s, 32, strsignal(st));
  3787. if (WCOREDUMP(status)) {
  3788. strcpy(s + col, " (core dumped)");
  3789. col += sizeof(" (core dumped)")-1;
  3790. }
  3791. } else if (!sigonly) {
  3792. st = WEXITSTATUS(status);
  3793. col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3794. }
  3795. out:
  3796. return col;
  3797. }
  3798. static int
  3799. wait_block_or_sig(int *status)
  3800. {
  3801. int pid;
  3802. do {
  3803. sigset_t mask;
  3804. /* Poll all children for changes in their state */
  3805. got_sigchld = 0;
  3806. /* if job control is active, accept stopped processes too */
  3807. pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
  3808. if (pid != 0)
  3809. break; /* Error (e.g. EINTR, ECHILD) or pid */
  3810. /* Children exist, but none are ready. Sleep until interesting signal */
  3811. #if 1
  3812. sigfillset(&mask);
  3813. sigprocmask(SIG_SETMASK, &mask, &mask);
  3814. while (!got_sigchld && !pending_sig)
  3815. sigsuspend(&mask);
  3816. sigprocmask(SIG_SETMASK, &mask, NULL);
  3817. #else /* unsafe: a signal can set pending_sig after check, but before pause() */
  3818. while (!got_sigchld && !pending_sig)
  3819. pause();
  3820. #endif
  3821. /* If it was SIGCHLD, poll children again */
  3822. } while (got_sigchld);
  3823. return pid;
  3824. }
  3825. #define DOWAIT_NONBLOCK 0
  3826. #define DOWAIT_BLOCK 1
  3827. #define DOWAIT_BLOCK_OR_SIG 2
  3828. static int
  3829. dowait(int block, struct job *job)
  3830. {
  3831. int pid;
  3832. int status;
  3833. struct job *jp;
  3834. struct job *thisjob = NULL;
  3835. TRACE(("dowait(0x%x) called\n", block));
  3836. /* It's wrong to call waitpid() outside of INT_OFF region:
  3837. * signal can arrive just after syscall return and handler can
  3838. * longjmp away, losing stop/exit notification processing.
  3839. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3840. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3841. *
  3842. * However, for "wait" builtin it is wrong to simply call waitpid()
  3843. * in INT_OFF region: "wait" needs to wait for any running job
  3844. * to change state, but should exit on any trap too.
  3845. * In INT_OFF region, a signal just before syscall entry can set
  3846. * pending_sig variables, but we can't check them, and we would
  3847. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3848. *
  3849. * Because of this, we run inside INT_OFF, but use a special routine
  3850. * which combines waitpid() and sigsuspend().
  3851. * This is the reason why we need to have a handler for SIGCHLD:
  3852. * SIG_DFL handler does not wake sigsuspend().
  3853. */
  3854. INT_OFF;
  3855. if (block == DOWAIT_BLOCK_OR_SIG) {
  3856. pid = wait_block_or_sig(&status);
  3857. } else {
  3858. int wait_flags = 0;
  3859. if (block == DOWAIT_NONBLOCK)
  3860. wait_flags = WNOHANG;
  3861. /* if job control is active, accept stopped processes too */
  3862. if (doing_jobctl)
  3863. wait_flags |= WUNTRACED;
  3864. /* NB: _not_ safe_waitpid, we need to detect EINTR */
  3865. pid = waitpid(-1, &status, wait_flags);
  3866. }
  3867. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3868. pid, status, errno, strerror(errno)));
  3869. if (pid <= 0)
  3870. goto out;
  3871. thisjob = NULL;
  3872. for (jp = curjob; jp; jp = jp->prev_job) {
  3873. int jobstate;
  3874. struct procstat *ps;
  3875. struct procstat *psend;
  3876. if (jp->state == JOBDONE)
  3877. continue;
  3878. jobstate = JOBDONE;
  3879. ps = jp->ps;
  3880. psend = ps + jp->nprocs;
  3881. do {
  3882. if (ps->ps_pid == pid) {
  3883. TRACE(("Job %d: changing status of proc %d "
  3884. "from 0x%x to 0x%x\n",
  3885. jobno(jp), pid, ps->ps_status, status));
  3886. ps->ps_status = status;
  3887. thisjob = jp;
  3888. }
  3889. if (ps->ps_status == -1)
  3890. jobstate = JOBRUNNING;
  3891. #if JOBS
  3892. if (jobstate == JOBRUNNING)
  3893. continue;
  3894. if (WIFSTOPPED(ps->ps_status)) {
  3895. jp->stopstatus = ps->ps_status;
  3896. jobstate = JOBSTOPPED;
  3897. }
  3898. #endif
  3899. } while (++ps < psend);
  3900. if (!thisjob)
  3901. continue;
  3902. /* Found the job where one of its processes changed its state.
  3903. * Is there at least one live and running process in this job? */
  3904. if (jobstate != JOBRUNNING) {
  3905. /* No. All live processes in the job are stopped
  3906. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3907. */
  3908. thisjob->changed = 1;
  3909. if (thisjob->state != jobstate) {
  3910. TRACE(("Job %d: changing state from %d to %d\n",
  3911. jobno(thisjob), thisjob->state, jobstate));
  3912. thisjob->state = jobstate;
  3913. #if JOBS
  3914. if (jobstate == JOBSTOPPED)
  3915. set_curjob(thisjob, CUR_STOPPED);
  3916. #endif
  3917. }
  3918. }
  3919. goto out;
  3920. }
  3921. /* The process wasn't found in job list */
  3922. #if JOBS
  3923. if (!WIFSTOPPED(status))
  3924. jobless--;
  3925. #endif
  3926. out:
  3927. INT_ON;
  3928. if (thisjob && thisjob == job) {
  3929. char s[48 + 1];
  3930. int len;
  3931. len = sprint_status48(s, status, 1);
  3932. if (len) {
  3933. s[len] = '\n';
  3934. s[len + 1] = '\0';
  3935. out2str(s);
  3936. }
  3937. }
  3938. return pid;
  3939. }
  3940. #if JOBS
  3941. static void
  3942. showjob(struct job *jp, int mode)
  3943. {
  3944. struct procstat *ps;
  3945. struct procstat *psend;
  3946. int col;
  3947. int indent_col;
  3948. char s[16 + 16 + 48];
  3949. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  3950. ps = jp->ps;
  3951. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3952. /* just output process (group) id of pipeline */
  3953. fprintf(out, "%d\n", ps->ps_pid);
  3954. return;
  3955. }
  3956. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3957. indent_col = col;
  3958. if (jp == curjob)
  3959. s[col - 3] = '+';
  3960. else if (curjob && jp == curjob->prev_job)
  3961. s[col - 3] = '-';
  3962. if (mode & SHOW_PIDS)
  3963. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3964. psend = ps + jp->nprocs;
  3965. if (jp->state == JOBRUNNING) {
  3966. strcpy(s + col, "Running");
  3967. col += sizeof("Running") - 1;
  3968. } else {
  3969. int status = psend[-1].ps_status;
  3970. if (jp->state == JOBSTOPPED)
  3971. status = jp->stopstatus;
  3972. col += sprint_status48(s + col, status, 0);
  3973. }
  3974. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3975. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3976. * or prints several "PID | <cmdN>" lines,
  3977. * depending on SHOW_PIDS bit.
  3978. * We do not print status of individual processes
  3979. * between PID and <cmdN>. bash does it, but not very well:
  3980. * first line shows overall job status, not process status,
  3981. * making it impossible to know 1st process status.
  3982. */
  3983. goto start;
  3984. do {
  3985. /* for each process */
  3986. s[0] = '\0';
  3987. col = 33;
  3988. if (mode & SHOW_PIDS)
  3989. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3990. start:
  3991. fprintf(out, "%s%*c%s%s",
  3992. s,
  3993. 33 - col >= 0 ? 33 - col : 0, ' ',
  3994. ps == jp->ps ? "" : "| ",
  3995. ps->ps_cmd
  3996. );
  3997. } while (++ps != psend);
  3998. newline_and_flush(out);
  3999. jp->changed = 0;
  4000. if (jp->state == JOBDONE) {
  4001. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4002. freejob(jp);
  4003. }
  4004. }
  4005. /*
  4006. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4007. * statuses have changed since the last call to showjobs.
  4008. */
  4009. static void
  4010. showjobs(int mode)
  4011. {
  4012. struct job *jp;
  4013. TRACE(("showjobs(0x%x) called\n", mode));
  4014. /* Handle all finished jobs */
  4015. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4016. continue;
  4017. for (jp = curjob; jp; jp = jp->prev_job) {
  4018. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4019. showjob(jp, mode);
  4020. }
  4021. }
  4022. }
  4023. static int FAST_FUNC
  4024. jobscmd(int argc UNUSED_PARAM, char **argv)
  4025. {
  4026. int mode, m;
  4027. mode = 0;
  4028. while ((m = nextopt("lp")) != '\0') {
  4029. if (m == 'l')
  4030. mode |= SHOW_PIDS;
  4031. else
  4032. mode |= SHOW_ONLY_PGID;
  4033. }
  4034. argv = argptr;
  4035. if (*argv) {
  4036. do
  4037. showjob(getjob(*argv, 0), mode);
  4038. while (*++argv);
  4039. } else {
  4040. showjobs(mode);
  4041. }
  4042. return 0;
  4043. }
  4044. #endif /* JOBS */
  4045. /* Called only on finished or stopped jobs (no members are running) */
  4046. static int
  4047. getstatus(struct job *job)
  4048. {
  4049. int status;
  4050. int retval;
  4051. struct procstat *ps;
  4052. /* Fetch last member's status */
  4053. ps = job->ps + job->nprocs - 1;
  4054. status = ps->ps_status;
  4055. if (pipefail) {
  4056. /* "set -o pipefail" mode: use last _nonzero_ status */
  4057. while (status == 0 && --ps >= job->ps)
  4058. status = ps->ps_status;
  4059. }
  4060. retval = WEXITSTATUS(status);
  4061. if (!WIFEXITED(status)) {
  4062. #if JOBS
  4063. retval = WSTOPSIG(status);
  4064. if (!WIFSTOPPED(status))
  4065. #endif
  4066. {
  4067. /* XXX: limits number of signals */
  4068. retval = WTERMSIG(status);
  4069. #if JOBS
  4070. if (retval == SIGINT)
  4071. job->sigint = 1;
  4072. #endif
  4073. }
  4074. retval += 128;
  4075. }
  4076. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4077. jobno(job), job->nprocs, status, retval));
  4078. return retval;
  4079. }
  4080. static int FAST_FUNC
  4081. waitcmd(int argc UNUSED_PARAM, char **argv)
  4082. {
  4083. struct job *job;
  4084. int retval;
  4085. struct job *jp;
  4086. nextopt(nullstr);
  4087. retval = 0;
  4088. argv = argptr;
  4089. if (!*argv) {
  4090. /* wait for all jobs */
  4091. for (;;) {
  4092. jp = curjob;
  4093. while (1) {
  4094. if (!jp) /* no running procs */
  4095. goto ret;
  4096. if (jp->state == JOBRUNNING)
  4097. break;
  4098. jp->waited = 1;
  4099. jp = jp->prev_job;
  4100. }
  4101. /* man bash:
  4102. * "When bash is waiting for an asynchronous command via
  4103. * the wait builtin, the reception of a signal for which a trap
  4104. * has been set will cause the wait builtin to return immediately
  4105. * with an exit status greater than 128, immediately after which
  4106. * the trap is executed."
  4107. */
  4108. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4109. /* if child sends us a signal *and immediately exits*,
  4110. * dowait() returns pid > 0. Check this case,
  4111. * not "if (dowait() < 0)"!
  4112. */
  4113. if (pending_sig)
  4114. goto sigout;
  4115. }
  4116. }
  4117. retval = 127;
  4118. do {
  4119. if (**argv != '%') {
  4120. pid_t pid = number(*argv);
  4121. job = curjob;
  4122. while (1) {
  4123. if (!job)
  4124. goto repeat;
  4125. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4126. break;
  4127. job = job->prev_job;
  4128. }
  4129. } else {
  4130. job = getjob(*argv, 0);
  4131. }
  4132. /* loop until process terminated or stopped */
  4133. while (job->state == JOBRUNNING) {
  4134. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4135. if (pending_sig)
  4136. goto sigout;
  4137. }
  4138. job->waited = 1;
  4139. retval = getstatus(job);
  4140. repeat: ;
  4141. } while (*++argv);
  4142. ret:
  4143. return retval;
  4144. sigout:
  4145. retval = 128 + pending_sig;
  4146. return retval;
  4147. }
  4148. static struct job *
  4149. growjobtab(void)
  4150. {
  4151. size_t len;
  4152. ptrdiff_t offset;
  4153. struct job *jp, *jq;
  4154. len = njobs * sizeof(*jp);
  4155. jq = jobtab;
  4156. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4157. offset = (char *)jp - (char *)jq;
  4158. if (offset) {
  4159. /* Relocate pointers */
  4160. size_t l = len;
  4161. jq = (struct job *)((char *)jq + l);
  4162. while (l) {
  4163. l -= sizeof(*jp);
  4164. jq--;
  4165. #define joff(p) ((struct job *)((char *)(p) + l))
  4166. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4167. if (joff(jp)->ps == &jq->ps0)
  4168. jmove(joff(jp)->ps);
  4169. if (joff(jp)->prev_job)
  4170. jmove(joff(jp)->prev_job);
  4171. }
  4172. if (curjob)
  4173. jmove(curjob);
  4174. #undef joff
  4175. #undef jmove
  4176. }
  4177. njobs += 4;
  4178. jobtab = jp;
  4179. jp = (struct job *)((char *)jp + len);
  4180. jq = jp + 3;
  4181. do {
  4182. jq->used = 0;
  4183. } while (--jq >= jp);
  4184. return jp;
  4185. }
  4186. /*
  4187. * Return a new job structure.
  4188. * Called with interrupts off.
  4189. */
  4190. static struct job *
  4191. makejob(/*union node *node,*/ int nprocs)
  4192. {
  4193. int i;
  4194. struct job *jp;
  4195. for (i = njobs, jp = jobtab; ; jp++) {
  4196. if (--i < 0) {
  4197. jp = growjobtab();
  4198. break;
  4199. }
  4200. if (jp->used == 0)
  4201. break;
  4202. if (jp->state != JOBDONE || !jp->waited)
  4203. continue;
  4204. #if JOBS
  4205. if (doing_jobctl)
  4206. continue;
  4207. #endif
  4208. freejob(jp);
  4209. break;
  4210. }
  4211. memset(jp, 0, sizeof(*jp));
  4212. #if JOBS
  4213. /* jp->jobctl is a bitfield.
  4214. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4215. if (doing_jobctl)
  4216. jp->jobctl = 1;
  4217. #endif
  4218. jp->prev_job = curjob;
  4219. curjob = jp;
  4220. jp->used = 1;
  4221. jp->ps = &jp->ps0;
  4222. if (nprocs > 1) {
  4223. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4224. }
  4225. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4226. jobno(jp)));
  4227. return jp;
  4228. }
  4229. #if JOBS
  4230. /*
  4231. * Return a string identifying a command (to be printed by the
  4232. * jobs command).
  4233. */
  4234. static char *cmdnextc;
  4235. static void
  4236. cmdputs(const char *s)
  4237. {
  4238. static const char vstype[VSTYPE + 1][3] = {
  4239. "", "}", "-", "+", "?", "=",
  4240. "%", "%%", "#", "##"
  4241. IF_BASH_SUBSTR(, ":")
  4242. IF_BASH_PATTERN_SUBST(, "/", "//")
  4243. };
  4244. const char *p, *str;
  4245. char cc[2];
  4246. char *nextc;
  4247. unsigned char c;
  4248. unsigned char subtype = 0;
  4249. int quoted = 0;
  4250. cc[1] = '\0';
  4251. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4252. p = s;
  4253. while ((c = *p++) != '\0') {
  4254. str = NULL;
  4255. switch (c) {
  4256. case CTLESC:
  4257. c = *p++;
  4258. break;
  4259. case CTLVAR:
  4260. subtype = *p++;
  4261. if ((subtype & VSTYPE) == VSLENGTH)
  4262. str = "${#";
  4263. else
  4264. str = "${";
  4265. goto dostr;
  4266. case CTLENDVAR:
  4267. str = "\"}" + !(quoted & 1);
  4268. quoted >>= 1;
  4269. subtype = 0;
  4270. goto dostr;
  4271. case CTLBACKQ:
  4272. str = "$(...)";
  4273. goto dostr;
  4274. #if ENABLE_FEATURE_SH_MATH
  4275. case CTLARI:
  4276. str = "$((";
  4277. goto dostr;
  4278. case CTLENDARI:
  4279. str = "))";
  4280. goto dostr;
  4281. #endif
  4282. case CTLQUOTEMARK:
  4283. quoted ^= 1;
  4284. c = '"';
  4285. break;
  4286. case '=':
  4287. if (subtype == 0)
  4288. break;
  4289. if ((subtype & VSTYPE) != VSNORMAL)
  4290. quoted <<= 1;
  4291. str = vstype[subtype & VSTYPE];
  4292. if (subtype & VSNUL)
  4293. c = ':';
  4294. else
  4295. goto checkstr;
  4296. break;
  4297. case '\'':
  4298. case '\\':
  4299. case '"':
  4300. case '$':
  4301. /* These can only happen inside quotes */
  4302. cc[0] = c;
  4303. str = cc;
  4304. //FIXME:
  4305. // $ true $$ &
  4306. // $ <cr>
  4307. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4308. c = '\\';
  4309. break;
  4310. default:
  4311. break;
  4312. }
  4313. USTPUTC(c, nextc);
  4314. checkstr:
  4315. if (!str)
  4316. continue;
  4317. dostr:
  4318. while ((c = *str++) != '\0') {
  4319. USTPUTC(c, nextc);
  4320. }
  4321. } /* while *p++ not NUL */
  4322. if (quoted & 1) {
  4323. USTPUTC('"', nextc);
  4324. }
  4325. *nextc = 0;
  4326. cmdnextc = nextc;
  4327. }
  4328. /* cmdtxt() and cmdlist() call each other */
  4329. static void cmdtxt(union node *n);
  4330. static void
  4331. cmdlist(union node *np, int sep)
  4332. {
  4333. for (; np; np = np->narg.next) {
  4334. if (!sep)
  4335. cmdputs(" ");
  4336. cmdtxt(np);
  4337. if (sep && np->narg.next)
  4338. cmdputs(" ");
  4339. }
  4340. }
  4341. static void
  4342. cmdtxt(union node *n)
  4343. {
  4344. union node *np;
  4345. struct nodelist *lp;
  4346. const char *p;
  4347. if (!n)
  4348. return;
  4349. switch (n->type) {
  4350. default:
  4351. #if DEBUG
  4352. abort();
  4353. #endif
  4354. case NPIPE:
  4355. lp = n->npipe.cmdlist;
  4356. for (;;) {
  4357. cmdtxt(lp->n);
  4358. lp = lp->next;
  4359. if (!lp)
  4360. break;
  4361. cmdputs(" | ");
  4362. }
  4363. break;
  4364. case NSEMI:
  4365. p = "; ";
  4366. goto binop;
  4367. case NAND:
  4368. p = " && ";
  4369. goto binop;
  4370. case NOR:
  4371. p = " || ";
  4372. binop:
  4373. cmdtxt(n->nbinary.ch1);
  4374. cmdputs(p);
  4375. n = n->nbinary.ch2;
  4376. goto donode;
  4377. case NREDIR:
  4378. case NBACKGND:
  4379. n = n->nredir.n;
  4380. goto donode;
  4381. case NNOT:
  4382. cmdputs("!");
  4383. n = n->nnot.com;
  4384. donode:
  4385. cmdtxt(n);
  4386. break;
  4387. case NIF:
  4388. cmdputs("if ");
  4389. cmdtxt(n->nif.test);
  4390. cmdputs("; then ");
  4391. if (n->nif.elsepart) {
  4392. cmdtxt(n->nif.ifpart);
  4393. cmdputs("; else ");
  4394. n = n->nif.elsepart;
  4395. } else {
  4396. n = n->nif.ifpart;
  4397. }
  4398. p = "; fi";
  4399. goto dotail;
  4400. case NSUBSHELL:
  4401. cmdputs("(");
  4402. n = n->nredir.n;
  4403. p = ")";
  4404. goto dotail;
  4405. case NWHILE:
  4406. p = "while ";
  4407. goto until;
  4408. case NUNTIL:
  4409. p = "until ";
  4410. until:
  4411. cmdputs(p);
  4412. cmdtxt(n->nbinary.ch1);
  4413. n = n->nbinary.ch2;
  4414. p = "; done";
  4415. dodo:
  4416. cmdputs("; do ");
  4417. dotail:
  4418. cmdtxt(n);
  4419. goto dotail2;
  4420. case NFOR:
  4421. cmdputs("for ");
  4422. cmdputs(n->nfor.var);
  4423. cmdputs(" in ");
  4424. cmdlist(n->nfor.args, 1);
  4425. n = n->nfor.body;
  4426. p = "; done";
  4427. goto dodo;
  4428. case NDEFUN:
  4429. cmdputs(n->ndefun.text);
  4430. p = "() { ... }";
  4431. goto dotail2;
  4432. case NCMD:
  4433. cmdlist(n->ncmd.args, 1);
  4434. cmdlist(n->ncmd.redirect, 0);
  4435. break;
  4436. case NARG:
  4437. p = n->narg.text;
  4438. dotail2:
  4439. cmdputs(p);
  4440. break;
  4441. case NHERE:
  4442. case NXHERE:
  4443. p = "<<...";
  4444. goto dotail2;
  4445. case NCASE:
  4446. cmdputs("case ");
  4447. cmdputs(n->ncase.expr->narg.text);
  4448. cmdputs(" in ");
  4449. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4450. cmdtxt(np->nclist.pattern);
  4451. cmdputs(") ");
  4452. cmdtxt(np->nclist.body);
  4453. cmdputs(";; ");
  4454. }
  4455. p = "esac";
  4456. goto dotail2;
  4457. case NTO:
  4458. p = ">";
  4459. goto redir;
  4460. case NCLOBBER:
  4461. p = ">|";
  4462. goto redir;
  4463. case NAPPEND:
  4464. p = ">>";
  4465. goto redir;
  4466. #if BASH_REDIR_OUTPUT
  4467. case NTO2:
  4468. #endif
  4469. case NTOFD:
  4470. p = ">&";
  4471. goto redir;
  4472. case NFROM:
  4473. p = "<";
  4474. goto redir;
  4475. case NFROMFD:
  4476. p = "<&";
  4477. goto redir;
  4478. case NFROMTO:
  4479. p = "<>";
  4480. redir:
  4481. cmdputs(utoa(n->nfile.fd));
  4482. cmdputs(p);
  4483. if (n->type == NTOFD || n->type == NFROMFD) {
  4484. if (n->ndup.dupfd >= 0)
  4485. cmdputs(utoa(n->ndup.dupfd));
  4486. else
  4487. cmdputs("-");
  4488. break;
  4489. }
  4490. n = n->nfile.fname;
  4491. goto donode;
  4492. }
  4493. }
  4494. static char *
  4495. commandtext(union node *n)
  4496. {
  4497. char *name;
  4498. STARTSTACKSTR(cmdnextc);
  4499. cmdtxt(n);
  4500. name = stackblock();
  4501. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4502. return ckstrdup(name);
  4503. }
  4504. #endif /* JOBS */
  4505. /*
  4506. * Fork off a subshell. If we are doing job control, give the subshell its
  4507. * own process group. Jp is a job structure that the job is to be added to.
  4508. * N is the command that will be evaluated by the child. Both jp and n may
  4509. * be NULL. The mode parameter can be one of the following:
  4510. * FORK_FG - Fork off a foreground process.
  4511. * FORK_BG - Fork off a background process.
  4512. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4513. * process group even if job control is on.
  4514. *
  4515. * When job control is turned off, background processes have their standard
  4516. * input redirected to /dev/null (except for the second and later processes
  4517. * in a pipeline).
  4518. *
  4519. * Called with interrupts off.
  4520. */
  4521. /*
  4522. * Clear traps on a fork.
  4523. */
  4524. static void
  4525. clear_traps(void)
  4526. {
  4527. char **tp;
  4528. INT_OFF;
  4529. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4530. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4531. if (trap_ptr == trap)
  4532. free(*tp);
  4533. /* else: it "belongs" to trap_ptr vector, don't free */
  4534. *tp = NULL;
  4535. if ((tp - trap) != 0)
  4536. setsignal(tp - trap);
  4537. }
  4538. }
  4539. may_have_traps = 0;
  4540. INT_ON;
  4541. }
  4542. /* Lives far away from here, needed for forkchild */
  4543. static void closescript(void);
  4544. /* Called after fork(), in child */
  4545. /* jp and n are NULL when called by openhere() for heredoc support */
  4546. static NOINLINE void
  4547. forkchild(struct job *jp, union node *n, int mode)
  4548. {
  4549. int oldlvl;
  4550. TRACE(("Child shell %d\n", getpid()));
  4551. oldlvl = shlvl;
  4552. shlvl++;
  4553. /* man bash: "Non-builtin commands run by bash have signal handlers
  4554. * set to the values inherited by the shell from its parent".
  4555. * Do we do it correctly? */
  4556. closescript();
  4557. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4558. && n && n->type == NCMD /* is it single cmd? */
  4559. /* && n->ncmd.args->type == NARG - always true? */
  4560. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4561. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4562. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4563. ) {
  4564. TRACE(("Trap hack\n"));
  4565. /* Awful hack for `trap` or $(trap).
  4566. *
  4567. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4568. * contains an example where "trap" is executed in a subshell:
  4569. *
  4570. * save_traps=$(trap)
  4571. * ...
  4572. * eval "$save_traps"
  4573. *
  4574. * Standard does not say that "trap" in subshell shall print
  4575. * parent shell's traps. It only says that its output
  4576. * must have suitable form, but then, in the above example
  4577. * (which is not supposed to be normative), it implies that.
  4578. *
  4579. * bash (and probably other shell) does implement it
  4580. * (traps are reset to defaults, but "trap" still shows them),
  4581. * but as a result, "trap" logic is hopelessly messed up:
  4582. *
  4583. * # trap
  4584. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4585. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4586. * # true | trap <--- trap is in subshell - no output (ditto)
  4587. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4588. * trap -- 'echo Ho' SIGWINCH
  4589. * # echo `(trap)` <--- in subshell in subshell - output
  4590. * trap -- 'echo Ho' SIGWINCH
  4591. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4592. * trap -- 'echo Ho' SIGWINCH
  4593. *
  4594. * The rules when to forget and when to not forget traps
  4595. * get really complex and nonsensical.
  4596. *
  4597. * Our solution: ONLY bare $(trap) or `trap` is special.
  4598. */
  4599. /* Save trap handler strings for trap builtin to print */
  4600. trap_ptr = xmemdup(trap, sizeof(trap));
  4601. /* Fall through into clearing traps */
  4602. }
  4603. clear_traps();
  4604. #if JOBS
  4605. /* do job control only in root shell */
  4606. doing_jobctl = 0;
  4607. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4608. pid_t pgrp;
  4609. if (jp->nprocs == 0)
  4610. pgrp = getpid();
  4611. else
  4612. pgrp = jp->ps[0].ps_pid;
  4613. /* this can fail because we are doing it in the parent also */
  4614. setpgid(0, pgrp);
  4615. if (mode == FORK_FG)
  4616. xtcsetpgrp(ttyfd, pgrp);
  4617. setsignal(SIGTSTP);
  4618. setsignal(SIGTTOU);
  4619. } else
  4620. #endif
  4621. if (mode == FORK_BG) {
  4622. /* man bash: "When job control is not in effect,
  4623. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4624. ignoresig(SIGINT);
  4625. ignoresig(SIGQUIT);
  4626. if (jp->nprocs == 0) {
  4627. close(0);
  4628. if (open(bb_dev_null, O_RDONLY) != 0)
  4629. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4630. }
  4631. }
  4632. if (oldlvl == 0) {
  4633. if (iflag) { /* why if iflag only? */
  4634. setsignal(SIGINT);
  4635. setsignal(SIGTERM);
  4636. }
  4637. /* man bash:
  4638. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4639. * commands run by bash have signal handlers
  4640. * set to the values inherited by the shell
  4641. * from its parent".
  4642. * Take care of the second rule: */
  4643. setsignal(SIGQUIT);
  4644. }
  4645. #if JOBS
  4646. if (n && n->type == NCMD
  4647. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4648. ) {
  4649. TRACE(("Job hack\n"));
  4650. /* "jobs": we do not want to clear job list for it,
  4651. * instead we remove only _its_ own_ job from job list.
  4652. * This makes "jobs .... | cat" more useful.
  4653. */
  4654. freejob(curjob);
  4655. return;
  4656. }
  4657. #endif
  4658. for (jp = curjob; jp; jp = jp->prev_job)
  4659. freejob(jp);
  4660. jobless = 0;
  4661. }
  4662. /* Called after fork(), in parent */
  4663. #if !JOBS
  4664. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4665. #endif
  4666. static void
  4667. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4668. {
  4669. TRACE(("In parent shell: child = %d\n", pid));
  4670. if (!jp) {
  4671. /* jp is NULL when called by openhere() for heredoc support */
  4672. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4673. continue;
  4674. jobless++;
  4675. return;
  4676. }
  4677. #if JOBS
  4678. if (mode != FORK_NOJOB && jp->jobctl) {
  4679. int pgrp;
  4680. if (jp->nprocs == 0)
  4681. pgrp = pid;
  4682. else
  4683. pgrp = jp->ps[0].ps_pid;
  4684. /* This can fail because we are doing it in the child also */
  4685. setpgid(pid, pgrp);
  4686. }
  4687. #endif
  4688. if (mode == FORK_BG) {
  4689. backgndpid = pid; /* set $! */
  4690. set_curjob(jp, CUR_RUNNING);
  4691. }
  4692. if (jp) {
  4693. struct procstat *ps = &jp->ps[jp->nprocs++];
  4694. ps->ps_pid = pid;
  4695. ps->ps_status = -1;
  4696. ps->ps_cmd = nullstr;
  4697. #if JOBS
  4698. if (doing_jobctl && n)
  4699. ps->ps_cmd = commandtext(n);
  4700. #endif
  4701. }
  4702. }
  4703. /* jp and n are NULL when called by openhere() for heredoc support */
  4704. static int
  4705. forkshell(struct job *jp, union node *n, int mode)
  4706. {
  4707. int pid;
  4708. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4709. pid = fork();
  4710. if (pid < 0) {
  4711. TRACE(("Fork failed, errno=%d", errno));
  4712. if (jp)
  4713. freejob(jp);
  4714. ash_msg_and_raise_perror("can't fork");
  4715. }
  4716. if (pid == 0) {
  4717. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4718. forkchild(jp, n, mode);
  4719. } else {
  4720. forkparent(jp, n, mode, pid);
  4721. }
  4722. return pid;
  4723. }
  4724. /*
  4725. * Wait for job to finish.
  4726. *
  4727. * Under job control we have the problem that while a child process
  4728. * is running interrupts generated by the user are sent to the child
  4729. * but not to the shell. This means that an infinite loop started by
  4730. * an interactive user may be hard to kill. With job control turned off,
  4731. * an interactive user may place an interactive program inside a loop.
  4732. * If the interactive program catches interrupts, the user doesn't want
  4733. * these interrupts to also abort the loop. The approach we take here
  4734. * is to have the shell ignore interrupt signals while waiting for a
  4735. * foreground process to terminate, and then send itself an interrupt
  4736. * signal if the child process was terminated by an interrupt signal.
  4737. * Unfortunately, some programs want to do a bit of cleanup and then
  4738. * exit on interrupt; unless these processes terminate themselves by
  4739. * sending a signal to themselves (instead of calling exit) they will
  4740. * confuse this approach.
  4741. *
  4742. * Called with interrupts off.
  4743. */
  4744. static int
  4745. waitforjob(struct job *jp)
  4746. {
  4747. int st;
  4748. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4749. INT_OFF;
  4750. while (jp->state == JOBRUNNING) {
  4751. /* In non-interactive shells, we _can_ get
  4752. * a keyboard signal here and be EINTRed,
  4753. * but we just loop back, waiting for command to complete.
  4754. *
  4755. * man bash:
  4756. * "If bash is waiting for a command to complete and receives
  4757. * a signal for which a trap has been set, the trap
  4758. * will not be executed until the command completes."
  4759. *
  4760. * Reality is that even if trap is not set, bash
  4761. * will not act on the signal until command completes.
  4762. * Try this. sleep5intoff.c:
  4763. * #include <signal.h>
  4764. * #include <unistd.h>
  4765. * int main() {
  4766. * sigset_t set;
  4767. * sigemptyset(&set);
  4768. * sigaddset(&set, SIGINT);
  4769. * sigaddset(&set, SIGQUIT);
  4770. * sigprocmask(SIG_BLOCK, &set, NULL);
  4771. * sleep(5);
  4772. * return 0;
  4773. * }
  4774. * $ bash -c './sleep5intoff; echo hi'
  4775. * ^C^C^C^C <--- pressing ^C once a second
  4776. * $ _
  4777. * $ bash -c './sleep5intoff; echo hi'
  4778. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4779. * $ _
  4780. */
  4781. dowait(DOWAIT_BLOCK, jp);
  4782. }
  4783. INT_ON;
  4784. st = getstatus(jp);
  4785. #if JOBS
  4786. if (jp->jobctl) {
  4787. xtcsetpgrp(ttyfd, rootpid);
  4788. restore_tty_if_stopped_or_signaled(jp);
  4789. /*
  4790. * This is truly gross.
  4791. * If we're doing job control, then we did a TIOCSPGRP which
  4792. * caused us (the shell) to no longer be in the controlling
  4793. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4794. * intuit from the subprocess exit status whether a SIGINT
  4795. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4796. */
  4797. if (jp->sigint) /* TODO: do the same with all signals */
  4798. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4799. }
  4800. if (jp->state == JOBDONE)
  4801. #endif
  4802. freejob(jp);
  4803. return st;
  4804. }
  4805. /*
  4806. * return 1 if there are stopped jobs, otherwise 0
  4807. */
  4808. static int
  4809. stoppedjobs(void)
  4810. {
  4811. struct job *jp;
  4812. int retval;
  4813. retval = 0;
  4814. if (job_warning)
  4815. goto out;
  4816. jp = curjob;
  4817. if (jp && jp->state == JOBSTOPPED) {
  4818. out2str("You have stopped jobs.\n");
  4819. job_warning = 2;
  4820. retval++;
  4821. }
  4822. out:
  4823. return retval;
  4824. }
  4825. /*
  4826. * Code for dealing with input/output redirection.
  4827. */
  4828. #undef EMPTY
  4829. #undef CLOSED
  4830. #define EMPTY -2 /* marks an unused slot in redirtab */
  4831. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4832. /*
  4833. * Handle here documents. Normally we fork off a process to write the
  4834. * data to a pipe. If the document is short, we can stuff the data in
  4835. * the pipe without forking.
  4836. */
  4837. /* openhere needs this forward reference */
  4838. static void expandhere(union node *arg, int fd);
  4839. static int
  4840. openhere(union node *redir)
  4841. {
  4842. int pip[2];
  4843. size_t len = 0;
  4844. if (pipe(pip) < 0)
  4845. ash_msg_and_raise_perror("can't create pipe");
  4846. if (redir->type == NHERE) {
  4847. len = strlen(redir->nhere.doc->narg.text);
  4848. if (len <= PIPE_BUF) {
  4849. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4850. goto out;
  4851. }
  4852. }
  4853. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4854. /* child */
  4855. close(pip[0]);
  4856. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4857. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4858. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4859. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4860. signal(SIGPIPE, SIG_DFL);
  4861. if (redir->type == NHERE)
  4862. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4863. else /* NXHERE */
  4864. expandhere(redir->nhere.doc, pip[1]);
  4865. _exit(EXIT_SUCCESS);
  4866. }
  4867. out:
  4868. close(pip[1]);
  4869. return pip[0];
  4870. }
  4871. static int
  4872. openredirect(union node *redir)
  4873. {
  4874. struct stat sb;
  4875. char *fname;
  4876. int f;
  4877. switch (redir->nfile.type) {
  4878. /* Can't happen, our single caller does this itself */
  4879. // case NTOFD:
  4880. // case NFROMFD:
  4881. // return -1;
  4882. case NHERE:
  4883. case NXHERE:
  4884. return openhere(redir);
  4885. }
  4886. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4887. * allocated space. Do it only when we know it is safe.
  4888. */
  4889. fname = redir->nfile.expfname;
  4890. switch (redir->nfile.type) {
  4891. default:
  4892. #if DEBUG
  4893. abort();
  4894. #endif
  4895. case NFROM:
  4896. f = open(fname, O_RDONLY);
  4897. if (f < 0)
  4898. goto eopen;
  4899. break;
  4900. case NFROMTO:
  4901. f = open(fname, O_RDWR|O_CREAT, 0666);
  4902. if (f < 0)
  4903. goto ecreate;
  4904. break;
  4905. case NTO:
  4906. #if BASH_REDIR_OUTPUT
  4907. case NTO2:
  4908. #endif
  4909. /* Take care of noclobber mode. */
  4910. if (Cflag) {
  4911. if (stat(fname, &sb) < 0) {
  4912. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4913. if (f < 0)
  4914. goto ecreate;
  4915. } else if (!S_ISREG(sb.st_mode)) {
  4916. f = open(fname, O_WRONLY, 0666);
  4917. if (f < 0)
  4918. goto ecreate;
  4919. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  4920. close(f);
  4921. errno = EEXIST;
  4922. goto ecreate;
  4923. }
  4924. } else {
  4925. errno = EEXIST;
  4926. goto ecreate;
  4927. }
  4928. break;
  4929. }
  4930. /* FALLTHROUGH */
  4931. case NCLOBBER:
  4932. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4933. if (f < 0)
  4934. goto ecreate;
  4935. break;
  4936. case NAPPEND:
  4937. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4938. if (f < 0)
  4939. goto ecreate;
  4940. break;
  4941. }
  4942. return f;
  4943. ecreate:
  4944. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4945. eopen:
  4946. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4947. }
  4948. /*
  4949. * Copy a file descriptor to be >= 10. Throws exception on error.
  4950. */
  4951. static int
  4952. savefd(int from)
  4953. {
  4954. int newfd;
  4955. int err;
  4956. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  4957. err = newfd < 0 ? errno : 0;
  4958. if (err != EBADF) {
  4959. if (err)
  4960. ash_msg_and_raise_perror("%d", from);
  4961. close(from);
  4962. if (F_DUPFD_CLOEXEC == F_DUPFD)
  4963. close_on_exec_on(newfd);
  4964. }
  4965. return newfd;
  4966. }
  4967. static int
  4968. dup2_or_raise(int from, int to)
  4969. {
  4970. int newfd;
  4971. newfd = (from != to) ? dup2(from, to) : to;
  4972. if (newfd < 0) {
  4973. /* Happens when source fd is not open: try "echo >&99" */
  4974. ash_msg_and_raise_perror("%d", from);
  4975. }
  4976. return newfd;
  4977. }
  4978. static int
  4979. dup_CLOEXEC(int fd, int avoid_fd)
  4980. {
  4981. int newfd;
  4982. repeat:
  4983. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  4984. if (newfd >= 0) {
  4985. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  4986. close_on_exec_on(newfd);
  4987. } else { /* newfd < 0 */
  4988. if (errno == EBUSY)
  4989. goto repeat;
  4990. if (errno == EINTR)
  4991. goto repeat;
  4992. }
  4993. return newfd;
  4994. }
  4995. static int
  4996. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  4997. {
  4998. int newfd;
  4999. repeat:
  5000. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5001. if (newfd < 0) {
  5002. if (errno == EBUSY)
  5003. goto repeat;
  5004. if (errno == EINTR)
  5005. goto repeat;
  5006. /* fd was not open? */
  5007. if (errno == EBADF)
  5008. return fd;
  5009. ash_msg_and_raise_perror("%d", newfd);
  5010. }
  5011. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5012. close_on_exec_on(newfd);
  5013. close(fd);
  5014. return newfd;
  5015. }
  5016. /* Struct def and variable are moved down to the first usage site */
  5017. struct squirrel {
  5018. int orig_fd;
  5019. int moved_to;
  5020. };
  5021. struct redirtab {
  5022. struct redirtab *next;
  5023. int pair_count;
  5024. struct squirrel two_fd[];
  5025. };
  5026. #define redirlist (G_var.redirlist)
  5027. static void
  5028. add_squirrel_closed(struct redirtab *sq, int fd)
  5029. {
  5030. int i;
  5031. if (!sq)
  5032. return;
  5033. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5034. /* If we collide with an already moved fd... */
  5035. if (fd == sq->two_fd[i].orig_fd) {
  5036. /* Examples:
  5037. * "echo 3>FILE 3>&- 3>FILE"
  5038. * "echo 3>&- 3>FILE"
  5039. * No need for last redirect to insert
  5040. * another "need to close 3" indicator.
  5041. */
  5042. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5043. return;
  5044. }
  5045. }
  5046. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5047. sq->two_fd[i].orig_fd = fd;
  5048. sq->two_fd[i].moved_to = CLOSED;
  5049. }
  5050. static int
  5051. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5052. {
  5053. int i, new_fd;
  5054. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5055. avoid_fd = 9;
  5056. #if JOBS
  5057. if (fd == ttyfd) {
  5058. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5059. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5060. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5061. return 1; /* "we closed fd" */
  5062. }
  5063. #endif
  5064. /* Are we called from redirect(0)? E.g. redirect
  5065. * in a forked child. No need to save fds,
  5066. * we aren't going to use them anymore, ok to trash.
  5067. */
  5068. if (!sq)
  5069. return 0;
  5070. /* If this one of script's fds? */
  5071. if (fd != 0) {
  5072. struct parsefile *pf = g_parsefile;
  5073. while (pf) {
  5074. /* We skip fd == 0 case because of the following:
  5075. * $ ash # running ash interactively
  5076. * $ . ./script.sh
  5077. * and in script.sh: "exec 9>&0".
  5078. * Even though top-level pf_fd _is_ 0,
  5079. * it's still ok to use it: "read" builtin uses it,
  5080. * why should we cripple "exec" builtin?
  5081. */
  5082. if (fd == pf->pf_fd) {
  5083. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5084. return 1; /* "we closed fd" */
  5085. }
  5086. pf = pf->prev;
  5087. }
  5088. }
  5089. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5090. /* First: do we collide with some already moved fds? */
  5091. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5092. /* If we collide with an already moved fd... */
  5093. if (fd == sq->two_fd[i].moved_to) {
  5094. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5095. sq->two_fd[i].moved_to = new_fd;
  5096. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5097. if (new_fd < 0) /* what? */
  5098. xfunc_die();
  5099. return 0; /* "we did not close fd" */
  5100. }
  5101. if (fd == sq->two_fd[i].orig_fd) {
  5102. /* Example: echo Hello >/dev/null 1>&2 */
  5103. TRACE(("redirect_fd %d: already moved\n", fd));
  5104. return 0; /* "we did not close fd" */
  5105. }
  5106. }
  5107. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5108. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5109. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5110. if (new_fd < 0) {
  5111. if (errno != EBADF)
  5112. xfunc_die();
  5113. /* new_fd = CLOSED; - already is -1 */
  5114. }
  5115. sq->two_fd[i].moved_to = new_fd;
  5116. sq->two_fd[i].orig_fd = fd;
  5117. /* if we move stderr, let "set -x" code know */
  5118. if (fd == preverrout_fd)
  5119. preverrout_fd = new_fd;
  5120. return 0; /* "we did not close fd" */
  5121. }
  5122. static int
  5123. internally_opened_fd(int fd, struct redirtab *sq)
  5124. {
  5125. int i;
  5126. #if JOBS
  5127. if (fd == ttyfd)
  5128. return 1;
  5129. #endif
  5130. /* If this one of script's fds? */
  5131. if (fd != 0) {
  5132. struct parsefile *pf = g_parsefile;
  5133. while (pf) {
  5134. if (fd == pf->pf_fd)
  5135. return 1;
  5136. pf = pf->prev;
  5137. }
  5138. }
  5139. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5140. if (fd == sq->two_fd[i].moved_to)
  5141. return 1;
  5142. }
  5143. return 0;
  5144. }
  5145. /*
  5146. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5147. * old file descriptors are stashed away so that the redirection can be
  5148. * undone by calling popredir.
  5149. */
  5150. /* flags passed to redirect */
  5151. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5152. static void
  5153. redirect(union node *redir, int flags)
  5154. {
  5155. struct redirtab *sv;
  5156. if (!redir)
  5157. return;
  5158. sv = NULL;
  5159. INT_OFF;
  5160. if (flags & REDIR_PUSH)
  5161. sv = redirlist;
  5162. do {
  5163. int fd;
  5164. int newfd;
  5165. int close_fd;
  5166. int closed;
  5167. fd = redir->nfile.fd;
  5168. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5169. //bb_error_msg("doing %d > %d", fd, newfd);
  5170. newfd = redir->ndup.dupfd;
  5171. close_fd = -1;
  5172. } else {
  5173. newfd = openredirect(redir); /* always >= 0 */
  5174. if (fd == newfd) {
  5175. /* open() gave us precisely the fd we wanted.
  5176. * This means that this fd was not busy
  5177. * (not opened to anywhere).
  5178. * Remember to close it on restore:
  5179. */
  5180. add_squirrel_closed(sv, fd);
  5181. continue;
  5182. }
  5183. close_fd = newfd;
  5184. }
  5185. if (fd == newfd)
  5186. continue;
  5187. /* if "N>FILE": move newfd to fd */
  5188. /* if "N>&M": dup newfd to fd */
  5189. /* if "N>&-": close fd (newfd is -1) */
  5190. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5191. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5192. if (newfd == -1) {
  5193. /* "N>&-" means "close me" */
  5194. if (!closed) {
  5195. /* ^^^ optimization: saving may already
  5196. * have closed it. If not... */
  5197. close(fd);
  5198. }
  5199. } else {
  5200. /* if newfd is a script fd or saved fd, simulate EBADF */
  5201. if (internally_opened_fd(newfd, sv)) {
  5202. errno = EBADF;
  5203. ash_msg_and_raise_perror("%d", newfd);
  5204. }
  5205. dup2_or_raise(newfd, fd);
  5206. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5207. close(close_fd);
  5208. #if BASH_REDIR_OUTPUT
  5209. if (redir->nfile.type == NTO2 && fd == 1) {
  5210. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5211. fd = 2;
  5212. newfd = 1;
  5213. close_fd = -1;
  5214. goto redirect_more;
  5215. }
  5216. #endif
  5217. }
  5218. } while ((redir = redir->nfile.next) != NULL);
  5219. INT_ON;
  5220. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5221. #define REDIR_SAVEFD2 0
  5222. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5223. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5224. // not only for calls with flags containing REDIR_SAVEFD2.
  5225. // We do this unconditionally (see save_fd_on_redirect()).
  5226. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5227. // preverrout_fd = copied_fd2;
  5228. }
  5229. static int
  5230. redirectsafe(union node *redir, int flags)
  5231. {
  5232. int err;
  5233. volatile int saveint;
  5234. struct jmploc *volatile savehandler = exception_handler;
  5235. struct jmploc jmploc;
  5236. SAVE_INT(saveint);
  5237. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5238. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5239. if (!err) {
  5240. exception_handler = &jmploc;
  5241. redirect(redir, flags);
  5242. }
  5243. exception_handler = savehandler;
  5244. if (err && exception_type != EXERROR)
  5245. longjmp(exception_handler->loc, 1);
  5246. RESTORE_INT(saveint);
  5247. return err;
  5248. }
  5249. static struct redirtab*
  5250. pushredir(union node *redir)
  5251. {
  5252. struct redirtab *sv;
  5253. int i;
  5254. if (!redir)
  5255. return redirlist;
  5256. i = 0;
  5257. do {
  5258. i++;
  5259. #if BASH_REDIR_OUTPUT
  5260. if (redir->nfile.type == NTO2)
  5261. i++;
  5262. #endif
  5263. redir = redir->nfile.next;
  5264. } while (redir);
  5265. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5266. sv->pair_count = i;
  5267. while (--i >= 0)
  5268. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5269. sv->next = redirlist;
  5270. redirlist = sv;
  5271. return sv->next;
  5272. }
  5273. /*
  5274. * Undo the effects of the last redirection.
  5275. */
  5276. static void
  5277. popredir(int drop)
  5278. {
  5279. struct redirtab *rp;
  5280. int i;
  5281. if (redirlist == NULL)
  5282. return;
  5283. INT_OFF;
  5284. rp = redirlist;
  5285. for (i = 0; i < rp->pair_count; i++) {
  5286. int fd = rp->two_fd[i].orig_fd;
  5287. int copy = rp->two_fd[i].moved_to;
  5288. if (copy == CLOSED) {
  5289. if (!drop)
  5290. close(fd);
  5291. continue;
  5292. }
  5293. if (copy != EMPTY) {
  5294. if (!drop) {
  5295. /*close(fd);*/
  5296. dup2_or_raise(copy, fd);
  5297. }
  5298. close(copy);
  5299. }
  5300. }
  5301. redirlist = rp->next;
  5302. free(rp);
  5303. INT_ON;
  5304. }
  5305. static void
  5306. unwindredir(struct redirtab *stop)
  5307. {
  5308. while (redirlist != stop)
  5309. popredir(/*drop:*/ 0);
  5310. }
  5311. /* ============ Routines to expand arguments to commands
  5312. *
  5313. * We have to deal with backquotes, shell variables, and file metacharacters.
  5314. */
  5315. #if ENABLE_FEATURE_SH_MATH
  5316. static arith_t
  5317. ash_arith(const char *s)
  5318. {
  5319. arith_state_t math_state;
  5320. arith_t result;
  5321. math_state.lookupvar = lookupvar;
  5322. math_state.setvar = setvar0;
  5323. //math_state.endofname = endofname;
  5324. INT_OFF;
  5325. result = arith(&math_state, s);
  5326. if (math_state.errmsg)
  5327. ash_msg_and_raise_error(math_state.errmsg);
  5328. INT_ON;
  5329. return result;
  5330. }
  5331. #endif
  5332. #if BASH_SUBSTR
  5333. # if ENABLE_FEATURE_SH_MATH
  5334. static int substr_atoi(const char *s)
  5335. {
  5336. arith_t t = ash_arith(s);
  5337. if (sizeof(t) > sizeof(int)) {
  5338. /* clamp very large or very large negative nums for ${v:N:M}:
  5339. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5340. */
  5341. if (t > INT_MAX)
  5342. t = INT_MAX;
  5343. if (t < INT_MIN)
  5344. t = INT_MIN;
  5345. }
  5346. return t;
  5347. }
  5348. # else
  5349. # define substr_atoi(s) number(s)
  5350. # endif
  5351. #endif
  5352. /*
  5353. * expandarg flags
  5354. */
  5355. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5356. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5357. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5358. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5359. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5360. * POSIX says for this case:
  5361. * Pathname expansion shall not be performed on the word by a
  5362. * non-interactive shell; an interactive shell may perform it, but shall
  5363. * do so only when the expansion would result in one word.
  5364. * Currently, our code complies to the above rule by never globbing
  5365. * redirection filenames.
  5366. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5367. * (this means that on a typical Linux distro, bash almost always
  5368. * performs globbing, and thus diverges from what we do).
  5369. */
  5370. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5371. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5372. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5373. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5374. /*
  5375. * rmescape() flags
  5376. */
  5377. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5378. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5379. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5380. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5381. /* Add CTLESC when necessary. */
  5382. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5383. /* Do not skip NUL characters. */
  5384. #define QUOTES_KEEPNUL EXP_TILDE
  5385. /*
  5386. * Structure specifying which parts of the string should be searched
  5387. * for IFS characters.
  5388. */
  5389. struct ifsregion {
  5390. struct ifsregion *next; /* next region in list */
  5391. int begoff; /* offset of start of region */
  5392. int endoff; /* offset of end of region */
  5393. int nulonly; /* search for nul bytes only */
  5394. };
  5395. struct arglist {
  5396. struct strlist *list;
  5397. struct strlist **lastp;
  5398. };
  5399. /* output of current string */
  5400. static char *expdest;
  5401. /* list of back quote expressions */
  5402. static struct nodelist *argbackq;
  5403. /* first struct in list of ifs regions */
  5404. static struct ifsregion ifsfirst;
  5405. /* last struct in list */
  5406. static struct ifsregion *ifslastp;
  5407. /* holds expanded arg list */
  5408. static struct arglist exparg;
  5409. /*
  5410. * Our own itoa().
  5411. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5412. */
  5413. static int
  5414. cvtnum(arith_t num)
  5415. {
  5416. int len;
  5417. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5418. len = sizeof(arith_t) * 3;
  5419. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5420. if (sizeof(arith_t) < 4) len += 2;
  5421. expdest = makestrspace(len, expdest);
  5422. len = fmtstr(expdest, len, ARITH_FMT, num);
  5423. STADJUST(len, expdest);
  5424. return len;
  5425. }
  5426. /*
  5427. * Break the argument string into pieces based upon IFS and add the
  5428. * strings to the argument list. The regions of the string to be
  5429. * searched for IFS characters have been stored by recordregion.
  5430. */
  5431. static void
  5432. ifsbreakup(char *string, struct arglist *arglist)
  5433. {
  5434. struct ifsregion *ifsp;
  5435. struct strlist *sp;
  5436. char *start;
  5437. char *p;
  5438. char *q;
  5439. const char *ifs, *realifs;
  5440. int ifsspc;
  5441. int nulonly;
  5442. start = string;
  5443. if (ifslastp != NULL) {
  5444. ifsspc = 0;
  5445. nulonly = 0;
  5446. realifs = ifsset() ? ifsval() : defifs;
  5447. ifsp = &ifsfirst;
  5448. do {
  5449. int afternul;
  5450. p = string + ifsp->begoff;
  5451. afternul = nulonly;
  5452. nulonly = ifsp->nulonly;
  5453. ifs = nulonly ? nullstr : realifs;
  5454. ifsspc = 0;
  5455. while (p < string + ifsp->endoff) {
  5456. q = p;
  5457. if ((unsigned char)*p == CTLESC)
  5458. p++;
  5459. if (!strchr(ifs, *p)) {
  5460. p++;
  5461. continue;
  5462. }
  5463. if (!(afternul || nulonly))
  5464. ifsspc = (strchr(defifs, *p) != NULL);
  5465. /* Ignore IFS whitespace at start */
  5466. if (q == start && ifsspc) {
  5467. p++;
  5468. start = p;
  5469. continue;
  5470. }
  5471. *q = '\0';
  5472. sp = stzalloc(sizeof(*sp));
  5473. sp->text = start;
  5474. *arglist->lastp = sp;
  5475. arglist->lastp = &sp->next;
  5476. p++;
  5477. if (!nulonly) {
  5478. for (;;) {
  5479. if (p >= string + ifsp->endoff) {
  5480. break;
  5481. }
  5482. q = p;
  5483. if ((unsigned char)*p == CTLESC)
  5484. p++;
  5485. if (strchr(ifs, *p) == NULL) {
  5486. p = q;
  5487. break;
  5488. }
  5489. if (strchr(defifs, *p) == NULL) {
  5490. if (ifsspc) {
  5491. p++;
  5492. ifsspc = 0;
  5493. } else {
  5494. p = q;
  5495. break;
  5496. }
  5497. } else
  5498. p++;
  5499. }
  5500. }
  5501. start = p;
  5502. } /* while */
  5503. ifsp = ifsp->next;
  5504. } while (ifsp != NULL);
  5505. if (nulonly)
  5506. goto add;
  5507. }
  5508. if (!*start)
  5509. return;
  5510. add:
  5511. sp = stzalloc(sizeof(*sp));
  5512. sp->text = start;
  5513. *arglist->lastp = sp;
  5514. arglist->lastp = &sp->next;
  5515. }
  5516. static void
  5517. ifsfree(void)
  5518. {
  5519. struct ifsregion *p = ifsfirst.next;
  5520. if (!p)
  5521. goto out;
  5522. INT_OFF;
  5523. do {
  5524. struct ifsregion *ifsp;
  5525. ifsp = p->next;
  5526. free(p);
  5527. p = ifsp;
  5528. } while (p);
  5529. ifsfirst.next = NULL;
  5530. INT_ON;
  5531. out:
  5532. ifslastp = NULL;
  5533. }
  5534. static size_t
  5535. esclen(const char *start, const char *p)
  5536. {
  5537. size_t esc = 0;
  5538. while (p > start && (unsigned char)*--p == CTLESC) {
  5539. esc++;
  5540. }
  5541. return esc;
  5542. }
  5543. /*
  5544. * Remove any CTLESC characters from a string.
  5545. */
  5546. #if !BASH_PATTERN_SUBST
  5547. #define rmescapes(str, flag, slash_position) \
  5548. rmescapes(str, flag)
  5549. #endif
  5550. static char *
  5551. rmescapes(char *str, int flag, int *slash_position)
  5552. {
  5553. static const char qchars[] ALIGN1 = {
  5554. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5555. char *p, *q, *r;
  5556. unsigned protect_against_glob;
  5557. unsigned globbing;
  5558. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5559. if (!p)
  5560. return str;
  5561. q = p;
  5562. r = str;
  5563. if (flag & RMESCAPE_ALLOC) {
  5564. size_t len = p - str;
  5565. size_t fulllen = len + strlen(p) + 1;
  5566. if (flag & RMESCAPE_GROW) {
  5567. int strloc = str - (char *)stackblock();
  5568. r = makestrspace(fulllen, expdest);
  5569. /* p and str may be invalidated by makestrspace */
  5570. str = (char *)stackblock() + strloc;
  5571. p = str + len;
  5572. } else if (flag & RMESCAPE_HEAP) {
  5573. r = ckmalloc(fulllen);
  5574. } else {
  5575. r = stalloc(fulllen);
  5576. }
  5577. q = r;
  5578. if (len > 0) {
  5579. q = (char *)mempcpy(q, str, len);
  5580. }
  5581. }
  5582. globbing = flag & RMESCAPE_GLOB;
  5583. protect_against_glob = globbing;
  5584. while (*p) {
  5585. if ((unsigned char)*p == CTLQUOTEMARK) {
  5586. // Note: protect_against_glob only affect whether
  5587. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5588. p++;
  5589. protect_against_glob = globbing;
  5590. continue;
  5591. }
  5592. if (*p == '\\') {
  5593. /* naked back slash */
  5594. protect_against_glob = 0;
  5595. goto copy;
  5596. }
  5597. if ((unsigned char)*p == CTLESC) {
  5598. p++;
  5599. #if DEBUG
  5600. if (*p == '\0')
  5601. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5602. #endif
  5603. if (protect_against_glob) {
  5604. /*
  5605. * We used to trust glob() and fnmatch() to eat
  5606. * superfluous escapes (\z where z has no
  5607. * special meaning anyway). But this causes
  5608. * bugs such as string of one greek letter rho
  5609. * (unicode-encoded as two bytes "cf,81")
  5610. * getting encoded as "cf,CTLESC,81"
  5611. * and here, converted to "cf,\,81" -
  5612. * which does not go well with some flavors
  5613. * of fnmatch() in unicode locales
  5614. * (for example, glibc <= 2.22).
  5615. *
  5616. * Lets add "\" only on the chars which need it.
  5617. * Testcases for less obvious chars are shown.
  5618. */
  5619. if (*p == '*'
  5620. || *p == '?'
  5621. || *p == '['
  5622. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5623. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5624. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5625. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5626. /* Some libc support [^negate], that's why "^" also needs love */
  5627. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5628. ) {
  5629. *q++ = '\\';
  5630. }
  5631. }
  5632. }
  5633. #if BASH_PATTERN_SUBST
  5634. else if (slash_position && p == str + *slash_position) {
  5635. /* stop handling globbing */
  5636. globbing = 0;
  5637. *slash_position = q - r;
  5638. slash_position = NULL;
  5639. }
  5640. #endif
  5641. protect_against_glob = globbing;
  5642. copy:
  5643. *q++ = *p++;
  5644. }
  5645. *q = '\0';
  5646. if (flag & RMESCAPE_GROW) {
  5647. expdest = r;
  5648. STADJUST(q - r + 1, expdest);
  5649. }
  5650. return r;
  5651. }
  5652. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5653. /*
  5654. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5655. *
  5656. * Returns an stalloced string.
  5657. */
  5658. static char *
  5659. preglob(const char *pattern, int flag)
  5660. {
  5661. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5662. }
  5663. /*
  5664. * Put a string on the stack.
  5665. */
  5666. static void
  5667. memtodest(const char *p, size_t len, int syntax, int quotes)
  5668. {
  5669. char *q;
  5670. if (!len)
  5671. return;
  5672. q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
  5673. do {
  5674. unsigned char c = *p++;
  5675. if (c) {
  5676. if (quotes & QUOTES_ESC) {
  5677. int n = SIT(c, syntax);
  5678. if (n == CCTL
  5679. || (syntax != BASESYNTAX && n == CBACK)
  5680. ) {
  5681. USTPUTC(CTLESC, q);
  5682. }
  5683. }
  5684. } else if (!(quotes & QUOTES_KEEPNUL))
  5685. continue;
  5686. USTPUTC(c, q);
  5687. } while (--len);
  5688. expdest = q;
  5689. }
  5690. static size_t
  5691. strtodest(const char *p, int syntax, int quotes)
  5692. {
  5693. size_t len = strlen(p);
  5694. memtodest(p, len, syntax, quotes);
  5695. return len;
  5696. }
  5697. /*
  5698. * Record the fact that we have to scan this region of the
  5699. * string for IFS characters.
  5700. */
  5701. static void
  5702. recordregion(int start, int end, int nulonly)
  5703. {
  5704. struct ifsregion *ifsp;
  5705. if (ifslastp == NULL) {
  5706. ifsp = &ifsfirst;
  5707. } else {
  5708. INT_OFF;
  5709. ifsp = ckzalloc(sizeof(*ifsp));
  5710. /*ifsp->next = NULL; - ckzalloc did it */
  5711. ifslastp->next = ifsp;
  5712. INT_ON;
  5713. }
  5714. ifslastp = ifsp;
  5715. ifslastp->begoff = start;
  5716. ifslastp->endoff = end;
  5717. ifslastp->nulonly = nulonly;
  5718. }
  5719. static void
  5720. removerecordregions(int endoff)
  5721. {
  5722. if (ifslastp == NULL)
  5723. return;
  5724. if (ifsfirst.endoff > endoff) {
  5725. while (ifsfirst.next) {
  5726. struct ifsregion *ifsp;
  5727. INT_OFF;
  5728. ifsp = ifsfirst.next->next;
  5729. free(ifsfirst.next);
  5730. ifsfirst.next = ifsp;
  5731. INT_ON;
  5732. }
  5733. if (ifsfirst.begoff > endoff) {
  5734. ifslastp = NULL;
  5735. } else {
  5736. ifslastp = &ifsfirst;
  5737. ifsfirst.endoff = endoff;
  5738. }
  5739. return;
  5740. }
  5741. ifslastp = &ifsfirst;
  5742. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5743. ifslastp = ifslastp->next;
  5744. while (ifslastp->next) {
  5745. struct ifsregion *ifsp;
  5746. INT_OFF;
  5747. ifsp = ifslastp->next->next;
  5748. free(ifslastp->next);
  5749. ifslastp->next = ifsp;
  5750. INT_ON;
  5751. }
  5752. if (ifslastp->endoff > endoff)
  5753. ifslastp->endoff = endoff;
  5754. }
  5755. static char *
  5756. exptilde(char *startp, char *p, int flags)
  5757. {
  5758. unsigned char c;
  5759. char *name;
  5760. struct passwd *pw;
  5761. const char *home;
  5762. int quotes = flags & QUOTES_ESC;
  5763. name = p + 1;
  5764. while ((c = *++p) != '\0') {
  5765. switch (c) {
  5766. case CTLESC:
  5767. return startp;
  5768. case CTLQUOTEMARK:
  5769. return startp;
  5770. case ':':
  5771. if (flags & EXP_VARTILDE)
  5772. goto done;
  5773. break;
  5774. case '/':
  5775. case CTLENDVAR:
  5776. goto done;
  5777. }
  5778. }
  5779. done:
  5780. *p = '\0';
  5781. if (*name == '\0') {
  5782. home = lookupvar("HOME");
  5783. } else {
  5784. pw = getpwnam(name);
  5785. if (pw == NULL)
  5786. goto lose;
  5787. home = pw->pw_dir;
  5788. }
  5789. if (!home || !*home)
  5790. goto lose;
  5791. *p = c;
  5792. strtodest(home, SQSYNTAX, quotes);
  5793. return p;
  5794. lose:
  5795. *p = c;
  5796. return startp;
  5797. }
  5798. /*
  5799. * Execute a command inside back quotes. If it's a builtin command, we
  5800. * want to save its output in a block obtained from malloc. Otherwise
  5801. * we fork off a subprocess and get the output of the command via a pipe.
  5802. * Should be called with interrupts off.
  5803. */
  5804. struct backcmd { /* result of evalbackcmd */
  5805. int fd; /* file descriptor to read from */
  5806. int nleft; /* number of chars in buffer */
  5807. char *buf; /* buffer */
  5808. struct job *jp; /* job structure for command */
  5809. };
  5810. /* These forward decls are needed to use "eval" code for backticks handling: */
  5811. /* flags in argument to evaltree */
  5812. #define EV_EXIT 01 /* exit after evaluating tree */
  5813. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5814. static int evaltree(union node *, int);
  5815. /* An evaltree() which is known to never return.
  5816. * Used to use an alias:
  5817. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5818. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5819. */
  5820. static ALWAYS_INLINE NORETURN void
  5821. evaltreenr(union node *n, int flags)
  5822. {
  5823. evaltree(n, flags);
  5824. bb_unreachable(abort());
  5825. /* NOTREACHED */
  5826. }
  5827. static void FAST_FUNC
  5828. evalbackcmd(union node *n, struct backcmd *result)
  5829. {
  5830. int pip[2];
  5831. struct job *jp;
  5832. result->fd = -1;
  5833. result->buf = NULL;
  5834. result->nleft = 0;
  5835. result->jp = NULL;
  5836. if (n == NULL) {
  5837. goto out;
  5838. }
  5839. if (pipe(pip) < 0)
  5840. ash_msg_and_raise_perror("can't create pipe");
  5841. jp = makejob(/*n,*/ 1);
  5842. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5843. /* child */
  5844. FORCE_INT_ON;
  5845. close(pip[0]);
  5846. if (pip[1] != 1) {
  5847. /*close(1);*/
  5848. dup2_or_raise(pip[1], 1);
  5849. close(pip[1]);
  5850. }
  5851. /* TODO: eflag clearing makes the following not abort:
  5852. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5853. * which is what bash does (unless it is in POSIX mode).
  5854. * dash deleted "eflag = 0" line in the commit
  5855. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5856. * [EVAL] Don't clear eflag in evalbackcmd
  5857. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5858. */
  5859. eflag = 0;
  5860. ifsfree();
  5861. evaltreenr(n, EV_EXIT);
  5862. /* NOTREACHED */
  5863. }
  5864. /* parent */
  5865. close(pip[1]);
  5866. result->fd = pip[0];
  5867. result->jp = jp;
  5868. out:
  5869. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5870. result->fd, result->buf, result->nleft, result->jp));
  5871. }
  5872. /*
  5873. * Expand stuff in backwards quotes.
  5874. */
  5875. static void
  5876. expbackq(union node *cmd, int flag)
  5877. {
  5878. struct backcmd in;
  5879. int i;
  5880. char buf[128];
  5881. char *p;
  5882. char *dest;
  5883. int startloc;
  5884. int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5885. struct stackmark smark;
  5886. INT_OFF;
  5887. startloc = expdest - (char *)stackblock();
  5888. pushstackmark(&smark, startloc);
  5889. evalbackcmd(cmd, &in);
  5890. popstackmark(&smark);
  5891. p = in.buf;
  5892. i = in.nleft;
  5893. if (i == 0)
  5894. goto read;
  5895. for (;;) {
  5896. memtodest(p, i, syntax, flag & QUOTES_ESC);
  5897. read:
  5898. if (in.fd < 0)
  5899. break;
  5900. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  5901. TRACE(("expbackq: read returns %d\n", i));
  5902. if (i <= 0)
  5903. break;
  5904. p = buf;
  5905. }
  5906. free(in.buf);
  5907. if (in.fd >= 0) {
  5908. close(in.fd);
  5909. back_exitstatus = waitforjob(in.jp);
  5910. }
  5911. INT_ON;
  5912. /* Eat all trailing newlines */
  5913. dest = expdest;
  5914. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5915. STUNPUTC(dest);
  5916. expdest = dest;
  5917. if (!(flag & EXP_QUOTED))
  5918. recordregion(startloc, dest - (char *)stackblock(), 0);
  5919. TRACE(("evalbackq: size:%d:'%.*s'\n",
  5920. (int)((dest - (char *)stackblock()) - startloc),
  5921. (int)((dest - (char *)stackblock()) - startloc),
  5922. stackblock() + startloc));
  5923. }
  5924. #if ENABLE_FEATURE_SH_MATH
  5925. /*
  5926. * Expand arithmetic expression. Backup to start of expression,
  5927. * evaluate, place result in (backed up) result, adjust string position.
  5928. */
  5929. static void
  5930. expari(int flag)
  5931. {
  5932. char *p, *start;
  5933. int begoff;
  5934. int len;
  5935. /* ifsfree(); */
  5936. /*
  5937. * This routine is slightly over-complicated for
  5938. * efficiency. Next we scan backwards looking for the
  5939. * start of arithmetic.
  5940. */
  5941. start = stackblock();
  5942. p = expdest - 1;
  5943. *p = '\0';
  5944. p--;
  5945. while (1) {
  5946. int esc;
  5947. while ((unsigned char)*p != CTLARI) {
  5948. p--;
  5949. #if DEBUG
  5950. if (p < start) {
  5951. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5952. }
  5953. #endif
  5954. }
  5955. esc = esclen(start, p);
  5956. if (!(esc % 2)) {
  5957. break;
  5958. }
  5959. p -= esc + 1;
  5960. }
  5961. begoff = p - start;
  5962. removerecordregions(begoff);
  5963. expdest = p;
  5964. if (flag & QUOTES_ESC)
  5965. rmescapes(p + 1, 0, NULL);
  5966. len = cvtnum(ash_arith(p + 1));
  5967. if (!(flag & EXP_QUOTED))
  5968. recordregion(begoff, begoff + len, 0);
  5969. }
  5970. #endif
  5971. /* argstr needs it */
  5972. static char *evalvar(char *p, int flags);
  5973. /*
  5974. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5975. * characters to allow for further processing. Otherwise treat
  5976. * $@ like $* since no splitting will be performed.
  5977. */
  5978. static void
  5979. argstr(char *p, int flags)
  5980. {
  5981. static const char spclchars[] ALIGN1 = {
  5982. '=',
  5983. ':',
  5984. CTLQUOTEMARK,
  5985. CTLENDVAR,
  5986. CTLESC,
  5987. CTLVAR,
  5988. CTLBACKQ,
  5989. #if ENABLE_FEATURE_SH_MATH
  5990. CTLENDARI,
  5991. #endif
  5992. '\0'
  5993. };
  5994. const char *reject = spclchars;
  5995. int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  5996. int inquotes;
  5997. size_t length;
  5998. int startloc;
  5999. if (!(flags & EXP_VARTILDE)) {
  6000. reject += 2;
  6001. } else if (flags & EXP_VARTILDE2) {
  6002. reject++;
  6003. }
  6004. inquotes = 0;
  6005. length = 0;
  6006. if (flags & EXP_TILDE) {
  6007. char *q;
  6008. flags &= ~EXP_TILDE;
  6009. tilde:
  6010. q = p;
  6011. if (*q == '~')
  6012. p = exptilde(p, q, flags);
  6013. }
  6014. start:
  6015. startloc = expdest - (char *)stackblock();
  6016. for (;;) {
  6017. unsigned char c;
  6018. length += strcspn(p + length, reject);
  6019. c = p[length];
  6020. if (c) {
  6021. if (!(c & 0x80)
  6022. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6023. ) {
  6024. /* c == '=' || c == ':' || c == CTLENDARI */
  6025. length++;
  6026. }
  6027. }
  6028. if (length > 0) {
  6029. int newloc;
  6030. expdest = stack_nputstr(p, length, expdest);
  6031. newloc = expdest - (char *)stackblock();
  6032. if (breakall && !inquotes && newloc > startloc) {
  6033. recordregion(startloc, newloc, 0);
  6034. }
  6035. startloc = newloc;
  6036. }
  6037. p += length + 1;
  6038. length = 0;
  6039. switch (c) {
  6040. case '\0':
  6041. goto breakloop;
  6042. case '=':
  6043. if (flags & EXP_VARTILDE2) {
  6044. p--;
  6045. continue;
  6046. }
  6047. flags |= EXP_VARTILDE2;
  6048. reject++;
  6049. /* fall through */
  6050. case ':':
  6051. /*
  6052. * sort of a hack - expand tildes in variable
  6053. * assignments (after the first '=' and after ':'s).
  6054. */
  6055. if (*--p == '~') {
  6056. goto tilde;
  6057. }
  6058. continue;
  6059. }
  6060. switch (c) {
  6061. case CTLENDVAR: /* ??? */
  6062. goto breakloop;
  6063. case CTLQUOTEMARK:
  6064. /* "$@" syntax adherence hack */
  6065. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6066. p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
  6067. goto start;
  6068. }
  6069. inquotes ^= EXP_QUOTED;
  6070. addquote:
  6071. if (flags & QUOTES_ESC) {
  6072. p--;
  6073. length++;
  6074. startloc++;
  6075. }
  6076. break;
  6077. case CTLESC:
  6078. startloc++;
  6079. length++;
  6080. goto addquote;
  6081. case CTLVAR:
  6082. TRACE(("argstr: evalvar('%s')\n", p));
  6083. p = evalvar(p, flags | inquotes);
  6084. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6085. goto start;
  6086. case CTLBACKQ:
  6087. expbackq(argbackq->n, flags | inquotes);
  6088. argbackq = argbackq->next;
  6089. goto start;
  6090. #if ENABLE_FEATURE_SH_MATH
  6091. case CTLENDARI:
  6092. p--;
  6093. expari(flags | inquotes);
  6094. goto start;
  6095. #endif
  6096. }
  6097. }
  6098. breakloop: ;
  6099. }
  6100. static char *
  6101. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6102. char *pattern, int quotes, int zero)
  6103. {
  6104. char *loc, *loc2;
  6105. char c;
  6106. loc = startp;
  6107. loc2 = rmesc;
  6108. do {
  6109. int match;
  6110. const char *s = loc2;
  6111. c = *loc2;
  6112. if (zero) {
  6113. *loc2 = '\0';
  6114. s = rmesc;
  6115. }
  6116. match = pmatch(pattern, s);
  6117. *loc2 = c;
  6118. if (match)
  6119. return loc;
  6120. if (quotes && (unsigned char)*loc == CTLESC)
  6121. loc++;
  6122. loc++;
  6123. loc2++;
  6124. } while (c);
  6125. return NULL;
  6126. }
  6127. static char *
  6128. scanright(char *startp, char *rmesc, char *rmescend,
  6129. char *pattern, int quotes, int match_at_start)
  6130. {
  6131. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6132. int try2optimize = match_at_start;
  6133. #endif
  6134. int esc = 0;
  6135. char *loc;
  6136. char *loc2;
  6137. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6138. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6139. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6140. * Logic:
  6141. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6142. * and on each iteration they go back two/one char until they reach the beginning.
  6143. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6144. */
  6145. /* TODO: document in what other circumstances we are called. */
  6146. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6147. int match;
  6148. char c = *loc2;
  6149. const char *s = loc2;
  6150. if (match_at_start) {
  6151. *loc2 = '\0';
  6152. s = rmesc;
  6153. }
  6154. match = pmatch(pattern, s);
  6155. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6156. *loc2 = c;
  6157. if (match)
  6158. return loc;
  6159. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6160. if (try2optimize) {
  6161. /* Maybe we can optimize this:
  6162. * if pattern ends with unescaped *, we can avoid checking
  6163. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6164. * it won't match truncated "raw_value_of_" strings too.
  6165. */
  6166. unsigned plen = strlen(pattern);
  6167. /* Does it end with "*"? */
  6168. if (plen != 0 && pattern[--plen] == '*') {
  6169. /* "xxxx*" is not escaped */
  6170. /* "xxx\*" is escaped */
  6171. /* "xx\\*" is not escaped */
  6172. /* "x\\\*" is escaped */
  6173. int slashes = 0;
  6174. while (plen != 0 && pattern[--plen] == '\\')
  6175. slashes++;
  6176. if (!(slashes & 1))
  6177. break; /* ends with unescaped "*" */
  6178. }
  6179. try2optimize = 0;
  6180. }
  6181. #endif
  6182. loc--;
  6183. if (quotes) {
  6184. if (--esc < 0) {
  6185. esc = esclen(startp, loc);
  6186. }
  6187. if (esc % 2) {
  6188. esc--;
  6189. loc--;
  6190. }
  6191. }
  6192. }
  6193. return NULL;
  6194. }
  6195. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6196. static void
  6197. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6198. {
  6199. const char *msg;
  6200. const char *tail;
  6201. tail = nullstr;
  6202. msg = "parameter not set";
  6203. if (umsg) {
  6204. if ((unsigned char)*end == CTLENDVAR) {
  6205. if (varflags & VSNUL)
  6206. tail = " or null";
  6207. } else {
  6208. msg = umsg;
  6209. }
  6210. }
  6211. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6212. }
  6213. static const char *
  6214. subevalvar(char *p, char *varname, int strloc, int subtype,
  6215. int startloc, int varflags, int flag)
  6216. {
  6217. struct nodelist *saveargbackq = argbackq;
  6218. int quotes = flag & QUOTES_ESC;
  6219. char *startp;
  6220. char *loc;
  6221. char *rmesc, *rmescend;
  6222. char *str;
  6223. int amount, resetloc;
  6224. int argstr_flags;
  6225. IF_BASH_PATTERN_SUBST(int workloc;)
  6226. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6227. IF_BASH_PATTERN_SUBST(char *repl;)
  6228. int zero;
  6229. char *(*scan)(char*, char*, char*, char*, int, int);
  6230. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  6231. // p, varname, strloc, subtype, startloc, varflags, quotes);
  6232. #if BASH_PATTERN_SUBST
  6233. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6234. * argstr() call expands possible variable references in pattern:
  6235. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6236. */
  6237. repl = NULL;
  6238. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6239. /* Find '/' and replace with NUL */
  6240. repl = p;
  6241. /* The pattern can't be empty.
  6242. * IOW: if the first char after "${v//" is a slash,
  6243. * it does not terminate the pattern - it's the first char of the pattern:
  6244. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6245. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6246. */
  6247. if (*repl == '/')
  6248. repl++;
  6249. for (;;) {
  6250. if (*repl == '\0') {
  6251. repl = NULL;
  6252. break;
  6253. }
  6254. if (*repl == '/') {
  6255. *repl = '\0';
  6256. break;
  6257. }
  6258. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6259. if ((unsigned char)*repl == CTLESC && repl[1])
  6260. repl++;
  6261. repl++;
  6262. }
  6263. }
  6264. #endif
  6265. argstr_flags = EXP_TILDE;
  6266. if (subtype != VSASSIGN
  6267. && subtype != VSQUESTION
  6268. #if BASH_SUBSTR
  6269. && subtype != VSSUBSTR
  6270. #endif
  6271. ) {
  6272. /* EXP_CASE keeps CTLESC's */
  6273. argstr_flags = EXP_TILDE | EXP_CASE;
  6274. }
  6275. argstr(p, argstr_flags);
  6276. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6277. #if BASH_PATTERN_SUBST
  6278. slash_pos = -1;
  6279. if (repl) {
  6280. slash_pos = expdest - ((char *)stackblock() + strloc);
  6281. STPUTC('/', expdest);
  6282. //bb_error_msg("repl+1:'%s'", repl + 1);
  6283. argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6284. *repl = '/';
  6285. }
  6286. #endif
  6287. STPUTC('\0', expdest);
  6288. argbackq = saveargbackq;
  6289. startp = (char *)stackblock() + startloc;
  6290. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6291. switch (subtype) {
  6292. case VSASSIGN:
  6293. setvar0(varname, startp);
  6294. amount = startp - expdest;
  6295. STADJUST(amount, expdest);
  6296. return startp;
  6297. case VSQUESTION:
  6298. varunset(p, varname, startp, varflags);
  6299. /* NOTREACHED */
  6300. #if BASH_SUBSTR
  6301. case VSSUBSTR: {
  6302. int pos, len, orig_len;
  6303. char *colon;
  6304. loc = str = stackblock() + strloc;
  6305. /* Read POS in ${var:POS:LEN} */
  6306. colon = strchr(loc, ':');
  6307. if (colon) *colon = '\0';
  6308. pos = substr_atoi(loc);
  6309. if (colon) *colon = ':';
  6310. /* Read LEN in ${var:POS:LEN} */
  6311. len = str - startp - 1;
  6312. /* *loc != '\0', guaranteed by parser */
  6313. if (quotes) {
  6314. char *ptr;
  6315. /* Adjust the length by the number of escapes */
  6316. for (ptr = startp; ptr < (str - 1); ptr++) {
  6317. if ((unsigned char)*ptr == CTLESC) {
  6318. len--;
  6319. ptr++;
  6320. }
  6321. }
  6322. }
  6323. orig_len = len;
  6324. if (*loc++ == ':') {
  6325. /* ${var::LEN} */
  6326. len = substr_atoi(loc);
  6327. } else {
  6328. /* Skip POS in ${var:POS:LEN} */
  6329. len = orig_len;
  6330. while (*loc && *loc != ':')
  6331. loc++;
  6332. if (*loc++ == ':')
  6333. len = substr_atoi(loc);
  6334. }
  6335. if (pos < 0) {
  6336. /* ${VAR:$((-n)):l} starts n chars from the end */
  6337. pos = orig_len + pos;
  6338. }
  6339. if ((unsigned)pos >= orig_len) {
  6340. /* apart from obvious ${VAR:999999:l},
  6341. * covers ${VAR:$((-9999999)):l} - result is ""
  6342. * (bash compat)
  6343. */
  6344. pos = 0;
  6345. len = 0;
  6346. }
  6347. if (len < 0) {
  6348. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6349. len = (orig_len - pos) + len;
  6350. }
  6351. if ((unsigned)len > (orig_len - pos))
  6352. len = orig_len - pos;
  6353. for (str = startp; pos; str++, pos--) {
  6354. if (quotes && (unsigned char)*str == CTLESC)
  6355. str++;
  6356. }
  6357. for (loc = startp; len; len--) {
  6358. if (quotes && (unsigned char)*str == CTLESC)
  6359. *loc++ = *str++;
  6360. *loc++ = *str++;
  6361. }
  6362. *loc = '\0';
  6363. amount = loc - expdest;
  6364. STADJUST(amount, expdest);
  6365. return loc;
  6366. }
  6367. #endif /* BASH_SUBSTR */
  6368. }
  6369. resetloc = expdest - (char *)stackblock();
  6370. #if BASH_PATTERN_SUBST
  6371. repl = NULL;
  6372. /* We'll comeback here if we grow the stack while handling
  6373. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6374. * stack will need rebasing, and we'll need to remove our work
  6375. * areas each time
  6376. */
  6377. restart:
  6378. #endif
  6379. amount = expdest - ((char *)stackblock() + resetloc);
  6380. STADJUST(-amount, expdest);
  6381. startp = (char *)stackblock() + startloc;
  6382. rmesc = startp;
  6383. rmescend = (char *)stackblock() + strloc;
  6384. //bb_error_msg("str7:'%s'", rmescend);
  6385. if (quotes) {
  6386. //TODO: how to handle slash_pos here if string changes (shortens?)
  6387. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6388. if (rmesc != startp) {
  6389. rmescend = expdest;
  6390. startp = (char *)stackblock() + startloc;
  6391. }
  6392. }
  6393. rmescend--;
  6394. str = (char *)stackblock() + strloc;
  6395. /*
  6396. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6397. * The result is a_\_z_c (not a\_\_z_c)!
  6398. *
  6399. * The search pattern and replace string treat backslashes differently!
  6400. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6401. * and string. It's only used on the first call.
  6402. */
  6403. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6404. rmescapes(str, RMESCAPE_GLOB,
  6405. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6406. );
  6407. #if BASH_PATTERN_SUBST
  6408. workloc = expdest - (char *)stackblock();
  6409. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6410. int len;
  6411. char *idx, *end;
  6412. if (!repl) {
  6413. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6414. repl = nullstr;
  6415. if (slash_pos >= 0) {
  6416. repl = str + slash_pos;
  6417. *repl++ = '\0';
  6418. }
  6419. }
  6420. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6421. /* If there's no pattern to match, return the expansion unmolested */
  6422. if (str[0] == '\0')
  6423. return NULL;
  6424. len = 0;
  6425. idx = startp;
  6426. end = str - 1;
  6427. while (idx < end) {
  6428. try_to_match:
  6429. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6430. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6431. if (!loc) {
  6432. /* No match, advance */
  6433. char *restart_detect = stackblock();
  6434. skip_matching:
  6435. STPUTC(*idx, expdest);
  6436. if (quotes && (unsigned char)*idx == CTLESC) {
  6437. idx++;
  6438. len++;
  6439. STPUTC(*idx, expdest);
  6440. }
  6441. if (stackblock() != restart_detect)
  6442. goto restart;
  6443. idx++;
  6444. len++;
  6445. rmesc++;
  6446. /* continue; - prone to quadratic behavior, smarter code: */
  6447. if (idx >= end)
  6448. break;
  6449. if (str[0] == '*') {
  6450. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6451. * it would never match "ong_string" etc, no point in trying.
  6452. */
  6453. goto skip_matching;
  6454. }
  6455. goto try_to_match;
  6456. }
  6457. if (subtype == VSREPLACEALL) {
  6458. while (idx < loc) {
  6459. if (quotes && (unsigned char)*idx == CTLESC)
  6460. idx++;
  6461. idx++;
  6462. rmesc++;
  6463. }
  6464. } else {
  6465. idx = loc;
  6466. }
  6467. //bb_error_msg("repl:'%s'", repl);
  6468. for (loc = (char*)repl; *loc; loc++) {
  6469. char *restart_detect = stackblock();
  6470. if (quotes && *loc == '\\') {
  6471. STPUTC(CTLESC, expdest);
  6472. len++;
  6473. }
  6474. STPUTC(*loc, expdest);
  6475. if (stackblock() != restart_detect)
  6476. goto restart;
  6477. len++;
  6478. }
  6479. if (subtype == VSREPLACE) {
  6480. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6481. while (*idx) {
  6482. char *restart_detect = stackblock();
  6483. STPUTC(*idx, expdest);
  6484. if (stackblock() != restart_detect)
  6485. goto restart;
  6486. len++;
  6487. idx++;
  6488. }
  6489. break;
  6490. }
  6491. }
  6492. /* We've put the replaced text into a buffer at workloc, now
  6493. * move it to the right place and adjust the stack.
  6494. */
  6495. STPUTC('\0', expdest);
  6496. startp = (char *)stackblock() + startloc;
  6497. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6498. //bb_error_msg("startp:'%s'", startp);
  6499. amount = expdest - (startp + len);
  6500. STADJUST(-amount, expdest);
  6501. return startp;
  6502. }
  6503. #endif /* BASH_PATTERN_SUBST */
  6504. subtype -= VSTRIMRIGHT;
  6505. #if DEBUG
  6506. if (subtype < 0 || subtype > 7)
  6507. abort();
  6508. #endif
  6509. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6510. zero = subtype >> 1;
  6511. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6512. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6513. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6514. if (loc) {
  6515. if (zero) {
  6516. memmove(startp, loc, str - loc);
  6517. loc = startp + (str - loc) - 1;
  6518. }
  6519. *loc = '\0';
  6520. amount = loc - expdest;
  6521. STADJUST(amount, expdest);
  6522. }
  6523. return loc;
  6524. }
  6525. /*
  6526. * Add the value of a specialized variable to the stack string.
  6527. * name parameter (examples):
  6528. * ash -c 'echo $1' name:'1='
  6529. * ash -c 'echo $qwe' name:'qwe='
  6530. * ash -c 'echo $$' name:'$='
  6531. * ash -c 'echo ${$}' name:'$='
  6532. * ash -c 'echo ${$##q}' name:'$=q'
  6533. * ash -c 'echo ${#$}' name:'$='
  6534. * note: examples with bad shell syntax:
  6535. * ash -c 'echo ${#$1}' name:'$=1'
  6536. * ash -c 'echo ${#1#}' name:'1=#'
  6537. */
  6538. static NOINLINE ssize_t
  6539. varvalue(char *name, int varflags, int flags, int quoted)
  6540. {
  6541. const char *p;
  6542. int num;
  6543. int i;
  6544. ssize_t len = 0;
  6545. int sep;
  6546. int subtype = varflags & VSTYPE;
  6547. int discard = subtype == VSPLUS || subtype == VSLENGTH;
  6548. int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
  6549. int syntax;
  6550. sep = (flags & EXP_FULL) << CHAR_BIT;
  6551. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  6552. switch (*name) {
  6553. case '$':
  6554. num = rootpid;
  6555. goto numvar;
  6556. case '?':
  6557. num = exitstatus;
  6558. goto numvar;
  6559. case '#':
  6560. num = shellparam.nparam;
  6561. goto numvar;
  6562. case '!':
  6563. num = backgndpid;
  6564. if (num == 0)
  6565. return -1;
  6566. numvar:
  6567. len = cvtnum(num);
  6568. goto check_1char_name;
  6569. case '-':
  6570. expdest = makestrspace(NOPTS, expdest);
  6571. for (i = NOPTS - 1; i >= 0; i--) {
  6572. if (optlist[i] && optletters(i)) {
  6573. USTPUTC(optletters(i), expdest);
  6574. len++;
  6575. }
  6576. }
  6577. check_1char_name:
  6578. #if 0
  6579. /* handles cases similar to ${#$1} */
  6580. if (name[2] != '\0')
  6581. raise_error_syntax("bad substitution");
  6582. #endif
  6583. break;
  6584. case '@':
  6585. if (quoted && sep)
  6586. goto param;
  6587. /* fall through */
  6588. case '*': {
  6589. char **ap;
  6590. char sepc;
  6591. char c;
  6592. /* We will set c to 0 or ~0 depending on whether
  6593. * we're doing field splitting. We won't do field
  6594. * splitting if either we're quoted or sep is zero.
  6595. *
  6596. * Instead of testing (quoted || !sep) the following
  6597. * trick optimises away any branches by using the
  6598. * fact that EXP_QUOTED (which is the only bit that
  6599. * can be set in quoted) is the same as EXP_FULL <<
  6600. * CHAR_BIT (which is the only bit that can be set
  6601. * in sep).
  6602. */
  6603. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6604. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6605. #endif
  6606. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6607. sep &= ~quoted;
  6608. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6609. param:
  6610. sepc = sep;
  6611. ap = shellparam.p;
  6612. if (!ap)
  6613. return -1;
  6614. while ((p = *ap++) != NULL) {
  6615. len += strtodest(p, syntax, quotes);
  6616. if (*ap && sep) {
  6617. len++;
  6618. memtodest(&sepc, 1, syntax, quotes);
  6619. }
  6620. }
  6621. break;
  6622. } /* case '*' */
  6623. case '0':
  6624. case '1':
  6625. case '2':
  6626. case '3':
  6627. case '4':
  6628. case '5':
  6629. case '6':
  6630. case '7':
  6631. case '8':
  6632. case '9':
  6633. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6634. if (num < 0 || num > shellparam.nparam)
  6635. return -1;
  6636. p = num ? shellparam.p[num - 1] : arg0;
  6637. goto value;
  6638. default:
  6639. /* NB: name has form "VAR=..." */
  6640. p = lookupvar(name);
  6641. value:
  6642. if (!p)
  6643. return -1;
  6644. len = strtodest(p, syntax, quotes);
  6645. #if ENABLE_UNICODE_SUPPORT
  6646. if (subtype == VSLENGTH && len > 0) {
  6647. reinit_unicode_for_ash();
  6648. if (unicode_status == UNICODE_ON) {
  6649. STADJUST(-len, expdest);
  6650. discard = 0;
  6651. len = unicode_strlen(p);
  6652. }
  6653. }
  6654. #endif
  6655. break;
  6656. }
  6657. if (discard)
  6658. STADJUST(-len, expdest);
  6659. return len;
  6660. }
  6661. /*
  6662. * Expand a variable, and return a pointer to the next character in the
  6663. * input string.
  6664. */
  6665. static char *
  6666. evalvar(char *p, int flag)
  6667. {
  6668. char varflags;
  6669. char subtype;
  6670. int quoted;
  6671. char *var;
  6672. int patloc;
  6673. int startloc;
  6674. ssize_t varlen;
  6675. varflags = (unsigned char) *p++;
  6676. subtype = varflags & VSTYPE;
  6677. if (!subtype)
  6678. raise_error_syntax("bad substitution");
  6679. quoted = flag & EXP_QUOTED;
  6680. var = p;
  6681. startloc = expdest - (char *)stackblock();
  6682. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6683. again:
  6684. varlen = varvalue(var, varflags, flag, quoted);
  6685. if (varflags & VSNUL)
  6686. varlen--;
  6687. if (subtype == VSPLUS) {
  6688. varlen = -1 - varlen;
  6689. goto vsplus;
  6690. }
  6691. if (subtype == VSMINUS) {
  6692. vsplus:
  6693. if (varlen < 0) {
  6694. argstr(
  6695. p,
  6696. flag | EXP_TILDE | EXP_WORD
  6697. );
  6698. goto end;
  6699. }
  6700. goto record;
  6701. }
  6702. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6703. if (varlen >= 0)
  6704. goto record;
  6705. subevalvar(p, var, 0, subtype, startloc, varflags,
  6706. flag & ~QUOTES_ESC);
  6707. varflags &= ~VSNUL;
  6708. /*
  6709. * Remove any recorded regions beyond
  6710. * start of variable
  6711. */
  6712. removerecordregions(startloc);
  6713. goto again;
  6714. }
  6715. if (varlen < 0 && uflag)
  6716. varunset(p, var, 0, 0);
  6717. if (subtype == VSLENGTH) {
  6718. cvtnum(varlen > 0 ? varlen : 0);
  6719. goto record;
  6720. }
  6721. if (subtype == VSNORMAL) {
  6722. record:
  6723. if (quoted) {
  6724. quoted = *var == '@' && shellparam.nparam;
  6725. if (!quoted)
  6726. goto end;
  6727. }
  6728. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6729. goto end;
  6730. }
  6731. #if DEBUG
  6732. switch (subtype) {
  6733. case VSTRIMLEFT:
  6734. case VSTRIMLEFTMAX:
  6735. case VSTRIMRIGHT:
  6736. case VSTRIMRIGHTMAX:
  6737. #if BASH_SUBSTR
  6738. case VSSUBSTR:
  6739. #endif
  6740. #if BASH_PATTERN_SUBST
  6741. case VSREPLACE:
  6742. case VSREPLACEALL:
  6743. #endif
  6744. break;
  6745. default:
  6746. abort();
  6747. }
  6748. #endif
  6749. if (varlen >= 0) {
  6750. /*
  6751. * Terminate the string and start recording the pattern
  6752. * right after it
  6753. */
  6754. STPUTC('\0', expdest);
  6755. patloc = expdest - (char *)stackblock();
  6756. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6757. startloc, varflags, flag)) {
  6758. int amount = expdest - (
  6759. (char *)stackblock() + patloc - 1
  6760. );
  6761. STADJUST(-amount, expdest);
  6762. }
  6763. /* Remove any recorded regions beyond start of variable */
  6764. removerecordregions(startloc);
  6765. goto record;
  6766. }
  6767. end:
  6768. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6769. int nesting = 1;
  6770. for (;;) {
  6771. unsigned char c = *p++;
  6772. if (c == CTLESC)
  6773. p++;
  6774. else if (c == CTLBACKQ) {
  6775. if (varlen >= 0)
  6776. argbackq = argbackq->next;
  6777. } else if (c == CTLVAR) {
  6778. if ((*p++ & VSTYPE) != VSNORMAL)
  6779. nesting++;
  6780. } else if (c == CTLENDVAR) {
  6781. if (--nesting == 0)
  6782. break;
  6783. }
  6784. }
  6785. }
  6786. return p;
  6787. }
  6788. /*
  6789. * Add a file name to the list.
  6790. */
  6791. static void
  6792. addfname(const char *name)
  6793. {
  6794. struct strlist *sp;
  6795. sp = stzalloc(sizeof(*sp));
  6796. sp->text = sstrdup(name);
  6797. *exparg.lastp = sp;
  6798. exparg.lastp = &sp->next;
  6799. }
  6800. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6801. static int
  6802. hasmeta(const char *p)
  6803. {
  6804. static const char chars[] ALIGN1 = {
  6805. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6806. };
  6807. for (;;) {
  6808. p = strpbrk(p, chars);
  6809. if (!p)
  6810. break;
  6811. switch ((unsigned char)*p) {
  6812. case CTLQUOTEMARK:
  6813. for (;;) {
  6814. p++;
  6815. if ((unsigned char)*p == CTLQUOTEMARK)
  6816. break;
  6817. if ((unsigned char)*p == CTLESC)
  6818. p++;
  6819. if (*p == '\0') /* huh? */
  6820. return 0;
  6821. }
  6822. break;
  6823. case '\\':
  6824. case CTLESC:
  6825. p++;
  6826. if (*p == '\0')
  6827. return 0;
  6828. break;
  6829. case '[':
  6830. if (!strchr(p + 1, ']')) {
  6831. /* It's not a properly closed [] pattern,
  6832. * but other metas may follow. Continue checking.
  6833. * my[file* _is_ globbed by bash
  6834. * and matches filenames like "my[file1".
  6835. */
  6836. break;
  6837. }
  6838. /* fallthrough */
  6839. default:
  6840. /* case '*': */
  6841. /* case '?': */
  6842. return 1;
  6843. }
  6844. p++;
  6845. }
  6846. return 0;
  6847. }
  6848. /* If we want to use glob() from libc... */
  6849. #if !ENABLE_ASH_INTERNAL_GLOB
  6850. /* Add the result of glob() to the list */
  6851. static void
  6852. addglob(const glob_t *pglob)
  6853. {
  6854. char **p = pglob->gl_pathv;
  6855. do {
  6856. addfname(*p);
  6857. } while (*++p);
  6858. }
  6859. static void
  6860. expandmeta(struct strlist *str /*, int flag*/)
  6861. {
  6862. /* TODO - EXP_REDIR */
  6863. while (str) {
  6864. char *p;
  6865. glob_t pglob;
  6866. int i;
  6867. if (fflag)
  6868. goto nometa;
  6869. if (!hasmeta(str->text))
  6870. goto nometa;
  6871. INT_OFF;
  6872. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6873. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6874. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6875. //
  6876. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6877. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6878. // Which means you need to unescape the string, right? Not so fast:
  6879. // if there _is_ a file named "file\?" (with backslash), it is returned
  6880. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6881. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6882. //
  6883. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6884. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6885. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6886. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6887. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6888. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6889. i = glob(p, 0, NULL, &pglob);
  6890. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6891. if (p != str->text)
  6892. free(p);
  6893. switch (i) {
  6894. case 0:
  6895. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6896. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6897. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6898. goto nometa2;
  6899. #endif
  6900. addglob(&pglob);
  6901. globfree(&pglob);
  6902. INT_ON;
  6903. break;
  6904. case GLOB_NOMATCH:
  6905. //nometa2:
  6906. globfree(&pglob);
  6907. INT_ON;
  6908. nometa:
  6909. *exparg.lastp = str;
  6910. rmescapes(str->text, 0, NULL);
  6911. exparg.lastp = &str->next;
  6912. break;
  6913. default: /* GLOB_NOSPACE */
  6914. globfree(&pglob);
  6915. INT_ON;
  6916. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  6917. }
  6918. str = str->next;
  6919. }
  6920. }
  6921. #else
  6922. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  6923. /*
  6924. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6925. */
  6926. typedef struct exp_t {
  6927. char *dir;
  6928. unsigned dir_max;
  6929. } exp_t;
  6930. static void
  6931. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  6932. {
  6933. #define expdir exp->dir
  6934. #define expdir_max exp->dir_max
  6935. char *enddir = expdir + expdir_len;
  6936. char *p;
  6937. const char *cp;
  6938. char *start;
  6939. char *endname;
  6940. int metaflag;
  6941. struct stat statb;
  6942. DIR *dirp;
  6943. struct dirent *dp;
  6944. int atend;
  6945. int matchdot;
  6946. int esc;
  6947. metaflag = 0;
  6948. start = name;
  6949. for (p = name; esc = 0, *p; p += esc + 1) {
  6950. if (*p == '*' || *p == '?')
  6951. metaflag = 1;
  6952. else if (*p == '[') {
  6953. char *q = p + 1;
  6954. if (*q == '!')
  6955. q++;
  6956. for (;;) {
  6957. if (*q == '\\')
  6958. q++;
  6959. if (*q == '/' || *q == '\0')
  6960. break;
  6961. if (*++q == ']') {
  6962. metaflag = 1;
  6963. break;
  6964. }
  6965. }
  6966. } else {
  6967. if (*p == '\\' && p[1])
  6968. esc++;
  6969. if (p[esc] == '/') {
  6970. if (metaflag)
  6971. break;
  6972. start = p + esc + 1;
  6973. }
  6974. }
  6975. }
  6976. if (metaflag == 0) { /* we've reached the end of the file name */
  6977. if (!expdir_len)
  6978. return;
  6979. p = name;
  6980. do {
  6981. if (*p == '\\' && p[1])
  6982. p++;
  6983. *enddir++ = *p;
  6984. } while (*p++);
  6985. if (lstat(expdir, &statb) == 0)
  6986. addfname(expdir);
  6987. return;
  6988. }
  6989. endname = p;
  6990. if (name < start) {
  6991. p = name;
  6992. do {
  6993. if (*p == '\\' && p[1])
  6994. p++;
  6995. *enddir++ = *p++;
  6996. } while (p < start);
  6997. }
  6998. *enddir = '\0';
  6999. cp = expdir;
  7000. expdir_len = enddir - cp;
  7001. if (!expdir_len)
  7002. cp = ".";
  7003. dirp = opendir(cp);
  7004. if (dirp == NULL)
  7005. return;
  7006. if (*endname == 0) {
  7007. atend = 1;
  7008. } else {
  7009. atend = 0;
  7010. *endname = '\0';
  7011. endname += esc + 1;
  7012. }
  7013. name_len -= endname - name;
  7014. matchdot = 0;
  7015. p = start;
  7016. if (*p == '\\')
  7017. p++;
  7018. if (*p == '.')
  7019. matchdot++;
  7020. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7021. if (dp->d_name[0] == '.' && !matchdot)
  7022. continue;
  7023. if (pmatch(start, dp->d_name)) {
  7024. if (atend) {
  7025. strcpy(enddir, dp->d_name);
  7026. addfname(expdir);
  7027. } else {
  7028. unsigned offset;
  7029. unsigned len;
  7030. p = stpcpy(enddir, dp->d_name);
  7031. *p = '/';
  7032. offset = p - expdir + 1;
  7033. len = offset + name_len + NAME_MAX;
  7034. if (len > expdir_max) {
  7035. len += PATH_MAX;
  7036. expdir = ckrealloc(expdir, len);
  7037. expdir_max = len;
  7038. }
  7039. expmeta(exp, endname, name_len, offset);
  7040. enddir = expdir + expdir_len;
  7041. }
  7042. }
  7043. }
  7044. closedir(dirp);
  7045. if (!atend)
  7046. endname[-esc - 1] = esc ? '\\' : '/';
  7047. #undef expdir
  7048. #undef expdir_max
  7049. }
  7050. static struct strlist *
  7051. msort(struct strlist *list, int len)
  7052. {
  7053. struct strlist *p, *q = NULL;
  7054. struct strlist **lpp;
  7055. int half;
  7056. int n;
  7057. if (len <= 1)
  7058. return list;
  7059. half = len >> 1;
  7060. p = list;
  7061. for (n = half; --n >= 0;) {
  7062. q = p;
  7063. p = p->next;
  7064. }
  7065. q->next = NULL; /* terminate first half of list */
  7066. q = msort(list, half); /* sort first half of list */
  7067. p = msort(p, len - half); /* sort second half */
  7068. lpp = &list;
  7069. for (;;) {
  7070. #if ENABLE_LOCALE_SUPPORT
  7071. if (strcoll(p->text, q->text) < 0)
  7072. #else
  7073. if (strcmp(p->text, q->text) < 0)
  7074. #endif
  7075. {
  7076. *lpp = p;
  7077. lpp = &p->next;
  7078. p = *lpp;
  7079. if (p == NULL) {
  7080. *lpp = q;
  7081. break;
  7082. }
  7083. } else {
  7084. *lpp = q;
  7085. lpp = &q->next;
  7086. q = *lpp;
  7087. if (q == NULL) {
  7088. *lpp = p;
  7089. break;
  7090. }
  7091. }
  7092. }
  7093. return list;
  7094. }
  7095. /*
  7096. * Sort the results of file name expansion. It calculates the number of
  7097. * strings to sort and then calls msort (short for merge sort) to do the
  7098. * work.
  7099. */
  7100. static struct strlist *
  7101. expsort(struct strlist *str)
  7102. {
  7103. int len;
  7104. struct strlist *sp;
  7105. len = 0;
  7106. for (sp = str; sp; sp = sp->next)
  7107. len++;
  7108. return msort(str, len);
  7109. }
  7110. static void
  7111. expandmeta(struct strlist *str /*, int flag*/)
  7112. {
  7113. /* TODO - EXP_REDIR */
  7114. while (str) {
  7115. exp_t exp;
  7116. struct strlist **savelastp;
  7117. struct strlist *sp;
  7118. char *p;
  7119. unsigned len;
  7120. if (fflag)
  7121. goto nometa;
  7122. if (!hasmeta(str->text))
  7123. goto nometa;
  7124. savelastp = exparg.lastp;
  7125. INT_OFF;
  7126. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7127. len = strlen(p);
  7128. exp.dir_max = len + PATH_MAX;
  7129. exp.dir = ckmalloc(exp.dir_max);
  7130. expmeta(&exp, p, len, 0);
  7131. free(exp.dir);
  7132. if (p != str->text)
  7133. free(p);
  7134. INT_ON;
  7135. if (exparg.lastp == savelastp) {
  7136. /*
  7137. * no matches
  7138. */
  7139. nometa:
  7140. *exparg.lastp = str;
  7141. rmescapes(str->text, 0, NULL);
  7142. exparg.lastp = &str->next;
  7143. } else {
  7144. *exparg.lastp = NULL;
  7145. *savelastp = sp = expsort(*savelastp);
  7146. while (sp->next != NULL)
  7147. sp = sp->next;
  7148. exparg.lastp = &sp->next;
  7149. }
  7150. str = str->next;
  7151. }
  7152. }
  7153. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7154. /*
  7155. * Perform variable substitution and command substitution on an argument,
  7156. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7157. * perform splitting and file name expansion. When arglist is NULL, perform
  7158. * here document expansion.
  7159. */
  7160. static void
  7161. expandarg(union node *arg, struct arglist *arglist, int flag)
  7162. {
  7163. struct strlist *sp;
  7164. char *p;
  7165. argbackq = arg->narg.backquote;
  7166. STARTSTACKSTR(expdest);
  7167. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7168. argstr(arg->narg.text, flag);
  7169. p = _STPUTC('\0', expdest);
  7170. expdest = p - 1;
  7171. if (arglist == NULL) {
  7172. /* here document expanded */
  7173. goto out;
  7174. }
  7175. p = grabstackstr(p);
  7176. TRACE(("expandarg: p:'%s'\n", p));
  7177. exparg.lastp = &exparg.list;
  7178. /*
  7179. * TODO - EXP_REDIR
  7180. */
  7181. if (flag & EXP_FULL) {
  7182. ifsbreakup(p, &exparg);
  7183. *exparg.lastp = NULL;
  7184. exparg.lastp = &exparg.list;
  7185. expandmeta(exparg.list /*, flag*/);
  7186. } else {
  7187. sp = stzalloc(sizeof(*sp));
  7188. sp->text = p;
  7189. *exparg.lastp = sp;
  7190. exparg.lastp = &sp->next;
  7191. }
  7192. *exparg.lastp = NULL;
  7193. if (exparg.list) {
  7194. *arglist->lastp = exparg.list;
  7195. arglist->lastp = exparg.lastp;
  7196. }
  7197. out:
  7198. ifsfree();
  7199. }
  7200. /*
  7201. * Expand shell variables and backquotes inside a here document.
  7202. */
  7203. static void
  7204. expandhere(union node *arg, int fd)
  7205. {
  7206. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7207. full_write(fd, stackblock(), expdest - (char *)stackblock());
  7208. }
  7209. /*
  7210. * Returns true if the pattern matches the string.
  7211. */
  7212. static int
  7213. patmatch(char *pattern, const char *string)
  7214. {
  7215. char *p = preglob(pattern, 0);
  7216. int r = pmatch(p, string);
  7217. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7218. return r;
  7219. }
  7220. /*
  7221. * See if a pattern matches in a case statement.
  7222. */
  7223. static int
  7224. casematch(union node *pattern, char *val)
  7225. {
  7226. struct stackmark smark;
  7227. int result;
  7228. setstackmark(&smark);
  7229. argbackq = pattern->narg.backquote;
  7230. STARTSTACKSTR(expdest);
  7231. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7232. STACKSTRNUL(expdest);
  7233. ifsfree();
  7234. result = patmatch(stackblock(), val);
  7235. popstackmark(&smark);
  7236. return result;
  7237. }
  7238. /* ============ find_command */
  7239. struct builtincmd {
  7240. const char *name;
  7241. int (*builtin)(int, char **) FAST_FUNC;
  7242. /* unsigned flags; */
  7243. };
  7244. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7245. /* "regular" builtins always take precedence over commands,
  7246. * regardless of PATH=....%builtin... position */
  7247. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7248. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7249. struct cmdentry {
  7250. smallint cmdtype; /* CMDxxx */
  7251. union param {
  7252. int index;
  7253. /* index >= 0 for commands without path (slashes) */
  7254. /* (TODO: what exactly does the value mean? PATH position?) */
  7255. /* index == -1 for commands with slashes */
  7256. /* index == (-2 - applet_no) for NOFORK applets */
  7257. const struct builtincmd *cmd;
  7258. struct funcnode *func;
  7259. } u;
  7260. };
  7261. /* values of cmdtype */
  7262. #define CMDUNKNOWN -1 /* no entry in table for command */
  7263. #define CMDNORMAL 0 /* command is an executable program */
  7264. #define CMDFUNCTION 1 /* command is a shell function */
  7265. #define CMDBUILTIN 2 /* command is a shell builtin */
  7266. /* action to find_command() */
  7267. #define DO_ERR 0x01 /* prints errors */
  7268. #define DO_ABS 0x02 /* checks absolute paths */
  7269. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7270. #define DO_ALTPATH 0x08 /* using alternate path */
  7271. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  7272. static void find_command(char *, struct cmdentry *, int, const char *);
  7273. /* ============ Hashing commands */
  7274. /*
  7275. * When commands are first encountered, they are entered in a hash table.
  7276. * This ensures that a full path search will not have to be done for them
  7277. * on each invocation.
  7278. *
  7279. * We should investigate converting to a linear search, even though that
  7280. * would make the command name "hash" a misnomer.
  7281. */
  7282. struct tblentry {
  7283. struct tblentry *next; /* next entry in hash chain */
  7284. union param param; /* definition of builtin function */
  7285. smallint cmdtype; /* CMDxxx */
  7286. char rehash; /* if set, cd done since entry created */
  7287. char cmdname[1]; /* name of command */
  7288. };
  7289. static struct tblentry **cmdtable;
  7290. #define INIT_G_cmdtable() do { \
  7291. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7292. } while (0)
  7293. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7294. static void
  7295. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7296. {
  7297. #if ENABLE_FEATURE_SH_STANDALONE
  7298. if (applet_no >= 0) {
  7299. if (APPLET_IS_NOEXEC(applet_no)) {
  7300. clearenv();
  7301. while (*envp)
  7302. putenv(*envp++);
  7303. popredir(/*drop:*/ 1);
  7304. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7305. }
  7306. /* re-exec ourselves with the new arguments */
  7307. execve(bb_busybox_exec_path, argv, envp);
  7308. /* If they called chroot or otherwise made the binary no longer
  7309. * executable, fall through */
  7310. }
  7311. #endif
  7312. repeat:
  7313. #ifdef SYSV
  7314. do {
  7315. execve(cmd, argv, envp);
  7316. } while (errno == EINTR);
  7317. #else
  7318. execve(cmd, argv, envp);
  7319. #endif
  7320. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7321. /* Run "cmd" as a shell script:
  7322. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7323. * "If the execve() function fails with ENOEXEC, the shell
  7324. * shall execute a command equivalent to having a shell invoked
  7325. * with the command name as its first operand,
  7326. * with any remaining arguments passed to the new shell"
  7327. *
  7328. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7329. * just call ourselves.
  7330. *
  7331. * Note that bash reads ~80 chars of the file, and if it sees
  7332. * a zero byte before it sees newline, it doesn't try to
  7333. * interpret it, but fails with "cannot execute binary file"
  7334. * message and exit code 126. For one, this prevents attempts
  7335. * to interpret foreign ELF binaries as shell scripts.
  7336. */
  7337. argv[0] = (char*) cmd;
  7338. cmd = bb_busybox_exec_path;
  7339. /* NB: this is only possible because all callers of shellexec()
  7340. * ensure that the argv[-1] slot exists!
  7341. */
  7342. argv--;
  7343. argv[0] = (char*) "ash";
  7344. goto repeat;
  7345. }
  7346. }
  7347. /*
  7348. * Exec a program. Never returns. If you change this routine, you may
  7349. * have to change the find_command routine as well.
  7350. * argv[-1] must exist and be writable! See tryexec() for why.
  7351. */
  7352. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7353. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7354. {
  7355. char *cmdname;
  7356. int e;
  7357. char **envp;
  7358. int exerrno;
  7359. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7360. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7361. if (strchr(prog, '/') != NULL
  7362. #if ENABLE_FEATURE_SH_STANDALONE
  7363. || (applet_no = find_applet_by_name(prog)) >= 0
  7364. #endif
  7365. ) {
  7366. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7367. if (applet_no >= 0) {
  7368. /* We tried execing ourself, but it didn't work.
  7369. * Maybe /proc/self/exe doesn't exist?
  7370. * Try $PATH search.
  7371. */
  7372. goto try_PATH;
  7373. }
  7374. e = errno;
  7375. } else {
  7376. try_PATH:
  7377. e = ENOENT;
  7378. while ((cmdname = path_advance(&path, prog)) != NULL) {
  7379. if (--idx < 0 && pathopt == NULL) {
  7380. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7381. if (errno != ENOENT && errno != ENOTDIR)
  7382. e = errno;
  7383. }
  7384. stunalloc(cmdname);
  7385. }
  7386. }
  7387. /* Map to POSIX errors */
  7388. switch (e) {
  7389. default:
  7390. exerrno = 126;
  7391. break;
  7392. case ELOOP:
  7393. case ENAMETOOLONG:
  7394. case ENOENT:
  7395. case ENOTDIR:
  7396. exerrno = 127;
  7397. break;
  7398. }
  7399. exitstatus = exerrno;
  7400. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7401. prog, e, suppress_int));
  7402. ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
  7403. /* NOTREACHED */
  7404. }
  7405. static void
  7406. printentry(struct tblentry *cmdp)
  7407. {
  7408. int idx;
  7409. const char *path;
  7410. char *name;
  7411. idx = cmdp->param.index;
  7412. path = pathval();
  7413. do {
  7414. name = path_advance(&path, cmdp->cmdname);
  7415. stunalloc(name);
  7416. } while (--idx >= 0);
  7417. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7418. }
  7419. /*
  7420. * Clear out command entries. The argument specifies the first entry in
  7421. * PATH which has changed.
  7422. */
  7423. static void
  7424. clearcmdentry(int firstchange)
  7425. {
  7426. struct tblentry **tblp;
  7427. struct tblentry **pp;
  7428. struct tblentry *cmdp;
  7429. INT_OFF;
  7430. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7431. pp = tblp;
  7432. while ((cmdp = *pp) != NULL) {
  7433. if ((cmdp->cmdtype == CMDNORMAL &&
  7434. cmdp->param.index >= firstchange)
  7435. || (cmdp->cmdtype == CMDBUILTIN &&
  7436. builtinloc >= firstchange)
  7437. ) {
  7438. *pp = cmdp->next;
  7439. free(cmdp);
  7440. } else {
  7441. pp = &cmdp->next;
  7442. }
  7443. }
  7444. }
  7445. INT_ON;
  7446. }
  7447. /*
  7448. * Locate a command in the command hash table. If "add" is nonzero,
  7449. * add the command to the table if it is not already present. The
  7450. * variable "lastcmdentry" is set to point to the address of the link
  7451. * pointing to the entry, so that delete_cmd_entry can delete the
  7452. * entry.
  7453. *
  7454. * Interrupts must be off if called with add != 0.
  7455. */
  7456. static struct tblentry **lastcmdentry;
  7457. static struct tblentry *
  7458. cmdlookup(const char *name, int add)
  7459. {
  7460. unsigned int hashval;
  7461. const char *p;
  7462. struct tblentry *cmdp;
  7463. struct tblentry **pp;
  7464. p = name;
  7465. hashval = (unsigned char)*p << 4;
  7466. while (*p)
  7467. hashval += (unsigned char)*p++;
  7468. hashval &= 0x7FFF;
  7469. pp = &cmdtable[hashval % CMDTABLESIZE];
  7470. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7471. if (strcmp(cmdp->cmdname, name) == 0)
  7472. break;
  7473. pp = &cmdp->next;
  7474. }
  7475. if (add && cmdp == NULL) {
  7476. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7477. + strlen(name)
  7478. /* + 1 - already done because
  7479. * tblentry::cmdname is char[1] */);
  7480. /*cmdp->next = NULL; - ckzalloc did it */
  7481. cmdp->cmdtype = CMDUNKNOWN;
  7482. strcpy(cmdp->cmdname, name);
  7483. }
  7484. lastcmdentry = pp;
  7485. return cmdp;
  7486. }
  7487. /*
  7488. * Delete the command entry returned on the last lookup.
  7489. */
  7490. static void
  7491. delete_cmd_entry(void)
  7492. {
  7493. struct tblentry *cmdp;
  7494. INT_OFF;
  7495. cmdp = *lastcmdentry;
  7496. *lastcmdentry = cmdp->next;
  7497. if (cmdp->cmdtype == CMDFUNCTION)
  7498. freefunc(cmdp->param.func);
  7499. free(cmdp);
  7500. INT_ON;
  7501. }
  7502. /*
  7503. * Add a new command entry, replacing any existing command entry for
  7504. * the same name - except special builtins.
  7505. */
  7506. static void
  7507. addcmdentry(char *name, struct cmdentry *entry)
  7508. {
  7509. struct tblentry *cmdp;
  7510. cmdp = cmdlookup(name, 1);
  7511. if (cmdp->cmdtype == CMDFUNCTION) {
  7512. freefunc(cmdp->param.func);
  7513. }
  7514. cmdp->cmdtype = entry->cmdtype;
  7515. cmdp->param = entry->u;
  7516. cmdp->rehash = 0;
  7517. }
  7518. static int FAST_FUNC
  7519. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7520. {
  7521. struct tblentry **pp;
  7522. struct tblentry *cmdp;
  7523. int c;
  7524. struct cmdentry entry;
  7525. char *name;
  7526. if (nextopt("r") != '\0') {
  7527. clearcmdentry(0);
  7528. return 0;
  7529. }
  7530. if (*argptr == NULL) {
  7531. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7532. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7533. if (cmdp->cmdtype == CMDNORMAL)
  7534. printentry(cmdp);
  7535. }
  7536. }
  7537. return 0;
  7538. }
  7539. c = 0;
  7540. while ((name = *argptr) != NULL) {
  7541. cmdp = cmdlookup(name, 0);
  7542. if (cmdp != NULL
  7543. && (cmdp->cmdtype == CMDNORMAL
  7544. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  7545. ) {
  7546. delete_cmd_entry();
  7547. }
  7548. find_command(name, &entry, DO_ERR, pathval());
  7549. if (entry.cmdtype == CMDUNKNOWN)
  7550. c = 1;
  7551. argptr++;
  7552. }
  7553. return c;
  7554. }
  7555. /*
  7556. * Called when a cd is done. Marks all commands so the next time they
  7557. * are executed they will be rehashed.
  7558. */
  7559. static void
  7560. hashcd(void)
  7561. {
  7562. struct tblentry **pp;
  7563. struct tblentry *cmdp;
  7564. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7565. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7566. if (cmdp->cmdtype == CMDNORMAL
  7567. || (cmdp->cmdtype == CMDBUILTIN
  7568. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7569. && builtinloc > 0)
  7570. ) {
  7571. cmdp->rehash = 1;
  7572. }
  7573. }
  7574. }
  7575. }
  7576. /*
  7577. * Fix command hash table when PATH changed.
  7578. * Called before PATH is changed. The argument is the new value of PATH;
  7579. * pathval() still returns the old value at this point.
  7580. * Called with interrupts off.
  7581. */
  7582. static void FAST_FUNC
  7583. changepath(const char *new)
  7584. {
  7585. const char *old;
  7586. int firstchange;
  7587. int idx;
  7588. int idx_bltin;
  7589. old = pathval();
  7590. firstchange = 9999; /* assume no change */
  7591. idx = 0;
  7592. idx_bltin = -1;
  7593. for (;;) {
  7594. if (*old != *new) {
  7595. firstchange = idx;
  7596. if ((*old == '\0' && *new == ':')
  7597. || (*old == ':' && *new == '\0')
  7598. ) {
  7599. firstchange++;
  7600. }
  7601. old = new; /* ignore subsequent differences */
  7602. }
  7603. if (*new == '\0')
  7604. break;
  7605. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7606. idx_bltin = idx;
  7607. if (*new == ':')
  7608. idx++;
  7609. new++;
  7610. old++;
  7611. }
  7612. if (builtinloc < 0 && idx_bltin >= 0)
  7613. builtinloc = idx_bltin; /* zap builtins */
  7614. if (builtinloc >= 0 && idx_bltin < 0)
  7615. firstchange = 0;
  7616. clearcmdentry(firstchange);
  7617. builtinloc = idx_bltin;
  7618. }
  7619. enum {
  7620. TEOF,
  7621. TNL,
  7622. TREDIR,
  7623. TWORD,
  7624. TSEMI,
  7625. TBACKGND,
  7626. TAND,
  7627. TOR,
  7628. TPIPE,
  7629. TLP,
  7630. TRP,
  7631. TENDCASE,
  7632. TENDBQUOTE,
  7633. TNOT,
  7634. TCASE,
  7635. TDO,
  7636. TDONE,
  7637. TELIF,
  7638. TELSE,
  7639. TESAC,
  7640. TFI,
  7641. TFOR,
  7642. #if BASH_FUNCTION
  7643. TFUNCTION,
  7644. #endif
  7645. TIF,
  7646. TIN,
  7647. TTHEN,
  7648. TUNTIL,
  7649. TWHILE,
  7650. TBEGIN,
  7651. TEND
  7652. };
  7653. typedef smallint token_id_t;
  7654. /* Nth bit indicates if token marks the end of a list */
  7655. enum {
  7656. tokendlist = 0
  7657. /* 0 */ | (1u << TEOF)
  7658. /* 1 */ | (0u << TNL)
  7659. /* 2 */ | (0u << TREDIR)
  7660. /* 3 */ | (0u << TWORD)
  7661. /* 4 */ | (0u << TSEMI)
  7662. /* 5 */ | (0u << TBACKGND)
  7663. /* 6 */ | (0u << TAND)
  7664. /* 7 */ | (0u << TOR)
  7665. /* 8 */ | (0u << TPIPE)
  7666. /* 9 */ | (0u << TLP)
  7667. /* 10 */ | (1u << TRP)
  7668. /* 11 */ | (1u << TENDCASE)
  7669. /* 12 */ | (1u << TENDBQUOTE)
  7670. /* 13 */ | (0u << TNOT)
  7671. /* 14 */ | (0u << TCASE)
  7672. /* 15 */ | (1u << TDO)
  7673. /* 16 */ | (1u << TDONE)
  7674. /* 17 */ | (1u << TELIF)
  7675. /* 18 */ | (1u << TELSE)
  7676. /* 19 */ | (1u << TESAC)
  7677. /* 20 */ | (1u << TFI)
  7678. /* 21 */ | (0u << TFOR)
  7679. #if BASH_FUNCTION
  7680. /* 22 */ | (0u << TFUNCTION)
  7681. #endif
  7682. /* 23 */ | (0u << TIF)
  7683. /* 24 */ | (0u << TIN)
  7684. /* 25 */ | (1u << TTHEN)
  7685. /* 26 */ | (0u << TUNTIL)
  7686. /* 27 */ | (0u << TWHILE)
  7687. /* 28 */ | (0u << TBEGIN)
  7688. /* 29 */ | (1u << TEND)
  7689. , /* thus far 29 bits used */
  7690. };
  7691. static const char *const tokname_array[] = {
  7692. "end of file",
  7693. "newline",
  7694. "redirection",
  7695. "word",
  7696. ";",
  7697. "&",
  7698. "&&",
  7699. "||",
  7700. "|",
  7701. "(",
  7702. ")",
  7703. ";;",
  7704. "`",
  7705. #define KWDOFFSET 13
  7706. /* the following are keywords */
  7707. "!",
  7708. "case",
  7709. "do",
  7710. "done",
  7711. "elif",
  7712. "else",
  7713. "esac",
  7714. "fi",
  7715. "for",
  7716. #if BASH_FUNCTION
  7717. "function",
  7718. #endif
  7719. "if",
  7720. "in",
  7721. "then",
  7722. "until",
  7723. "while",
  7724. "{",
  7725. "}",
  7726. };
  7727. /* Wrapper around strcmp for qsort/bsearch/... */
  7728. static int
  7729. pstrcmp(const void *a, const void *b)
  7730. {
  7731. return strcmp((char*)a, *(char**)b);
  7732. }
  7733. static const char *const *
  7734. findkwd(const char *s)
  7735. {
  7736. return bsearch(s, tokname_array + KWDOFFSET,
  7737. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7738. sizeof(tokname_array[0]), pstrcmp);
  7739. }
  7740. /*
  7741. * Locate and print what a word is...
  7742. */
  7743. static int
  7744. describe_command(char *command, const char *path, int describe_command_verbose)
  7745. {
  7746. struct cmdentry entry;
  7747. #if ENABLE_ASH_ALIAS
  7748. const struct alias *ap;
  7749. #endif
  7750. path = path ? path : pathval();
  7751. if (describe_command_verbose) {
  7752. out1str(command);
  7753. }
  7754. /* First look at the keywords */
  7755. if (findkwd(command)) {
  7756. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7757. goto out;
  7758. }
  7759. #if ENABLE_ASH_ALIAS
  7760. /* Then look at the aliases */
  7761. ap = lookupalias(command, 0);
  7762. if (ap != NULL) {
  7763. if (!describe_command_verbose) {
  7764. out1str("alias ");
  7765. printalias(ap);
  7766. return 0;
  7767. }
  7768. out1fmt(" is an alias for %s", ap->val);
  7769. goto out;
  7770. }
  7771. #endif
  7772. /* Brute force */
  7773. find_command(command, &entry, DO_ABS, path);
  7774. switch (entry.cmdtype) {
  7775. case CMDNORMAL: {
  7776. int j = entry.u.index;
  7777. char *p;
  7778. if (j < 0) {
  7779. p = command;
  7780. } else {
  7781. do {
  7782. p = path_advance(&path, command);
  7783. stunalloc(p);
  7784. } while (--j >= 0);
  7785. }
  7786. if (describe_command_verbose) {
  7787. out1fmt(" is %s", p);
  7788. } else {
  7789. out1str(p);
  7790. }
  7791. break;
  7792. }
  7793. case CMDFUNCTION:
  7794. if (describe_command_verbose) {
  7795. /*out1str(" is a shell function");*/
  7796. out1str(" is a function"); /* bash says this */
  7797. } else {
  7798. out1str(command);
  7799. }
  7800. break;
  7801. case CMDBUILTIN:
  7802. if (describe_command_verbose) {
  7803. out1fmt(" is a %sshell builtin",
  7804. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7805. "special " : nullstr
  7806. );
  7807. } else {
  7808. out1str(command);
  7809. }
  7810. break;
  7811. default:
  7812. if (describe_command_verbose) {
  7813. out1str(": not found\n");
  7814. }
  7815. return 127;
  7816. }
  7817. out:
  7818. out1str("\n");
  7819. return 0;
  7820. }
  7821. static int FAST_FUNC
  7822. typecmd(int argc UNUSED_PARAM, char **argv)
  7823. {
  7824. int i = 1;
  7825. int err = 0;
  7826. int verbose = 1;
  7827. /* type -p ... ? (we don't bother checking for 'p') */
  7828. if (argv[1] && argv[1][0] == '-') {
  7829. i++;
  7830. verbose = 0;
  7831. }
  7832. while (argv[i]) {
  7833. err |= describe_command(argv[i++], NULL, verbose);
  7834. }
  7835. return err;
  7836. }
  7837. #if ENABLE_ASH_CMDCMD
  7838. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7839. static char **
  7840. parse_command_args(char **argv, const char **path)
  7841. {
  7842. char *cp, c;
  7843. for (;;) {
  7844. cp = *++argv;
  7845. if (!cp)
  7846. return NULL;
  7847. if (*cp++ != '-')
  7848. break;
  7849. c = *cp++;
  7850. if (!c)
  7851. break;
  7852. if (c == '-' && !*cp) {
  7853. if (!*++argv)
  7854. return NULL;
  7855. break;
  7856. }
  7857. do {
  7858. switch (c) {
  7859. case 'p':
  7860. *path = bb_default_path;
  7861. break;
  7862. default:
  7863. /* run 'typecmd' for other options */
  7864. return NULL;
  7865. }
  7866. c = *cp++;
  7867. } while (c);
  7868. }
  7869. return argv;
  7870. }
  7871. static int FAST_FUNC
  7872. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7873. {
  7874. char *cmd;
  7875. int c;
  7876. enum {
  7877. VERIFY_BRIEF = 1,
  7878. VERIFY_VERBOSE = 2,
  7879. } verify = 0;
  7880. const char *path = NULL;
  7881. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7882. * never reaches this function.
  7883. */
  7884. while ((c = nextopt("pvV")) != '\0')
  7885. if (c == 'V')
  7886. verify |= VERIFY_VERBOSE;
  7887. else if (c == 'v')
  7888. /*verify |= VERIFY_BRIEF*/;
  7889. #if DEBUG
  7890. else if (c != 'p')
  7891. abort();
  7892. #endif
  7893. else
  7894. path = bb_default_path;
  7895. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7896. cmd = *argptr;
  7897. if (/*verify && */ cmd)
  7898. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7899. return 0;
  7900. }
  7901. #endif
  7902. /*static int funcblocksize; // size of structures in function */
  7903. /*static int funcstringsize; // size of strings in node */
  7904. static void *funcblock; /* block to allocate function from */
  7905. static char *funcstring_end; /* end of block to allocate strings from */
  7906. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7907. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7908. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7909. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7910. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7911. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7912. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7913. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7914. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7915. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7916. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7917. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7918. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7919. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7920. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7921. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7922. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7923. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7924. #if BASH_REDIR_OUTPUT
  7925. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7926. #endif
  7927. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7928. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7929. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7930. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7931. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7932. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7933. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7934. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7935. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7936. };
  7937. static int calcsize(int funcblocksize, union node *n);
  7938. static int
  7939. sizenodelist(int funcblocksize, struct nodelist *lp)
  7940. {
  7941. while (lp) {
  7942. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7943. funcblocksize = calcsize(funcblocksize, lp->n);
  7944. lp = lp->next;
  7945. }
  7946. return funcblocksize;
  7947. }
  7948. static int
  7949. calcsize(int funcblocksize, union node *n)
  7950. {
  7951. if (n == NULL)
  7952. return funcblocksize;
  7953. funcblocksize += nodesize[n->type];
  7954. switch (n->type) {
  7955. case NCMD:
  7956. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  7957. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  7958. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  7959. break;
  7960. case NPIPE:
  7961. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  7962. break;
  7963. case NREDIR:
  7964. case NBACKGND:
  7965. case NSUBSHELL:
  7966. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  7967. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  7968. break;
  7969. case NAND:
  7970. case NOR:
  7971. case NSEMI:
  7972. case NWHILE:
  7973. case NUNTIL:
  7974. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  7975. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  7976. break;
  7977. case NIF:
  7978. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  7979. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  7980. funcblocksize = calcsize(funcblocksize, n->nif.test);
  7981. break;
  7982. case NFOR:
  7983. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  7984. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  7985. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  7986. break;
  7987. case NCASE:
  7988. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  7989. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  7990. break;
  7991. case NCLIST:
  7992. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  7993. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  7994. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  7995. break;
  7996. case NDEFUN:
  7997. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  7998. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  7999. break;
  8000. case NARG:
  8001. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8002. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8003. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8004. break;
  8005. case NTO:
  8006. #if BASH_REDIR_OUTPUT
  8007. case NTO2:
  8008. #endif
  8009. case NCLOBBER:
  8010. case NFROM:
  8011. case NFROMTO:
  8012. case NAPPEND:
  8013. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8014. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8015. break;
  8016. case NTOFD:
  8017. case NFROMFD:
  8018. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8019. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8020. break;
  8021. case NHERE:
  8022. case NXHERE:
  8023. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8024. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8025. break;
  8026. case NNOT:
  8027. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8028. break;
  8029. };
  8030. return funcblocksize;
  8031. }
  8032. static char *
  8033. nodeckstrdup(char *s)
  8034. {
  8035. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8036. return strcpy(funcstring_end, s);
  8037. }
  8038. static union node *copynode(union node *);
  8039. static struct nodelist *
  8040. copynodelist(struct nodelist *lp)
  8041. {
  8042. struct nodelist *start;
  8043. struct nodelist **lpp;
  8044. lpp = &start;
  8045. while (lp) {
  8046. *lpp = funcblock;
  8047. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8048. (*lpp)->n = copynode(lp->n);
  8049. lp = lp->next;
  8050. lpp = &(*lpp)->next;
  8051. }
  8052. *lpp = NULL;
  8053. return start;
  8054. }
  8055. static union node *
  8056. copynode(union node *n)
  8057. {
  8058. union node *new;
  8059. if (n == NULL)
  8060. return NULL;
  8061. new = funcblock;
  8062. funcblock = (char *) funcblock + nodesize[n->type];
  8063. switch (n->type) {
  8064. case NCMD:
  8065. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8066. new->ncmd.args = copynode(n->ncmd.args);
  8067. new->ncmd.assign = copynode(n->ncmd.assign);
  8068. new->ncmd.linno = n->ncmd.linno;
  8069. break;
  8070. case NPIPE:
  8071. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8072. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8073. break;
  8074. case NREDIR:
  8075. case NBACKGND:
  8076. case NSUBSHELL:
  8077. new->nredir.redirect = copynode(n->nredir.redirect);
  8078. new->nredir.n = copynode(n->nredir.n);
  8079. new->nredir.linno = n->nredir.linno;
  8080. break;
  8081. case NAND:
  8082. case NOR:
  8083. case NSEMI:
  8084. case NWHILE:
  8085. case NUNTIL:
  8086. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8087. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8088. break;
  8089. case NIF:
  8090. new->nif.elsepart = copynode(n->nif.elsepart);
  8091. new->nif.ifpart = copynode(n->nif.ifpart);
  8092. new->nif.test = copynode(n->nif.test);
  8093. break;
  8094. case NFOR:
  8095. new->nfor.var = nodeckstrdup(n->nfor.var);
  8096. new->nfor.body = copynode(n->nfor.body);
  8097. new->nfor.args = copynode(n->nfor.args);
  8098. new->nfor.linno = n->nfor.linno;
  8099. break;
  8100. case NCASE:
  8101. new->ncase.cases = copynode(n->ncase.cases);
  8102. new->ncase.expr = copynode(n->ncase.expr);
  8103. new->ncase.linno = n->ncase.linno;
  8104. break;
  8105. case NCLIST:
  8106. new->nclist.body = copynode(n->nclist.body);
  8107. new->nclist.pattern = copynode(n->nclist.pattern);
  8108. new->nclist.next = copynode(n->nclist.next);
  8109. break;
  8110. case NDEFUN:
  8111. new->ndefun.body = copynode(n->ndefun.body);
  8112. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8113. new->ndefun.linno = n->ndefun.linno;
  8114. break;
  8115. case NARG:
  8116. new->narg.backquote = copynodelist(n->narg.backquote);
  8117. new->narg.text = nodeckstrdup(n->narg.text);
  8118. new->narg.next = copynode(n->narg.next);
  8119. break;
  8120. case NTO:
  8121. #if BASH_REDIR_OUTPUT
  8122. case NTO2:
  8123. #endif
  8124. case NCLOBBER:
  8125. case NFROM:
  8126. case NFROMTO:
  8127. case NAPPEND:
  8128. new->nfile.fname = copynode(n->nfile.fname);
  8129. new->nfile.fd = n->nfile.fd;
  8130. new->nfile.next = copynode(n->nfile.next);
  8131. break;
  8132. case NTOFD:
  8133. case NFROMFD:
  8134. new->ndup.vname = copynode(n->ndup.vname);
  8135. new->ndup.dupfd = n->ndup.dupfd;
  8136. new->ndup.fd = n->ndup.fd;
  8137. new->ndup.next = copynode(n->ndup.next);
  8138. break;
  8139. case NHERE:
  8140. case NXHERE:
  8141. new->nhere.doc = copynode(n->nhere.doc);
  8142. new->nhere.fd = n->nhere.fd;
  8143. new->nhere.next = copynode(n->nhere.next);
  8144. break;
  8145. case NNOT:
  8146. new->nnot.com = copynode(n->nnot.com);
  8147. break;
  8148. };
  8149. new->type = n->type;
  8150. return new;
  8151. }
  8152. /*
  8153. * Make a copy of a parse tree.
  8154. */
  8155. static struct funcnode *
  8156. copyfunc(union node *n)
  8157. {
  8158. struct funcnode *f;
  8159. size_t blocksize;
  8160. /*funcstringsize = 0;*/
  8161. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8162. f = ckzalloc(blocksize /* + funcstringsize */);
  8163. funcblock = (char *) f + offsetof(struct funcnode, n);
  8164. funcstring_end = (char *) f + blocksize;
  8165. copynode(n);
  8166. /* f->count = 0; - ckzalloc did it */
  8167. return f;
  8168. }
  8169. /*
  8170. * Define a shell function.
  8171. */
  8172. static void
  8173. defun(union node *func)
  8174. {
  8175. struct cmdentry entry;
  8176. INT_OFF;
  8177. entry.cmdtype = CMDFUNCTION;
  8178. entry.u.func = copyfunc(func);
  8179. addcmdentry(func->ndefun.text, &entry);
  8180. INT_ON;
  8181. }
  8182. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8183. #define SKIPBREAK (1 << 0)
  8184. #define SKIPCONT (1 << 1)
  8185. #define SKIPFUNC (1 << 2)
  8186. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8187. static int skipcount; /* number of levels to skip */
  8188. static int loopnest; /* current loop nesting level */
  8189. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8190. /* Forward decl way out to parsing code - dotrap needs it */
  8191. static int evalstring(char *s, int flags);
  8192. /* Called to execute a trap.
  8193. * Single callsite - at the end of evaltree().
  8194. * If we return non-zero, evaltree raises EXEXIT exception.
  8195. *
  8196. * Perhaps we should avoid entering new trap handlers
  8197. * while we are executing a trap handler. [is it a TODO?]
  8198. */
  8199. static void
  8200. dotrap(void)
  8201. {
  8202. uint8_t *g;
  8203. int sig;
  8204. uint8_t last_status;
  8205. if (!pending_sig)
  8206. return;
  8207. last_status = exitstatus;
  8208. pending_sig = 0;
  8209. barrier();
  8210. TRACE(("dotrap entered\n"));
  8211. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8212. char *p;
  8213. if (!*g)
  8214. continue;
  8215. if (evalskip) {
  8216. pending_sig = sig;
  8217. break;
  8218. }
  8219. p = trap[sig];
  8220. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8221. * don't upset it by resetting gotsig[SIGINT-1] */
  8222. if (sig == SIGINT && !p)
  8223. continue;
  8224. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8225. *g = 0;
  8226. if (!p)
  8227. continue;
  8228. evalstring(p, 0);
  8229. }
  8230. exitstatus = last_status;
  8231. TRACE(("dotrap returns\n"));
  8232. }
  8233. /* forward declarations - evaluation is fairly recursive business... */
  8234. static int evalloop(union node *, int);
  8235. static int evalfor(union node *, int);
  8236. static int evalcase(union node *, int);
  8237. static int evalsubshell(union node *, int);
  8238. static void expredir(union node *);
  8239. static int evalpipe(union node *, int);
  8240. static int evalcommand(union node *, int);
  8241. static int evalbltin(const struct builtincmd *, int, char **, int);
  8242. static void prehash(union node *);
  8243. /*
  8244. * Evaluate a parse tree. The value is left in the global variable
  8245. * exitstatus.
  8246. */
  8247. static int
  8248. evaltree(union node *n, int flags)
  8249. {
  8250. int checkexit = 0;
  8251. int (*evalfn)(union node *, int);
  8252. int status = 0;
  8253. if (n == NULL) {
  8254. TRACE(("evaltree(NULL) called\n"));
  8255. goto out;
  8256. }
  8257. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8258. dotrap();
  8259. switch (n->type) {
  8260. default:
  8261. #if DEBUG
  8262. out1fmt("Node type = %d\n", n->type);
  8263. fflush_all();
  8264. break;
  8265. #endif
  8266. case NNOT:
  8267. status = !evaltree(n->nnot.com, EV_TESTED);
  8268. goto setstatus;
  8269. case NREDIR:
  8270. errlinno = lineno = n->nredir.linno;
  8271. if (funcline)
  8272. lineno -= funcline - 1;
  8273. expredir(n->nredir.redirect);
  8274. pushredir(n->nredir.redirect);
  8275. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8276. if (!status) {
  8277. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8278. }
  8279. if (n->nredir.redirect)
  8280. popredir(/*drop:*/ 0);
  8281. goto setstatus;
  8282. case NCMD:
  8283. evalfn = evalcommand;
  8284. checkexit:
  8285. if (eflag && !(flags & EV_TESTED))
  8286. checkexit = ~0;
  8287. goto calleval;
  8288. case NFOR:
  8289. evalfn = evalfor;
  8290. goto calleval;
  8291. case NWHILE:
  8292. case NUNTIL:
  8293. evalfn = evalloop;
  8294. goto calleval;
  8295. case NSUBSHELL:
  8296. case NBACKGND:
  8297. evalfn = evalsubshell;
  8298. goto checkexit;
  8299. case NPIPE:
  8300. evalfn = evalpipe;
  8301. goto checkexit;
  8302. case NCASE:
  8303. evalfn = evalcase;
  8304. goto calleval;
  8305. case NAND:
  8306. case NOR:
  8307. case NSEMI: {
  8308. #if NAND + 1 != NOR
  8309. #error NAND + 1 != NOR
  8310. #endif
  8311. #if NOR + 1 != NSEMI
  8312. #error NOR + 1 != NSEMI
  8313. #endif
  8314. unsigned is_or = n->type - NAND;
  8315. status = evaltree(
  8316. n->nbinary.ch1,
  8317. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8318. );
  8319. if ((!status) == is_or || evalskip)
  8320. break;
  8321. n = n->nbinary.ch2;
  8322. evaln:
  8323. evalfn = evaltree;
  8324. calleval:
  8325. status = evalfn(n, flags);
  8326. goto setstatus;
  8327. }
  8328. case NIF:
  8329. status = evaltree(n->nif.test, EV_TESTED);
  8330. if (evalskip)
  8331. break;
  8332. if (!status) {
  8333. n = n->nif.ifpart;
  8334. goto evaln;
  8335. }
  8336. if (n->nif.elsepart) {
  8337. n = n->nif.elsepart;
  8338. goto evaln;
  8339. }
  8340. status = 0;
  8341. goto setstatus;
  8342. case NDEFUN:
  8343. defun(n);
  8344. /* Not necessary. To test it:
  8345. * "false; f() { qwerty; }; echo $?" should print 0.
  8346. */
  8347. /* status = 0; */
  8348. setstatus:
  8349. exitstatus = status;
  8350. break;
  8351. }
  8352. out:
  8353. /* Order of checks below is important:
  8354. * signal handlers trigger before exit caused by "set -e".
  8355. */
  8356. dotrap();
  8357. if (checkexit & status)
  8358. raise_exception(EXEXIT);
  8359. if (flags & EV_EXIT)
  8360. raise_exception(EXEXIT);
  8361. TRACE(("leaving evaltree (no interrupts)\n"));
  8362. return exitstatus;
  8363. }
  8364. static int
  8365. skiploop(void)
  8366. {
  8367. int skip = evalskip;
  8368. switch (skip) {
  8369. case 0:
  8370. break;
  8371. case SKIPBREAK:
  8372. case SKIPCONT:
  8373. if (--skipcount <= 0) {
  8374. evalskip = 0;
  8375. break;
  8376. }
  8377. skip = SKIPBREAK;
  8378. break;
  8379. }
  8380. return skip;
  8381. }
  8382. static int
  8383. evalloop(union node *n, int flags)
  8384. {
  8385. int skip;
  8386. int status;
  8387. loopnest++;
  8388. status = 0;
  8389. flags &= EV_TESTED;
  8390. do {
  8391. int i;
  8392. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8393. skip = skiploop();
  8394. if (skip == SKIPFUNC)
  8395. status = i;
  8396. if (skip)
  8397. continue;
  8398. if (n->type != NWHILE)
  8399. i = !i;
  8400. if (i != 0)
  8401. break;
  8402. status = evaltree(n->nbinary.ch2, flags);
  8403. skip = skiploop();
  8404. } while (!(skip & ~SKIPCONT));
  8405. loopnest--;
  8406. return status;
  8407. }
  8408. static int
  8409. evalfor(union node *n, int flags)
  8410. {
  8411. struct arglist arglist;
  8412. union node *argp;
  8413. struct strlist *sp;
  8414. struct stackmark smark;
  8415. int status = 0;
  8416. errlinno = lineno = n->ncase.linno;
  8417. if (funcline)
  8418. lineno -= funcline - 1;
  8419. setstackmark(&smark);
  8420. arglist.list = NULL;
  8421. arglist.lastp = &arglist.list;
  8422. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8423. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8424. }
  8425. *arglist.lastp = NULL;
  8426. loopnest++;
  8427. flags &= EV_TESTED;
  8428. for (sp = arglist.list; sp; sp = sp->next) {
  8429. setvar0(n->nfor.var, sp->text);
  8430. status = evaltree(n->nfor.body, flags);
  8431. if (skiploop() & ~SKIPCONT)
  8432. break;
  8433. }
  8434. loopnest--;
  8435. popstackmark(&smark);
  8436. return status;
  8437. }
  8438. static int
  8439. evalcase(union node *n, int flags)
  8440. {
  8441. union node *cp;
  8442. union node *patp;
  8443. struct arglist arglist;
  8444. struct stackmark smark;
  8445. int status = 0;
  8446. errlinno = lineno = n->ncase.linno;
  8447. if (funcline)
  8448. lineno -= funcline - 1;
  8449. setstackmark(&smark);
  8450. arglist.list = NULL;
  8451. arglist.lastp = &arglist.list;
  8452. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8453. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8454. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8455. if (casematch(patp, arglist.list->text)) {
  8456. /* Ensure body is non-empty as otherwise
  8457. * EV_EXIT may prevent us from setting the
  8458. * exit status.
  8459. */
  8460. if (evalskip == 0 && cp->nclist.body) {
  8461. status = evaltree(cp->nclist.body, flags);
  8462. }
  8463. goto out;
  8464. }
  8465. }
  8466. }
  8467. out:
  8468. popstackmark(&smark);
  8469. return status;
  8470. }
  8471. /*
  8472. * Kick off a subshell to evaluate a tree.
  8473. */
  8474. static int
  8475. evalsubshell(union node *n, int flags)
  8476. {
  8477. struct job *jp;
  8478. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8479. int status;
  8480. errlinno = lineno = n->nredir.linno;
  8481. if (funcline)
  8482. lineno -= funcline - 1;
  8483. expredir(n->nredir.redirect);
  8484. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8485. goto nofork;
  8486. INT_OFF;
  8487. if (backgnd == FORK_FG)
  8488. get_tty_state();
  8489. jp = makejob(/*n,*/ 1);
  8490. if (forkshell(jp, n, backgnd) == 0) {
  8491. /* child */
  8492. INT_ON;
  8493. flags |= EV_EXIT;
  8494. if (backgnd)
  8495. flags &= ~EV_TESTED;
  8496. nofork:
  8497. redirect(n->nredir.redirect, 0);
  8498. evaltreenr(n->nredir.n, flags);
  8499. /* never returns */
  8500. }
  8501. /* parent */
  8502. status = 0;
  8503. if (backgnd == FORK_FG)
  8504. status = waitforjob(jp);
  8505. INT_ON;
  8506. return status;
  8507. }
  8508. /*
  8509. * Compute the names of the files in a redirection list.
  8510. */
  8511. static void fixredir(union node *, const char *, int);
  8512. static void
  8513. expredir(union node *n)
  8514. {
  8515. union node *redir;
  8516. for (redir = n; redir; redir = redir->nfile.next) {
  8517. struct arglist fn;
  8518. fn.list = NULL;
  8519. fn.lastp = &fn.list;
  8520. switch (redir->type) {
  8521. case NFROMTO:
  8522. case NFROM:
  8523. case NTO:
  8524. #if BASH_REDIR_OUTPUT
  8525. case NTO2:
  8526. #endif
  8527. case NCLOBBER:
  8528. case NAPPEND:
  8529. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8530. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8531. #if BASH_REDIR_OUTPUT
  8532. store_expfname:
  8533. #endif
  8534. #if 0
  8535. // By the design of stack allocator, the loop of this kind:
  8536. // while true; do while true; do break; done </dev/null; done
  8537. // will look like a memory leak: ash plans to free expfname's
  8538. // of "/dev/null" as soon as it finishes running the loop
  8539. // (in this case, never).
  8540. // This "fix" is wrong:
  8541. if (redir->nfile.expfname)
  8542. stunalloc(redir->nfile.expfname);
  8543. // It results in corrupted state of stacked allocations.
  8544. #endif
  8545. redir->nfile.expfname = fn.list->text;
  8546. break;
  8547. case NFROMFD:
  8548. case NTOFD: /* >& */
  8549. if (redir->ndup.vname) {
  8550. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  8551. if (fn.list == NULL)
  8552. ash_msg_and_raise_error("redir error");
  8553. #if BASH_REDIR_OUTPUT
  8554. //FIXME: we used expandarg with different args!
  8555. if (!isdigit_str9(fn.list->text)) {
  8556. /* >&file, not >&fd */
  8557. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8558. ash_msg_and_raise_error("redir error");
  8559. redir->type = NTO2;
  8560. goto store_expfname;
  8561. }
  8562. #endif
  8563. fixredir(redir, fn.list->text, 1);
  8564. }
  8565. break;
  8566. }
  8567. }
  8568. }
  8569. /*
  8570. * Evaluate a pipeline. All the processes in the pipeline are children
  8571. * of the process creating the pipeline. (This differs from some versions
  8572. * of the shell, which make the last process in a pipeline the parent
  8573. * of all the rest.)
  8574. */
  8575. static int
  8576. evalpipe(union node *n, int flags)
  8577. {
  8578. struct job *jp;
  8579. struct nodelist *lp;
  8580. int pipelen;
  8581. int prevfd;
  8582. int pip[2];
  8583. int status = 0;
  8584. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8585. pipelen = 0;
  8586. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8587. pipelen++;
  8588. flags |= EV_EXIT;
  8589. INT_OFF;
  8590. if (n->npipe.pipe_backgnd == 0)
  8591. get_tty_state();
  8592. jp = makejob(/*n,*/ pipelen);
  8593. prevfd = -1;
  8594. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8595. prehash(lp->n);
  8596. pip[1] = -1;
  8597. if (lp->next) {
  8598. if (pipe(pip) < 0) {
  8599. close(prevfd);
  8600. ash_msg_and_raise_perror("can't create pipe");
  8601. }
  8602. }
  8603. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8604. /* child */
  8605. INT_ON;
  8606. if (pip[1] >= 0) {
  8607. close(pip[0]);
  8608. }
  8609. if (prevfd > 0) {
  8610. dup2(prevfd, 0);
  8611. close(prevfd);
  8612. }
  8613. if (pip[1] > 1) {
  8614. dup2(pip[1], 1);
  8615. close(pip[1]);
  8616. }
  8617. evaltreenr(lp->n, flags);
  8618. /* never returns */
  8619. }
  8620. /* parent */
  8621. if (prevfd >= 0)
  8622. close(prevfd);
  8623. prevfd = pip[0];
  8624. /* Don't want to trigger debugging */
  8625. if (pip[1] != -1)
  8626. close(pip[1]);
  8627. }
  8628. if (n->npipe.pipe_backgnd == 0) {
  8629. status = waitforjob(jp);
  8630. TRACE(("evalpipe: job done exit status %d\n", status));
  8631. }
  8632. INT_ON;
  8633. return status;
  8634. }
  8635. /*
  8636. * Controls whether the shell is interactive or not.
  8637. */
  8638. static void
  8639. setinteractive(int on)
  8640. {
  8641. static smallint is_interactive;
  8642. if (++on == is_interactive)
  8643. return;
  8644. is_interactive = on;
  8645. setsignal(SIGINT);
  8646. setsignal(SIGQUIT);
  8647. setsignal(SIGTERM);
  8648. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8649. if (is_interactive > 1) {
  8650. /* Looks like they want an interactive shell */
  8651. static smallint did_banner;
  8652. if (!did_banner) {
  8653. /* note: ash and hush share this string */
  8654. out1fmt("\n\n%s %s\n"
  8655. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8656. "\n",
  8657. bb_banner,
  8658. "built-in shell (ash)"
  8659. );
  8660. did_banner = 1;
  8661. }
  8662. }
  8663. #endif
  8664. }
  8665. static void
  8666. optschanged(void)
  8667. {
  8668. #if DEBUG
  8669. opentrace();
  8670. #endif
  8671. setinteractive(iflag);
  8672. setjobctl(mflag);
  8673. #if ENABLE_FEATURE_EDITING_VI
  8674. if (viflag)
  8675. line_input_state->flags |= VI_MODE;
  8676. else
  8677. line_input_state->flags &= ~VI_MODE;
  8678. #else
  8679. viflag = 0; /* forcibly keep the option off */
  8680. #endif
  8681. }
  8682. struct localvar_list {
  8683. struct localvar_list *next;
  8684. struct localvar *lv;
  8685. };
  8686. static struct localvar_list *localvar_stack;
  8687. /*
  8688. * Called after a function returns.
  8689. * Interrupts must be off.
  8690. */
  8691. static void
  8692. poplocalvars(int keep)
  8693. {
  8694. struct localvar_list *ll;
  8695. struct localvar *lvp, *next;
  8696. struct var *vp;
  8697. INT_OFF;
  8698. ll = localvar_stack;
  8699. localvar_stack = ll->next;
  8700. next = ll->lv;
  8701. free(ll);
  8702. while ((lvp = next) != NULL) {
  8703. next = lvp->next;
  8704. vp = lvp->vp;
  8705. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8706. if (keep) {
  8707. int bits = VSTRFIXED;
  8708. if (lvp->flags != VUNSET) {
  8709. if (vp->var_text == lvp->text)
  8710. bits |= VTEXTFIXED;
  8711. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8712. free((char*)lvp->text);
  8713. }
  8714. vp->flags &= ~bits;
  8715. vp->flags |= (lvp->flags & bits);
  8716. if ((vp->flags &
  8717. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8718. unsetvar(vp->var_text);
  8719. } else if (vp == NULL) { /* $- saved */
  8720. memcpy(optlist, lvp->text, sizeof(optlist));
  8721. free((char*)lvp->text);
  8722. optschanged();
  8723. } else if (lvp->flags == VUNSET) {
  8724. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8725. unsetvar(vp->var_text);
  8726. } else {
  8727. if (vp->var_func)
  8728. vp->var_func(var_end(lvp->text));
  8729. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8730. free((char*)vp->var_text);
  8731. vp->flags = lvp->flags;
  8732. vp->var_text = lvp->text;
  8733. }
  8734. free(lvp);
  8735. }
  8736. INT_ON;
  8737. }
  8738. /*
  8739. * Create a new localvar environment.
  8740. */
  8741. static struct localvar_list *
  8742. pushlocalvars(void)
  8743. {
  8744. struct localvar_list *ll;
  8745. INT_OFF;
  8746. ll = ckzalloc(sizeof(*ll));
  8747. /*ll->lv = NULL; - zalloc did it */
  8748. ll->next = localvar_stack;
  8749. localvar_stack = ll;
  8750. INT_ON;
  8751. return ll->next;
  8752. }
  8753. static void
  8754. unwindlocalvars(struct localvar_list *stop)
  8755. {
  8756. while (localvar_stack != stop)
  8757. poplocalvars(0);
  8758. }
  8759. static int
  8760. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8761. {
  8762. volatile struct shparam saveparam;
  8763. struct jmploc *volatile savehandler;
  8764. struct jmploc jmploc;
  8765. int e;
  8766. int savefuncline;
  8767. saveparam = shellparam;
  8768. savefuncline = funcline;
  8769. savehandler = exception_handler;
  8770. e = setjmp(jmploc.loc);
  8771. if (e) {
  8772. goto funcdone;
  8773. }
  8774. INT_OFF;
  8775. exception_handler = &jmploc;
  8776. shellparam.malloced = 0;
  8777. func->count++;
  8778. funcline = func->n.ndefun.linno;
  8779. INT_ON;
  8780. shellparam.nparam = argc - 1;
  8781. shellparam.p = argv + 1;
  8782. #if ENABLE_ASH_GETOPTS
  8783. shellparam.optind = 1;
  8784. shellparam.optoff = -1;
  8785. #endif
  8786. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  8787. funcdone:
  8788. INT_OFF;
  8789. funcline = savefuncline;
  8790. freefunc(func);
  8791. freeparam(&shellparam);
  8792. shellparam = saveparam;
  8793. exception_handler = savehandler;
  8794. INT_ON;
  8795. evalskip &= ~SKIPFUNC;
  8796. return e;
  8797. }
  8798. /*
  8799. * Make a variable a local variable. When a variable is made local, it's
  8800. * value and flags are saved in a localvar structure. The saved values
  8801. * will be restored when the shell function returns. We handle the name
  8802. * "-" as a special case: it makes changes to "set +-options" local
  8803. * (options will be restored on return from the function).
  8804. */
  8805. static void
  8806. mklocal(char *name)
  8807. {
  8808. struct localvar *lvp;
  8809. struct var **vpp;
  8810. struct var *vp;
  8811. char *eq = strchr(name, '=');
  8812. INT_OFF;
  8813. /* Cater for duplicate "local". Examples:
  8814. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8815. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8816. */
  8817. lvp = localvar_stack->lv;
  8818. while (lvp) {
  8819. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8820. if (eq)
  8821. setvareq(name, 0);
  8822. /* else:
  8823. * it's a duplicate "local VAR" declaration, do nothing
  8824. */
  8825. goto ret;
  8826. }
  8827. lvp = lvp->next;
  8828. }
  8829. lvp = ckzalloc(sizeof(*lvp));
  8830. if (LONE_DASH(name)) {
  8831. char *p;
  8832. p = ckmalloc(sizeof(optlist));
  8833. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8834. vp = NULL;
  8835. } else {
  8836. vpp = hashvar(name);
  8837. vp = *findvar(vpp, name);
  8838. if (vp == NULL) {
  8839. /* variable did not exist yet */
  8840. if (eq)
  8841. vp = setvareq(name, VSTRFIXED);
  8842. else
  8843. vp = setvar(name, NULL, VSTRFIXED);
  8844. lvp->flags = VUNSET;
  8845. } else {
  8846. lvp->text = vp->var_text;
  8847. lvp->flags = vp->flags;
  8848. /* make sure neither "struct var" nor string gets freed
  8849. * during (un)setting:
  8850. */
  8851. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8852. if (eq)
  8853. setvareq(name, 0);
  8854. else
  8855. /* "local VAR" unsets VAR: */
  8856. setvar0(name, NULL);
  8857. }
  8858. }
  8859. lvp->vp = vp;
  8860. lvp->next = localvar_stack->lv;
  8861. localvar_stack->lv = lvp;
  8862. ret:
  8863. INT_ON;
  8864. }
  8865. /*
  8866. * The "local" command.
  8867. */
  8868. static int FAST_FUNC
  8869. localcmd(int argc UNUSED_PARAM, char **argv)
  8870. {
  8871. char *name;
  8872. if (!localvar_stack)
  8873. ash_msg_and_raise_error("not in a function");
  8874. argv = argptr;
  8875. while ((name = *argv++) != NULL) {
  8876. mklocal(name);
  8877. }
  8878. return 0;
  8879. }
  8880. static int FAST_FUNC
  8881. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8882. {
  8883. return 1;
  8884. }
  8885. static int FAST_FUNC
  8886. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8887. {
  8888. return 0;
  8889. }
  8890. static int FAST_FUNC
  8891. execcmd(int argc UNUSED_PARAM, char **argv)
  8892. {
  8893. optionarg = NULL;
  8894. while (nextopt("a:") != '\0')
  8895. /* nextopt() sets optionarg to "-a ARGV0" */;
  8896. argv = argptr;
  8897. if (argv[0]) {
  8898. char *prog;
  8899. iflag = 0; /* exit on error */
  8900. mflag = 0;
  8901. optschanged();
  8902. /* We should set up signals for "exec CMD"
  8903. * the same way as for "CMD" without "exec".
  8904. * But optschanged->setinteractive->setsignal
  8905. * still thought we are a root shell. Therefore, for example,
  8906. * SIGQUIT is still set to IGN. Fix it:
  8907. */
  8908. shlvl++;
  8909. setsignal(SIGQUIT);
  8910. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  8911. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  8912. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  8913. prog = argv[0];
  8914. if (optionarg)
  8915. argv[0] = optionarg;
  8916. shellexec(prog, argv, pathval(), 0);
  8917. /* NOTREACHED */
  8918. }
  8919. return 0;
  8920. }
  8921. /*
  8922. * The return command.
  8923. */
  8924. static int FAST_FUNC
  8925. returncmd(int argc UNUSED_PARAM, char **argv)
  8926. {
  8927. /*
  8928. * If called outside a function, do what ksh does;
  8929. * skip the rest of the file.
  8930. */
  8931. evalskip = SKIPFUNC;
  8932. return argv[1] ? number(argv[1]) : exitstatus;
  8933. }
  8934. /* Forward declarations for builtintab[] */
  8935. static int breakcmd(int, char **) FAST_FUNC;
  8936. static int dotcmd(int, char **) FAST_FUNC;
  8937. static int evalcmd(int, char **, int) FAST_FUNC;
  8938. static int exitcmd(int, char **) FAST_FUNC;
  8939. static int exportcmd(int, char **) FAST_FUNC;
  8940. #if ENABLE_ASH_GETOPTS
  8941. static int getoptscmd(int, char **) FAST_FUNC;
  8942. #endif
  8943. #if ENABLE_ASH_HELP
  8944. static int helpcmd(int, char **) FAST_FUNC;
  8945. #endif
  8946. #if MAX_HISTORY
  8947. static int historycmd(int, char **) FAST_FUNC;
  8948. #endif
  8949. #if ENABLE_FEATURE_SH_MATH
  8950. static int letcmd(int, char **) FAST_FUNC;
  8951. #endif
  8952. static int readcmd(int, char **) FAST_FUNC;
  8953. static int setcmd(int, char **) FAST_FUNC;
  8954. static int shiftcmd(int, char **) FAST_FUNC;
  8955. static int timescmd(int, char **) FAST_FUNC;
  8956. static int trapcmd(int, char **) FAST_FUNC;
  8957. static int umaskcmd(int, char **) FAST_FUNC;
  8958. static int unsetcmd(int, char **) FAST_FUNC;
  8959. static int ulimitcmd(int, char **) FAST_FUNC;
  8960. #define BUILTIN_NOSPEC "0"
  8961. #define BUILTIN_SPECIAL "1"
  8962. #define BUILTIN_REGULAR "2"
  8963. #define BUILTIN_SPEC_REG "3"
  8964. #define BUILTIN_ASSIGN "4"
  8965. #define BUILTIN_SPEC_ASSG "5"
  8966. #define BUILTIN_REG_ASSG "6"
  8967. #define BUILTIN_SPEC_REG_ASSG "7"
  8968. /* Stubs for calling non-FAST_FUNC's */
  8969. #if ENABLE_ASH_ECHO
  8970. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8971. #endif
  8972. #if ENABLE_ASH_PRINTF
  8973. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8974. #endif
  8975. #if ENABLE_ASH_TEST || BASH_TEST2
  8976. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8977. #endif
  8978. /* Keep these in proper order since it is searched via bsearch() */
  8979. static const struct builtincmd builtintab[] = {
  8980. { BUILTIN_SPEC_REG "." , dotcmd },
  8981. { BUILTIN_SPEC_REG ":" , truecmd },
  8982. #if ENABLE_ASH_TEST
  8983. { BUILTIN_REGULAR "[" , testcmd },
  8984. #endif
  8985. #if BASH_TEST2
  8986. { BUILTIN_REGULAR "[[" , testcmd },
  8987. #endif
  8988. #if ENABLE_ASH_ALIAS
  8989. { BUILTIN_REG_ASSG "alias" , aliascmd },
  8990. #endif
  8991. #if JOBS
  8992. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  8993. #endif
  8994. { BUILTIN_SPEC_REG "break" , breakcmd },
  8995. { BUILTIN_REGULAR "cd" , cdcmd },
  8996. { BUILTIN_NOSPEC "chdir" , cdcmd },
  8997. #if ENABLE_ASH_CMDCMD
  8998. { BUILTIN_REGULAR "command" , commandcmd },
  8999. #endif
  9000. { BUILTIN_SPEC_REG "continue", breakcmd },
  9001. #if ENABLE_ASH_ECHO
  9002. { BUILTIN_REGULAR "echo" , echocmd },
  9003. #endif
  9004. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9005. { BUILTIN_SPEC_REG "exec" , execcmd },
  9006. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9007. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9008. { BUILTIN_REGULAR "false" , falsecmd },
  9009. #if JOBS
  9010. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9011. #endif
  9012. #if ENABLE_ASH_GETOPTS
  9013. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9014. #endif
  9015. { BUILTIN_NOSPEC "hash" , hashcmd },
  9016. #if ENABLE_ASH_HELP
  9017. { BUILTIN_NOSPEC "help" , helpcmd },
  9018. #endif
  9019. #if MAX_HISTORY
  9020. { BUILTIN_NOSPEC "history" , historycmd },
  9021. #endif
  9022. #if JOBS
  9023. { BUILTIN_REGULAR "jobs" , jobscmd },
  9024. { BUILTIN_REGULAR "kill" , killcmd },
  9025. #endif
  9026. #if ENABLE_FEATURE_SH_MATH
  9027. { BUILTIN_NOSPEC "let" , letcmd },
  9028. #endif
  9029. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9030. #if ENABLE_ASH_PRINTF
  9031. { BUILTIN_REGULAR "printf" , printfcmd },
  9032. #endif
  9033. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  9034. { BUILTIN_REGULAR "read" , readcmd },
  9035. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9036. { BUILTIN_SPEC_REG "return" , returncmd },
  9037. { BUILTIN_SPEC_REG "set" , setcmd },
  9038. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9039. #if BASH_SOURCE
  9040. { BUILTIN_SPEC_REG "source" , dotcmd },
  9041. #endif
  9042. #if ENABLE_ASH_TEST
  9043. { BUILTIN_REGULAR "test" , testcmd },
  9044. #endif
  9045. { BUILTIN_SPEC_REG "times" , timescmd },
  9046. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9047. { BUILTIN_REGULAR "true" , truecmd },
  9048. { BUILTIN_NOSPEC "type" , typecmd },
  9049. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  9050. { BUILTIN_REGULAR "umask" , umaskcmd },
  9051. #if ENABLE_ASH_ALIAS
  9052. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9053. #endif
  9054. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9055. { BUILTIN_REGULAR "wait" , waitcmd },
  9056. };
  9057. /* Should match the above table! */
  9058. #define COMMANDCMD (builtintab + \
  9059. /* . : */ 2 + \
  9060. /* [ */ 1 * ENABLE_ASH_TEST + \
  9061. /* [[ */ 1 * BASH_TEST2 + \
  9062. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9063. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9064. /* break cd cddir */ 3)
  9065. #define EVALCMD (COMMANDCMD + \
  9066. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9067. /* continue */ 1 + \
  9068. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9069. 0)
  9070. #define EXECCMD (EVALCMD + \
  9071. /* eval */ 1)
  9072. /*
  9073. * Search the table of builtin commands.
  9074. */
  9075. static int
  9076. pstrcmp1(const void *a, const void *b)
  9077. {
  9078. return strcmp((char*)a, *(char**)b + 1);
  9079. }
  9080. static struct builtincmd *
  9081. find_builtin(const char *name)
  9082. {
  9083. struct builtincmd *bp;
  9084. bp = bsearch(
  9085. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9086. pstrcmp1
  9087. );
  9088. return bp;
  9089. }
  9090. /*
  9091. * Execute a simple command.
  9092. */
  9093. static void unwindfiles(struct parsefile *stop);
  9094. static int
  9095. isassignment(const char *p)
  9096. {
  9097. const char *q = endofname(p);
  9098. if (p == q)
  9099. return 0;
  9100. return *q == '=';
  9101. }
  9102. static int FAST_FUNC
  9103. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9104. {
  9105. /* Preserve exitstatus of a previous possible redirection
  9106. * as POSIX mandates */
  9107. return back_exitstatus;
  9108. }
  9109. static int
  9110. evalcommand(union node *cmd, int flags)
  9111. {
  9112. static const struct builtincmd null_bltin = {
  9113. "\0\0", bltincmd /* why three NULs? */
  9114. };
  9115. struct localvar_list *localvar_stop;
  9116. struct parsefile *file_stop;
  9117. struct redirtab *redir_stop;
  9118. struct stackmark smark;
  9119. union node *argp;
  9120. struct arglist arglist;
  9121. struct arglist varlist;
  9122. char **argv;
  9123. int argc;
  9124. const struct strlist *sp;
  9125. struct cmdentry cmdentry;
  9126. struct job *jp;
  9127. char *lastarg;
  9128. const char *path;
  9129. int spclbltin;
  9130. int status;
  9131. char **nargv;
  9132. smallint cmd_is_exec;
  9133. errlinno = lineno = cmd->ncmd.linno;
  9134. if (funcline)
  9135. lineno -= funcline - 1;
  9136. /* First expand the arguments. */
  9137. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9138. setstackmark(&smark);
  9139. localvar_stop = pushlocalvars();
  9140. file_stop = g_parsefile;
  9141. back_exitstatus = 0;
  9142. cmdentry.cmdtype = CMDBUILTIN;
  9143. cmdentry.u.cmd = &null_bltin;
  9144. varlist.lastp = &varlist.list;
  9145. *varlist.lastp = NULL;
  9146. arglist.lastp = &arglist.list;
  9147. *arglist.lastp = NULL;
  9148. argc = 0;
  9149. if (cmd->ncmd.args) {
  9150. struct builtincmd *bcmd;
  9151. smallint pseudovarflag;
  9152. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  9153. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  9154. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  9155. struct strlist **spp;
  9156. spp = arglist.lastp;
  9157. if (pseudovarflag && isassignment(argp->narg.text))
  9158. expandarg(argp, &arglist, EXP_VARTILDE);
  9159. else
  9160. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  9161. for (sp = *spp; sp; sp = sp->next)
  9162. argc++;
  9163. }
  9164. }
  9165. /* Reserve one extra spot at the front for shellexec. */
  9166. nargv = stalloc(sizeof(char *) * (argc + 2));
  9167. argv = ++nargv;
  9168. for (sp = arglist.list; sp; sp = sp->next) {
  9169. TRACE(("evalcommand arg: %s\n", sp->text));
  9170. *nargv++ = sp->text;
  9171. }
  9172. *nargv = NULL;
  9173. lastarg = NULL;
  9174. if (iflag && funcline == 0 && argc > 0)
  9175. lastarg = nargv[-1];
  9176. expredir(cmd->ncmd.redirect);
  9177. redir_stop = pushredir(cmd->ncmd.redirect);
  9178. preverrout_fd = 2;
  9179. if (BASH_XTRACEFD && xflag) {
  9180. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9181. * we do not emulate this. We only use its value.
  9182. */
  9183. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9184. if (xtracefd && is_number(xtracefd))
  9185. preverrout_fd = atoi(xtracefd);
  9186. }
  9187. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9188. path = vpath.var_text;
  9189. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9190. struct strlist **spp;
  9191. char *p;
  9192. spp = varlist.lastp;
  9193. expandarg(argp, &varlist, EXP_VARTILDE);
  9194. mklocal((*spp)->text);
  9195. /*
  9196. * Modify the command lookup path, if a PATH= assignment
  9197. * is present
  9198. */
  9199. p = (*spp)->text;
  9200. if (varcmp(p, path) == 0)
  9201. path = p;
  9202. }
  9203. /* Print the command if xflag is set. */
  9204. if (xflag) {
  9205. const char *pfx = "";
  9206. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9207. sp = varlist.list;
  9208. while (sp) {
  9209. char *varval = sp->text;
  9210. char *eq = strchrnul(varval, '=');
  9211. if (*eq)
  9212. eq++;
  9213. fdprintf(preverrout_fd, "%s%.*s%s",
  9214. pfx,
  9215. (int)(eq - varval), varval,
  9216. maybe_single_quote(eq)
  9217. );
  9218. sp = sp->next;
  9219. pfx = " ";
  9220. }
  9221. sp = arglist.list;
  9222. while (sp) {
  9223. fdprintf(preverrout_fd, "%s%s",
  9224. pfx,
  9225. /* always quote if matches reserved word: */
  9226. findkwd(sp->text)
  9227. ? single_quote(sp->text)
  9228. : maybe_single_quote(sp->text)
  9229. );
  9230. sp = sp->next;
  9231. pfx = " ";
  9232. }
  9233. safe_write(preverrout_fd, "\n", 1);
  9234. }
  9235. cmd_is_exec = 0;
  9236. spclbltin = -1;
  9237. /* Now locate the command. */
  9238. if (argc) {
  9239. int cmd_flag = DO_ERR;
  9240. #if ENABLE_ASH_CMDCMD
  9241. const char *oldpath = path + 5;
  9242. #endif
  9243. path += 5;
  9244. for (;;) {
  9245. find_command(argv[0], &cmdentry, cmd_flag, path);
  9246. if (cmdentry.cmdtype == CMDUNKNOWN) {
  9247. flush_stdout_stderr();
  9248. status = 127;
  9249. goto bail;
  9250. }
  9251. /* implement bltin and command here */
  9252. if (cmdentry.cmdtype != CMDBUILTIN)
  9253. break;
  9254. if (spclbltin < 0)
  9255. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9256. if (cmdentry.u.cmd == EXECCMD)
  9257. cmd_is_exec = 1;
  9258. #if ENABLE_ASH_CMDCMD
  9259. if (cmdentry.u.cmd == COMMANDCMD) {
  9260. path = oldpath;
  9261. nargv = parse_command_args(argv, &path);
  9262. if (!nargv)
  9263. break;
  9264. /* It's "command [-p] PROG ARGS" (that is, no -Vv).
  9265. * nargv => "PROG". path is updated if -p.
  9266. */
  9267. argc -= nargv - argv;
  9268. argv = nargv;
  9269. cmd_flag |= DO_NOFUNC;
  9270. } else
  9271. #endif
  9272. break;
  9273. }
  9274. }
  9275. if (status) {
  9276. bail:
  9277. exitstatus = status;
  9278. /* We have a redirection error. */
  9279. if (spclbltin > 0)
  9280. raise_exception(EXERROR);
  9281. goto out;
  9282. }
  9283. /* Execute the command. */
  9284. switch (cmdentry.cmdtype) {
  9285. default: {
  9286. #if ENABLE_FEATURE_SH_STANDALONE \
  9287. && ENABLE_FEATURE_SH_NOFORK \
  9288. && NUM_APPLETS > 1
  9289. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9290. * around run_nofork_applet() call.
  9291. * (2) Should this check also be done in forkshell()?
  9292. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9293. */
  9294. /* find_command() encodes applet_no as (-2 - applet_no) */
  9295. int applet_no = (- cmdentry.u.index - 2);
  9296. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9297. char **sv_environ;
  9298. INT_OFF;
  9299. sv_environ = environ;
  9300. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9301. /*
  9302. * Run <applet>_main().
  9303. * Signals (^C) can't interrupt here.
  9304. * Otherwise we can mangle stdio or malloc internal state.
  9305. * This makes applets which can run for a long time
  9306. * and/or wait for user input ineligible for NOFORK:
  9307. * for example, "yes" or "rm" (rm -i waits for input).
  9308. */
  9309. status = run_nofork_applet(applet_no, argv);
  9310. environ = sv_environ;
  9311. /*
  9312. * Try enabling NOFORK for "yes" applet.
  9313. * ^C _will_ stop it (write returns EINTR),
  9314. * but this causes stdout FILE to be stuck
  9315. * and needing clearerr(). What if other applets
  9316. * also can get EINTRs? Do we need to switch
  9317. * our signals to SA_RESTART?
  9318. */
  9319. /*clearerr(stdout);*/
  9320. INT_ON;
  9321. break;
  9322. }
  9323. #endif
  9324. /* Can we avoid forking? For example, very last command
  9325. * in a script or a subshell does not need forking,
  9326. * we can just exec it.
  9327. */
  9328. if (!(flags & EV_EXIT) || may_have_traps) {
  9329. /* No, forking off a child is necessary */
  9330. INT_OFF;
  9331. get_tty_state();
  9332. jp = makejob(/*cmd,*/ 1);
  9333. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9334. /* parent */
  9335. status = waitforjob(jp);
  9336. INT_ON;
  9337. TRACE(("forked child exited with %d\n", status));
  9338. break;
  9339. }
  9340. /* child */
  9341. FORCE_INT_ON;
  9342. /* fall through to exec'ing external program */
  9343. }
  9344. listsetvar(varlist.list, VEXPORT|VSTACK);
  9345. shellexec(argv[0], argv, path, cmdentry.u.index);
  9346. /* NOTREACHED */
  9347. } /* default */
  9348. case CMDBUILTIN:
  9349. if (spclbltin > 0 || argc == 0) {
  9350. poplocalvars(1);
  9351. if (cmd_is_exec && argc > 1)
  9352. listsetvar(varlist.list, VEXPORT);
  9353. }
  9354. /* Tight loop with builtins only:
  9355. * "while kill -0 $child; do true; done"
  9356. * will never exit even if $child died, unless we do this
  9357. * to reap the zombie and make kill detect that it's gone: */
  9358. dowait(DOWAIT_NONBLOCK, NULL);
  9359. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
  9360. if (exception_type == EXERROR && spclbltin <= 0) {
  9361. FORCE_INT_ON;
  9362. goto readstatus;
  9363. }
  9364. raise:
  9365. longjmp(exception_handler->loc, 1);
  9366. }
  9367. goto readstatus;
  9368. case CMDFUNCTION:
  9369. /* See above for the rationale */
  9370. dowait(DOWAIT_NONBLOCK, NULL);
  9371. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9372. goto raise;
  9373. readstatus:
  9374. status = exitstatus;
  9375. break;
  9376. } /* switch */
  9377. out:
  9378. if (cmd->ncmd.redirect)
  9379. popredir(/*drop:*/ cmd_is_exec);
  9380. unwindredir(redir_stop);
  9381. unwindfiles(file_stop);
  9382. unwindlocalvars(localvar_stop);
  9383. if (lastarg) {
  9384. /* dsl: I think this is intended to be used to support
  9385. * '_' in 'vi' command mode during line editing...
  9386. * However I implemented that within libedit itself.
  9387. */
  9388. setvar0("_", lastarg);
  9389. }
  9390. popstackmark(&smark);
  9391. return status;
  9392. }
  9393. static int
  9394. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9395. {
  9396. char *volatile savecmdname;
  9397. struct jmploc *volatile savehandler;
  9398. struct jmploc jmploc;
  9399. int status;
  9400. int i;
  9401. savecmdname = commandname;
  9402. savehandler = exception_handler;
  9403. i = setjmp(jmploc.loc);
  9404. if (i)
  9405. goto cmddone;
  9406. exception_handler = &jmploc;
  9407. commandname = argv[0];
  9408. argptr = argv + 1;
  9409. optptr = NULL; /* initialize nextopt */
  9410. if (cmd == EVALCMD)
  9411. status = evalcmd(argc, argv, flags);
  9412. else
  9413. status = (*cmd->builtin)(argc, argv);
  9414. flush_stdout_stderr();
  9415. status |= ferror(stdout);
  9416. exitstatus = status;
  9417. cmddone:
  9418. clearerr(stdout);
  9419. commandname = savecmdname;
  9420. exception_handler = savehandler;
  9421. return i;
  9422. }
  9423. static int
  9424. goodname(const char *p)
  9425. {
  9426. return endofname(p)[0] == '\0';
  9427. }
  9428. /*
  9429. * Search for a command. This is called before we fork so that the
  9430. * location of the command will be available in the parent as well as
  9431. * the child. The check for "goodname" is an overly conservative
  9432. * check that the name will not be subject to expansion.
  9433. */
  9434. static void
  9435. prehash(union node *n)
  9436. {
  9437. struct cmdentry entry;
  9438. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9439. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9440. }
  9441. /* ============ Builtin commands
  9442. *
  9443. * Builtin commands whose functions are closely tied to evaluation
  9444. * are implemented here.
  9445. */
  9446. /*
  9447. * Handle break and continue commands. Break, continue, and return are
  9448. * all handled by setting the evalskip flag. The evaluation routines
  9449. * above all check this flag, and if it is set they start skipping
  9450. * commands rather than executing them. The variable skipcount is
  9451. * the number of loops to break/continue, or the number of function
  9452. * levels to return. (The latter is always 1.) It should probably
  9453. * be an error to break out of more loops than exist, but it isn't
  9454. * in the standard shell so we don't make it one here.
  9455. */
  9456. static int FAST_FUNC
  9457. breakcmd(int argc UNUSED_PARAM, char **argv)
  9458. {
  9459. int n = argv[1] ? number(argv[1]) : 1;
  9460. if (n <= 0)
  9461. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9462. if (n > loopnest)
  9463. n = loopnest;
  9464. if (n > 0) {
  9465. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9466. skipcount = n;
  9467. }
  9468. return 0;
  9469. }
  9470. /*
  9471. * This implements the input routines used by the parser.
  9472. */
  9473. enum {
  9474. INPUT_PUSH_FILE = 1,
  9475. INPUT_NOFILE_OK = 2,
  9476. };
  9477. static smallint checkkwd;
  9478. /* values of checkkwd variable */
  9479. #define CHKALIAS 0x1
  9480. #define CHKKWD 0x2
  9481. #define CHKNL 0x4
  9482. #define CHKEOFMARK 0x8
  9483. /*
  9484. * Push a string back onto the input at this current parsefile level.
  9485. * We handle aliases this way.
  9486. */
  9487. #if !ENABLE_ASH_ALIAS
  9488. #define pushstring(s, ap) pushstring(s)
  9489. #endif
  9490. static void
  9491. pushstring(char *s, struct alias *ap)
  9492. {
  9493. struct strpush *sp;
  9494. int len;
  9495. len = strlen(s);
  9496. INT_OFF;
  9497. if (g_parsefile->strpush) {
  9498. sp = ckzalloc(sizeof(*sp));
  9499. sp->prev = g_parsefile->strpush;
  9500. } else {
  9501. sp = &(g_parsefile->basestrpush);
  9502. }
  9503. g_parsefile->strpush = sp;
  9504. sp->prev_string = g_parsefile->next_to_pgetc;
  9505. sp->prev_left_in_line = g_parsefile->left_in_line;
  9506. sp->unget = g_parsefile->unget;
  9507. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9508. #if ENABLE_ASH_ALIAS
  9509. sp->ap = ap;
  9510. if (ap) {
  9511. ap->flag |= ALIASINUSE;
  9512. sp->string = s;
  9513. }
  9514. #endif
  9515. g_parsefile->next_to_pgetc = s;
  9516. g_parsefile->left_in_line = len;
  9517. g_parsefile->unget = 0;
  9518. INT_ON;
  9519. }
  9520. static void
  9521. popstring(void)
  9522. {
  9523. struct strpush *sp = g_parsefile->strpush;
  9524. INT_OFF;
  9525. #if ENABLE_ASH_ALIAS
  9526. if (sp->ap) {
  9527. if (g_parsefile->next_to_pgetc[-1] == ' '
  9528. || g_parsefile->next_to_pgetc[-1] == '\t'
  9529. ) {
  9530. checkkwd |= CHKALIAS;
  9531. }
  9532. if (sp->string != sp->ap->val) {
  9533. free(sp->string);
  9534. }
  9535. sp->ap->flag &= ~ALIASINUSE;
  9536. if (sp->ap->flag & ALIASDEAD) {
  9537. unalias(sp->ap->name);
  9538. }
  9539. }
  9540. #endif
  9541. g_parsefile->next_to_pgetc = sp->prev_string;
  9542. g_parsefile->left_in_line = sp->prev_left_in_line;
  9543. g_parsefile->unget = sp->unget;
  9544. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9545. g_parsefile->strpush = sp->prev;
  9546. if (sp != &(g_parsefile->basestrpush))
  9547. free(sp);
  9548. INT_ON;
  9549. }
  9550. static int
  9551. preadfd(void)
  9552. {
  9553. int nr;
  9554. char *buf = g_parsefile->buf;
  9555. g_parsefile->next_to_pgetc = buf;
  9556. #if ENABLE_FEATURE_EDITING
  9557. retry:
  9558. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9559. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9560. else {
  9561. # if ENABLE_ASH_IDLE_TIMEOUT
  9562. int timeout = -1;
  9563. if (iflag) {
  9564. const char *tmout_var = lookupvar("TMOUT");
  9565. if (tmout_var) {
  9566. timeout = atoi(tmout_var) * 1000;
  9567. if (timeout <= 0)
  9568. timeout = -1;
  9569. }
  9570. }
  9571. line_input_state->timeout = timeout;
  9572. # endif
  9573. # if ENABLE_FEATURE_TAB_COMPLETION
  9574. line_input_state->path_lookup = pathval();
  9575. # endif
  9576. reinit_unicode_for_ash();
  9577. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9578. if (nr == 0) {
  9579. /* ^C pressed, "convert" to SIGINT */
  9580. write(STDOUT_FILENO, "^C", 2);
  9581. if (trap[SIGINT]) {
  9582. buf[0] = '\n';
  9583. buf[1] = '\0';
  9584. raise(SIGINT);
  9585. return 1;
  9586. }
  9587. exitstatus = 128 + SIGINT;
  9588. bb_putchar('\n');
  9589. goto retry;
  9590. }
  9591. if (nr < 0) {
  9592. if (errno == 0) {
  9593. /* Ctrl+D pressed */
  9594. nr = 0;
  9595. }
  9596. # if ENABLE_ASH_IDLE_TIMEOUT
  9597. else if (errno == EAGAIN && timeout > 0) {
  9598. puts("\007timed out waiting for input: auto-logout");
  9599. exitshell();
  9600. }
  9601. # endif
  9602. }
  9603. }
  9604. #else
  9605. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9606. #endif
  9607. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9608. if (nr < 0) {
  9609. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9610. int flags = fcntl(0, F_GETFL);
  9611. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9612. flags &= ~O_NONBLOCK;
  9613. if (fcntl(0, F_SETFL, flags) >= 0) {
  9614. out2str("sh: turning off NDELAY mode\n");
  9615. goto retry;
  9616. }
  9617. }
  9618. }
  9619. }
  9620. #endif
  9621. return nr;
  9622. }
  9623. /*
  9624. * Refill the input buffer and return the next input character:
  9625. *
  9626. * 1) If a string was pushed back on the input, pop it;
  9627. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9628. * or we are reading from a string so we can't refill the buffer,
  9629. * return EOF.
  9630. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9631. * 4) Process input up to the next newline, deleting nul characters.
  9632. */
  9633. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9634. #define pgetc_debug(...) ((void)0)
  9635. static int pgetc(void);
  9636. static int
  9637. preadbuffer(void)
  9638. {
  9639. char *q;
  9640. int more;
  9641. if (g_parsefile->strpush) {
  9642. #if ENABLE_ASH_ALIAS
  9643. if (g_parsefile->left_in_line == -1
  9644. && g_parsefile->strpush->ap
  9645. && g_parsefile->next_to_pgetc[-1] != ' '
  9646. && g_parsefile->next_to_pgetc[-1] != '\t'
  9647. ) {
  9648. pgetc_debug("preadbuffer PEOA");
  9649. return PEOA;
  9650. }
  9651. #endif
  9652. popstring();
  9653. return pgetc();
  9654. }
  9655. /* on both branches above g_parsefile->left_in_line < 0.
  9656. * "pgetc" needs refilling.
  9657. */
  9658. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9659. * pungetc() may increment it a few times.
  9660. * Assuming it won't increment it to less than -90.
  9661. */
  9662. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9663. pgetc_debug("preadbuffer PEOF1");
  9664. /* even in failure keep left_in_line and next_to_pgetc
  9665. * in lock step, for correct multi-layer pungetc.
  9666. * left_in_line was decremented before preadbuffer(),
  9667. * must inc next_to_pgetc: */
  9668. g_parsefile->next_to_pgetc++;
  9669. return PEOF;
  9670. }
  9671. more = g_parsefile->left_in_buffer;
  9672. if (more <= 0) {
  9673. flush_stdout_stderr();
  9674. again:
  9675. more = preadfd();
  9676. if (more <= 0) {
  9677. /* don't try reading again */
  9678. g_parsefile->left_in_line = -99;
  9679. pgetc_debug("preadbuffer PEOF2");
  9680. g_parsefile->next_to_pgetc++;
  9681. return PEOF;
  9682. }
  9683. }
  9684. /* Find out where's the end of line.
  9685. * Set g_parsefile->left_in_line
  9686. * and g_parsefile->left_in_buffer acordingly.
  9687. * NUL chars are deleted.
  9688. */
  9689. q = g_parsefile->next_to_pgetc;
  9690. for (;;) {
  9691. char c;
  9692. more--;
  9693. c = *q;
  9694. if (c == '\0') {
  9695. memmove(q, q + 1, more);
  9696. } else {
  9697. q++;
  9698. if (c == '\n') {
  9699. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9700. break;
  9701. }
  9702. }
  9703. if (more <= 0) {
  9704. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9705. if (g_parsefile->left_in_line < 0)
  9706. goto again;
  9707. break;
  9708. }
  9709. }
  9710. g_parsefile->left_in_buffer = more;
  9711. if (vflag) {
  9712. char save = *q;
  9713. *q = '\0';
  9714. out2str(g_parsefile->next_to_pgetc);
  9715. *q = save;
  9716. }
  9717. pgetc_debug("preadbuffer at %d:%p'%s'",
  9718. g_parsefile->left_in_line,
  9719. g_parsefile->next_to_pgetc,
  9720. g_parsefile->next_to_pgetc);
  9721. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9722. }
  9723. static void
  9724. nlprompt(void)
  9725. {
  9726. g_parsefile->linno++;
  9727. setprompt_if(doprompt, 2);
  9728. }
  9729. static void
  9730. nlnoprompt(void)
  9731. {
  9732. g_parsefile->linno++;
  9733. needprompt = doprompt;
  9734. }
  9735. static int
  9736. pgetc(void)
  9737. {
  9738. int c;
  9739. pgetc_debug("pgetc at %d:%p'%s'",
  9740. g_parsefile->left_in_line,
  9741. g_parsefile->next_to_pgetc,
  9742. g_parsefile->next_to_pgetc);
  9743. if (g_parsefile->unget)
  9744. return g_parsefile->lastc[--g_parsefile->unget];
  9745. if (--g_parsefile->left_in_line >= 0)
  9746. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9747. else
  9748. c = preadbuffer();
  9749. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9750. g_parsefile->lastc[0] = c;
  9751. return c;
  9752. }
  9753. #if ENABLE_ASH_ALIAS
  9754. static int
  9755. pgetc_without_PEOA(void)
  9756. {
  9757. int c;
  9758. do {
  9759. pgetc_debug("pgetc at %d:%p'%s'",
  9760. g_parsefile->left_in_line,
  9761. g_parsefile->next_to_pgetc,
  9762. g_parsefile->next_to_pgetc);
  9763. c = pgetc();
  9764. } while (c == PEOA);
  9765. return c;
  9766. }
  9767. #else
  9768. # define pgetc_without_PEOA() pgetc()
  9769. #endif
  9770. /*
  9771. * Undo a call to pgetc. Only two characters may be pushed back.
  9772. * PEOF may be pushed back.
  9773. */
  9774. static void
  9775. pungetc(void)
  9776. {
  9777. g_parsefile->unget++;
  9778. }
  9779. /* This one eats backslash+newline */
  9780. static int
  9781. pgetc_eatbnl(void)
  9782. {
  9783. int c;
  9784. while ((c = pgetc()) == '\\') {
  9785. if (pgetc() != '\n') {
  9786. pungetc();
  9787. break;
  9788. }
  9789. nlprompt();
  9790. }
  9791. return c;
  9792. }
  9793. struct synstack {
  9794. smalluint syntax;
  9795. uint8_t innerdq :1;
  9796. uint8_t varpushed :1;
  9797. uint8_t dblquote :1;
  9798. int varnest; /* levels of variables expansion */
  9799. int dqvarnest; /* levels of variables expansion within double quotes */
  9800. int parenlevel; /* levels of parens in arithmetic */
  9801. struct synstack *prev;
  9802. struct synstack *next;
  9803. };
  9804. static void
  9805. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  9806. {
  9807. memset(next, 0, sizeof(*next));
  9808. next->syntax = syntax;
  9809. next->next = *stack;
  9810. (*stack)->prev = next;
  9811. *stack = next;
  9812. }
  9813. static ALWAYS_INLINE void
  9814. synstack_pop(struct synstack **stack)
  9815. {
  9816. *stack = (*stack)->next;
  9817. }
  9818. /*
  9819. * To handle the "." command, a stack of input files is used. Pushfile
  9820. * adds a new entry to the stack and popfile restores the previous level.
  9821. */
  9822. static void
  9823. pushfile(void)
  9824. {
  9825. struct parsefile *pf;
  9826. pf = ckzalloc(sizeof(*pf));
  9827. pf->prev = g_parsefile;
  9828. pf->pf_fd = -1;
  9829. /*pf->strpush = NULL; - ckzalloc did it */
  9830. /*pf->basestrpush.prev = NULL;*/
  9831. /*pf->unget = 0;*/
  9832. g_parsefile = pf;
  9833. }
  9834. static void
  9835. popfile(void)
  9836. {
  9837. struct parsefile *pf = g_parsefile;
  9838. if (pf == &basepf)
  9839. return;
  9840. INT_OFF;
  9841. if (pf->pf_fd >= 0)
  9842. close(pf->pf_fd);
  9843. free(pf->buf);
  9844. while (pf->strpush)
  9845. popstring();
  9846. g_parsefile = pf->prev;
  9847. free(pf);
  9848. INT_ON;
  9849. }
  9850. static void
  9851. unwindfiles(struct parsefile *stop)
  9852. {
  9853. while (g_parsefile != stop)
  9854. popfile();
  9855. }
  9856. /*
  9857. * Return to top level.
  9858. */
  9859. static void
  9860. popallfiles(void)
  9861. {
  9862. unwindfiles(&basepf);
  9863. }
  9864. /*
  9865. * Close the file(s) that the shell is reading commands from. Called
  9866. * after a fork is done.
  9867. */
  9868. static void
  9869. closescript(void)
  9870. {
  9871. popallfiles();
  9872. if (g_parsefile->pf_fd > 0) {
  9873. close(g_parsefile->pf_fd);
  9874. g_parsefile->pf_fd = 0;
  9875. }
  9876. }
  9877. /*
  9878. * Like setinputfile, but takes an open file descriptor. Call this with
  9879. * interrupts off.
  9880. */
  9881. static void
  9882. setinputfd(int fd, int push)
  9883. {
  9884. if (push) {
  9885. pushfile();
  9886. g_parsefile->buf = NULL;
  9887. }
  9888. g_parsefile->pf_fd = fd;
  9889. if (g_parsefile->buf == NULL)
  9890. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9891. g_parsefile->left_in_buffer = 0;
  9892. g_parsefile->left_in_line = 0;
  9893. g_parsefile->linno = 1;
  9894. }
  9895. /*
  9896. * Set the input to take input from a file. If push is set, push the
  9897. * old input onto the stack first.
  9898. */
  9899. static int
  9900. setinputfile(const char *fname, int flags)
  9901. {
  9902. int fd;
  9903. INT_OFF;
  9904. fd = open(fname, O_RDONLY | O_CLOEXEC);
  9905. if (fd < 0) {
  9906. if (flags & INPUT_NOFILE_OK)
  9907. goto out;
  9908. exitstatus = 127;
  9909. ash_msg_and_raise_perror("can't open '%s'", fname);
  9910. }
  9911. if (fd < 10)
  9912. fd = savefd(fd);
  9913. else if (O_CLOEXEC == 0) /* old libc */
  9914. close_on_exec_on(fd);
  9915. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9916. out:
  9917. INT_ON;
  9918. return fd;
  9919. }
  9920. /*
  9921. * Like setinputfile, but takes input from a string.
  9922. */
  9923. static void
  9924. setinputstring(char *string)
  9925. {
  9926. INT_OFF;
  9927. pushfile();
  9928. g_parsefile->next_to_pgetc = string;
  9929. g_parsefile->left_in_line = strlen(string);
  9930. g_parsefile->buf = NULL;
  9931. g_parsefile->linno = 1;
  9932. INT_ON;
  9933. }
  9934. /*
  9935. * Routines to check for mail.
  9936. */
  9937. #if ENABLE_ASH_MAIL
  9938. /* Hash of mtimes of mailboxes */
  9939. static unsigned mailtime_hash;
  9940. /* Set if MAIL or MAILPATH is changed. */
  9941. static smallint mail_var_path_changed;
  9942. /*
  9943. * Print appropriate message(s) if mail has arrived.
  9944. * If mail_var_path_changed is set,
  9945. * then the value of MAIL has mail_var_path_changed,
  9946. * so we just update the values.
  9947. */
  9948. static void
  9949. chkmail(void)
  9950. {
  9951. const char *mpath;
  9952. char *p;
  9953. char *q;
  9954. unsigned new_hash;
  9955. struct stackmark smark;
  9956. struct stat statb;
  9957. setstackmark(&smark);
  9958. mpath = mpathset() ? mpathval() : mailval();
  9959. new_hash = 0;
  9960. for (;;) {
  9961. p = path_advance(&mpath, nullstr);
  9962. if (p == NULL)
  9963. break;
  9964. if (*p == '\0')
  9965. continue;
  9966. for (q = p; *q; q++)
  9967. continue;
  9968. #if DEBUG
  9969. if (q[-1] != '/')
  9970. abort();
  9971. #endif
  9972. q[-1] = '\0'; /* delete trailing '/' */
  9973. if (stat(p, &statb) < 0) {
  9974. continue;
  9975. }
  9976. /* Very simplistic "hash": just a sum of all mtimes */
  9977. new_hash += (unsigned)statb.st_mtime;
  9978. }
  9979. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  9980. if (mailtime_hash != 0)
  9981. out2str("you have mail\n");
  9982. mailtime_hash = new_hash;
  9983. }
  9984. mail_var_path_changed = 0;
  9985. popstackmark(&smark);
  9986. }
  9987. static void FAST_FUNC
  9988. changemail(const char *val UNUSED_PARAM)
  9989. {
  9990. mail_var_path_changed = 1;
  9991. }
  9992. #endif /* ASH_MAIL */
  9993. /* ============ ??? */
  9994. /*
  9995. * Set the shell parameters.
  9996. */
  9997. static void
  9998. setparam(char **argv)
  9999. {
  10000. char **newparam;
  10001. char **ap;
  10002. int nparam;
  10003. for (nparam = 0; argv[nparam]; nparam++)
  10004. continue;
  10005. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10006. while (*argv) {
  10007. *ap++ = ckstrdup(*argv++);
  10008. }
  10009. *ap = NULL;
  10010. freeparam(&shellparam);
  10011. shellparam.malloced = 1;
  10012. shellparam.nparam = nparam;
  10013. shellparam.p = newparam;
  10014. #if ENABLE_ASH_GETOPTS
  10015. shellparam.optind = 1;
  10016. shellparam.optoff = -1;
  10017. #endif
  10018. }
  10019. /*
  10020. * Process shell options. The global variable argptr contains a pointer
  10021. * to the argument list; we advance it past the options.
  10022. *
  10023. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10024. * For a non-interactive shell, an error condition encountered
  10025. * by a special built-in ... shall cause the shell to write a diagnostic message
  10026. * to standard error and exit as shown in the following table:
  10027. * Error Special Built-In
  10028. * ...
  10029. * Utility syntax error (option or operand error) Shall exit
  10030. * ...
  10031. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10032. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10033. * and shell continues), and people rely on this behavior!
  10034. * Testcase:
  10035. * set -o barfoo 2>/dev/null
  10036. * echo $?
  10037. *
  10038. * Oh well. Let's mimic that.
  10039. */
  10040. static int
  10041. plus_minus_o(char *name, int val)
  10042. {
  10043. int i;
  10044. if (name) {
  10045. for (i = 0; i < NOPTS; i++) {
  10046. if (strcmp(name, optnames(i)) == 0) {
  10047. optlist[i] = val;
  10048. return 0;
  10049. }
  10050. }
  10051. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10052. return 1;
  10053. }
  10054. for (i = 0; i < NOPTS; i++) {
  10055. if (val) {
  10056. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10057. } else {
  10058. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10059. }
  10060. }
  10061. return 0;
  10062. }
  10063. static void
  10064. setoption(int flag, int val)
  10065. {
  10066. int i;
  10067. for (i = 0; i < NOPTS; i++) {
  10068. if (optletters(i) == flag) {
  10069. optlist[i] = val;
  10070. return;
  10071. }
  10072. }
  10073. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10074. /* NOTREACHED */
  10075. }
  10076. static int
  10077. options(int cmdline, int *login_sh)
  10078. {
  10079. char *p;
  10080. int val;
  10081. int c;
  10082. if (cmdline)
  10083. minusc = NULL;
  10084. while ((p = *argptr) != NULL) {
  10085. c = *p++;
  10086. if (c != '-' && c != '+')
  10087. break;
  10088. argptr++;
  10089. val = 0; /* val = 0 if c == '+' */
  10090. if (c == '-') {
  10091. val = 1;
  10092. if (p[0] == '\0' || LONE_DASH(p)) {
  10093. if (!cmdline) {
  10094. /* "-" means turn off -x and -v */
  10095. if (p[0] == '\0')
  10096. xflag = vflag = 0;
  10097. /* "--" means reset params */
  10098. else if (*argptr == NULL)
  10099. setparam(argptr);
  10100. }
  10101. break; /* "-" or "--" terminates options */
  10102. }
  10103. }
  10104. /* first char was + or - */
  10105. while ((c = *p++) != '\0') {
  10106. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10107. if (c == 'c' && cmdline) {
  10108. minusc = p; /* command is after shell args */
  10109. } else if (c == 'o') {
  10110. if (plus_minus_o(*argptr, val)) {
  10111. /* it already printed err message */
  10112. return 1; /* error */
  10113. }
  10114. if (*argptr)
  10115. argptr++;
  10116. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  10117. if (login_sh)
  10118. *login_sh = 1;
  10119. /* bash does not accept +-login, we also won't */
  10120. } else if (cmdline && val && (c == '-')) { /* long options */
  10121. if (strcmp(p, "login") == 0) {
  10122. if (login_sh)
  10123. *login_sh = 1;
  10124. }
  10125. break;
  10126. } else {
  10127. setoption(c, val);
  10128. }
  10129. }
  10130. }
  10131. return 0;
  10132. }
  10133. /*
  10134. * The shift builtin command.
  10135. */
  10136. static int FAST_FUNC
  10137. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10138. {
  10139. int n;
  10140. char **ap1, **ap2;
  10141. n = 1;
  10142. if (argv[1])
  10143. n = number(argv[1]);
  10144. if (n > shellparam.nparam)
  10145. return 1;
  10146. INT_OFF;
  10147. shellparam.nparam -= n;
  10148. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10149. if (shellparam.malloced)
  10150. free(*ap1);
  10151. }
  10152. ap2 = shellparam.p;
  10153. while ((*ap2++ = *ap1++) != NULL)
  10154. continue;
  10155. #if ENABLE_ASH_GETOPTS
  10156. shellparam.optind = 1;
  10157. shellparam.optoff = -1;
  10158. #endif
  10159. INT_ON;
  10160. return 0;
  10161. }
  10162. /*
  10163. * POSIX requires that 'set' (but not export or readonly) output the
  10164. * variables in lexicographic order - by the locale's collating order (sigh).
  10165. * Maybe we could keep them in an ordered balanced binary tree
  10166. * instead of hashed lists.
  10167. * For now just roll 'em through qsort for printing...
  10168. */
  10169. static int
  10170. showvars(const char *sep_prefix, int on, int off)
  10171. {
  10172. const char *sep;
  10173. char **ep, **epend;
  10174. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10175. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10176. sep = *sep_prefix ? " " : sep_prefix;
  10177. for (; ep < epend; ep++) {
  10178. const char *p;
  10179. const char *q;
  10180. p = endofname(*ep);
  10181. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10182. * makes "export -p" to have output not suitable for "eval":
  10183. * import os
  10184. * os.environ["test-test"]="test"
  10185. * if os.fork() == 0:
  10186. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10187. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10188. */
  10189. q = nullstr;
  10190. if (*p == '=')
  10191. q = single_quote(++p);
  10192. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10193. }
  10194. return 0;
  10195. }
  10196. /*
  10197. * The set command builtin.
  10198. */
  10199. static int FAST_FUNC
  10200. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10201. {
  10202. int retval;
  10203. if (!argv[1])
  10204. return showvars(nullstr, 0, VUNSET);
  10205. INT_OFF;
  10206. retval = options(/*cmdline:*/ 0, NULL);
  10207. if (retval == 0) { /* if no parse error... */
  10208. optschanged();
  10209. if (*argptr != NULL) {
  10210. setparam(argptr);
  10211. }
  10212. }
  10213. INT_ON;
  10214. return retval;
  10215. }
  10216. #if ENABLE_ASH_RANDOM_SUPPORT
  10217. static void FAST_FUNC
  10218. change_random(const char *value)
  10219. {
  10220. uint32_t t;
  10221. if (value == NULL) {
  10222. /* "get", generate */
  10223. t = next_random(&random_gen);
  10224. /* set without recursion */
  10225. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10226. vrandom.flags &= ~VNOFUNC;
  10227. } else {
  10228. /* set/reset */
  10229. t = strtoul(value, NULL, 10);
  10230. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10231. }
  10232. }
  10233. #endif
  10234. #if ENABLE_ASH_GETOPTS
  10235. static int
  10236. getopts(char *optstr, char *optvar, char **optfirst)
  10237. {
  10238. char *p, *q;
  10239. char c = '?';
  10240. int done = 0;
  10241. char sbuf[2];
  10242. char **optnext;
  10243. int ind = shellparam.optind;
  10244. int off = shellparam.optoff;
  10245. sbuf[1] = '\0';
  10246. shellparam.optind = -1;
  10247. optnext = optfirst + ind - 1;
  10248. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10249. p = NULL;
  10250. else
  10251. p = optnext[-1] + off;
  10252. if (p == NULL || *p == '\0') {
  10253. /* Current word is done, advance */
  10254. p = *optnext;
  10255. if (p == NULL || *p != '-' || *++p == '\0') {
  10256. atend:
  10257. unsetvar("OPTARG");
  10258. p = NULL;
  10259. done = 1;
  10260. goto out;
  10261. }
  10262. optnext++;
  10263. if (LONE_DASH(p)) /* check for "--" */
  10264. goto atend;
  10265. }
  10266. c = *p++;
  10267. for (q = optstr; *q != c;) {
  10268. if (*q == '\0') {
  10269. /* OPTERR is a bashism */
  10270. const char *cp = lookupvar("OPTERR");
  10271. if ((cp && LONE_CHAR(cp, '0'))
  10272. || (optstr[0] == ':')
  10273. ) {
  10274. sbuf[0] = c;
  10275. /*sbuf[1] = '\0'; - already is */
  10276. setvar0("OPTARG", sbuf);
  10277. } else {
  10278. fprintf(stderr, "Illegal option -%c\n", c);
  10279. unsetvar("OPTARG");
  10280. }
  10281. c = '?';
  10282. goto out;
  10283. }
  10284. if (*++q == ':')
  10285. q++;
  10286. }
  10287. if (*++q == ':') {
  10288. if (*p == '\0' && (p = *optnext) == NULL) {
  10289. /* OPTERR is a bashism */
  10290. const char *cp = lookupvar("OPTERR");
  10291. if ((cp && LONE_CHAR(cp, '0'))
  10292. || (optstr[0] == ':')
  10293. ) {
  10294. sbuf[0] = c;
  10295. /*sbuf[1] = '\0'; - already is */
  10296. setvar0("OPTARG", sbuf);
  10297. c = ':';
  10298. } else {
  10299. fprintf(stderr, "No arg for -%c option\n", c);
  10300. unsetvar("OPTARG");
  10301. c = '?';
  10302. }
  10303. goto out;
  10304. }
  10305. if (p == *optnext)
  10306. optnext++;
  10307. setvar0("OPTARG", p);
  10308. p = NULL;
  10309. } else
  10310. setvar0("OPTARG", nullstr);
  10311. out:
  10312. ind = optnext - optfirst + 1;
  10313. setvar("OPTIND", itoa(ind), VNOFUNC);
  10314. sbuf[0] = c;
  10315. /*sbuf[1] = '\0'; - already is */
  10316. setvar0(optvar, sbuf);
  10317. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10318. shellparam.optind = ind;
  10319. return done;
  10320. }
  10321. /*
  10322. * The getopts builtin. Shellparam.optnext points to the next argument
  10323. * to be processed. Shellparam.optptr points to the next character to
  10324. * be processed in the current argument. If shellparam.optnext is NULL,
  10325. * then it's the first time getopts has been called.
  10326. */
  10327. static int FAST_FUNC
  10328. getoptscmd(int argc, char **argv)
  10329. {
  10330. char **optbase;
  10331. if (argc < 3)
  10332. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10333. if (argc == 3) {
  10334. optbase = shellparam.p;
  10335. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10336. shellparam.optind = 1;
  10337. shellparam.optoff = -1;
  10338. }
  10339. } else {
  10340. optbase = &argv[3];
  10341. if ((unsigned)shellparam.optind > argc - 2) {
  10342. shellparam.optind = 1;
  10343. shellparam.optoff = -1;
  10344. }
  10345. }
  10346. return getopts(argv[1], argv[2], optbase);
  10347. }
  10348. #endif /* ASH_GETOPTS */
  10349. /* ============ Shell parser */
  10350. struct heredoc {
  10351. struct heredoc *next; /* next here document in list */
  10352. union node *here; /* redirection node */
  10353. char *eofmark; /* string indicating end of input */
  10354. smallint striptabs; /* if set, strip leading tabs */
  10355. };
  10356. static smallint tokpushback; /* last token pushed back */
  10357. static smallint quoteflag; /* set if (part of) last token was quoted */
  10358. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10359. static struct heredoc *heredoclist; /* list of here documents to read */
  10360. static char *wordtext; /* text of last word returned by readtoken */
  10361. static struct nodelist *backquotelist;
  10362. static union node *redirnode;
  10363. static struct heredoc *heredoc;
  10364. static const char *
  10365. tokname(char *buf, int tok)
  10366. {
  10367. if (tok < TSEMI)
  10368. return tokname_array[tok];
  10369. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10370. return buf;
  10371. }
  10372. /* raise_error_unexpected_syntax:
  10373. * Called when an unexpected token is read during the parse. The argument
  10374. * is the token that is expected, or -1 if more than one type of token can
  10375. * occur at this point.
  10376. */
  10377. static void raise_error_unexpected_syntax(int) NORETURN;
  10378. static void
  10379. raise_error_unexpected_syntax(int token)
  10380. {
  10381. char msg[64];
  10382. char buf[16];
  10383. int l;
  10384. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10385. if (token >= 0)
  10386. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10387. raise_error_syntax(msg);
  10388. /* NOTREACHED */
  10389. }
  10390. /* parsing is heavily cross-recursive, need these forward decls */
  10391. static union node *andor(void);
  10392. static union node *pipeline(void);
  10393. static union node *parse_command(void);
  10394. static void parseheredoc(void);
  10395. static int peektoken(void);
  10396. static int readtoken(void);
  10397. static union node *
  10398. list(int nlflag)
  10399. {
  10400. union node *n1, *n2, *n3;
  10401. int tok;
  10402. n1 = NULL;
  10403. for (;;) {
  10404. switch (peektoken()) {
  10405. case TNL:
  10406. if (!(nlflag & 1))
  10407. break;
  10408. parseheredoc();
  10409. return n1;
  10410. case TEOF:
  10411. if (!n1 && (nlflag & 1))
  10412. n1 = NODE_EOF;
  10413. parseheredoc();
  10414. return n1;
  10415. }
  10416. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10417. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10418. return n1;
  10419. nlflag |= 2;
  10420. n2 = andor();
  10421. tok = readtoken();
  10422. if (tok == TBACKGND) {
  10423. if (n2->type == NPIPE) {
  10424. n2->npipe.pipe_backgnd = 1;
  10425. } else {
  10426. if (n2->type != NREDIR) {
  10427. n3 = stzalloc(sizeof(struct nredir));
  10428. n3->nredir.n = n2;
  10429. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10430. n2 = n3;
  10431. }
  10432. n2->type = NBACKGND;
  10433. }
  10434. }
  10435. if (n1 == NULL) {
  10436. n1 = n2;
  10437. } else {
  10438. n3 = stzalloc(sizeof(struct nbinary));
  10439. n3->type = NSEMI;
  10440. n3->nbinary.ch1 = n1;
  10441. n3->nbinary.ch2 = n2;
  10442. n1 = n3;
  10443. }
  10444. switch (tok) {
  10445. case TNL:
  10446. case TEOF:
  10447. tokpushback = 1;
  10448. /* fall through */
  10449. case TBACKGND:
  10450. case TSEMI:
  10451. break;
  10452. default:
  10453. if ((nlflag & 1))
  10454. raise_error_unexpected_syntax(-1);
  10455. tokpushback = 1;
  10456. return n1;
  10457. }
  10458. }
  10459. }
  10460. static union node *
  10461. andor(void)
  10462. {
  10463. union node *n1, *n2, *n3;
  10464. int t;
  10465. n1 = pipeline();
  10466. for (;;) {
  10467. t = readtoken();
  10468. if (t == TAND) {
  10469. t = NAND;
  10470. } else if (t == TOR) {
  10471. t = NOR;
  10472. } else {
  10473. tokpushback = 1;
  10474. return n1;
  10475. }
  10476. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10477. n2 = pipeline();
  10478. n3 = stzalloc(sizeof(struct nbinary));
  10479. n3->type = t;
  10480. n3->nbinary.ch1 = n1;
  10481. n3->nbinary.ch2 = n2;
  10482. n1 = n3;
  10483. }
  10484. }
  10485. static union node *
  10486. pipeline(void)
  10487. {
  10488. union node *n1, *n2, *pipenode;
  10489. struct nodelist *lp, *prev;
  10490. int negate;
  10491. negate = 0;
  10492. TRACE(("pipeline: entered\n"));
  10493. if (readtoken() == TNOT) {
  10494. negate = !negate;
  10495. checkkwd = CHKKWD | CHKALIAS;
  10496. } else
  10497. tokpushback = 1;
  10498. n1 = parse_command();
  10499. if (readtoken() == TPIPE) {
  10500. pipenode = stzalloc(sizeof(struct npipe));
  10501. pipenode->type = NPIPE;
  10502. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10503. lp = stzalloc(sizeof(struct nodelist));
  10504. pipenode->npipe.cmdlist = lp;
  10505. lp->n = n1;
  10506. do {
  10507. prev = lp;
  10508. lp = stzalloc(sizeof(struct nodelist));
  10509. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10510. lp->n = parse_command();
  10511. prev->next = lp;
  10512. } while (readtoken() == TPIPE);
  10513. lp->next = NULL;
  10514. n1 = pipenode;
  10515. }
  10516. tokpushback = 1;
  10517. if (negate) {
  10518. n2 = stzalloc(sizeof(struct nnot));
  10519. n2->type = NNOT;
  10520. n2->nnot.com = n1;
  10521. return n2;
  10522. }
  10523. return n1;
  10524. }
  10525. static union node *
  10526. makename(void)
  10527. {
  10528. union node *n;
  10529. n = stzalloc(sizeof(struct narg));
  10530. n->type = NARG;
  10531. /*n->narg.next = NULL; - stzalloc did it */
  10532. n->narg.text = wordtext;
  10533. n->narg.backquote = backquotelist;
  10534. return n;
  10535. }
  10536. static void
  10537. fixredir(union node *n, const char *text, int err)
  10538. {
  10539. int fd;
  10540. TRACE(("Fix redir %s %d\n", text, err));
  10541. if (!err)
  10542. n->ndup.vname = NULL;
  10543. fd = bb_strtou(text, NULL, 10);
  10544. if (!errno && fd >= 0)
  10545. n->ndup.dupfd = fd;
  10546. else if (LONE_DASH(text))
  10547. n->ndup.dupfd = -1;
  10548. else {
  10549. if (err)
  10550. raise_error_syntax("bad fd number");
  10551. n->ndup.vname = makename();
  10552. }
  10553. }
  10554. static void
  10555. parsefname(void)
  10556. {
  10557. union node *n = redirnode;
  10558. if (n->type == NHERE)
  10559. checkkwd = CHKEOFMARK;
  10560. if (readtoken() != TWORD)
  10561. raise_error_unexpected_syntax(-1);
  10562. if (n->type == NHERE) {
  10563. struct heredoc *here = heredoc;
  10564. struct heredoc *p;
  10565. if (quoteflag == 0)
  10566. n->type = NXHERE;
  10567. TRACE(("Here document %d\n", n->type));
  10568. rmescapes(wordtext, 0, NULL);
  10569. here->eofmark = wordtext;
  10570. here->next = NULL;
  10571. if (heredoclist == NULL)
  10572. heredoclist = here;
  10573. else {
  10574. for (p = heredoclist; p->next; p = p->next)
  10575. continue;
  10576. p->next = here;
  10577. }
  10578. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10579. fixredir(n, wordtext, 0);
  10580. } else {
  10581. n->nfile.fname = makename();
  10582. }
  10583. }
  10584. static union node *
  10585. simplecmd(void)
  10586. {
  10587. union node *args, **app;
  10588. union node *n = NULL;
  10589. union node *vars, **vpp;
  10590. union node **rpp, *redir;
  10591. int savecheckkwd;
  10592. int savelinno;
  10593. #if BASH_TEST2
  10594. smallint double_brackets_flag = 0;
  10595. #endif
  10596. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10597. args = NULL;
  10598. app = &args;
  10599. vars = NULL;
  10600. vpp = &vars;
  10601. redir = NULL;
  10602. rpp = &redir;
  10603. savecheckkwd = CHKALIAS;
  10604. savelinno = g_parsefile->linno;
  10605. for (;;) {
  10606. int t;
  10607. checkkwd = savecheckkwd;
  10608. t = readtoken();
  10609. switch (t) {
  10610. #if BASH_FUNCTION
  10611. case TFUNCTION:
  10612. if (peektoken() != TWORD)
  10613. raise_error_unexpected_syntax(TWORD);
  10614. function_flag = 1;
  10615. break;
  10616. #endif
  10617. #if BASH_TEST2
  10618. case TAND: /* "&&" */
  10619. case TOR: /* "||" */
  10620. if (!double_brackets_flag) {
  10621. tokpushback = 1;
  10622. goto out;
  10623. }
  10624. wordtext = (char *) (t == TAND ? "-a" : "-o");
  10625. #endif
  10626. case TWORD:
  10627. n = stzalloc(sizeof(struct narg));
  10628. n->type = NARG;
  10629. /*n->narg.next = NULL; - stzalloc did it */
  10630. n->narg.text = wordtext;
  10631. #if BASH_TEST2
  10632. if (strcmp("[[", wordtext) == 0)
  10633. double_brackets_flag = 1;
  10634. else if (strcmp("]]", wordtext) == 0)
  10635. double_brackets_flag = 0;
  10636. #endif
  10637. n->narg.backquote = backquotelist;
  10638. if (savecheckkwd && isassignment(wordtext)) {
  10639. *vpp = n;
  10640. vpp = &n->narg.next;
  10641. } else {
  10642. *app = n;
  10643. app = &n->narg.next;
  10644. savecheckkwd = 0;
  10645. }
  10646. #if BASH_FUNCTION
  10647. if (function_flag) {
  10648. checkkwd = CHKNL | CHKKWD;
  10649. switch (peektoken()) {
  10650. case TBEGIN:
  10651. case TIF:
  10652. case TCASE:
  10653. case TUNTIL:
  10654. case TWHILE:
  10655. case TFOR:
  10656. goto do_func;
  10657. case TLP:
  10658. function_flag = 0;
  10659. break;
  10660. # if BASH_TEST2
  10661. case TWORD:
  10662. if (strcmp("[[", wordtext) == 0)
  10663. goto do_func;
  10664. /* fall through */
  10665. # endif
  10666. default:
  10667. raise_error_unexpected_syntax(-1);
  10668. }
  10669. }
  10670. #endif
  10671. break;
  10672. case TREDIR:
  10673. *rpp = n = redirnode;
  10674. rpp = &n->nfile.next;
  10675. parsefname(); /* read name of redirection file */
  10676. break;
  10677. case TLP:
  10678. IF_BASH_FUNCTION(do_func:)
  10679. if (args && app == &args->narg.next
  10680. && !vars && !redir
  10681. ) {
  10682. struct builtincmd *bcmd;
  10683. const char *name;
  10684. /* We have a function */
  10685. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10686. raise_error_unexpected_syntax(TRP);
  10687. name = n->narg.text;
  10688. if (!goodname(name)
  10689. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10690. ) {
  10691. raise_error_syntax("bad function name");
  10692. }
  10693. n->type = NDEFUN;
  10694. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10695. n->ndefun.text = n->narg.text;
  10696. n->ndefun.linno = g_parsefile->linno;
  10697. n->ndefun.body = parse_command();
  10698. return n;
  10699. }
  10700. IF_BASH_FUNCTION(function_flag = 0;)
  10701. /* fall through */
  10702. default:
  10703. tokpushback = 1;
  10704. goto out;
  10705. }
  10706. }
  10707. out:
  10708. *app = NULL;
  10709. *vpp = NULL;
  10710. *rpp = NULL;
  10711. n = stzalloc(sizeof(struct ncmd));
  10712. if (NCMD != 0)
  10713. n->type = NCMD;
  10714. n->ncmd.linno = savelinno;
  10715. n->ncmd.args = args;
  10716. n->ncmd.assign = vars;
  10717. n->ncmd.redirect = redir;
  10718. return n;
  10719. }
  10720. static union node *
  10721. parse_command(void)
  10722. {
  10723. union node *n1, *n2;
  10724. union node *ap, **app;
  10725. union node *cp, **cpp;
  10726. union node *redir, **rpp;
  10727. union node **rpp2;
  10728. int t;
  10729. int savelinno;
  10730. redir = NULL;
  10731. rpp2 = &redir;
  10732. savelinno = g_parsefile->linno;
  10733. switch (readtoken()) {
  10734. default:
  10735. raise_error_unexpected_syntax(-1);
  10736. /* NOTREACHED */
  10737. case TIF:
  10738. n1 = stzalloc(sizeof(struct nif));
  10739. n1->type = NIF;
  10740. n1->nif.test = list(0);
  10741. if (readtoken() != TTHEN)
  10742. raise_error_unexpected_syntax(TTHEN);
  10743. n1->nif.ifpart = list(0);
  10744. n2 = n1;
  10745. while (readtoken() == TELIF) {
  10746. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10747. n2 = n2->nif.elsepart;
  10748. n2->type = NIF;
  10749. n2->nif.test = list(0);
  10750. if (readtoken() != TTHEN)
  10751. raise_error_unexpected_syntax(TTHEN);
  10752. n2->nif.ifpart = list(0);
  10753. }
  10754. if (lasttoken == TELSE)
  10755. n2->nif.elsepart = list(0);
  10756. else {
  10757. n2->nif.elsepart = NULL;
  10758. tokpushback = 1;
  10759. }
  10760. t = TFI;
  10761. break;
  10762. case TWHILE:
  10763. case TUNTIL: {
  10764. int got;
  10765. n1 = stzalloc(sizeof(struct nbinary));
  10766. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10767. n1->nbinary.ch1 = list(0);
  10768. got = readtoken();
  10769. if (got != TDO) {
  10770. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10771. got == TWORD ? wordtext : ""));
  10772. raise_error_unexpected_syntax(TDO);
  10773. }
  10774. n1->nbinary.ch2 = list(0);
  10775. t = TDONE;
  10776. break;
  10777. }
  10778. case TFOR:
  10779. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10780. raise_error_syntax("bad for loop variable");
  10781. n1 = stzalloc(sizeof(struct nfor));
  10782. n1->type = NFOR;
  10783. n1->nfor.linno = savelinno;
  10784. n1->nfor.var = wordtext;
  10785. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10786. if (readtoken() == TIN) {
  10787. app = &ap;
  10788. while (readtoken() == TWORD) {
  10789. n2 = stzalloc(sizeof(struct narg));
  10790. n2->type = NARG;
  10791. /*n2->narg.next = NULL; - stzalloc did it */
  10792. n2->narg.text = wordtext;
  10793. n2->narg.backquote = backquotelist;
  10794. *app = n2;
  10795. app = &n2->narg.next;
  10796. }
  10797. *app = NULL;
  10798. n1->nfor.args = ap;
  10799. if (lasttoken != TNL && lasttoken != TSEMI)
  10800. raise_error_unexpected_syntax(-1);
  10801. } else {
  10802. n2 = stzalloc(sizeof(struct narg));
  10803. n2->type = NARG;
  10804. /*n2->narg.next = NULL; - stzalloc did it */
  10805. n2->narg.text = (char *)dolatstr;
  10806. /*n2->narg.backquote = NULL;*/
  10807. n1->nfor.args = n2;
  10808. /*
  10809. * Newline or semicolon here is optional (but note
  10810. * that the original Bourne shell only allowed NL).
  10811. */
  10812. if (lasttoken != TSEMI)
  10813. tokpushback = 1;
  10814. }
  10815. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10816. if (readtoken() != TDO)
  10817. raise_error_unexpected_syntax(TDO);
  10818. n1->nfor.body = list(0);
  10819. t = TDONE;
  10820. break;
  10821. case TCASE:
  10822. n1 = stzalloc(sizeof(struct ncase));
  10823. n1->type = NCASE;
  10824. n1->ncase.linno = savelinno;
  10825. if (readtoken() != TWORD)
  10826. raise_error_unexpected_syntax(TWORD);
  10827. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10828. n2->type = NARG;
  10829. /*n2->narg.next = NULL; - stzalloc did it */
  10830. n2->narg.text = wordtext;
  10831. n2->narg.backquote = backquotelist;
  10832. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10833. if (readtoken() != TIN)
  10834. raise_error_unexpected_syntax(TIN);
  10835. cpp = &n1->ncase.cases;
  10836. next_case:
  10837. checkkwd = CHKNL | CHKKWD;
  10838. t = readtoken();
  10839. while (t != TESAC) {
  10840. if (lasttoken == TLP)
  10841. readtoken();
  10842. *cpp = cp = stzalloc(sizeof(struct nclist));
  10843. cp->type = NCLIST;
  10844. app = &cp->nclist.pattern;
  10845. for (;;) {
  10846. *app = ap = stzalloc(sizeof(struct narg));
  10847. ap->type = NARG;
  10848. /*ap->narg.next = NULL; - stzalloc did it */
  10849. ap->narg.text = wordtext;
  10850. ap->narg.backquote = backquotelist;
  10851. if (readtoken() != TPIPE)
  10852. break;
  10853. app = &ap->narg.next;
  10854. readtoken();
  10855. }
  10856. //ap->narg.next = NULL;
  10857. if (lasttoken != TRP)
  10858. raise_error_unexpected_syntax(TRP);
  10859. cp->nclist.body = list(2);
  10860. cpp = &cp->nclist.next;
  10861. checkkwd = CHKNL | CHKKWD;
  10862. t = readtoken();
  10863. if (t != TESAC) {
  10864. if (t != TENDCASE)
  10865. raise_error_unexpected_syntax(TENDCASE);
  10866. goto next_case;
  10867. }
  10868. }
  10869. *cpp = NULL;
  10870. goto redir;
  10871. case TLP:
  10872. n1 = stzalloc(sizeof(struct nredir));
  10873. n1->type = NSUBSHELL;
  10874. n1->nredir.linno = savelinno;
  10875. n1->nredir.n = list(0);
  10876. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10877. t = TRP;
  10878. break;
  10879. case TBEGIN:
  10880. n1 = list(0);
  10881. t = TEND;
  10882. break;
  10883. IF_BASH_FUNCTION(case TFUNCTION:)
  10884. case TWORD:
  10885. case TREDIR:
  10886. tokpushback = 1;
  10887. return simplecmd();
  10888. }
  10889. if (readtoken() != t)
  10890. raise_error_unexpected_syntax(t);
  10891. redir:
  10892. /* Now check for redirection which may follow command */
  10893. checkkwd = CHKKWD | CHKALIAS;
  10894. rpp = rpp2;
  10895. while (readtoken() == TREDIR) {
  10896. *rpp = n2 = redirnode;
  10897. rpp = &n2->nfile.next;
  10898. parsefname();
  10899. }
  10900. tokpushback = 1;
  10901. *rpp = NULL;
  10902. if (redir) {
  10903. if (n1->type != NSUBSHELL) {
  10904. n2 = stzalloc(sizeof(struct nredir));
  10905. n2->type = NREDIR;
  10906. n2->nredir.linno = savelinno;
  10907. n2->nredir.n = n1;
  10908. n1 = n2;
  10909. }
  10910. n1->nredir.redirect = redir;
  10911. }
  10912. return n1;
  10913. }
  10914. #if BASH_DOLLAR_SQUOTE
  10915. static int
  10916. decode_dollar_squote(void)
  10917. {
  10918. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  10919. int c, cnt;
  10920. char *p;
  10921. char buf[4];
  10922. c = pgetc();
  10923. p = strchr(C_escapes, c);
  10924. if (p) {
  10925. buf[0] = c;
  10926. p = buf;
  10927. cnt = 3;
  10928. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  10929. do {
  10930. c = pgetc();
  10931. *++p = c;
  10932. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  10933. pungetc();
  10934. } else if (c == 'x') { /* \xHH */
  10935. do {
  10936. c = pgetc();
  10937. *++p = c;
  10938. } while (isxdigit(c) && --cnt);
  10939. pungetc();
  10940. if (cnt == 3) { /* \x but next char is "bad" */
  10941. c = 'x';
  10942. goto unrecognized;
  10943. }
  10944. } else { /* simple seq like \\ or \t */
  10945. p++;
  10946. }
  10947. *p = '\0';
  10948. p = buf;
  10949. c = bb_process_escape_sequence((void*)&p);
  10950. } else { /* unrecognized "\z": print both chars unless ' or " */
  10951. if (c != '\'' && c != '"') {
  10952. unrecognized:
  10953. c |= 0x100; /* "please encode \, then me" */
  10954. }
  10955. }
  10956. return c;
  10957. }
  10958. #endif
  10959. /* Used by expandstr to get here-doc like behaviour. */
  10960. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  10961. static ALWAYS_INLINE int
  10962. realeofmark(const char *eofmark)
  10963. {
  10964. return eofmark && eofmark != FAKEEOFMARK;
  10965. }
  10966. /*
  10967. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  10968. * is not NULL, read a here document. In the latter case, eofmark is the
  10969. * word which marks the end of the document and striptabs is true if
  10970. * leading tabs should be stripped from the document. The argument c
  10971. * is the first character of the input token or document.
  10972. *
  10973. * Because C does not have internal subroutines, I have simulated them
  10974. * using goto's to implement the subroutine linkage. The following macros
  10975. * will run code that appears at the end of readtoken1.
  10976. */
  10977. #define CHECKEND() {goto checkend; checkend_return:;}
  10978. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  10979. #define PARSESUB() {goto parsesub; parsesub_return:;}
  10980. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  10981. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  10982. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  10983. static int
  10984. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  10985. {
  10986. /* NB: syntax parameter fits into smallint */
  10987. /* c parameter is an unsigned char or PEOF or PEOA */
  10988. char *out;
  10989. size_t len;
  10990. struct nodelist *bqlist;
  10991. smallint quotef;
  10992. smallint oldstyle;
  10993. smallint pssyntax; /* we are expanding a prompt string */
  10994. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  10995. /* syntax stack */
  10996. struct synstack synbase = { };
  10997. struct synstack *synstack = &synbase;
  10998. #if ENABLE_ASH_EXPAND_PRMT
  10999. pssyntax = (syntax == PSSYNTAX);
  11000. if (pssyntax)
  11001. syntax = DQSYNTAX;
  11002. #else
  11003. pssyntax = 0; /* constant */
  11004. #endif
  11005. synstack->syntax = syntax;
  11006. if (syntax == DQSYNTAX)
  11007. synstack->dblquote = 1;
  11008. quotef = 0;
  11009. bqlist = NULL;
  11010. STARTSTACKSTR(out);
  11011. loop:
  11012. /* For each line, until end of word */
  11013. CHECKEND(); /* set c to PEOF if at end of here document */
  11014. for (;;) { /* until end of line or end of word */
  11015. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11016. switch (SIT(c, synstack->syntax)) {
  11017. case CNL: /* '\n' */
  11018. if (synstack->syntax == BASESYNTAX
  11019. && !synstack->varnest
  11020. ) {
  11021. goto endword; /* exit outer loop */
  11022. }
  11023. USTPUTC(c, out);
  11024. nlprompt();
  11025. c = pgetc();
  11026. goto loop; /* continue outer loop */
  11027. case CWORD:
  11028. USTPUTC(c, out);
  11029. break;
  11030. case CCTL:
  11031. #if BASH_DOLLAR_SQUOTE
  11032. if (c == '\\' && bash_dollar_squote) {
  11033. c = decode_dollar_squote();
  11034. if (c == '\0') {
  11035. /* skip $'\000', $'\x00' (like bash) */
  11036. break;
  11037. }
  11038. if (c & 0x100) {
  11039. /* Unknown escape. Encode as '\z' */
  11040. c = (unsigned char)c;
  11041. if (eofmark == NULL || synstack->dblquote)
  11042. USTPUTC(CTLESC, out);
  11043. USTPUTC('\\', out);
  11044. }
  11045. }
  11046. #endif
  11047. if (!eofmark || synstack->dblquote || synstack->varnest)
  11048. USTPUTC(CTLESC, out);
  11049. USTPUTC(c, out);
  11050. break;
  11051. case CBACK: /* backslash */
  11052. c = pgetc_without_PEOA();
  11053. if (c == PEOF) {
  11054. USTPUTC(CTLESC, out);
  11055. USTPUTC('\\', out);
  11056. pungetc();
  11057. } else if (c == '\n') {
  11058. nlprompt();
  11059. } else {
  11060. if (pssyntax && c == '$') {
  11061. USTPUTC(CTLESC, out);
  11062. USTPUTC('\\', out);
  11063. }
  11064. /* Backslash is retained if we are in "str"
  11065. * and next char isn't dquote-special.
  11066. */
  11067. if (synstack->dblquote
  11068. && c != '\\'
  11069. && c != '`'
  11070. && c != '$'
  11071. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11072. && (c != '}' || !synstack->varnest)
  11073. ) {
  11074. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11075. USTPUTC('\\', out);
  11076. }
  11077. USTPUTC(CTLESC, out);
  11078. USTPUTC(c, out);
  11079. quotef = 1;
  11080. }
  11081. break;
  11082. case CSQUOTE:
  11083. synstack->syntax = SQSYNTAX;
  11084. quotemark:
  11085. if (eofmark == NULL) {
  11086. USTPUTC(CTLQUOTEMARK, out);
  11087. }
  11088. break;
  11089. case CDQUOTE:
  11090. synstack->syntax = DQSYNTAX;
  11091. synstack->dblquote = 1;
  11092. toggledq:
  11093. if (synstack->varnest)
  11094. synstack->innerdq ^= 1;
  11095. goto quotemark;
  11096. case CENDQUOTE:
  11097. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11098. if (eofmark != NULL && synstack->varnest == 0) {
  11099. USTPUTC(c, out);
  11100. break;
  11101. }
  11102. if (synstack->dqvarnest == 0) {
  11103. synstack->syntax = BASESYNTAX;
  11104. synstack->dblquote = 0;
  11105. }
  11106. quotef = 1;
  11107. if (c == '"')
  11108. goto toggledq;
  11109. goto quotemark;
  11110. case CVAR: /* '$' */
  11111. PARSESUB(); /* parse substitution */
  11112. break;
  11113. case CENDVAR: /* '}' */
  11114. if (!synstack->innerdq && synstack->varnest > 0) {
  11115. if (!--synstack->varnest && synstack->varpushed)
  11116. synstack_pop(&synstack);
  11117. else if (synstack->dqvarnest > 0)
  11118. synstack->dqvarnest--;
  11119. c = CTLENDVAR;
  11120. }
  11121. USTPUTC(c, out);
  11122. break;
  11123. #if ENABLE_FEATURE_SH_MATH
  11124. case CLP: /* '(' in arithmetic */
  11125. synstack->parenlevel++;
  11126. USTPUTC(c, out);
  11127. break;
  11128. case CRP: /* ')' in arithmetic */
  11129. if (synstack->parenlevel > 0) {
  11130. synstack->parenlevel--;
  11131. } else {
  11132. if (pgetc_eatbnl() == ')') {
  11133. c = CTLENDARI;
  11134. synstack_pop(&synstack);
  11135. } else {
  11136. /*
  11137. * unbalanced parens
  11138. * (don't 2nd guess - no error)
  11139. */
  11140. pungetc();
  11141. }
  11142. }
  11143. USTPUTC(c, out);
  11144. break;
  11145. #endif
  11146. case CBQUOTE: /* '`' */
  11147. if (checkkwd & CHKEOFMARK) {
  11148. quotef = 1;
  11149. USTPUTC('`', out);
  11150. break;
  11151. }
  11152. PARSEBACKQOLD();
  11153. break;
  11154. case CENDFILE:
  11155. goto endword; /* exit outer loop */
  11156. case CIGN:
  11157. break;
  11158. default:
  11159. if (synstack->varnest == 0) {
  11160. #if BASH_REDIR_OUTPUT
  11161. if (c == '&') {
  11162. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11163. if (pgetc() == '>')
  11164. c = 0x100 + '>'; /* flag &> */
  11165. pungetc();
  11166. }
  11167. #endif
  11168. goto endword; /* exit outer loop */
  11169. }
  11170. IF_ASH_ALIAS(if (c != PEOA))
  11171. USTPUTC(c, out);
  11172. }
  11173. c = pgetc();
  11174. } /* for (;;) */
  11175. endword:
  11176. #if ENABLE_FEATURE_SH_MATH
  11177. if (synstack->syntax == ARISYNTAX)
  11178. raise_error_syntax("missing '))'");
  11179. #endif
  11180. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11181. raise_error_syntax("unterminated quoted string");
  11182. if (synstack->varnest != 0) {
  11183. /* { */
  11184. raise_error_syntax("missing '}'");
  11185. }
  11186. USTPUTC('\0', out);
  11187. len = out - (char *)stackblock();
  11188. out = stackblock();
  11189. if (eofmark == NULL) {
  11190. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11191. && quotef == 0
  11192. ) {
  11193. if (isdigit_str9(out)) {
  11194. PARSEREDIR(); /* passed as params: out, c */
  11195. lasttoken = TREDIR;
  11196. return lasttoken;
  11197. }
  11198. /* else: non-number X seen, interpret it
  11199. * as "NNNX>file" = "NNNX >file" */
  11200. }
  11201. pungetc();
  11202. }
  11203. quoteflag = quotef;
  11204. backquotelist = bqlist;
  11205. grabstackblock(len);
  11206. wordtext = out;
  11207. lasttoken = TWORD;
  11208. return lasttoken;
  11209. /* end of readtoken routine */
  11210. /*
  11211. * Check to see whether we are at the end of the here document. When this
  11212. * is called, c is set to the first character of the next input line. If
  11213. * we are at the end of the here document, this routine sets the c to PEOF.
  11214. */
  11215. checkend: {
  11216. if (realeofmark(eofmark)) {
  11217. int markloc;
  11218. char *p;
  11219. #if ENABLE_ASH_ALIAS
  11220. if (c == PEOA)
  11221. c = pgetc_without_PEOA();
  11222. #endif
  11223. if (striptabs) {
  11224. while (c == '\t') {
  11225. c = pgetc_without_PEOA();
  11226. }
  11227. }
  11228. markloc = out - (char *)stackblock();
  11229. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11230. if (c != *p)
  11231. goto more_heredoc;
  11232. c = pgetc_without_PEOA();
  11233. }
  11234. if (c == '\n' || c == PEOF) {
  11235. c = PEOF;
  11236. g_parsefile->linno++;
  11237. needprompt = doprompt;
  11238. } else {
  11239. int len_here;
  11240. more_heredoc:
  11241. p = (char *)stackblock() + markloc + 1;
  11242. len_here = out - p;
  11243. if (len_here) {
  11244. len_here -= (c >= PEOF);
  11245. c = p[-1];
  11246. if (len_here) {
  11247. char *str;
  11248. str = alloca(len_here + 1);
  11249. *(char *)mempcpy(str, p, len_here) = '\0';
  11250. pushstring(str, NULL);
  11251. }
  11252. }
  11253. }
  11254. STADJUST((char *)stackblock() + markloc - out, out);
  11255. }
  11256. goto checkend_return;
  11257. }
  11258. /*
  11259. * Parse a redirection operator. The variable "out" points to a string
  11260. * specifying the fd to be redirected. The variable "c" contains the
  11261. * first character of the redirection operator.
  11262. */
  11263. parseredir: {
  11264. /* out is already checked to be a valid number or "" */
  11265. int fd = (*out == '\0' ? -1 : atoi(out));
  11266. union node *np;
  11267. np = stzalloc(sizeof(struct nfile));
  11268. if (c == '>') {
  11269. np->nfile.fd = 1;
  11270. c = pgetc_eatbnl();
  11271. if (c == '>')
  11272. np->type = NAPPEND;
  11273. else if (c == '|')
  11274. np->type = NCLOBBER;
  11275. else if (c == '&')
  11276. np->type = NTOFD;
  11277. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11278. else {
  11279. np->type = NTO;
  11280. pungetc();
  11281. }
  11282. }
  11283. #if BASH_REDIR_OUTPUT
  11284. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11285. np->nfile.fd = 1;
  11286. pgetc(); /* this is '>', no need to check */
  11287. np->type = NTO2;
  11288. }
  11289. #endif
  11290. else { /* c == '<' */
  11291. /*np->nfile.fd = 0; - stzalloc did it */
  11292. c = pgetc_eatbnl();
  11293. switch (c) {
  11294. case '<':
  11295. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11296. np = stzalloc(sizeof(struct nhere));
  11297. /*np->nfile.fd = 0; - stzalloc did it */
  11298. }
  11299. np->type = NHERE;
  11300. heredoc = stzalloc(sizeof(struct heredoc));
  11301. heredoc->here = np;
  11302. c = pgetc_eatbnl();
  11303. if (c == '-') {
  11304. heredoc->striptabs = 1;
  11305. } else {
  11306. /*heredoc->striptabs = 0; - stzalloc did it */
  11307. pungetc();
  11308. }
  11309. break;
  11310. case '&':
  11311. np->type = NFROMFD;
  11312. break;
  11313. case '>':
  11314. np->type = NFROMTO;
  11315. break;
  11316. default:
  11317. np->type = NFROM;
  11318. pungetc();
  11319. break;
  11320. }
  11321. }
  11322. if (fd >= 0)
  11323. np->nfile.fd = fd;
  11324. redirnode = np;
  11325. goto parseredir_return;
  11326. }
  11327. /*
  11328. * Parse a substitution. At this point, we have read the dollar sign
  11329. * and nothing else.
  11330. */
  11331. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11332. * (assuming ascii char codes, as the original implementation did) */
  11333. #define is_special(c) \
  11334. (((unsigned)(c) - 33 < 32) \
  11335. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11336. parsesub: {
  11337. unsigned char subtype;
  11338. int typeloc;
  11339. c = pgetc_eatbnl();
  11340. if ((checkkwd & CHKEOFMARK)
  11341. || c > 255 /* PEOA or PEOF */
  11342. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11343. ) {
  11344. #if BASH_DOLLAR_SQUOTE
  11345. if (synstack->syntax != DQSYNTAX && c == '\'')
  11346. bash_dollar_squote = 1;
  11347. else
  11348. #endif
  11349. USTPUTC('$', out);
  11350. pungetc();
  11351. } else if (c == '(') {
  11352. /* $(command) or $((arith)) */
  11353. if (pgetc_eatbnl() == '(') {
  11354. #if ENABLE_FEATURE_SH_MATH
  11355. PARSEARITH();
  11356. #else
  11357. raise_error_syntax("support for $((arith)) is disabled");
  11358. #endif
  11359. } else {
  11360. pungetc();
  11361. PARSEBACKQNEW();
  11362. }
  11363. } else {
  11364. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11365. smalluint newsyn = synstack->syntax;
  11366. USTPUTC(CTLVAR, out);
  11367. typeloc = out - (char *)stackblock();
  11368. STADJUST(1, out);
  11369. subtype = VSNORMAL;
  11370. if (c == '{') {
  11371. c = pgetc_eatbnl();
  11372. subtype = 0;
  11373. }
  11374. varname:
  11375. if (is_name(c)) {
  11376. /* $[{[#]]NAME[}] */
  11377. do {
  11378. STPUTC(c, out);
  11379. c = pgetc_eatbnl();
  11380. } while (is_in_name(c));
  11381. } else if (isdigit(c)) {
  11382. /* $[{[#]]NUM[}] */
  11383. do {
  11384. STPUTC(c, out);
  11385. c = pgetc_eatbnl();
  11386. } while (isdigit(c));
  11387. } else if (c != '}') {
  11388. /* $[{[#]]<specialchar>[}] */
  11389. int cc = c;
  11390. c = pgetc_eatbnl();
  11391. if (!subtype && cc == '#') {
  11392. subtype = VSLENGTH;
  11393. if (c == '_' || isalnum(c))
  11394. goto varname;
  11395. cc = c;
  11396. c = pgetc_eatbnl();
  11397. if (cc == '}' || c != '}') {
  11398. pungetc();
  11399. subtype = 0;
  11400. c = cc;
  11401. cc = '#';
  11402. }
  11403. }
  11404. if (!is_special(cc)) {
  11405. if (subtype == VSLENGTH)
  11406. subtype = 0;
  11407. goto badsub;
  11408. }
  11409. USTPUTC(cc, out);
  11410. } else
  11411. goto badsub;
  11412. if (c != '}' && subtype == VSLENGTH) {
  11413. /* ${#VAR didn't end with } */
  11414. goto badsub;
  11415. }
  11416. if (subtype == 0) {
  11417. static const char types[] ALIGN1 = "}-+?=";
  11418. /* ${VAR...} but not $VAR or ${#VAR} */
  11419. /* c == first char after VAR */
  11420. int cc = c;
  11421. switch (c) {
  11422. case ':':
  11423. c = pgetc_eatbnl();
  11424. #if BASH_SUBSTR
  11425. /* This check is only needed to not misinterpret
  11426. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11427. * constructs.
  11428. */
  11429. if (!strchr(types, c)) {
  11430. subtype = VSSUBSTR;
  11431. pungetc();
  11432. break; /* "goto badsub" is bigger (!) */
  11433. }
  11434. #endif
  11435. subtype = VSNUL;
  11436. /*FALLTHROUGH*/
  11437. default: {
  11438. const char *p = strchr(types, c);
  11439. if (p == NULL)
  11440. break;
  11441. subtype |= p - types + VSNORMAL;
  11442. break;
  11443. }
  11444. case '%':
  11445. case '#':
  11446. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11447. c = pgetc_eatbnl();
  11448. if (c == cc)
  11449. subtype++;
  11450. else
  11451. pungetc();
  11452. newsyn = BASESYNTAX;
  11453. break;
  11454. #if BASH_PATTERN_SUBST
  11455. case '/':
  11456. /* ${v/[/]pattern/repl} */
  11457. //TODO: encode pattern and repl separately.
  11458. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11459. // are broken (should print "ONE")
  11460. subtype = VSREPLACE;
  11461. newsyn = BASESYNTAX;
  11462. c = pgetc_eatbnl();
  11463. if (c != '/')
  11464. goto badsub;
  11465. subtype++; /* VSREPLACEALL */
  11466. break;
  11467. #endif
  11468. }
  11469. } else {
  11470. badsub:
  11471. pungetc();
  11472. }
  11473. if (newsyn == ARISYNTAX)
  11474. newsyn = DQSYNTAX;
  11475. if ((newsyn != synstack->syntax || synstack->innerdq)
  11476. && subtype != VSNORMAL
  11477. ) {
  11478. synstack_push(&synstack,
  11479. synstack->prev ?: alloca(sizeof(*synstack)),
  11480. newsyn);
  11481. synstack->varpushed = 1;
  11482. synstack->dblquote = newsyn != BASESYNTAX;
  11483. }
  11484. ((unsigned char *)stackblock())[typeloc] = subtype;
  11485. if (subtype != VSNORMAL) {
  11486. synstack->varnest++;
  11487. if (synstack->dblquote)
  11488. synstack->dqvarnest++;
  11489. }
  11490. STPUTC('=', out);
  11491. }
  11492. goto parsesub_return;
  11493. }
  11494. /*
  11495. * Called to parse command substitutions. Newstyle is set if the command
  11496. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11497. * list of commands (passed by reference), and savelen is the number of
  11498. * characters on the top of the stack which must be preserved.
  11499. */
  11500. parsebackq: {
  11501. struct nodelist **nlpp;
  11502. union node *n;
  11503. char *str;
  11504. size_t savelen;
  11505. smallint saveprompt = 0;
  11506. str = NULL;
  11507. savelen = out - (char *)stackblock();
  11508. if (savelen > 0) {
  11509. /*
  11510. * FIXME: this can allocate very large block on stack and SEGV.
  11511. * Example:
  11512. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11513. * allocates 100kb for every command subst. With about
  11514. * a hundred command substitutions stack overflows.
  11515. * With larger prepended string, SEGV happens sooner.
  11516. */
  11517. str = alloca(savelen);
  11518. memcpy(str, stackblock(), savelen);
  11519. }
  11520. if (oldstyle) {
  11521. /* We must read until the closing backquote, giving special
  11522. * treatment to some slashes, and then push the string and
  11523. * reread it as input, interpreting it normally.
  11524. */
  11525. char *pout;
  11526. size_t psavelen;
  11527. char *pstr;
  11528. STARTSTACKSTR(pout);
  11529. for (;;) {
  11530. int pc;
  11531. setprompt_if(needprompt, 2);
  11532. pc = pgetc_eatbnl();
  11533. switch (pc) {
  11534. case '`':
  11535. goto done;
  11536. case '\\':
  11537. pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
  11538. if (pc != '\\' && pc != '`' && pc != '$'
  11539. && (!synstack->dblquote || pc != '"')
  11540. ) {
  11541. STPUTC('\\', pout);
  11542. }
  11543. if (pc <= 255 /* not PEOA or PEOF */) {
  11544. break;
  11545. }
  11546. /* fall through */
  11547. case PEOF:
  11548. IF_ASH_ALIAS(case PEOA:)
  11549. raise_error_syntax("EOF in backquote substitution");
  11550. case '\n':
  11551. nlnoprompt();
  11552. break;
  11553. default:
  11554. break;
  11555. }
  11556. STPUTC(pc, pout);
  11557. }
  11558. done:
  11559. STPUTC('\0', pout);
  11560. psavelen = pout - (char *)stackblock();
  11561. if (psavelen > 0) {
  11562. pstr = grabstackstr(pout);
  11563. setinputstring(pstr);
  11564. }
  11565. }
  11566. nlpp = &bqlist;
  11567. while (*nlpp)
  11568. nlpp = &(*nlpp)->next;
  11569. *nlpp = stzalloc(sizeof(**nlpp));
  11570. /* (*nlpp)->next = NULL; - stzalloc did it */
  11571. if (oldstyle) {
  11572. saveprompt = doprompt;
  11573. doprompt = 0;
  11574. }
  11575. n = list(2);
  11576. if (oldstyle)
  11577. doprompt = saveprompt;
  11578. else if (readtoken() != TRP)
  11579. raise_error_unexpected_syntax(TRP);
  11580. (*nlpp)->n = n;
  11581. if (oldstyle) {
  11582. /*
  11583. * Start reading from old file again, ignoring any pushed back
  11584. * tokens left from the backquote parsing
  11585. */
  11586. popfile();
  11587. tokpushback = 0;
  11588. }
  11589. while (stackblocksize() <= savelen)
  11590. growstackblock();
  11591. STARTSTACKSTR(out);
  11592. if (str) {
  11593. memcpy(out, str, savelen);
  11594. STADJUST(savelen, out);
  11595. }
  11596. USTPUTC(CTLBACKQ, out);
  11597. if (oldstyle)
  11598. goto parsebackq_oldreturn;
  11599. goto parsebackq_newreturn;
  11600. }
  11601. #if ENABLE_FEATURE_SH_MATH
  11602. /*
  11603. * Parse an arithmetic expansion (indicate start of one and set state)
  11604. */
  11605. parsearith: {
  11606. synstack_push(&synstack,
  11607. synstack->prev ?: alloca(sizeof(*synstack)),
  11608. ARISYNTAX);
  11609. synstack->dblquote = 1;
  11610. USTPUTC(CTLARI, out);
  11611. goto parsearith_return;
  11612. }
  11613. #endif
  11614. } /* end of readtoken */
  11615. /*
  11616. * Read the next input token.
  11617. * If the token is a word, we set backquotelist to the list of cmds in
  11618. * backquotes. We set quoteflag to true if any part of the word was
  11619. * quoted.
  11620. * If the token is TREDIR, then we set redirnode to a structure containing
  11621. * the redirection.
  11622. *
  11623. * [Change comment: here documents and internal procedures]
  11624. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11625. * word parsing code into a separate routine. In this case, readtoken
  11626. * doesn't need to have any internal procedures, but parseword does.
  11627. * We could also make parseoperator in essence the main routine, and
  11628. * have parseword (readtoken1?) handle both words and redirection.]
  11629. */
  11630. #define NEW_xxreadtoken
  11631. #ifdef NEW_xxreadtoken
  11632. /* singles must be first! */
  11633. static const char xxreadtoken_chars[7] ALIGN1 = {
  11634. '\n', '(', ')', /* singles */
  11635. '&', '|', ';', /* doubles */
  11636. 0
  11637. };
  11638. #define xxreadtoken_singles 3
  11639. #define xxreadtoken_doubles 3
  11640. static const char xxreadtoken_tokens[] ALIGN1 = {
  11641. TNL, TLP, TRP, /* only single occurrence allowed */
  11642. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11643. TEOF, /* corresponds to trailing nul */
  11644. TAND, TOR, TENDCASE /* if double occurrence */
  11645. };
  11646. static int
  11647. xxreadtoken(void)
  11648. {
  11649. int c;
  11650. if (tokpushback) {
  11651. tokpushback = 0;
  11652. return lasttoken;
  11653. }
  11654. setprompt_if(needprompt, 2);
  11655. for (;;) { /* until token or start of word found */
  11656. c = pgetc_eatbnl();
  11657. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11658. continue;
  11659. if (c == '#') {
  11660. while ((c = pgetc()) != '\n' && c != PEOF)
  11661. continue;
  11662. pungetc();
  11663. } else if (c == '\\') {
  11664. break; /* return readtoken1(...) */
  11665. } else {
  11666. const char *p;
  11667. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11668. if (c != PEOF) {
  11669. if (c == '\n') {
  11670. nlnoprompt();
  11671. }
  11672. p = strchr(xxreadtoken_chars, c);
  11673. if (p == NULL)
  11674. break; /* return readtoken1(...) */
  11675. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11676. int cc = pgetc_eatbnl();
  11677. if (cc == c) { /* double occurrence? */
  11678. p += xxreadtoken_doubles + 1;
  11679. } else {
  11680. pungetc();
  11681. #if BASH_REDIR_OUTPUT
  11682. if (c == '&' && cc == '>') /* &> */
  11683. break; /* return readtoken1(...) */
  11684. #endif
  11685. }
  11686. }
  11687. }
  11688. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11689. return lasttoken;
  11690. }
  11691. } /* for (;;) */
  11692. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11693. }
  11694. #else /* old xxreadtoken */
  11695. #define RETURN(token) return lasttoken = token
  11696. static int
  11697. xxreadtoken(void)
  11698. {
  11699. int c;
  11700. if (tokpushback) {
  11701. tokpushback = 0;
  11702. return lasttoken;
  11703. }
  11704. setprompt_if(needprompt, 2);
  11705. for (;;) { /* until token or start of word found */
  11706. c = pgetc_eatbnl();
  11707. switch (c) {
  11708. case ' ': case '\t':
  11709. IF_ASH_ALIAS(case PEOA:)
  11710. continue;
  11711. case '#':
  11712. while ((c = pgetc()) != '\n' && c != PEOF)
  11713. continue;
  11714. pungetc();
  11715. continue;
  11716. case '\n':
  11717. nlnoprompt();
  11718. RETURN(TNL);
  11719. case PEOF:
  11720. RETURN(TEOF);
  11721. case '&':
  11722. if (pgetc_eatbnl() == '&')
  11723. RETURN(TAND);
  11724. pungetc();
  11725. RETURN(TBACKGND);
  11726. case '|':
  11727. if (pgetc_eatbnl() == '|')
  11728. RETURN(TOR);
  11729. pungetc();
  11730. RETURN(TPIPE);
  11731. case ';':
  11732. if (pgetc_eatbnl() == ';')
  11733. RETURN(TENDCASE);
  11734. pungetc();
  11735. RETURN(TSEMI);
  11736. case '(':
  11737. RETURN(TLP);
  11738. case ')':
  11739. RETURN(TRP);
  11740. }
  11741. break;
  11742. }
  11743. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11744. #undef RETURN
  11745. }
  11746. #endif /* old xxreadtoken */
  11747. static int
  11748. readtoken(void)
  11749. {
  11750. int t;
  11751. int kwd = checkkwd;
  11752. #if DEBUG
  11753. smallint alreadyseen = tokpushback;
  11754. #endif
  11755. #if ENABLE_ASH_ALIAS
  11756. top:
  11757. #endif
  11758. t = xxreadtoken();
  11759. /*
  11760. * eat newlines
  11761. */
  11762. if (kwd & CHKNL) {
  11763. while (t == TNL) {
  11764. parseheredoc();
  11765. t = xxreadtoken();
  11766. }
  11767. }
  11768. if (t != TWORD || quoteflag) {
  11769. goto out;
  11770. }
  11771. /*
  11772. * check for keywords
  11773. */
  11774. if (kwd & CHKKWD) {
  11775. const char *const *pp;
  11776. pp = findkwd(wordtext);
  11777. if (pp) {
  11778. lasttoken = t = pp - tokname_array;
  11779. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11780. goto out;
  11781. }
  11782. }
  11783. if (checkkwd & CHKALIAS) {
  11784. #if ENABLE_ASH_ALIAS
  11785. struct alias *ap;
  11786. ap = lookupalias(wordtext, 1);
  11787. if (ap != NULL) {
  11788. if (*ap->val) {
  11789. pushstring(ap->val, ap);
  11790. }
  11791. goto top;
  11792. }
  11793. #endif
  11794. }
  11795. out:
  11796. checkkwd = 0;
  11797. #if DEBUG
  11798. if (!alreadyseen)
  11799. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11800. else
  11801. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11802. #endif
  11803. return t;
  11804. }
  11805. static int
  11806. peektoken(void)
  11807. {
  11808. int t;
  11809. t = readtoken();
  11810. tokpushback = 1;
  11811. return t;
  11812. }
  11813. /*
  11814. * Read and parse a command. Returns NODE_EOF on end of file.
  11815. * (NULL is a valid parse tree indicating a blank line.)
  11816. */
  11817. static union node *
  11818. parsecmd(int interact)
  11819. {
  11820. tokpushback = 0;
  11821. checkkwd = 0;
  11822. heredoclist = 0;
  11823. doprompt = interact;
  11824. setprompt_if(doprompt, doprompt);
  11825. needprompt = 0;
  11826. return list(1);
  11827. }
  11828. /*
  11829. * Input any here documents.
  11830. */
  11831. static void
  11832. parseheredoc(void)
  11833. {
  11834. struct heredoc *here;
  11835. union node *n;
  11836. here = heredoclist;
  11837. heredoclist = NULL;
  11838. while (here) {
  11839. setprompt_if(needprompt, 2);
  11840. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11841. here->eofmark, here->striptabs);
  11842. n = stzalloc(sizeof(struct narg));
  11843. n->narg.type = NARG;
  11844. /*n->narg.next = NULL; - stzalloc did it */
  11845. n->narg.text = wordtext;
  11846. n->narg.backquote = backquotelist;
  11847. here->here->nhere.doc = n;
  11848. here = here->next;
  11849. }
  11850. }
  11851. static const char *
  11852. expandstr(const char *ps, int syntax_type)
  11853. {
  11854. union node n;
  11855. int saveprompt;
  11856. /* XXX Fix (char *) cast. */
  11857. setinputstring((char *)ps);
  11858. saveprompt = doprompt;
  11859. doprompt = 0;
  11860. /* readtoken1() might die horribly.
  11861. * Try a prompt with syntactically wrong command:
  11862. * PS1='$(date "+%H:%M:%S) > '
  11863. */
  11864. {
  11865. volatile int saveint;
  11866. struct jmploc *volatile savehandler = exception_handler;
  11867. struct jmploc jmploc;
  11868. SAVE_INT(saveint);
  11869. if (setjmp(jmploc.loc) == 0) {
  11870. exception_handler = &jmploc;
  11871. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  11872. }
  11873. exception_handler = savehandler;
  11874. RESTORE_INT(saveint);
  11875. }
  11876. doprompt = saveprompt;
  11877. popfile();
  11878. n.narg.type = NARG;
  11879. n.narg.next = NULL;
  11880. n.narg.text = wordtext;
  11881. n.narg.backquote = backquotelist;
  11882. expandarg(&n, NULL, EXP_QUOTED);
  11883. return stackblock();
  11884. }
  11885. static inline int
  11886. parser_eof(void)
  11887. {
  11888. return tokpushback && lasttoken == TEOF;
  11889. }
  11890. /*
  11891. * Execute a command or commands contained in a string.
  11892. */
  11893. static int
  11894. evalstring(char *s, int flags)
  11895. {
  11896. struct jmploc *volatile savehandler;
  11897. struct jmploc jmploc;
  11898. int ex;
  11899. union node *n;
  11900. struct stackmark smark;
  11901. int status;
  11902. s = sstrdup(s);
  11903. setinputstring(s);
  11904. setstackmark(&smark);
  11905. status = 0;
  11906. /* On exception inside execution loop, we must popfile().
  11907. * Try interactively:
  11908. * readonly a=a
  11909. * command eval "a=b" # throws "is read only" error
  11910. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  11911. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  11912. */
  11913. savehandler = exception_handler;
  11914. ex = setjmp(jmploc.loc);
  11915. if (ex)
  11916. goto out;
  11917. exception_handler = &jmploc;
  11918. while ((n = parsecmd(0)) != NODE_EOF) {
  11919. int i;
  11920. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  11921. if (n)
  11922. status = i;
  11923. popstackmark(&smark);
  11924. if (evalskip)
  11925. break;
  11926. }
  11927. out:
  11928. popstackmark(&smark);
  11929. popfile();
  11930. stunalloc(s);
  11931. exception_handler = savehandler;
  11932. if (ex)
  11933. longjmp(exception_handler->loc, ex);
  11934. return status;
  11935. }
  11936. /*
  11937. * The eval command.
  11938. */
  11939. static int FAST_FUNC
  11940. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  11941. {
  11942. char *p;
  11943. char *concat;
  11944. if (argv[1]) {
  11945. p = argv[1];
  11946. argv += 2;
  11947. if (argv[0]) {
  11948. STARTSTACKSTR(concat);
  11949. for (;;) {
  11950. concat = stack_putstr(p, concat);
  11951. p = *argv++;
  11952. if (p == NULL)
  11953. break;
  11954. STPUTC(' ', concat);
  11955. }
  11956. STPUTC('\0', concat);
  11957. p = grabstackstr(concat);
  11958. }
  11959. return evalstring(p, flags & EV_TESTED);
  11960. }
  11961. return 0;
  11962. }
  11963. /*
  11964. * Read and execute commands.
  11965. * "Top" is nonzero for the top level command loop;
  11966. * it turns on prompting if the shell is interactive.
  11967. */
  11968. static int
  11969. cmdloop(int top)
  11970. {
  11971. union node *n;
  11972. struct stackmark smark;
  11973. int inter;
  11974. int status = 0;
  11975. int numeof = 0;
  11976. TRACE(("cmdloop(%d) called\n", top));
  11977. for (;;) {
  11978. int skip;
  11979. setstackmark(&smark);
  11980. #if JOBS
  11981. if (doing_jobctl)
  11982. showjobs(SHOW_CHANGED|SHOW_STDERR);
  11983. #endif
  11984. inter = 0;
  11985. if (iflag && top) {
  11986. inter++;
  11987. chkmail();
  11988. }
  11989. n = parsecmd(inter);
  11990. #if DEBUG
  11991. if (DEBUG > 2 && debug && (n != NODE_EOF))
  11992. showtree(n);
  11993. #endif
  11994. if (n == NODE_EOF) {
  11995. if (!top || numeof >= 50)
  11996. break;
  11997. if (!stoppedjobs()) {
  11998. if (!Iflag)
  11999. break;
  12000. out2str("\nUse \"exit\" to leave shell.\n");
  12001. }
  12002. numeof++;
  12003. } else if (nflag == 0) {
  12004. int i;
  12005. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12006. job_warning >>= 1;
  12007. numeof = 0;
  12008. i = evaltree(n, 0);
  12009. if (n)
  12010. status = i;
  12011. }
  12012. popstackmark(&smark);
  12013. skip = evalskip;
  12014. if (skip) {
  12015. evalskip &= ~SKIPFUNC;
  12016. break;
  12017. }
  12018. }
  12019. return status;
  12020. }
  12021. /*
  12022. * Take commands from a file. To be compatible we should do a path
  12023. * search for the file, which is necessary to find sub-commands.
  12024. */
  12025. static char *
  12026. find_dot_file(char *name)
  12027. {
  12028. char *fullname;
  12029. const char *path = pathval();
  12030. struct stat statb;
  12031. /* don't try this for absolute or relative paths */
  12032. if (strchr(name, '/'))
  12033. return name;
  12034. while ((fullname = path_advance(&path, name)) != NULL) {
  12035. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  12036. /*
  12037. * Don't bother freeing here, since it will
  12038. * be freed by the caller.
  12039. */
  12040. return fullname;
  12041. }
  12042. if (fullname != name)
  12043. stunalloc(fullname);
  12044. }
  12045. /* not found in PATH */
  12046. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12047. return name;
  12048. #else
  12049. ash_msg_and_raise_error("%s: not found", name);
  12050. /* NOTREACHED */
  12051. #endif
  12052. }
  12053. static int FAST_FUNC
  12054. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12055. {
  12056. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12057. int status = 0;
  12058. char *fullname;
  12059. char **argv;
  12060. char *args_need_save;
  12061. volatile struct shparam saveparam;
  12062. //???
  12063. // struct strlist *sp;
  12064. // for (sp = cmdenviron; sp; sp = sp->next)
  12065. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12066. nextopt(nullstr); /* handle possible "--" */
  12067. argv = argptr;
  12068. if (!argv[0]) {
  12069. /* bash says: "bash: .: filename argument required" */
  12070. return 2; /* bash compat */
  12071. }
  12072. /* This aborts if file isn't found, which is POSIXly correct.
  12073. * bash returns exitcode 1 instead.
  12074. */
  12075. fullname = find_dot_file(argv[0]);
  12076. argv++;
  12077. args_need_save = argv[0];
  12078. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12079. int argc;
  12080. saveparam = shellparam;
  12081. shellparam.malloced = 0;
  12082. argc = 1;
  12083. while (argv[argc])
  12084. argc++;
  12085. shellparam.nparam = argc;
  12086. shellparam.p = argv;
  12087. };
  12088. /* This aborts if file can't be opened, which is POSIXly correct.
  12089. * bash returns exitcode 1 instead.
  12090. */
  12091. setinputfile(fullname, INPUT_PUSH_FILE);
  12092. commandname = fullname;
  12093. status = cmdloop(0);
  12094. popfile();
  12095. if (args_need_save) {
  12096. freeparam(&shellparam);
  12097. shellparam = saveparam;
  12098. };
  12099. return status;
  12100. }
  12101. static int FAST_FUNC
  12102. exitcmd(int argc UNUSED_PARAM, char **argv)
  12103. {
  12104. if (stoppedjobs())
  12105. return 0;
  12106. if (argv[1])
  12107. exitstatus = number(argv[1]);
  12108. raise_exception(EXEXIT);
  12109. /* NOTREACHED */
  12110. }
  12111. /*
  12112. * Read a file containing shell functions.
  12113. */
  12114. static void
  12115. readcmdfile(char *name)
  12116. {
  12117. setinputfile(name, INPUT_PUSH_FILE);
  12118. cmdloop(0);
  12119. popfile();
  12120. }
  12121. /* ============ find_command inplementation */
  12122. /*
  12123. * Resolve a command name. If you change this routine, you may have to
  12124. * change the shellexec routine as well.
  12125. */
  12126. static void
  12127. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12128. {
  12129. struct tblentry *cmdp;
  12130. int idx;
  12131. int prev;
  12132. char *fullname;
  12133. struct stat statb;
  12134. int e;
  12135. int updatetbl;
  12136. struct builtincmd *bcmd;
  12137. /* If name contains a slash, don't use PATH or hash table */
  12138. if (strchr(name, '/') != NULL) {
  12139. entry->u.index = -1;
  12140. if (act & DO_ABS) {
  12141. while (stat(name, &statb) < 0) {
  12142. #ifdef SYSV
  12143. if (errno == EINTR)
  12144. continue;
  12145. #endif
  12146. entry->cmdtype = CMDUNKNOWN;
  12147. return;
  12148. }
  12149. }
  12150. entry->cmdtype = CMDNORMAL;
  12151. return;
  12152. }
  12153. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12154. updatetbl = (path == pathval());
  12155. if (!updatetbl) {
  12156. act |= DO_ALTPATH;
  12157. if (strstr(path, "%builtin") != NULL)
  12158. act |= DO_ALTBLTIN;
  12159. }
  12160. /* If name is in the table, check answer will be ok */
  12161. cmdp = cmdlookup(name, 0);
  12162. if (cmdp != NULL) {
  12163. int bit;
  12164. switch (cmdp->cmdtype) {
  12165. default:
  12166. #if DEBUG
  12167. abort();
  12168. #endif
  12169. case CMDNORMAL:
  12170. bit = DO_ALTPATH;
  12171. break;
  12172. case CMDFUNCTION:
  12173. bit = DO_NOFUNC;
  12174. break;
  12175. case CMDBUILTIN:
  12176. bit = DO_ALTBLTIN;
  12177. break;
  12178. }
  12179. if (act & bit) {
  12180. updatetbl = 0;
  12181. cmdp = NULL;
  12182. } else if (cmdp->rehash == 0)
  12183. /* if not invalidated by cd, we're done */
  12184. goto success;
  12185. }
  12186. /* If %builtin not in path, check for builtin next */
  12187. bcmd = find_builtin(name);
  12188. if (bcmd) {
  12189. if (IS_BUILTIN_REGULAR(bcmd))
  12190. goto builtin_success;
  12191. if (act & DO_ALTPATH) {
  12192. if (!(act & DO_ALTBLTIN))
  12193. goto builtin_success;
  12194. } else if (builtinloc <= 0) {
  12195. goto builtin_success;
  12196. }
  12197. }
  12198. #if ENABLE_FEATURE_SH_STANDALONE
  12199. {
  12200. int applet_no = find_applet_by_name(name);
  12201. if (applet_no >= 0) {
  12202. entry->cmdtype = CMDNORMAL;
  12203. entry->u.index = -2 - applet_no;
  12204. return;
  12205. }
  12206. }
  12207. #endif
  12208. /* We have to search path. */
  12209. prev = -1; /* where to start */
  12210. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12211. if (cmdp->cmdtype == CMDBUILTIN)
  12212. prev = builtinloc;
  12213. else
  12214. prev = cmdp->param.index;
  12215. }
  12216. e = ENOENT;
  12217. idx = -1;
  12218. loop:
  12219. while ((fullname = path_advance(&path, name)) != NULL) {
  12220. stunalloc(fullname);
  12221. /* NB: code below will still use fullname
  12222. * despite it being "unallocated" */
  12223. idx++;
  12224. if (pathopt) {
  12225. if (prefix(pathopt, "builtin")) {
  12226. if (bcmd)
  12227. goto builtin_success;
  12228. continue;
  12229. }
  12230. if ((act & DO_NOFUNC)
  12231. || !prefix(pathopt, "func")
  12232. ) { /* ignore unimplemented options */
  12233. continue;
  12234. }
  12235. }
  12236. /* if rehash, don't redo absolute path names */
  12237. if (fullname[0] == '/' && idx <= prev) {
  12238. if (idx < prev)
  12239. continue;
  12240. TRACE(("searchexec \"%s\": no change\n", name));
  12241. goto success;
  12242. }
  12243. while (stat(fullname, &statb) < 0) {
  12244. #ifdef SYSV
  12245. if (errno == EINTR)
  12246. continue;
  12247. #endif
  12248. if (errno != ENOENT && errno != ENOTDIR)
  12249. e = errno;
  12250. goto loop;
  12251. }
  12252. e = EACCES; /* if we fail, this will be the error */
  12253. if (!S_ISREG(statb.st_mode))
  12254. continue;
  12255. if (pathopt) { /* this is a %func directory */
  12256. stalloc(strlen(fullname) + 1);
  12257. /* NB: stalloc will return space pointed by fullname
  12258. * (because we don't have any intervening allocations
  12259. * between stunalloc above and this stalloc) */
  12260. readcmdfile(fullname);
  12261. cmdp = cmdlookup(name, 0);
  12262. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12263. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12264. stunalloc(fullname);
  12265. goto success;
  12266. }
  12267. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12268. if (!updatetbl) {
  12269. entry->cmdtype = CMDNORMAL;
  12270. entry->u.index = idx;
  12271. return;
  12272. }
  12273. INT_OFF;
  12274. cmdp = cmdlookup(name, 1);
  12275. cmdp->cmdtype = CMDNORMAL;
  12276. cmdp->param.index = idx;
  12277. INT_ON;
  12278. goto success;
  12279. }
  12280. /* We failed. If there was an entry for this command, delete it */
  12281. if (cmdp && updatetbl)
  12282. delete_cmd_entry();
  12283. if (act & DO_ERR) {
  12284. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12285. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12286. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12287. char *argv[3];
  12288. argv[0] = (char*) "command_not_found_handle";
  12289. argv[1] = name;
  12290. argv[2] = NULL;
  12291. evalfun(hookp->param.func, 2, argv, 0);
  12292. entry->cmdtype = CMDUNKNOWN;
  12293. return;
  12294. }
  12295. #endif
  12296. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12297. }
  12298. entry->cmdtype = CMDUNKNOWN;
  12299. return;
  12300. builtin_success:
  12301. if (!updatetbl) {
  12302. entry->cmdtype = CMDBUILTIN;
  12303. entry->u.cmd = bcmd;
  12304. return;
  12305. }
  12306. INT_OFF;
  12307. cmdp = cmdlookup(name, 1);
  12308. cmdp->cmdtype = CMDBUILTIN;
  12309. cmdp->param.cmd = bcmd;
  12310. INT_ON;
  12311. success:
  12312. cmdp->rehash = 0;
  12313. entry->cmdtype = cmdp->cmdtype;
  12314. entry->u = cmdp->param;
  12315. }
  12316. /*
  12317. * The trap builtin.
  12318. */
  12319. static int FAST_FUNC
  12320. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12321. {
  12322. char *action;
  12323. char **ap;
  12324. int signo, exitcode;
  12325. nextopt(nullstr);
  12326. ap = argptr;
  12327. if (!*ap) {
  12328. for (signo = 0; signo < NSIG; signo++) {
  12329. char *tr = trap_ptr[signo];
  12330. if (tr) {
  12331. /* note: bash adds "SIG", but only if invoked
  12332. * as "bash". If called as "sh", or if set -o posix,
  12333. * then it prints short signal names.
  12334. * We are printing short names: */
  12335. out1fmt("trap -- %s %s\n",
  12336. single_quote(tr),
  12337. get_signame(signo));
  12338. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12339. * In this case, we will exit very soon, no need to free(). */
  12340. /* if (trap_ptr != trap && tp[0]) */
  12341. /* free(tr); */
  12342. }
  12343. }
  12344. /*
  12345. if (trap_ptr != trap) {
  12346. free(trap_ptr);
  12347. trap_ptr = trap;
  12348. }
  12349. */
  12350. return 0;
  12351. }
  12352. /* Why the second check?
  12353. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12354. * In this case, NUM is signal no, not an action.
  12355. */
  12356. action = NULL;
  12357. if (ap[1] && !is_number(ap[0]))
  12358. action = *ap++;
  12359. exitcode = 0;
  12360. while (*ap) {
  12361. signo = get_signum(*ap);
  12362. if (signo < 0) {
  12363. /* Mimic bash message exactly */
  12364. ash_msg("%s: invalid signal specification", *ap);
  12365. exitcode = 1;
  12366. goto next;
  12367. }
  12368. INT_OFF;
  12369. if (action) {
  12370. if (LONE_DASH(action))
  12371. action = NULL;
  12372. else {
  12373. if (action[0]) /* not NULL and not "" and not "-" */
  12374. may_have_traps = 1;
  12375. action = ckstrdup(action);
  12376. }
  12377. }
  12378. free(trap[signo]);
  12379. trap[signo] = action;
  12380. if (signo != 0)
  12381. setsignal(signo);
  12382. INT_ON;
  12383. next:
  12384. ap++;
  12385. }
  12386. return exitcode;
  12387. }
  12388. /* ============ Builtins */
  12389. #if ENABLE_ASH_HELP
  12390. static int FAST_FUNC
  12391. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12392. {
  12393. unsigned col;
  12394. unsigned i;
  12395. out1fmt(
  12396. "Built-in commands:\n"
  12397. "------------------\n");
  12398. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12399. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12400. builtintab[i].name + 1);
  12401. if (col > 60) {
  12402. out1fmt("\n");
  12403. col = 0;
  12404. }
  12405. }
  12406. # if ENABLE_FEATURE_SH_STANDALONE
  12407. {
  12408. const char *a = applet_names;
  12409. while (*a) {
  12410. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12411. if (col > 60) {
  12412. out1fmt("\n");
  12413. col = 0;
  12414. }
  12415. while (*a++ != '\0')
  12416. continue;
  12417. }
  12418. }
  12419. # endif
  12420. newline_and_flush(stdout);
  12421. return EXIT_SUCCESS;
  12422. }
  12423. #endif
  12424. #if MAX_HISTORY
  12425. static int FAST_FUNC
  12426. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12427. {
  12428. show_history(line_input_state);
  12429. return EXIT_SUCCESS;
  12430. }
  12431. #endif
  12432. /*
  12433. * The export and readonly commands.
  12434. */
  12435. static int FAST_FUNC
  12436. exportcmd(int argc UNUSED_PARAM, char **argv)
  12437. {
  12438. struct var *vp;
  12439. char *name;
  12440. const char *p;
  12441. char **aptr;
  12442. char opt;
  12443. int flag;
  12444. int flag_off;
  12445. /* "readonly" in bash accepts, but ignores -n.
  12446. * We do the same: it saves a conditional in nextopt's param.
  12447. */
  12448. flag_off = 0;
  12449. while ((opt = nextopt("np")) != '\0') {
  12450. if (opt == 'n')
  12451. flag_off = VEXPORT;
  12452. }
  12453. flag = VEXPORT;
  12454. if (argv[0][0] == 'r') {
  12455. flag = VREADONLY;
  12456. flag_off = 0; /* readonly ignores -n */
  12457. }
  12458. flag_off = ~flag_off;
  12459. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12460. {
  12461. aptr = argptr;
  12462. name = *aptr;
  12463. if (name) {
  12464. do {
  12465. p = strchr(name, '=');
  12466. if (p != NULL) {
  12467. p++;
  12468. } else {
  12469. vp = *findvar(hashvar(name), name);
  12470. if (vp) {
  12471. vp->flags = ((vp->flags | flag) & flag_off);
  12472. continue;
  12473. }
  12474. }
  12475. setvar(name, p, (flag & flag_off));
  12476. } while ((name = *++aptr) != NULL);
  12477. return 0;
  12478. }
  12479. }
  12480. /* No arguments. Show the list of exported or readonly vars.
  12481. * -n is ignored.
  12482. */
  12483. showvars(argv[0], flag, 0);
  12484. return 0;
  12485. }
  12486. /*
  12487. * Delete a function if it exists.
  12488. */
  12489. static void
  12490. unsetfunc(const char *name)
  12491. {
  12492. struct tblentry *cmdp;
  12493. cmdp = cmdlookup(name, 0);
  12494. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12495. delete_cmd_entry();
  12496. }
  12497. /*
  12498. * The unset builtin command. We unset the function before we unset the
  12499. * variable to allow a function to be unset when there is a readonly variable
  12500. * with the same name.
  12501. */
  12502. static int FAST_FUNC
  12503. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12504. {
  12505. char **ap;
  12506. int i;
  12507. int flag = 0;
  12508. while ((i = nextopt("vf")) != 0) {
  12509. flag = i;
  12510. }
  12511. for (ap = argptr; *ap; ap++) {
  12512. if (flag != 'f') {
  12513. unsetvar(*ap);
  12514. continue;
  12515. }
  12516. if (flag != 'v')
  12517. unsetfunc(*ap);
  12518. }
  12519. return 0;
  12520. }
  12521. static const unsigned char timescmd_str[] ALIGN1 = {
  12522. ' ', offsetof(struct tms, tms_utime),
  12523. '\n', offsetof(struct tms, tms_stime),
  12524. ' ', offsetof(struct tms, tms_cutime),
  12525. '\n', offsetof(struct tms, tms_cstime),
  12526. 0
  12527. };
  12528. static int FAST_FUNC
  12529. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12530. {
  12531. unsigned clk_tck;
  12532. const unsigned char *p;
  12533. struct tms buf;
  12534. clk_tck = bb_clk_tck();
  12535. times(&buf);
  12536. p = timescmd_str;
  12537. do {
  12538. unsigned sec, frac;
  12539. unsigned long t;
  12540. t = *(clock_t *)(((char *) &buf) + p[1]);
  12541. sec = t / clk_tck;
  12542. frac = t % clk_tck;
  12543. out1fmt("%um%u.%03us%c",
  12544. sec / 60, sec % 60,
  12545. (frac * 1000) / clk_tck,
  12546. p[0]);
  12547. p += 2;
  12548. } while (*p);
  12549. return 0;
  12550. }
  12551. #if ENABLE_FEATURE_SH_MATH
  12552. /*
  12553. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12554. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12555. *
  12556. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12557. */
  12558. static int FAST_FUNC
  12559. letcmd(int argc UNUSED_PARAM, char **argv)
  12560. {
  12561. arith_t i;
  12562. argv++;
  12563. if (!*argv)
  12564. ash_msg_and_raise_error("expression expected");
  12565. do {
  12566. i = ash_arith(*argv);
  12567. } while (*++argv);
  12568. return !i;
  12569. }
  12570. #endif
  12571. /*
  12572. * The read builtin. Options:
  12573. * -r Do not interpret '\' specially
  12574. * -s Turn off echo (tty only)
  12575. * -n NCHARS Read NCHARS max
  12576. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12577. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12578. * -u FD Read from given FD instead of fd 0
  12579. * -d DELIM End on DELIM char, not newline
  12580. * This uses unbuffered input, which may be avoidable in some cases.
  12581. * TODO: bash also has:
  12582. * -a ARRAY Read into array[0],[1],etc
  12583. * -e Use line editing (tty only)
  12584. */
  12585. static int FAST_FUNC
  12586. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12587. {
  12588. struct builtin_read_params params;
  12589. const char *r;
  12590. int i;
  12591. memset(&params, 0, sizeof(params));
  12592. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12593. switch (i) {
  12594. case 'p':
  12595. params.opt_p = optionarg;
  12596. break;
  12597. case 'n':
  12598. params.opt_n = optionarg;
  12599. break;
  12600. case 's':
  12601. params.read_flags |= BUILTIN_READ_SILENT;
  12602. break;
  12603. case 't':
  12604. params.opt_t = optionarg;
  12605. break;
  12606. case 'r':
  12607. params.read_flags |= BUILTIN_READ_RAW;
  12608. break;
  12609. case 'u':
  12610. params.opt_u = optionarg;
  12611. break;
  12612. #if BASH_READ_D
  12613. case 'd':
  12614. params.opt_d = optionarg;
  12615. break;
  12616. #endif
  12617. default:
  12618. break;
  12619. }
  12620. }
  12621. params.argv = argptr;
  12622. params.setvar = setvar0;
  12623. params.ifs = bltinlookup("IFS"); /* can be NULL */
  12624. /* "read -s" needs to save/restore termios, can't allow ^C
  12625. * to jump out of it.
  12626. */
  12627. again:
  12628. INT_OFF;
  12629. r = shell_builtin_read(&params);
  12630. INT_ON;
  12631. if ((uintptr_t)r == 1 && errno == EINTR) {
  12632. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12633. * Correct behavior is to not exit "read"
  12634. */
  12635. if (pending_sig == 0)
  12636. goto again;
  12637. }
  12638. if ((uintptr_t)r > 1)
  12639. ash_msg_and_raise_error(r);
  12640. return (uintptr_t)r;
  12641. }
  12642. static int FAST_FUNC
  12643. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12644. {
  12645. static const char permuser[3] ALIGN1 = "ogu";
  12646. mode_t mask;
  12647. int symbolic_mode = 0;
  12648. while (nextopt("S") != '\0') {
  12649. symbolic_mode = 1;
  12650. }
  12651. INT_OFF;
  12652. mask = umask(0);
  12653. umask(mask);
  12654. INT_ON;
  12655. if (*argptr == NULL) {
  12656. if (symbolic_mode) {
  12657. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12658. char *p = buf;
  12659. int i;
  12660. i = 2;
  12661. for (;;) {
  12662. *p++ = ',';
  12663. *p++ = permuser[i];
  12664. *p++ = '=';
  12665. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12666. if (!(mask & 0400)) *p++ = 'r';
  12667. if (!(mask & 0200)) *p++ = 'w';
  12668. if (!(mask & 0100)) *p++ = 'x';
  12669. mask <<= 3;
  12670. if (--i < 0)
  12671. break;
  12672. }
  12673. *p = '\0';
  12674. puts(buf + 1);
  12675. } else {
  12676. out1fmt("%04o\n", mask);
  12677. }
  12678. } else {
  12679. char *modestr = *argptr;
  12680. /* numeric umasks are taken as-is */
  12681. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12682. if (!isdigit(modestr[0]))
  12683. mask ^= 0777;
  12684. mask = bb_parse_mode(modestr, mask);
  12685. if ((unsigned)mask > 0777) {
  12686. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12687. }
  12688. if (!isdigit(modestr[0]))
  12689. mask ^= 0777;
  12690. umask(mask);
  12691. }
  12692. return 0;
  12693. }
  12694. static int FAST_FUNC
  12695. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12696. {
  12697. return shell_builtin_ulimit(argv);
  12698. }
  12699. /* ============ main() and helpers */
  12700. /*
  12701. * Called to exit the shell.
  12702. */
  12703. static void
  12704. exitshell(void)
  12705. {
  12706. struct jmploc loc;
  12707. char *p;
  12708. int status;
  12709. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12710. save_history(line_input_state);
  12711. #endif
  12712. status = exitstatus;
  12713. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  12714. if (setjmp(loc.loc)) {
  12715. if (exception_type == EXEXIT)
  12716. status = exitstatus;
  12717. goto out;
  12718. }
  12719. exception_handler = &loc;
  12720. p = trap[0];
  12721. if (p) {
  12722. trap[0] = NULL;
  12723. evalskip = 0;
  12724. evalstring(p, 0);
  12725. /*free(p); - we'll exit soon */
  12726. }
  12727. out:
  12728. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12729. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12730. */
  12731. setjobctl(0);
  12732. flush_stdout_stderr();
  12733. _exit(status);
  12734. /* NOTREACHED */
  12735. }
  12736. /* Don't inline: conserve stack of caller from having our locals too */
  12737. static NOINLINE void
  12738. init(void)
  12739. {
  12740. /* we will never free this */
  12741. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12742. basepf.linno = 1;
  12743. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  12744. setsignal(SIGCHLD);
  12745. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  12746. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  12747. */
  12748. signal(SIGHUP, SIG_DFL);
  12749. {
  12750. char **envp;
  12751. const char *p;
  12752. initvar();
  12753. for (envp = environ; envp && *envp; envp++) {
  12754. /* Used to have
  12755. * p = endofname(*envp);
  12756. * if (p != *envp && *p == '=') {
  12757. * here to weed out badly-named variables, but this breaks
  12758. * scenarios where people do want them passed to children:
  12759. * import os
  12760. * os.environ["test-test"]="test"
  12761. * if os.fork() == 0:
  12762. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  12763. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  12764. */
  12765. if (strchr(*envp, '=')) {
  12766. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12767. }
  12768. }
  12769. setvareq((char*)defifsvar, VTEXTFIXED);
  12770. setvareq((char*)defoptindvar, VTEXTFIXED);
  12771. setvar0("PPID", utoa(getppid()));
  12772. #if BASH_SHLVL_VAR
  12773. p = lookupvar("SHLVL");
  12774. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12775. #endif
  12776. #if BASH_HOSTNAME_VAR
  12777. if (!lookupvar("HOSTNAME")) {
  12778. struct utsname uts;
  12779. uname(&uts);
  12780. setvar0("HOSTNAME", uts.nodename);
  12781. }
  12782. #endif
  12783. p = lookupvar("PWD");
  12784. if (p) {
  12785. struct stat st1, st2;
  12786. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12787. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12788. ) {
  12789. p = NULL;
  12790. }
  12791. }
  12792. setpwd(p, 0);
  12793. }
  12794. }
  12795. //usage:#define ash_trivial_usage
  12796. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  12797. //usage:#define ash_full_usage "\n\n"
  12798. //usage: "Unix shell interpreter"
  12799. /*
  12800. * Process the shell command line arguments.
  12801. */
  12802. static int
  12803. procargs(char **argv)
  12804. {
  12805. int i;
  12806. const char *xminusc;
  12807. char **xargv;
  12808. int login_sh;
  12809. xargv = argv;
  12810. login_sh = xargv[0] && xargv[0][0] == '-';
  12811. arg0 = xargv[0];
  12812. /* if (xargv[0]) - mmm, this is always true! */
  12813. xargv++;
  12814. for (i = 0; i < NOPTS; i++)
  12815. optlist[i] = 2;
  12816. argptr = xargv;
  12817. if (options(/*cmdline:*/ 1, &login_sh)) {
  12818. /* it already printed err message */
  12819. raise_exception(EXERROR);
  12820. }
  12821. xargv = argptr;
  12822. xminusc = minusc;
  12823. if (*xargv == NULL) {
  12824. if (xminusc)
  12825. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  12826. sflag = 1;
  12827. }
  12828. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  12829. iflag = 1;
  12830. if (mflag == 2)
  12831. mflag = iflag;
  12832. for (i = 0; i < NOPTS; i++)
  12833. if (optlist[i] == 2)
  12834. optlist[i] = 0;
  12835. #if DEBUG == 2
  12836. debug = 1;
  12837. #endif
  12838. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  12839. if (xminusc) {
  12840. minusc = *xargv++;
  12841. if (*xargv)
  12842. goto setarg0;
  12843. } else if (!sflag) {
  12844. setinputfile(*xargv, 0);
  12845. setarg0:
  12846. arg0 = *xargv++;
  12847. commandname = arg0;
  12848. }
  12849. shellparam.p = xargv;
  12850. #if ENABLE_ASH_GETOPTS
  12851. shellparam.optind = 1;
  12852. shellparam.optoff = -1;
  12853. #endif
  12854. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  12855. while (*xargv) {
  12856. shellparam.nparam++;
  12857. xargv++;
  12858. }
  12859. optschanged();
  12860. return login_sh;
  12861. }
  12862. /*
  12863. * Read /etc/profile, ~/.profile, $ENV.
  12864. */
  12865. static void
  12866. read_profile(const char *name)
  12867. {
  12868. name = expandstr(name, DQSYNTAX);
  12869. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  12870. return;
  12871. cmdloop(0);
  12872. popfile();
  12873. }
  12874. /*
  12875. * This routine is called when an error or an interrupt occurs in an
  12876. * interactive shell and control is returned to the main command loop.
  12877. * (In dash, this function is auto-generated by build machinery).
  12878. */
  12879. static void
  12880. reset(void)
  12881. {
  12882. /* from eval.c: */
  12883. evalskip = 0;
  12884. loopnest = 0;
  12885. /* from expand.c: */
  12886. ifsfree();
  12887. /* from input.c: */
  12888. g_parsefile->left_in_buffer = 0;
  12889. g_parsefile->left_in_line = 0; /* clear input buffer */
  12890. popallfiles();
  12891. /* from redir.c: */
  12892. unwindredir(NULL);
  12893. /* from var.c: */
  12894. unwindlocalvars(NULL);
  12895. }
  12896. #if PROFILE
  12897. static short profile_buf[16384];
  12898. extern int etext();
  12899. #endif
  12900. /*
  12901. * Main routine. We initialize things, parse the arguments, execute
  12902. * profiles if we're a login shell, and then call cmdloop to execute
  12903. * commands. The setjmp call sets up the location to jump to when an
  12904. * exception occurs. When an exception occurs the variable "state"
  12905. * is used to figure out how far we had gotten.
  12906. */
  12907. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12908. int ash_main(int argc UNUSED_PARAM, char **argv)
  12909. {
  12910. volatile smallint state;
  12911. struct jmploc jmploc;
  12912. struct stackmark smark;
  12913. int login_sh;
  12914. /* Initialize global data */
  12915. INIT_G_misc();
  12916. INIT_G_memstack();
  12917. INIT_G_var();
  12918. #if ENABLE_ASH_ALIAS
  12919. INIT_G_alias();
  12920. #endif
  12921. INIT_G_cmdtable();
  12922. #if PROFILE
  12923. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12924. #endif
  12925. #if ENABLE_FEATURE_EDITING
  12926. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12927. #endif
  12928. state = 0;
  12929. if (setjmp(jmploc.loc)) {
  12930. smallint e;
  12931. smallint s;
  12932. reset();
  12933. e = exception_type;
  12934. s = state;
  12935. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  12936. exitshell();
  12937. }
  12938. if (e == EXINT) {
  12939. newline_and_flush(stderr);
  12940. }
  12941. popstackmark(&smark);
  12942. FORCE_INT_ON; /* enable interrupts */
  12943. if (s == 1)
  12944. goto state1;
  12945. if (s == 2)
  12946. goto state2;
  12947. if (s == 3)
  12948. goto state3;
  12949. goto state4;
  12950. }
  12951. exception_handler = &jmploc;
  12952. rootpid = getpid();
  12953. init();
  12954. setstackmark(&smark);
  12955. login_sh = procargs(argv);
  12956. #if DEBUG
  12957. TRACE(("Shell args: "));
  12958. trace_puts_args(argv);
  12959. #endif
  12960. if (login_sh) {
  12961. const char *hp;
  12962. state = 1;
  12963. read_profile("/etc/profile");
  12964. state1:
  12965. state = 2;
  12966. hp = lookupvar("HOME");
  12967. if (hp)
  12968. read_profile("$HOME/.profile");
  12969. }
  12970. state2:
  12971. state = 3;
  12972. if (
  12973. #ifndef linux
  12974. getuid() == geteuid() && getgid() == getegid() &&
  12975. #endif
  12976. iflag
  12977. ) {
  12978. const char *shinit = lookupvar("ENV");
  12979. if (shinit != NULL && *shinit != '\0')
  12980. read_profile(shinit);
  12981. }
  12982. popstackmark(&smark);
  12983. state3:
  12984. state = 4;
  12985. if (minusc) {
  12986. /* evalstring pushes parsefile stack.
  12987. * Ensure we don't falsely claim that 0 (stdin)
  12988. * is one of stacked source fds.
  12989. * Testcase: ash -c 'exec 1>&0' must not complain. */
  12990. // if (!sflag) g_parsefile->pf_fd = -1;
  12991. // ^^ not necessary since now we special-case fd 0
  12992. // in save_fd_on_redirect()
  12993. evalstring(minusc, sflag ? 0 : EV_EXIT);
  12994. }
  12995. if (sflag || minusc == NULL) {
  12996. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  12997. if (iflag) {
  12998. const char *hp = lookupvar("HISTFILE");
  12999. if (!hp) {
  13000. hp = lookupvar("HOME");
  13001. if (hp) {
  13002. INT_OFF;
  13003. hp = concat_path_file(hp, ".ash_history");
  13004. setvar0("HISTFILE", hp);
  13005. free((char*)hp);
  13006. INT_ON;
  13007. hp = lookupvar("HISTFILE");
  13008. }
  13009. }
  13010. if (hp)
  13011. line_input_state->hist_file = hp;
  13012. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13013. hp = lookupvar("HISTFILESIZE");
  13014. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13015. # endif
  13016. }
  13017. #endif
  13018. state4: /* XXX ??? - why isn't this before the "if" statement */
  13019. cmdloop(1);
  13020. }
  13021. #if PROFILE
  13022. monitor(0);
  13023. #endif
  13024. #ifdef GPROF
  13025. {
  13026. extern void _mcleanup(void);
  13027. _mcleanup();
  13028. }
  13029. #endif
  13030. TRACE(("End of main reached\n"));
  13031. exitshell();
  13032. /* NOTREACHED */
  13033. }
  13034. /*-
  13035. * Copyright (c) 1989, 1991, 1993, 1994
  13036. * The Regents of the University of California. All rights reserved.
  13037. *
  13038. * This code is derived from software contributed to Berkeley by
  13039. * Kenneth Almquist.
  13040. *
  13041. * Redistribution and use in source and binary forms, with or without
  13042. * modification, are permitted provided that the following conditions
  13043. * are met:
  13044. * 1. Redistributions of source code must retain the above copyright
  13045. * notice, this list of conditions and the following disclaimer.
  13046. * 2. Redistributions in binary form must reproduce the above copyright
  13047. * notice, this list of conditions and the following disclaimer in the
  13048. * documentation and/or other materials provided with the distribution.
  13049. * 3. Neither the name of the University nor the names of its contributors
  13050. * may be used to endorse or promote products derived from this software
  13051. * without specific prior written permission.
  13052. *
  13053. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13054. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13055. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13056. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13057. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13058. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13059. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13060. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13061. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13062. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13063. * SUCH DAMAGE.
  13064. */