3
0

ash.c 325 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * This code is derived from software contributed to Berkeley by
  6. * Kenneth Almquist.
  7. *
  8. * Original BSD copyright notice is retained at the end of this file.
  9. *
  10. * Copyright (c) 1989, 1991, 1993, 1994
  11. * The Regents of the University of California. All rights reserved.
  12. *
  13. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  14. * was re-ported from NetBSD and debianized.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  17. */
  18. //config:config ASH
  19. //config: bool "ash (78 kb)"
  20. //config: default y
  21. //config: depends on !NOMMU
  22. //config: help
  23. //config: The most complete and most pedantically correct shell included with
  24. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  25. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  26. //config: (written by Kenneth Almquist) from NetBSD.
  27. //config:
  28. //config:# ash options
  29. //config:# note: Don't remove !NOMMU part in the next line; it would break
  30. //config:# menuconfig's indenting.
  31. //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
  32. //config:
  33. //config:config ASH_OPTIMIZE_FOR_SIZE
  34. //config: bool "Optimize for size instead of speed"
  35. //config: default y
  36. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  37. //config:
  38. //config:config ASH_INTERNAL_GLOB
  39. //config: bool "Use internal glob() implementation"
  40. //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
  41. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  42. //config: help
  43. //config: Do not use glob() function from libc, use internal implementation.
  44. //config: Use this if you are getting "glob.h: No such file or directory"
  45. //config: or similar build errors.
  46. //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
  47. //config: which would break ash if you select N here.
  48. //config:
  49. //config:config ASH_BASH_COMPAT
  50. //config: bool "bash-compatible extensions"
  51. //config: default y
  52. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  53. //config:
  54. //config:config ASH_BASH_SOURCE_CURDIR
  55. //config: bool "'source' and '.' builtins search current directory after $PATH"
  56. //config: default n # do not encourage non-standard behavior
  57. //config: depends on ASH_BASH_COMPAT
  58. //config: help
  59. //config: This is not compliant with standards. Avoid if possible.
  60. //config:
  61. //config:config ASH_BASH_NOT_FOUND_HOOK
  62. //config: bool "command_not_found_handle hook support"
  63. //config: default y
  64. //config: depends on ASH_BASH_COMPAT
  65. //config: help
  66. //config: Enable support for the 'command_not_found_handle' hook function,
  67. //config: from GNU bash, which allows for alternative command not found
  68. //config: handling.
  69. //config:
  70. //config:config ASH_JOB_CONTROL
  71. //config: bool "Job control"
  72. //config: default y
  73. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  74. //config:
  75. //config:config ASH_ALIAS
  76. //config: bool "Alias support"
  77. //config: default y
  78. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  79. //config:
  80. //config:config ASH_RANDOM_SUPPORT
  81. //config: bool "Pseudorandom generator and $RANDOM variable"
  82. //config: default y
  83. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  84. //config: help
  85. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  86. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  87. //config: You can reset the generator by using a specified start value.
  88. //config: After "unset RANDOM" the generator will switch off and this
  89. //config: variable will no longer have special treatment.
  90. //config:
  91. //config:config ASH_EXPAND_PRMT
  92. //config: bool "Expand prompt string"
  93. //config: default y
  94. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  95. //config: help
  96. //config: $PS# may contain volatile content, such as backquote commands.
  97. //config: This option recreates the prompt string from the environment
  98. //config: variable each time it is displayed.
  99. //config:
  100. //config:config ASH_IDLE_TIMEOUT
  101. //config: bool "Idle timeout variable $TMOUT"
  102. //config: default y
  103. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  104. //config: help
  105. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  106. //config:
  107. //config:config ASH_MAIL
  108. //config: bool "Check for new mail in interactive shell"
  109. //config: default y
  110. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  111. //config: help
  112. //config: Enable "check for new mail" function:
  113. //config: if set, $MAIL file and $MAILPATH list of files
  114. //config: are checked for mtime changes, and "you have mail"
  115. //config: message is printed if change is detected.
  116. //config:
  117. //config:config ASH_ECHO
  118. //config: bool "echo builtin"
  119. //config: default y
  120. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  121. //config:
  122. //config:config ASH_PRINTF
  123. //config: bool "printf builtin"
  124. //config: default y
  125. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  126. //config:
  127. //config:config ASH_TEST
  128. //config: bool "test builtin"
  129. //config: default y
  130. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  131. //config:
  132. //config:config ASH_HELP
  133. //config: bool "help builtin"
  134. //config: default y
  135. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  136. //config:
  137. //config:config ASH_GETOPTS
  138. //config: bool "getopts builtin"
  139. //config: default y
  140. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  141. //config:
  142. //config:config ASH_CMDCMD
  143. //config: bool "command builtin"
  144. //config: default y
  145. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  146. //config: help
  147. //config: Enable support for the 'command' builtin, which allows
  148. //config: you to run the specified command or builtin,
  149. //config: even when there is a function with the same name.
  150. //config:
  151. //config:endif # ash options
  152. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  153. // APPLET_ODDNAME:name main location suid_type help
  154. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  155. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  156. //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
  157. //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  158. //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  159. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  160. /*
  161. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  162. * DEBUG=2 to compile in and turn on debugging.
  163. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  164. * debugging info is written to ./trace, quit signal generates core dump.
  165. */
  166. #define DEBUG 0
  167. /* Tweak debug output verbosity here */
  168. #define DEBUG_TIME 0
  169. #define DEBUG_PID 1
  170. #define DEBUG_SIG 1
  171. #define DEBUG_INTONOFF 0
  172. #define PROFILE 0
  173. #define JOBS ENABLE_ASH_JOB_CONTROL
  174. #include <fnmatch.h>
  175. #include <sys/times.h>
  176. #include <sys/utsname.h> /* for setting $HOSTNAME */
  177. #include "busybox.h" /* for applet_names */
  178. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
  179. # include "embedded_scripts.h"
  180. #else
  181. # define NUM_SCRIPTS 0
  182. #endif
  183. /* So far, all bash compat is controlled by one config option */
  184. /* Separate defines document which part of code implements what */
  185. /* function keyword */
  186. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  187. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  188. /* &>file */
  189. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  190. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  191. /* $'...' */
  192. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  193. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  194. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  195. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  196. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  197. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  198. /* BASH_TEST2: [[ EXPR ]]
  199. * Status of [[ support:
  200. * We replace && and || with -a and -o
  201. * TODO:
  202. * singleword+noglob expansion:
  203. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  204. * [[ /bin/n* ]]; echo 0:$?
  205. * -a/-o are not AND/OR ops! (they are just strings)
  206. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  207. * = is glob match operator, not equality operator: STR = GLOB
  208. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  209. * == same as =
  210. * add =~ regex match operator: STR =~ REGEX
  211. */
  212. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  213. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  214. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  215. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  216. #define BASH_EPOCH_VARS ENABLE_ASH_BASH_COMPAT
  217. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  218. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  219. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  220. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  221. #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
  222. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  223. /* Bionic at least up to version 24 has no glob() */
  224. # undef ENABLE_ASH_INTERNAL_GLOB
  225. # define ENABLE_ASH_INTERNAL_GLOB 1
  226. #endif
  227. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  228. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  229. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  230. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  231. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  232. # error fails to match dirname, subsequently not expanding <pattern> in it.
  233. // Testcase:
  234. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  235. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  236. #endif
  237. #if !ENABLE_ASH_INTERNAL_GLOB
  238. # include <glob.h>
  239. #endif
  240. #include "unicode.h"
  241. #include "shell_common.h"
  242. #if ENABLE_FEATURE_SH_MATH
  243. # include "math.h"
  244. #else
  245. typedef long arith_t;
  246. # define ARITH_FMT "%ld"
  247. #endif
  248. #if ENABLE_ASH_RANDOM_SUPPORT
  249. # include "random.h"
  250. #else
  251. # define CLEAR_RANDOM_T(rnd) ((void)0)
  252. #endif
  253. #include "NUM_APPLETS.h"
  254. #if NUM_APPLETS == 1
  255. /* STANDALONE does not make sense, and won't compile */
  256. # undef CONFIG_FEATURE_SH_STANDALONE
  257. # undef ENABLE_FEATURE_SH_STANDALONE
  258. # undef IF_FEATURE_SH_STANDALONE
  259. # undef IF_NOT_FEATURE_SH_STANDALONE
  260. # define ENABLE_FEATURE_SH_STANDALONE 0
  261. # define IF_FEATURE_SH_STANDALONE(...)
  262. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  263. #endif
  264. #ifndef F_DUPFD_CLOEXEC
  265. # define F_DUPFD_CLOEXEC F_DUPFD
  266. #endif
  267. #ifndef O_CLOEXEC
  268. # define O_CLOEXEC 0
  269. #endif
  270. #ifndef PIPE_BUF
  271. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  272. #endif
  273. #if !BB_MMU
  274. # error "Do not even bother, ash will not run on NOMMU machine"
  275. #endif
  276. /* We use a trick to have more optimized code (fewer pointer reloads):
  277. * ash.c: extern struct globals *const ash_ptr_to_globals;
  278. * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
  279. * This way, compiler in ash.c knows the pointer can not change.
  280. *
  281. * However, this may break on weird arches or toolchains. In this case,
  282. * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
  283. * this optimization.
  284. */
  285. #ifndef BB_GLOBAL_CONST
  286. # define BB_GLOBAL_CONST const
  287. #endif
  288. /* ============ Hash table sizes. Configurable. */
  289. #define VTABSIZE 39
  290. #define ATABSIZE 39
  291. #define CMDTABLESIZE 31 /* should be prime */
  292. /* ============ Shell options */
  293. static const char *const optletters_optnames[] = {
  294. "e" "errexit",
  295. "f" "noglob",
  296. "I" "ignoreeof",
  297. /* The below allowed this invocation:
  298. * ash -c 'set -i; echo $-; sleep 5; echo $-'
  299. * to be ^C-ed and get to interactive ash prompt.
  300. * bash does not support such "set -i".
  301. * In our code, this is denoted by empty long name:
  302. */
  303. "i" "",
  304. "m" "monitor",
  305. "n" "noexec",
  306. /* Ditto: bash has no "set -s" */
  307. "s" "",
  308. "c" "",
  309. "x" "xtrace",
  310. "v" "verbose",
  311. "C" "noclobber",
  312. "a" "allexport",
  313. "b" "notify",
  314. "u" "nounset",
  315. "\0" "vi"
  316. #if BASH_PIPEFAIL
  317. ,"\0" "pipefail"
  318. #endif
  319. #if DEBUG
  320. ,"\0" "nolog"
  321. ,"\0" "debug"
  322. #endif
  323. };
  324. //bash 4.4.23 also has these opts (with these defaults):
  325. //braceexpand on
  326. //emacs on
  327. //errtrace off
  328. //functrace off
  329. //hashall on
  330. //histexpand off
  331. //history on
  332. //interactive-comments on
  333. //keyword off
  334. //onecmd off
  335. //physical off
  336. //posix off
  337. //privileged off
  338. #define optletters(n) optletters_optnames[n][0]
  339. #define optnames(n) (optletters_optnames[n] + 1)
  340. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  341. /* ============ Misc data */
  342. #define msg_illnum "Illegal number: %s"
  343. /*
  344. * We enclose jmp_buf in a structure so that we can declare pointers to
  345. * jump locations. The global variable handler contains the location to
  346. * jump to when an exception occurs, and the global variable exception_type
  347. * contains a code identifying the exception. To implement nested
  348. * exception handlers, the user should save the value of handler on entry
  349. * to an inner scope, set handler to point to a jmploc structure for the
  350. * inner scope, and restore handler on exit from the scope.
  351. */
  352. struct jmploc {
  353. jmp_buf loc;
  354. };
  355. struct globals_misc {
  356. uint8_t exitstatus; /* exit status of last command */
  357. uint8_t back_exitstatus;/* exit status of backquoted command */
  358. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  359. int rootpid; /* pid of main shell */
  360. /* shell level: 0 for the main shell, 1 for its children, and so on */
  361. int shlvl;
  362. #define rootshell (!shlvl)
  363. int errlinno;
  364. char *minusc; /* argument to -c option */
  365. char *curdir; // = nullstr; /* current working directory */
  366. char *physdir; // = nullstr; /* physical working directory */
  367. char *arg0; /* value of $0 */
  368. struct jmploc *exception_handler;
  369. volatile int suppress_int; /* counter */
  370. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  371. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  372. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  373. smallint exception_type; /* kind of exception (0..5) */
  374. /* exceptions */
  375. #define EXINT 0 /* SIGINT received */
  376. #define EXERROR 1 /* a generic error */
  377. #define EXEXIT 4 /* exit the shell */
  378. char nullstr[1]; /* zero length string */
  379. char optlist[NOPTS];
  380. #define eflag optlist[0]
  381. #define fflag optlist[1]
  382. #define Iflag optlist[2]
  383. #define iflag optlist[3]
  384. #define mflag optlist[4]
  385. #define nflag optlist[5]
  386. #define sflag optlist[6]
  387. #define cflag optlist[7]
  388. #define xflag optlist[8]
  389. #define vflag optlist[9]
  390. #define Cflag optlist[10]
  391. #define aflag optlist[11]
  392. #define bflag optlist[12]
  393. #define uflag optlist[13]
  394. #define viflag optlist[14]
  395. #if BASH_PIPEFAIL
  396. # define pipefail optlist[15]
  397. #else
  398. # define pipefail 0
  399. #endif
  400. #if DEBUG
  401. # define nolog optlist[15 + BASH_PIPEFAIL]
  402. # define debug optlist[16 + BASH_PIPEFAIL]
  403. #endif
  404. /* trap handler commands */
  405. /*
  406. * Sigmode records the current value of the signal handlers for the various
  407. * modes. A value of zero means that the current handler is not known.
  408. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  409. */
  410. char sigmode[NSIG - 1];
  411. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  412. #define S_CATCH 2 /* signal is caught */
  413. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  414. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  415. /* indicates specified signal received */
  416. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  417. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  418. char *trap[NSIG];
  419. char **trap_ptr; /* used only by "trap hack" */
  420. /* Rarely referenced stuff */
  421. #if ENABLE_ASH_RANDOM_SUPPORT
  422. random_t random_gen;
  423. #endif
  424. pid_t backgndpid; /* pid of last background process */
  425. };
  426. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  427. #define G_misc (*ash_ptr_to_globals_misc)
  428. #define exitstatus (G_misc.exitstatus )
  429. #define back_exitstatus (G_misc.back_exitstatus )
  430. #define job_warning (G_misc.job_warning)
  431. #define rootpid (G_misc.rootpid )
  432. #define shlvl (G_misc.shlvl )
  433. #define errlinno (G_misc.errlinno )
  434. #define minusc (G_misc.minusc )
  435. #define curdir (G_misc.curdir )
  436. #define physdir (G_misc.physdir )
  437. #define arg0 (G_misc.arg0 )
  438. #define exception_handler (G_misc.exception_handler)
  439. #define exception_type (G_misc.exception_type )
  440. #define suppress_int (G_misc.suppress_int )
  441. #define pending_int (G_misc.pending_int )
  442. #define got_sigchld (G_misc.got_sigchld )
  443. #define pending_sig (G_misc.pending_sig )
  444. #define nullstr (G_misc.nullstr )
  445. #define optlist (G_misc.optlist )
  446. #define sigmode (G_misc.sigmode )
  447. #define gotsig (G_misc.gotsig )
  448. #define may_have_traps (G_misc.may_have_traps )
  449. #define trap (G_misc.trap )
  450. #define trap_ptr (G_misc.trap_ptr )
  451. #define random_gen (G_misc.random_gen )
  452. #define backgndpid (G_misc.backgndpid )
  453. #define INIT_G_misc() do { \
  454. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  455. barrier(); \
  456. curdir = nullstr; \
  457. physdir = nullstr; \
  458. trap_ptr = trap; \
  459. } while (0)
  460. /* ============ DEBUG */
  461. #if DEBUG
  462. static void trace_printf(const char *fmt, ...);
  463. static void trace_vprintf(const char *fmt, va_list va);
  464. # define TRACE(param) trace_printf param
  465. # define TRACEV(param) trace_vprintf param
  466. # define close(fd) do { \
  467. int dfd = (fd); \
  468. if (close(dfd) < 0) \
  469. bb_error_msg("bug on %d: closing %d(0x%x)", \
  470. __LINE__, dfd, dfd); \
  471. } while (0)
  472. #else
  473. # define TRACE(param)
  474. # define TRACEV(param)
  475. #endif
  476. /* ============ Utility functions */
  477. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  478. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  479. static int
  480. isdigit_str9(const char *str)
  481. {
  482. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  483. while (--maxlen && isdigit(*str))
  484. str++;
  485. return (*str == '\0');
  486. }
  487. static const char *
  488. var_end(const char *var)
  489. {
  490. while (*var)
  491. if (*var++ == '=')
  492. break;
  493. return var;
  494. }
  495. /* ============ Interrupts / exceptions */
  496. static void exitshell(void) NORETURN;
  497. /*
  498. * These macros allow the user to suspend the handling of interrupt signals
  499. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  500. * much more efficient and portable. (But hacking the kernel is so much
  501. * more fun than worrying about efficiency and portability. :-))
  502. */
  503. #if DEBUG_INTONOFF
  504. # define INT_OFF do { \
  505. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  506. suppress_int++; \
  507. barrier(); \
  508. } while (0)
  509. #else
  510. # define INT_OFF do { \
  511. suppress_int++; \
  512. barrier(); \
  513. } while (0)
  514. #endif
  515. /*
  516. * Called to raise an exception. Since C doesn't include exceptions, we
  517. * just do a longjmp to the exception handler. The type of exception is
  518. * stored in the global variable "exception_type".
  519. */
  520. static void raise_exception(int) NORETURN;
  521. static void
  522. raise_exception(int e)
  523. {
  524. #if DEBUG
  525. if (exception_handler == NULL)
  526. abort();
  527. #endif
  528. INT_OFF;
  529. exception_type = e;
  530. longjmp(exception_handler->loc, 1);
  531. }
  532. #if DEBUG
  533. #define raise_exception(e) do { \
  534. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  535. raise_exception(e); \
  536. } while (0)
  537. #endif
  538. /*
  539. * Called when a SIGINT is received. (If the user specifies
  540. * that SIGINT is to be trapped or ignored using the trap builtin, then
  541. * this routine is not called.) Suppressint is nonzero when interrupts
  542. * are held using the INT_OFF macro. (The test for iflag is just
  543. * defensive programming.)
  544. */
  545. static void raise_interrupt(void) NORETURN;
  546. static void
  547. raise_interrupt(void)
  548. {
  549. pending_int = 0;
  550. /* Signal is not automatically unmasked after it is raised,
  551. * do it ourself - unmask all signals */
  552. sigprocmask_allsigs(SIG_UNBLOCK);
  553. /* pending_sig = 0; - now done in signal_handler() */
  554. if (!(rootshell && iflag)) {
  555. /* Kill ourself with SIGINT */
  556. signal(SIGINT, SIG_DFL);
  557. raise(SIGINT);
  558. }
  559. /* bash: ^C even on empty command line sets $? */
  560. exitstatus = SIGINT + 128;
  561. raise_exception(EXINT);
  562. /* NOTREACHED */
  563. }
  564. #if DEBUG
  565. #define raise_interrupt() do { \
  566. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  567. raise_interrupt(); \
  568. } while (0)
  569. #endif
  570. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  571. int_on(void)
  572. {
  573. barrier();
  574. if (--suppress_int == 0 && pending_int) {
  575. raise_interrupt();
  576. }
  577. }
  578. #if DEBUG_INTONOFF
  579. # define INT_ON do { \
  580. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  581. int_on(); \
  582. } while (0)
  583. #else
  584. # define INT_ON int_on()
  585. #endif
  586. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  587. force_int_on(void)
  588. {
  589. barrier();
  590. suppress_int = 0;
  591. if (pending_int)
  592. raise_interrupt();
  593. }
  594. #define FORCE_INT_ON force_int_on()
  595. #define SAVE_INT(v) ((v) = suppress_int)
  596. #define RESTORE_INT(v) do { \
  597. barrier(); \
  598. suppress_int = (v); \
  599. if (suppress_int == 0 && pending_int) \
  600. raise_interrupt(); \
  601. } while (0)
  602. /* ============ Stdout/stderr output */
  603. static void
  604. outstr(const char *p, FILE *file)
  605. {
  606. INT_OFF;
  607. fputs(p, file);
  608. INT_ON;
  609. }
  610. static void
  611. flush_stdout_stderr(void)
  612. {
  613. INT_OFF;
  614. fflush_all();
  615. INT_ON;
  616. }
  617. /* Was called outcslow(c,FILE*), but c was always '\n' */
  618. static void
  619. newline_and_flush(FILE *dest)
  620. {
  621. INT_OFF;
  622. putc('\n', dest);
  623. fflush(dest);
  624. INT_ON;
  625. }
  626. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  627. static int
  628. out1fmt(const char *fmt, ...)
  629. {
  630. va_list ap;
  631. int r;
  632. INT_OFF;
  633. va_start(ap, fmt);
  634. r = vprintf(fmt, ap);
  635. va_end(ap);
  636. INT_ON;
  637. return r;
  638. }
  639. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  640. static int
  641. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  642. {
  643. va_list ap;
  644. int ret;
  645. INT_OFF;
  646. va_start(ap, fmt);
  647. ret = vsnprintf(outbuf, length, fmt, ap);
  648. va_end(ap);
  649. INT_ON;
  650. return ret;
  651. }
  652. static void
  653. out1str(const char *p)
  654. {
  655. outstr(p, stdout);
  656. }
  657. static void
  658. out2str(const char *p)
  659. {
  660. outstr(p, stderr);
  661. flush_stdout_stderr();
  662. }
  663. /* ============ Parser structures */
  664. /* control characters in argument strings */
  665. #define CTL_FIRST CTLESC
  666. #define CTLESC ((unsigned char)'\201') /* escape next character */
  667. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  668. #define CTLENDVAR ((unsigned char)'\203')
  669. #define CTLBACKQ ((unsigned char)'\204')
  670. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  671. #define CTLENDARI ((unsigned char)'\207')
  672. #define CTLQUOTEMARK ((unsigned char)'\210')
  673. #define CTL_LAST CTLQUOTEMARK
  674. /* variable substitution byte (follows CTLVAR) */
  675. #define VSTYPE 0x0f /* type of variable substitution */
  676. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  677. /* values of VSTYPE field */
  678. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  679. #define VSMINUS 0x2 /* ${var-text} */
  680. #define VSPLUS 0x3 /* ${var+text} */
  681. #define VSQUESTION 0x4 /* ${var?message} */
  682. #define VSASSIGN 0x5 /* ${var=text} */
  683. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  684. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  685. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  686. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  687. #define VSLENGTH 0xa /* ${#var} */
  688. #if BASH_SUBSTR
  689. #define VSSUBSTR 0xc /* ${var:position:length} */
  690. #endif
  691. #if BASH_PATTERN_SUBST
  692. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  693. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  694. #endif
  695. static const char dolatstr[] ALIGN1 = {
  696. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  697. };
  698. #define DOLATSTRLEN 6
  699. #define NCMD 0
  700. #define NPIPE 1
  701. #define NREDIR 2
  702. #define NBACKGND 3
  703. #define NSUBSHELL 4
  704. #define NAND 5
  705. #define NOR 6
  706. #define NSEMI 7
  707. #define NIF 8
  708. #define NWHILE 9
  709. #define NUNTIL 10
  710. #define NFOR 11
  711. #define NCASE 12
  712. #define NCLIST 13
  713. #define NDEFUN 14
  714. #define NARG 15
  715. #define NTO 16
  716. #if BASH_REDIR_OUTPUT
  717. #define NTO2 17
  718. #endif
  719. #define NCLOBBER 18
  720. #define NFROM 19
  721. #define NFROMTO 20
  722. #define NAPPEND 21
  723. #define NTOFD 22
  724. #define NFROMFD 23
  725. #define NHERE 24
  726. #define NXHERE 25
  727. #define NNOT 26
  728. #define N_NUMBER 27
  729. union node;
  730. struct ncmd {
  731. smallint type; /* Nxxxx */
  732. int linno;
  733. union node *assign;
  734. union node *args;
  735. union node *redirect;
  736. };
  737. struct npipe {
  738. smallint type;
  739. smallint pipe_backgnd;
  740. struct nodelist *cmdlist;
  741. };
  742. struct nredir {
  743. smallint type;
  744. int linno;
  745. union node *n;
  746. union node *redirect;
  747. };
  748. struct nbinary {
  749. smallint type;
  750. union node *ch1;
  751. union node *ch2;
  752. };
  753. struct nif {
  754. smallint type;
  755. union node *test;
  756. union node *ifpart;
  757. union node *elsepart;
  758. };
  759. struct nfor {
  760. smallint type;
  761. int linno;
  762. union node *args;
  763. union node *body;
  764. char *var;
  765. };
  766. struct ncase {
  767. smallint type;
  768. int linno;
  769. union node *expr;
  770. union node *cases;
  771. };
  772. struct nclist {
  773. smallint type;
  774. union node *next;
  775. union node *pattern;
  776. union node *body;
  777. };
  778. struct ndefun {
  779. smallint type;
  780. int linno;
  781. char *text;
  782. union node *body;
  783. };
  784. struct narg {
  785. smallint type;
  786. union node *next;
  787. char *text;
  788. struct nodelist *backquote;
  789. };
  790. /* nfile and ndup layout must match!
  791. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  792. * that it is actually NTO2 (>&file), and change its type.
  793. */
  794. struct nfile {
  795. smallint type;
  796. union node *next;
  797. int fd;
  798. int _unused_dupfd;
  799. union node *fname;
  800. char *expfname;
  801. };
  802. struct ndup {
  803. smallint type;
  804. union node *next;
  805. int fd;
  806. int dupfd;
  807. union node *vname;
  808. char *_unused_expfname;
  809. };
  810. struct nhere {
  811. smallint type;
  812. union node *next;
  813. int fd;
  814. union node *doc;
  815. };
  816. struct nnot {
  817. smallint type;
  818. union node *com;
  819. };
  820. union node {
  821. smallint type;
  822. struct ncmd ncmd;
  823. struct npipe npipe;
  824. struct nredir nredir;
  825. struct nbinary nbinary;
  826. struct nif nif;
  827. struct nfor nfor;
  828. struct ncase ncase;
  829. struct nclist nclist;
  830. struct ndefun ndefun;
  831. struct narg narg;
  832. struct nfile nfile;
  833. struct ndup ndup;
  834. struct nhere nhere;
  835. struct nnot nnot;
  836. };
  837. /*
  838. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  839. * It must be distinct from NULL.
  840. */
  841. #define NODE_EOF ((union node *) -1L)
  842. struct nodelist {
  843. struct nodelist *next;
  844. union node *n;
  845. };
  846. struct funcnode {
  847. int count;
  848. union node n;
  849. };
  850. /*
  851. * Free a parse tree.
  852. */
  853. static void
  854. freefunc(struct funcnode *f)
  855. {
  856. if (f && --f->count < 0)
  857. free(f);
  858. }
  859. /* ============ Debugging output */
  860. #if DEBUG
  861. static FILE *tracefile;
  862. static void
  863. trace_printf(const char *fmt, ...)
  864. {
  865. va_list va;
  866. if (debug != 1)
  867. return;
  868. if (DEBUG_TIME)
  869. fprintf(tracefile, "%u ", (int) time(NULL));
  870. if (DEBUG_PID)
  871. fprintf(tracefile, "[%u] ", (int) getpid());
  872. if (DEBUG_SIG)
  873. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  874. va_start(va, fmt);
  875. vfprintf(tracefile, fmt, va);
  876. va_end(va);
  877. }
  878. static void
  879. trace_vprintf(const char *fmt, va_list va)
  880. {
  881. if (debug != 1)
  882. return;
  883. vfprintf(tracefile, fmt, va);
  884. fprintf(tracefile, "\n");
  885. }
  886. static void
  887. trace_puts(const char *s)
  888. {
  889. if (debug != 1)
  890. return;
  891. fputs(s, tracefile);
  892. }
  893. static void
  894. trace_puts_quoted(char *s)
  895. {
  896. char *p;
  897. char c;
  898. if (debug != 1)
  899. return;
  900. putc('"', tracefile);
  901. for (p = s; *p; p++) {
  902. switch ((unsigned char)*p) {
  903. case '\n': c = 'n'; goto backslash;
  904. case '\t': c = 't'; goto backslash;
  905. case '\r': c = 'r'; goto backslash;
  906. case '\"': c = '\"'; goto backslash;
  907. case '\\': c = '\\'; goto backslash;
  908. case CTLESC: c = 'e'; goto backslash;
  909. case CTLVAR: c = 'v'; goto backslash;
  910. case CTLBACKQ: c = 'q'; goto backslash;
  911. backslash:
  912. putc('\\', tracefile);
  913. putc(c, tracefile);
  914. break;
  915. default:
  916. if (*p >= ' ' && *p <= '~')
  917. putc(*p, tracefile);
  918. else {
  919. putc('\\', tracefile);
  920. putc((*p >> 6) & 03, tracefile);
  921. putc((*p >> 3) & 07, tracefile);
  922. putc(*p & 07, tracefile);
  923. }
  924. break;
  925. }
  926. }
  927. putc('"', tracefile);
  928. }
  929. static void
  930. trace_puts_args(char **ap)
  931. {
  932. if (debug != 1)
  933. return;
  934. if (!*ap)
  935. return;
  936. while (1) {
  937. trace_puts_quoted(*ap);
  938. if (!*++ap) {
  939. putc('\n', tracefile);
  940. break;
  941. }
  942. putc(' ', tracefile);
  943. }
  944. }
  945. static void
  946. opentrace(void)
  947. {
  948. char s[100];
  949. #ifdef O_APPEND
  950. int flags;
  951. #endif
  952. if (debug != 1) {
  953. if (tracefile)
  954. fflush(tracefile);
  955. /* leave open because libedit might be using it */
  956. return;
  957. }
  958. strcpy(s, "./trace");
  959. if (tracefile) {
  960. if (!freopen(s, "a", tracefile)) {
  961. fprintf(stderr, "Can't re-open %s\n", s);
  962. debug = 0;
  963. return;
  964. }
  965. } else {
  966. tracefile = fopen(s, "a");
  967. if (tracefile == NULL) {
  968. fprintf(stderr, "Can't open %s\n", s);
  969. debug = 0;
  970. return;
  971. }
  972. }
  973. #ifdef O_APPEND
  974. flags = fcntl(fileno(tracefile), F_GETFL);
  975. if (flags >= 0)
  976. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  977. #endif
  978. setlinebuf(tracefile);
  979. fputs("\nTracing started.\n", tracefile);
  980. }
  981. static void
  982. indent(int amount, char *pfx, FILE *fp)
  983. {
  984. int i;
  985. for (i = 0; i < amount; i++) {
  986. if (pfx && i == amount - 1)
  987. fputs(pfx, fp);
  988. putc('\t', fp);
  989. }
  990. }
  991. /* little circular references here... */
  992. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  993. static void
  994. sharg(union node *arg, FILE *fp)
  995. {
  996. char *p;
  997. struct nodelist *bqlist;
  998. unsigned char subtype;
  999. if (arg->type != NARG) {
  1000. out1fmt("<node type %d>\n", arg->type);
  1001. abort();
  1002. }
  1003. bqlist = arg->narg.backquote;
  1004. for (p = arg->narg.text; *p; p++) {
  1005. switch ((unsigned char)*p) {
  1006. case CTLESC:
  1007. p++;
  1008. putc(*p, fp);
  1009. break;
  1010. case CTLVAR:
  1011. putc('$', fp);
  1012. putc('{', fp);
  1013. subtype = *++p;
  1014. if (subtype == VSLENGTH)
  1015. putc('#', fp);
  1016. while (*p != '=') {
  1017. putc(*p, fp);
  1018. p++;
  1019. }
  1020. if (subtype & VSNUL)
  1021. putc(':', fp);
  1022. switch (subtype & VSTYPE) {
  1023. case VSNORMAL:
  1024. putc('}', fp);
  1025. break;
  1026. case VSMINUS:
  1027. putc('-', fp);
  1028. break;
  1029. case VSPLUS:
  1030. putc('+', fp);
  1031. break;
  1032. case VSQUESTION:
  1033. putc('?', fp);
  1034. break;
  1035. case VSASSIGN:
  1036. putc('=', fp);
  1037. break;
  1038. case VSTRIMLEFT:
  1039. putc('#', fp);
  1040. break;
  1041. case VSTRIMLEFTMAX:
  1042. putc('#', fp);
  1043. putc('#', fp);
  1044. break;
  1045. case VSTRIMRIGHT:
  1046. putc('%', fp);
  1047. break;
  1048. case VSTRIMRIGHTMAX:
  1049. putc('%', fp);
  1050. putc('%', fp);
  1051. break;
  1052. case VSLENGTH:
  1053. break;
  1054. default:
  1055. out1fmt("<subtype %d>", subtype);
  1056. }
  1057. break;
  1058. case CTLENDVAR:
  1059. putc('}', fp);
  1060. break;
  1061. case CTLBACKQ:
  1062. putc('$', fp);
  1063. putc('(', fp);
  1064. shtree(bqlist->n, -1, NULL, fp);
  1065. putc(')', fp);
  1066. break;
  1067. default:
  1068. putc(*p, fp);
  1069. break;
  1070. }
  1071. }
  1072. }
  1073. static void
  1074. shcmd(union node *cmd, FILE *fp)
  1075. {
  1076. union node *np;
  1077. int first;
  1078. const char *s;
  1079. int dftfd;
  1080. first = 1;
  1081. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1082. if (!first)
  1083. putc(' ', fp);
  1084. sharg(np, fp);
  1085. first = 0;
  1086. }
  1087. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1088. if (!first)
  1089. putc(' ', fp);
  1090. dftfd = 0;
  1091. switch (np->nfile.type) {
  1092. case NTO: s = ">>"+1; dftfd = 1; break;
  1093. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1094. case NAPPEND: s = ">>"; dftfd = 1; break;
  1095. #if BASH_REDIR_OUTPUT
  1096. case NTO2:
  1097. #endif
  1098. case NTOFD: s = ">&"; dftfd = 1; break;
  1099. case NFROM: s = "<"; break;
  1100. case NFROMFD: s = "<&"; break;
  1101. case NFROMTO: s = "<>"; break;
  1102. default: s = "*error*"; break;
  1103. }
  1104. if (np->nfile.fd != dftfd)
  1105. fprintf(fp, "%d", np->nfile.fd);
  1106. fputs(s, fp);
  1107. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1108. fprintf(fp, "%d", np->ndup.dupfd);
  1109. } else {
  1110. sharg(np->nfile.fname, fp);
  1111. }
  1112. first = 0;
  1113. }
  1114. }
  1115. static void
  1116. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1117. {
  1118. struct nodelist *lp;
  1119. const char *s;
  1120. if (n == NULL)
  1121. return;
  1122. indent(ind, pfx, fp);
  1123. if (n == NODE_EOF) {
  1124. fputs("<EOF>", fp);
  1125. return;
  1126. }
  1127. switch (n->type) {
  1128. case NSEMI:
  1129. s = "; ";
  1130. goto binop;
  1131. case NAND:
  1132. s = " && ";
  1133. goto binop;
  1134. case NOR:
  1135. s = " || ";
  1136. binop:
  1137. shtree(n->nbinary.ch1, ind, NULL, fp);
  1138. /* if (ind < 0) */
  1139. fputs(s, fp);
  1140. shtree(n->nbinary.ch2, ind, NULL, fp);
  1141. break;
  1142. case NCMD:
  1143. shcmd(n, fp);
  1144. if (ind >= 0)
  1145. putc('\n', fp);
  1146. break;
  1147. case NPIPE:
  1148. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1149. shtree(lp->n, 0, NULL, fp);
  1150. if (lp->next)
  1151. fputs(" | ", fp);
  1152. }
  1153. if (n->npipe.pipe_backgnd)
  1154. fputs(" &", fp);
  1155. if (ind >= 0)
  1156. putc('\n', fp);
  1157. break;
  1158. default:
  1159. fprintf(fp, "<node type %d>", n->type);
  1160. if (ind >= 0)
  1161. putc('\n', fp);
  1162. break;
  1163. }
  1164. }
  1165. static void
  1166. showtree(union node *n)
  1167. {
  1168. trace_puts("showtree called\n");
  1169. shtree(n, 1, NULL, stderr);
  1170. }
  1171. #endif /* DEBUG */
  1172. /* ============ Parser data */
  1173. /*
  1174. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1175. */
  1176. struct strlist {
  1177. struct strlist *next;
  1178. char *text;
  1179. };
  1180. struct alias;
  1181. struct strpush {
  1182. struct strpush *prev; /* preceding string on stack */
  1183. char *prev_string;
  1184. int prev_left_in_line;
  1185. #if ENABLE_ASH_ALIAS
  1186. struct alias *ap; /* if push was associated with an alias */
  1187. #endif
  1188. char *string; /* remember the string since it may change */
  1189. /* Remember last two characters for pungetc. */
  1190. int lastc[2];
  1191. /* Number of outstanding calls to pungetc. */
  1192. int unget;
  1193. };
  1194. /*
  1195. * The parsefile structure pointed to by the global variable parsefile
  1196. * contains information about the current file being read.
  1197. */
  1198. struct parsefile {
  1199. struct parsefile *prev; /* preceding file on stack */
  1200. int linno; /* current line */
  1201. int pf_fd; /* file descriptor (or -1 if string) */
  1202. int left_in_line; /* number of chars left in this line */
  1203. int left_in_buffer; /* number of chars left in this buffer past the line */
  1204. char *next_to_pgetc; /* next char in buffer */
  1205. char *buf; /* input buffer */
  1206. struct strpush *strpush; /* for pushing strings at this level */
  1207. struct strpush basestrpush; /* so pushing one is fast */
  1208. /* Remember last two characters for pungetc. */
  1209. int lastc[2];
  1210. /* Number of outstanding calls to pungetc. */
  1211. int unget;
  1212. };
  1213. static struct parsefile basepf; /* top level input file */
  1214. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1215. static char *commandname; /* currently executing command */
  1216. /* ============ Message printing */
  1217. static void
  1218. ash_vmsg(const char *msg, va_list ap)
  1219. {
  1220. fprintf(stderr, "%s: ", arg0);
  1221. if (commandname) {
  1222. if (strcmp(arg0, commandname))
  1223. fprintf(stderr, "%s: ", commandname);
  1224. if (!iflag || g_parsefile->pf_fd > 0)
  1225. fprintf(stderr, "line %d: ", errlinno);
  1226. }
  1227. vfprintf(stderr, msg, ap);
  1228. newline_and_flush(stderr);
  1229. }
  1230. /*
  1231. * Exverror is called to raise the error exception. If the second argument
  1232. * is not NULL then error prints an error message using printf style
  1233. * formatting. It then raises the error exception.
  1234. */
  1235. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1236. static void
  1237. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1238. {
  1239. #if DEBUG
  1240. if (msg) {
  1241. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1242. TRACEV((msg, ap));
  1243. } else
  1244. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1245. if (msg)
  1246. #endif
  1247. ash_vmsg(msg, ap);
  1248. flush_stdout_stderr();
  1249. raise_exception(cond);
  1250. /* NOTREACHED */
  1251. }
  1252. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1253. static void
  1254. ash_msg_and_raise_error(const char *msg, ...)
  1255. {
  1256. va_list ap;
  1257. exitstatus = 2;
  1258. va_start(ap, msg);
  1259. ash_vmsg_and_raise(EXERROR, msg, ap);
  1260. /* NOTREACHED */
  1261. va_end(ap);
  1262. }
  1263. /*
  1264. * 'fmt' must be a string literal.
  1265. */
  1266. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1267. static void raise_error_syntax(const char *) NORETURN;
  1268. static void
  1269. raise_error_syntax(const char *msg)
  1270. {
  1271. errlinno = g_parsefile->linno;
  1272. ash_msg_and_raise_error("syntax error: %s", msg);
  1273. /* NOTREACHED */
  1274. }
  1275. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1276. static void
  1277. ash_msg_and_raise(int cond, const char *msg, ...)
  1278. {
  1279. va_list ap;
  1280. va_start(ap, msg);
  1281. ash_vmsg_and_raise(cond, msg, ap);
  1282. /* NOTREACHED */
  1283. va_end(ap);
  1284. }
  1285. /*
  1286. * error/warning routines for external builtins
  1287. */
  1288. static void
  1289. ash_msg(const char *fmt, ...)
  1290. {
  1291. va_list ap;
  1292. va_start(ap, fmt);
  1293. ash_vmsg(fmt, ap);
  1294. va_end(ap);
  1295. }
  1296. /*
  1297. * Return a string describing an error. The returned string may be a
  1298. * pointer to a static buffer that will be overwritten on the next call.
  1299. * Action describes the operation that got the error.
  1300. */
  1301. static const char *
  1302. errmsg(int e, const char *em)
  1303. {
  1304. if (e == ENOENT || e == ENOTDIR) {
  1305. return em;
  1306. }
  1307. return strerror(e);
  1308. }
  1309. /* ============ Memory allocation */
  1310. #if 0
  1311. /* I consider these wrappers nearly useless:
  1312. * ok, they return you to nearest exception handler, but
  1313. * how much memory do you leak in the process, making
  1314. * memory starvation worse?
  1315. */
  1316. static void *
  1317. ckrealloc(void * p, size_t nbytes)
  1318. {
  1319. p = realloc(p, nbytes);
  1320. if (!p)
  1321. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1322. return p;
  1323. }
  1324. static void *
  1325. ckmalloc(size_t nbytes)
  1326. {
  1327. return ckrealloc(NULL, nbytes);
  1328. }
  1329. static void *
  1330. ckzalloc(size_t nbytes)
  1331. {
  1332. return memset(ckmalloc(nbytes), 0, nbytes);
  1333. }
  1334. static char *
  1335. ckstrdup(const char *s)
  1336. {
  1337. char *p = strdup(s);
  1338. if (!p)
  1339. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1340. return p;
  1341. }
  1342. #else
  1343. /* Using bbox equivalents. They exit if out of memory */
  1344. # define ckrealloc xrealloc
  1345. # define ckmalloc xmalloc
  1346. # define ckzalloc xzalloc
  1347. # define ckstrdup xstrdup
  1348. #endif
  1349. /*
  1350. * It appears that grabstackstr() will barf with such alignments
  1351. * because stalloc() will return a string allocated in a new stackblock.
  1352. */
  1353. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1354. enum {
  1355. /* Most machines require the value returned from malloc to be aligned
  1356. * in some way. The following macro will get this right
  1357. * on many machines. */
  1358. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1359. /* Minimum size of a block */
  1360. MINSIZE = SHELL_ALIGN(504),
  1361. };
  1362. struct stack_block {
  1363. struct stack_block *prev;
  1364. char space[MINSIZE];
  1365. };
  1366. struct stackmark {
  1367. struct stack_block *stackp;
  1368. char *stacknxt;
  1369. size_t stacknleft;
  1370. };
  1371. struct globals_memstack {
  1372. struct stack_block *g_stackp; // = &stackbase;
  1373. char *g_stacknxt; // = stackbase.space;
  1374. char *sstrend; // = stackbase.space + MINSIZE;
  1375. size_t g_stacknleft; // = MINSIZE;
  1376. struct stack_block stackbase;
  1377. };
  1378. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1379. #define G_memstack (*ash_ptr_to_globals_memstack)
  1380. #define g_stackp (G_memstack.g_stackp )
  1381. #define g_stacknxt (G_memstack.g_stacknxt )
  1382. #define sstrend (G_memstack.sstrend )
  1383. #define g_stacknleft (G_memstack.g_stacknleft)
  1384. #define stackbase (G_memstack.stackbase )
  1385. #define INIT_G_memstack() do { \
  1386. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1387. barrier(); \
  1388. g_stackp = &stackbase; \
  1389. g_stacknxt = stackbase.space; \
  1390. g_stacknleft = MINSIZE; \
  1391. sstrend = stackbase.space + MINSIZE; \
  1392. } while (0)
  1393. #define stackblock() ((void *)g_stacknxt)
  1394. #define stackblocksize() g_stacknleft
  1395. /*
  1396. * Parse trees for commands are allocated in lifo order, so we use a stack
  1397. * to make this more efficient, and also to avoid all sorts of exception
  1398. * handling code to handle interrupts in the middle of a parse.
  1399. *
  1400. * The size 504 was chosen because the Ultrix malloc handles that size
  1401. * well.
  1402. */
  1403. static void *
  1404. stalloc(size_t nbytes)
  1405. {
  1406. char *p;
  1407. size_t aligned;
  1408. aligned = SHELL_ALIGN(nbytes);
  1409. if (aligned > g_stacknleft) {
  1410. size_t len;
  1411. size_t blocksize;
  1412. struct stack_block *sp;
  1413. blocksize = aligned;
  1414. if (blocksize < MINSIZE)
  1415. blocksize = MINSIZE;
  1416. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1417. if (len < blocksize)
  1418. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1419. INT_OFF;
  1420. sp = ckmalloc(len);
  1421. sp->prev = g_stackp;
  1422. g_stacknxt = sp->space;
  1423. g_stacknleft = blocksize;
  1424. sstrend = g_stacknxt + blocksize;
  1425. g_stackp = sp;
  1426. INT_ON;
  1427. }
  1428. p = g_stacknxt;
  1429. g_stacknxt += aligned;
  1430. g_stacknleft -= aligned;
  1431. return p;
  1432. }
  1433. static void *
  1434. stzalloc(size_t nbytes)
  1435. {
  1436. return memset(stalloc(nbytes), 0, nbytes);
  1437. }
  1438. static void
  1439. stunalloc(void *p)
  1440. {
  1441. #if DEBUG
  1442. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1443. write(STDERR_FILENO, "stunalloc\n", 10);
  1444. abort();
  1445. }
  1446. #endif
  1447. g_stacknleft += g_stacknxt - (char *)p;
  1448. g_stacknxt = p;
  1449. }
  1450. /*
  1451. * Like strdup but works with the ash stack.
  1452. */
  1453. static char *
  1454. sstrdup(const char *p)
  1455. {
  1456. size_t len = strlen(p) + 1;
  1457. return memcpy(stalloc(len), p, len);
  1458. }
  1459. static ALWAYS_INLINE void
  1460. grabstackblock(size_t len)
  1461. {
  1462. stalloc(len);
  1463. }
  1464. static void
  1465. pushstackmark(struct stackmark *mark, size_t len)
  1466. {
  1467. mark->stackp = g_stackp;
  1468. mark->stacknxt = g_stacknxt;
  1469. mark->stacknleft = g_stacknleft;
  1470. grabstackblock(len);
  1471. }
  1472. static void
  1473. setstackmark(struct stackmark *mark)
  1474. {
  1475. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1476. }
  1477. static void
  1478. popstackmark(struct stackmark *mark)
  1479. {
  1480. struct stack_block *sp;
  1481. if (!mark->stackp)
  1482. return;
  1483. INT_OFF;
  1484. while (g_stackp != mark->stackp) {
  1485. sp = g_stackp;
  1486. g_stackp = sp->prev;
  1487. free(sp);
  1488. }
  1489. g_stacknxt = mark->stacknxt;
  1490. g_stacknleft = mark->stacknleft;
  1491. sstrend = mark->stacknxt + mark->stacknleft;
  1492. INT_ON;
  1493. }
  1494. /*
  1495. * When the parser reads in a string, it wants to stick the string on the
  1496. * stack and only adjust the stack pointer when it knows how big the
  1497. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1498. * of space on top of the stack and stackblocklen returns the length of
  1499. * this block. Growstackblock will grow this space by at least one byte,
  1500. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1501. * part of the block that has been used.
  1502. */
  1503. static void
  1504. growstackblock(void)
  1505. {
  1506. size_t newlen;
  1507. newlen = g_stacknleft * 2;
  1508. if (newlen < g_stacknleft)
  1509. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1510. if (newlen < 128)
  1511. newlen += 128;
  1512. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1513. struct stack_block *sp;
  1514. struct stack_block *prevstackp;
  1515. size_t grosslen;
  1516. INT_OFF;
  1517. sp = g_stackp;
  1518. prevstackp = sp->prev;
  1519. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1520. sp = ckrealloc(sp, grosslen);
  1521. sp->prev = prevstackp;
  1522. g_stackp = sp;
  1523. g_stacknxt = sp->space;
  1524. g_stacknleft = newlen;
  1525. sstrend = sp->space + newlen;
  1526. INT_ON;
  1527. } else {
  1528. char *oldspace = g_stacknxt;
  1529. size_t oldlen = g_stacknleft;
  1530. char *p = stalloc(newlen);
  1531. /* free the space we just allocated */
  1532. g_stacknxt = memcpy(p, oldspace, oldlen);
  1533. g_stacknleft += newlen;
  1534. }
  1535. }
  1536. /*
  1537. * The following routines are somewhat easier to use than the above.
  1538. * The user declares a variable of type STACKSTR, which may be declared
  1539. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1540. * the user uses the macro STPUTC to add characters to the string. In
  1541. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1542. * grown as necessary. When the user is done, she can just leave the
  1543. * string there and refer to it using stackblock(). Or she can allocate
  1544. * the space for it using grabstackstr(). If it is necessary to allow
  1545. * someone else to use the stack temporarily and then continue to grow
  1546. * the string, the user should use grabstack to allocate the space, and
  1547. * then call ungrabstr(p) to return to the previous mode of operation.
  1548. *
  1549. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1550. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1551. * is space for at least one character.
  1552. */
  1553. static void *
  1554. growstackstr(void)
  1555. {
  1556. size_t len = stackblocksize();
  1557. growstackblock();
  1558. return (char *)stackblock() + len;
  1559. }
  1560. /*
  1561. * Called from CHECKSTRSPACE.
  1562. */
  1563. static char *
  1564. makestrspace(size_t newlen, char *p)
  1565. {
  1566. size_t len = p - g_stacknxt;
  1567. size_t size;
  1568. for (;;) {
  1569. size_t nleft;
  1570. size = stackblocksize();
  1571. nleft = size - len;
  1572. if (nleft >= newlen)
  1573. break;
  1574. growstackblock();
  1575. }
  1576. return (char *)stackblock() + len;
  1577. }
  1578. static char *
  1579. stack_nputstr(const char *s, size_t n, char *p)
  1580. {
  1581. p = makestrspace(n, p);
  1582. p = (char *)mempcpy(p, s, n);
  1583. return p;
  1584. }
  1585. static char *
  1586. stack_putstr(const char *s, char *p)
  1587. {
  1588. return stack_nputstr(s, strlen(s), p);
  1589. }
  1590. static char *
  1591. _STPUTC(int c, char *p)
  1592. {
  1593. if (p == sstrend)
  1594. p = growstackstr();
  1595. *p++ = c;
  1596. return p;
  1597. }
  1598. #define STARTSTACKSTR(p) ((p) = stackblock())
  1599. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1600. #define CHECKSTRSPACE(n, p) do { \
  1601. char *q = (p); \
  1602. size_t l = (n); \
  1603. size_t m = sstrend - q; \
  1604. if (l > m) \
  1605. (p) = makestrspace(l, q); \
  1606. } while (0)
  1607. #define USTPUTC(c, p) (*(p)++ = (c))
  1608. #define STACKSTRNUL(p) do { \
  1609. if ((p) == sstrend) \
  1610. (p) = growstackstr(); \
  1611. *(p) = '\0'; \
  1612. } while (0)
  1613. #define STUNPUTC(p) (--(p))
  1614. #define STTOPC(p) ((p)[-1])
  1615. #define STADJUST(amount, p) ((p) += (amount))
  1616. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1617. #define ungrabstackstr(s, p) stunalloc(s)
  1618. #define stackstrend() ((void *)sstrend)
  1619. /* ============ String helpers */
  1620. /*
  1621. * prefix -- see if pfx is a prefix of string.
  1622. */
  1623. static char *
  1624. prefix(const char *string, const char *pfx)
  1625. {
  1626. while (*pfx) {
  1627. if (*pfx++ != *string++)
  1628. return NULL;
  1629. }
  1630. return (char *) string;
  1631. }
  1632. /*
  1633. * Check for a valid number. This should be elsewhere.
  1634. */
  1635. static int
  1636. is_number(const char *p)
  1637. {
  1638. do {
  1639. if (!isdigit(*p))
  1640. return 0;
  1641. } while (*++p != '\0');
  1642. return 1;
  1643. }
  1644. /*
  1645. * Convert a string of digits to an integer, printing an error message on
  1646. * failure.
  1647. */
  1648. static int
  1649. number(const char *s)
  1650. {
  1651. if (!is_number(s))
  1652. ash_msg_and_raise_error(msg_illnum, s);
  1653. return atoi(s);
  1654. }
  1655. /*
  1656. * Produce a single quoted string suitable as input to the shell.
  1657. * The return string is allocated on the stack.
  1658. */
  1659. static char *
  1660. single_quote(const char *s)
  1661. {
  1662. char *p;
  1663. STARTSTACKSTR(p);
  1664. do {
  1665. char *q;
  1666. size_t len;
  1667. len = strchrnul(s, '\'') - s;
  1668. q = p = makestrspace(len + 3, p);
  1669. *q++ = '\'';
  1670. q = (char *)mempcpy(q, s, len);
  1671. *q++ = '\'';
  1672. s += len;
  1673. STADJUST(q - p, p);
  1674. if (*s != '\'')
  1675. break;
  1676. len = 0;
  1677. do len++; while (*++s == '\'');
  1678. q = p = makestrspace(len + 3, p);
  1679. *q++ = '"';
  1680. q = (char *)mempcpy(q, s - len, len);
  1681. *q++ = '"';
  1682. STADJUST(q - p, p);
  1683. } while (*s);
  1684. USTPUTC('\0', p);
  1685. return stackblock();
  1686. }
  1687. /*
  1688. * Produce a possibly single quoted string suitable as input to the shell.
  1689. * If quoting was done, the return string is allocated on the stack,
  1690. * otherwise a pointer to the original string is returned.
  1691. */
  1692. static const char *
  1693. maybe_single_quote(const char *s)
  1694. {
  1695. const char *p = s;
  1696. while (*p) {
  1697. /* Assuming ACSII */
  1698. /* quote ctrl_chars space !"#$%&'()* */
  1699. if (*p < '+')
  1700. goto need_quoting;
  1701. /* quote ;<=>? */
  1702. if (*p >= ';' && *p <= '?')
  1703. goto need_quoting;
  1704. /* quote `[\ */
  1705. if (*p == '`')
  1706. goto need_quoting;
  1707. if (*p == '[')
  1708. goto need_quoting;
  1709. if (*p == '\\')
  1710. goto need_quoting;
  1711. /* quote {|}~ DEL and high bytes */
  1712. if (*p > 'z')
  1713. goto need_quoting;
  1714. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1715. /* TODO: maybe avoid quoting % */
  1716. p++;
  1717. }
  1718. return s;
  1719. need_quoting:
  1720. return single_quote(s);
  1721. }
  1722. /* ============ nextopt */
  1723. static char **argptr; /* argument list for builtin commands */
  1724. static char *optionarg; /* set by nextopt (like getopt) */
  1725. static char *optptr; /* used by nextopt */
  1726. /*
  1727. * XXX - should get rid of. Have all builtins use getopt(3).
  1728. * The library getopt must have the BSD extension static variable
  1729. * "optreset", otherwise it can't be used within the shell safely.
  1730. *
  1731. * Standard option processing (a la getopt) for builtin routines.
  1732. * The only argument that is passed to nextopt is the option string;
  1733. * the other arguments are unnecessary. It returns the character,
  1734. * or '\0' on end of input.
  1735. */
  1736. static int
  1737. nextopt(const char *optstring)
  1738. {
  1739. char *p;
  1740. const char *q;
  1741. char c;
  1742. p = optptr;
  1743. if (p == NULL || *p == '\0') {
  1744. /* We ate entire "-param", take next one */
  1745. p = *argptr;
  1746. if (p == NULL)
  1747. return '\0';
  1748. if (*p != '-')
  1749. return '\0';
  1750. if (*++p == '\0') /* just "-" ? */
  1751. return '\0';
  1752. argptr++;
  1753. if (LONE_DASH(p)) /* "--" ? */
  1754. return '\0';
  1755. /* p => next "-param" */
  1756. }
  1757. /* p => some option char in the middle of a "-param" */
  1758. c = *p++;
  1759. for (q = optstring; *q != c;) {
  1760. if (*q == '\0')
  1761. ash_msg_and_raise_error("illegal option -%c", c);
  1762. if (*++q == ':')
  1763. q++;
  1764. }
  1765. if (*++q == ':') {
  1766. if (*p == '\0') {
  1767. p = *argptr++;
  1768. if (p == NULL)
  1769. ash_msg_and_raise_error("no arg for -%c option", c);
  1770. }
  1771. optionarg = p;
  1772. p = NULL;
  1773. }
  1774. optptr = p;
  1775. return c;
  1776. }
  1777. /* ============ Shell variables */
  1778. struct shparam {
  1779. int nparam; /* # of positional parameters (without $0) */
  1780. #if ENABLE_ASH_GETOPTS
  1781. int optind; /* next parameter to be processed by getopts */
  1782. int optoff; /* used by getopts */
  1783. #endif
  1784. unsigned char malloced; /* if parameter list dynamically allocated */
  1785. char **p; /* parameter list */
  1786. };
  1787. /*
  1788. * Free the list of positional parameters.
  1789. */
  1790. static void
  1791. freeparam(volatile struct shparam *param)
  1792. {
  1793. if (param->malloced) {
  1794. char **ap, **ap1;
  1795. ap = ap1 = param->p;
  1796. while (*ap)
  1797. free(*ap++);
  1798. free(ap1);
  1799. }
  1800. }
  1801. #if ENABLE_ASH_GETOPTS
  1802. static void FAST_FUNC getoptsreset(const char *value);
  1803. #endif
  1804. struct var {
  1805. struct var *next; /* next entry in hash list */
  1806. int flags; /* flags are defined above */
  1807. const char *var_text; /* name=value */
  1808. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1809. /* the variable gets set/unset */
  1810. };
  1811. struct localvar {
  1812. struct localvar *next; /* next local variable in list */
  1813. struct var *vp; /* the variable that was made local */
  1814. int flags; /* saved flags */
  1815. const char *text; /* saved text */
  1816. };
  1817. /* flags */
  1818. #define VEXPORT 0x01 /* variable is exported */
  1819. #define VREADONLY 0x02 /* variable cannot be modified */
  1820. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1821. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1822. #define VSTACK 0x10 /* text is allocated on the stack */
  1823. #define VUNSET 0x20 /* the variable is not set */
  1824. #define VNOFUNC 0x40 /* don't call the callback function */
  1825. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1826. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1827. #if ENABLE_ASH_RANDOM_SUPPORT
  1828. # define VDYNAMIC 0x200 /* dynamic variable */
  1829. #else
  1830. # define VDYNAMIC 0
  1831. #endif
  1832. /* Need to be before varinit_data[] */
  1833. #if ENABLE_LOCALE_SUPPORT
  1834. static void FAST_FUNC
  1835. change_lc_all(const char *value)
  1836. {
  1837. if (value && *value != '\0')
  1838. setlocale(LC_ALL, value);
  1839. }
  1840. static void FAST_FUNC
  1841. change_lc_ctype(const char *value)
  1842. {
  1843. if (value && *value != '\0')
  1844. setlocale(LC_CTYPE, value);
  1845. }
  1846. #endif
  1847. #if ENABLE_ASH_MAIL
  1848. static void chkmail(void);
  1849. static void changemail(const char *var_value) FAST_FUNC;
  1850. #else
  1851. # define chkmail() ((void)0)
  1852. #endif
  1853. static void changepath(const char *) FAST_FUNC;
  1854. #if ENABLE_ASH_RANDOM_SUPPORT
  1855. static void change_random(const char *) FAST_FUNC;
  1856. #endif
  1857. #if BASH_EPOCH_VARS
  1858. static void change_seconds(const char *) FAST_FUNC;
  1859. static void change_realtime(const char *) FAST_FUNC;
  1860. #endif
  1861. static const struct {
  1862. int flags;
  1863. const char *var_text;
  1864. void (*var_func)(const char *) FAST_FUNC;
  1865. } varinit_data[] = {
  1866. /*
  1867. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1868. * some environment strings may be constant.
  1869. */
  1870. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1871. #if ENABLE_ASH_MAIL
  1872. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1873. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1874. #endif
  1875. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1876. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1877. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1878. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1879. #if ENABLE_ASH_GETOPTS
  1880. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1881. #endif
  1882. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1883. #if ENABLE_ASH_RANDOM_SUPPORT
  1884. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1885. #endif
  1886. #if BASH_EPOCH_VARS
  1887. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
  1888. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
  1889. #endif
  1890. #if ENABLE_LOCALE_SUPPORT
  1891. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1892. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1893. #endif
  1894. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1895. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1896. #endif
  1897. };
  1898. struct redirtab;
  1899. struct globals_var {
  1900. struct shparam shellparam; /* $@ current positional parameters */
  1901. struct redirtab *redirlist;
  1902. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1903. struct var *vartab[VTABSIZE];
  1904. struct var varinit[ARRAY_SIZE(varinit_data)];
  1905. int lineno;
  1906. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1907. };
  1908. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1909. #define G_var (*ash_ptr_to_globals_var)
  1910. #define shellparam (G_var.shellparam )
  1911. //#define redirlist (G_var.redirlist )
  1912. #define preverrout_fd (G_var.preverrout_fd)
  1913. #define vartab (G_var.vartab )
  1914. #define varinit (G_var.varinit )
  1915. #define lineno (G_var.lineno )
  1916. #define linenovar (G_var.linenovar )
  1917. #define vifs varinit[0]
  1918. #if ENABLE_ASH_MAIL
  1919. # define vmail varinit[1]
  1920. # define vmpath varinit[2]
  1921. #endif
  1922. #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
  1923. #define vpath varinit[VAR_OFFSET1 + 1]
  1924. #define vps1 varinit[VAR_OFFSET1 + 2]
  1925. #define vps2 varinit[VAR_OFFSET1 + 3]
  1926. #define vps4 varinit[VAR_OFFSET1 + 4]
  1927. #if ENABLE_ASH_GETOPTS
  1928. # define voptind varinit[VAR_OFFSET1 + 5]
  1929. #endif
  1930. #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
  1931. #define vlineno varinit[VAR_OFFSET2 + 5]
  1932. #if ENABLE_ASH_RANDOM_SUPPORT
  1933. # define vrandom varinit[VAR_OFFSET2 + 6]
  1934. #endif
  1935. #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
  1936. #if BASH_EPOCH_VARS
  1937. # define vepochs varinit[VAR_OFFSET3 + 6]
  1938. # define vepochr varinit[VAR_OFFSET3 + 7]
  1939. #endif
  1940. #define INIT_G_var() do { \
  1941. unsigned i; \
  1942. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1943. barrier(); \
  1944. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1945. varinit[i].flags = varinit_data[i].flags; \
  1946. varinit[i].var_text = varinit_data[i].var_text; \
  1947. varinit[i].var_func = varinit_data[i].var_func; \
  1948. } \
  1949. strcpy(linenovar, "LINENO="); \
  1950. vlineno.var_text = linenovar; \
  1951. } while (0)
  1952. /*
  1953. * The following macros access the values of the above variables.
  1954. * They have to skip over the name. They return the null string
  1955. * for unset variables.
  1956. */
  1957. #define ifsval() (vifs.var_text + 4)
  1958. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1959. #if ENABLE_ASH_MAIL
  1960. # define mailval() (vmail.var_text + 5)
  1961. # define mpathval() (vmpath.var_text + 9)
  1962. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1963. #endif
  1964. #define pathval() (vpath.var_text + 5)
  1965. #define ps1val() (vps1.var_text + 4)
  1966. #define ps2val() (vps2.var_text + 4)
  1967. #define ps4val() (vps4.var_text + 4)
  1968. #if ENABLE_ASH_GETOPTS
  1969. # define optindval() (voptind.var_text + 7)
  1970. #endif
  1971. #if ENABLE_ASH_GETOPTS
  1972. static void FAST_FUNC
  1973. getoptsreset(const char *value)
  1974. {
  1975. shellparam.optind = 1;
  1976. if (is_number(value))
  1977. shellparam.optind = number(value) ?: 1;
  1978. shellparam.optoff = -1;
  1979. }
  1980. #endif
  1981. /*
  1982. * Compares two strings up to the first = or '\0'. The first
  1983. * string must be terminated by '='; the second may be terminated by
  1984. * either '=' or '\0'.
  1985. */
  1986. static int
  1987. varcmp(const char *p, const char *q)
  1988. {
  1989. int c, d;
  1990. while ((c = *p) == (d = *q)) {
  1991. if (c == '\0' || c == '=')
  1992. goto out;
  1993. p++;
  1994. q++;
  1995. }
  1996. if (c == '=')
  1997. c = '\0';
  1998. if (d == '=')
  1999. d = '\0';
  2000. out:
  2001. return c - d;
  2002. }
  2003. /*
  2004. * Find the appropriate entry in the hash table from the name.
  2005. */
  2006. static struct var **
  2007. hashvar(const char *p)
  2008. {
  2009. unsigned hashval;
  2010. hashval = ((unsigned char) *p) << 4;
  2011. while (*p && *p != '=')
  2012. hashval += (unsigned char) *p++;
  2013. return &vartab[hashval % VTABSIZE];
  2014. }
  2015. static int
  2016. vpcmp(const void *a, const void *b)
  2017. {
  2018. return varcmp(*(const char **)a, *(const char **)b);
  2019. }
  2020. /*
  2021. * This routine initializes the builtin variables.
  2022. */
  2023. static void
  2024. initvar(void)
  2025. {
  2026. struct var *vp;
  2027. struct var *end;
  2028. struct var **vpp;
  2029. /*
  2030. * PS1 depends on uid
  2031. */
  2032. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2033. vps1.var_text = "PS1=\\w \\$ ";
  2034. #else
  2035. if (!geteuid())
  2036. vps1.var_text = "PS1=# ";
  2037. #endif
  2038. vp = varinit;
  2039. end = vp + ARRAY_SIZE(varinit);
  2040. do {
  2041. vpp = hashvar(vp->var_text);
  2042. vp->next = *vpp;
  2043. *vpp = vp;
  2044. } while (++vp < end);
  2045. }
  2046. static struct var **
  2047. findvar(struct var **vpp, const char *name)
  2048. {
  2049. for (; *vpp; vpp = &(*vpp)->next) {
  2050. if (varcmp((*vpp)->var_text, name) == 0) {
  2051. break;
  2052. }
  2053. }
  2054. return vpp;
  2055. }
  2056. /*
  2057. * Find the value of a variable. Returns NULL if not set.
  2058. */
  2059. static const char* FAST_FUNC
  2060. lookupvar(const char *name)
  2061. {
  2062. struct var *v;
  2063. v = *findvar(hashvar(name), name);
  2064. if (v) {
  2065. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2066. /*
  2067. * Dynamic variables are implemented roughly the same way they are
  2068. * in bash. Namely, they're "special" so long as they aren't unset.
  2069. * As soon as they're unset, they're no longer dynamic, and dynamic
  2070. * lookup will no longer happen at that point. -- PFM.
  2071. */
  2072. if (v->flags & VDYNAMIC)
  2073. v->var_func(NULL);
  2074. #endif
  2075. if (!(v->flags & VUNSET)) {
  2076. if (v == &vlineno && v->var_text == linenovar) {
  2077. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2078. }
  2079. return var_end(v->var_text);
  2080. }
  2081. }
  2082. return NULL;
  2083. }
  2084. #if ENABLE_UNICODE_SUPPORT
  2085. static void
  2086. reinit_unicode_for_ash(void)
  2087. {
  2088. /* Unicode support should be activated even if LANG is set
  2089. * _during_ shell execution, not only if it was set when
  2090. * shell was started. Therefore, re-check LANG every time:
  2091. */
  2092. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2093. || ENABLE_UNICODE_USING_LOCALE
  2094. ) {
  2095. const char *s = lookupvar("LC_ALL");
  2096. if (!s) s = lookupvar("LC_CTYPE");
  2097. if (!s) s = lookupvar("LANG");
  2098. reinit_unicode(s);
  2099. }
  2100. }
  2101. #else
  2102. # define reinit_unicode_for_ash() ((void)0)
  2103. #endif
  2104. /*
  2105. * Search the environment of a builtin command.
  2106. */
  2107. static ALWAYS_INLINE const char *
  2108. bltinlookup(const char *name)
  2109. {
  2110. return lookupvar(name);
  2111. }
  2112. /*
  2113. * Same as setvar except that the variable and value are passed in
  2114. * the first argument as name=value. Since the first argument will
  2115. * be actually stored in the table, it should not be a string that
  2116. * will go away.
  2117. * Called with interrupts off.
  2118. */
  2119. static struct var *
  2120. setvareq(char *s, int flags)
  2121. {
  2122. struct var *vp, **vpp;
  2123. vpp = hashvar(s);
  2124. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2125. vpp = findvar(vpp, s);
  2126. vp = *vpp;
  2127. if (vp) {
  2128. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2129. const char *n;
  2130. if (flags & VNOSAVE)
  2131. free(s);
  2132. n = vp->var_text;
  2133. exitstatus = 1;
  2134. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2135. }
  2136. if (flags & VNOSET)
  2137. goto out;
  2138. if (vp->var_func && !(flags & VNOFUNC))
  2139. vp->var_func(var_end(s));
  2140. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2141. free((char*)vp->var_text);
  2142. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2143. *vpp = vp->next;
  2144. free(vp);
  2145. out_free:
  2146. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2147. free(s);
  2148. goto out;
  2149. }
  2150. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2151. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2152. if (flags & VUNSET)
  2153. flags &= ~VDYNAMIC;
  2154. #endif
  2155. } else {
  2156. /* variable s is not found */
  2157. if (flags & VNOSET)
  2158. goto out;
  2159. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2160. goto out_free;
  2161. vp = ckzalloc(sizeof(*vp));
  2162. vp->next = *vpp;
  2163. /*vp->func = NULL; - ckzalloc did it */
  2164. *vpp = vp;
  2165. }
  2166. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2167. s = ckstrdup(s);
  2168. vp->var_text = s;
  2169. vp->flags = flags;
  2170. out:
  2171. return vp;
  2172. }
  2173. /*
  2174. * Set the value of a variable. The flags argument is ored with the
  2175. * flags of the variable. If val is NULL, the variable is unset.
  2176. */
  2177. static struct var *
  2178. setvar(const char *name, const char *val, int flags)
  2179. {
  2180. const char *q;
  2181. char *p;
  2182. char *nameeq;
  2183. size_t namelen;
  2184. size_t vallen;
  2185. struct var *vp;
  2186. q = endofname(name);
  2187. p = strchrnul(q, '=');
  2188. namelen = p - name;
  2189. if (!namelen || p != q)
  2190. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2191. vallen = 0;
  2192. if (val == NULL) {
  2193. flags |= VUNSET;
  2194. } else {
  2195. vallen = strlen(val);
  2196. }
  2197. INT_OFF;
  2198. nameeq = ckzalloc(namelen + vallen + 2);
  2199. p = mempcpy(nameeq, name, namelen);
  2200. if (val) {
  2201. *p++ = '=';
  2202. memcpy(p, val, vallen);
  2203. }
  2204. vp = setvareq(nameeq, flags | VNOSAVE);
  2205. INT_ON;
  2206. return vp;
  2207. }
  2208. static void FAST_FUNC
  2209. setvar0(const char *name, const char *val)
  2210. {
  2211. setvar(name, val, 0);
  2212. }
  2213. /*
  2214. * Unset the specified variable.
  2215. */
  2216. static void
  2217. unsetvar(const char *s)
  2218. {
  2219. setvar(s, NULL, 0);
  2220. }
  2221. /*
  2222. * Process a linked list of variable assignments.
  2223. */
  2224. static void
  2225. listsetvar(struct strlist *list_set_var, int flags)
  2226. {
  2227. struct strlist *lp = list_set_var;
  2228. if (!lp)
  2229. return;
  2230. INT_OFF;
  2231. do {
  2232. setvareq(lp->text, flags);
  2233. lp = lp->next;
  2234. } while (lp);
  2235. INT_ON;
  2236. }
  2237. /*
  2238. * Generate a list of variables satisfying the given conditions.
  2239. */
  2240. #if !ENABLE_FEATURE_SH_NOFORK
  2241. # define listvars(on, off, lp, end) listvars(on, off, end)
  2242. #endif
  2243. static char **
  2244. listvars(int on, int off, struct strlist *lp, char ***end)
  2245. {
  2246. struct var **vpp;
  2247. struct var *vp;
  2248. char **ep;
  2249. int mask;
  2250. STARTSTACKSTR(ep);
  2251. vpp = vartab;
  2252. mask = on | off;
  2253. do {
  2254. for (vp = *vpp; vp; vp = vp->next) {
  2255. if ((vp->flags & mask) == on) {
  2256. #if ENABLE_FEATURE_SH_NOFORK
  2257. /* If variable with the same name is both
  2258. * exported and temporarily set for a command:
  2259. * export ZVAR=5
  2260. * ZVAR=6 printenv
  2261. * then "ZVAR=6" will be both in vartab and
  2262. * lp lists. Do not pass it twice to printenv.
  2263. */
  2264. struct strlist *lp1 = lp;
  2265. while (lp1) {
  2266. if (strcmp(lp1->text, vp->var_text) == 0)
  2267. goto skip;
  2268. lp1 = lp1->next;
  2269. }
  2270. #endif
  2271. if (ep == stackstrend())
  2272. ep = growstackstr();
  2273. *ep++ = (char*)vp->var_text;
  2274. #if ENABLE_FEATURE_SH_NOFORK
  2275. skip: ;
  2276. #endif
  2277. }
  2278. }
  2279. } while (++vpp < vartab + VTABSIZE);
  2280. #if ENABLE_FEATURE_SH_NOFORK
  2281. while (lp) {
  2282. if (ep == stackstrend())
  2283. ep = growstackstr();
  2284. *ep++ = lp->text;
  2285. lp = lp->next;
  2286. }
  2287. #endif
  2288. if (ep == stackstrend())
  2289. ep = growstackstr();
  2290. if (end)
  2291. *end = ep;
  2292. *ep++ = NULL;
  2293. return grabstackstr(ep);
  2294. }
  2295. /* ============ Path search helper
  2296. *
  2297. * The variable path (passed by reference) should be set to the start
  2298. * of the path before the first call; path_advance will update
  2299. * this value as it proceeds. Successive calls to path_advance will return
  2300. * the possible path expansions in sequence. If an option (indicated by
  2301. * a percent sign) appears in the path entry then the global variable
  2302. * pathopt will be set to point to it; otherwise pathopt will be set to
  2303. * NULL.
  2304. */
  2305. static const char *pathopt; /* set by path_advance */
  2306. static char *
  2307. path_advance(const char **path, const char *name)
  2308. {
  2309. const char *p;
  2310. char *q;
  2311. const char *start;
  2312. size_t len;
  2313. if (*path == NULL)
  2314. return NULL;
  2315. start = *path;
  2316. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2317. continue;
  2318. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2319. while (stackblocksize() < len)
  2320. growstackblock();
  2321. q = stackblock();
  2322. if (p != start) {
  2323. q = mempcpy(q, start, p - start);
  2324. *q++ = '/';
  2325. }
  2326. strcpy(q, name);
  2327. pathopt = NULL;
  2328. if (*p == '%') {
  2329. pathopt = ++p;
  2330. while (*p && *p != ':')
  2331. p++;
  2332. }
  2333. if (*p == ':')
  2334. *path = p + 1;
  2335. else
  2336. *path = NULL;
  2337. return stalloc(len);
  2338. }
  2339. /* ============ Prompt */
  2340. static smallint doprompt; /* if set, prompt the user */
  2341. static smallint needprompt; /* true if interactive and at start of line */
  2342. #if ENABLE_FEATURE_EDITING
  2343. static line_input_t *line_input_state;
  2344. static const char *cmdedit_prompt;
  2345. static void
  2346. putprompt(const char *s)
  2347. {
  2348. if (ENABLE_ASH_EXPAND_PRMT) {
  2349. free((char*)cmdedit_prompt);
  2350. cmdedit_prompt = ckstrdup(s);
  2351. return;
  2352. }
  2353. cmdedit_prompt = s;
  2354. }
  2355. #else
  2356. static void
  2357. putprompt(const char *s)
  2358. {
  2359. out2str(s);
  2360. }
  2361. #endif
  2362. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2363. static const char *expandstr(const char *ps, int syntax_type);
  2364. /* Values for syntax param */
  2365. #define BASESYNTAX 0 /* not in quotes */
  2366. #define DQSYNTAX 1 /* in double quotes */
  2367. #define SQSYNTAX 2 /* in single quotes */
  2368. #define ARISYNTAX 3 /* in arithmetic */
  2369. #if ENABLE_ASH_EXPAND_PRMT
  2370. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2371. #endif
  2372. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2373. /*
  2374. * called by editline -- any expansions to the prompt should be added here.
  2375. */
  2376. static void
  2377. setprompt_if(smallint do_set, int whichprompt)
  2378. {
  2379. const char *prompt;
  2380. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2381. if (!do_set)
  2382. return;
  2383. needprompt = 0;
  2384. switch (whichprompt) {
  2385. case 1:
  2386. prompt = ps1val();
  2387. break;
  2388. case 2:
  2389. prompt = ps2val();
  2390. break;
  2391. default: /* 0 */
  2392. prompt = nullstr;
  2393. }
  2394. #if ENABLE_ASH_EXPAND_PRMT
  2395. pushstackmark(&smark, stackblocksize());
  2396. putprompt(expandstr(prompt, PSSYNTAX));
  2397. popstackmark(&smark);
  2398. #else
  2399. putprompt(prompt);
  2400. #endif
  2401. }
  2402. /* ============ The cd and pwd commands */
  2403. #define CD_PHYSICAL 1
  2404. #define CD_PRINT 2
  2405. static int
  2406. cdopt(void)
  2407. {
  2408. int flags = 0;
  2409. int i, j;
  2410. j = 'L';
  2411. while ((i = nextopt("LP")) != '\0') {
  2412. if (i != j) {
  2413. flags ^= CD_PHYSICAL;
  2414. j = i;
  2415. }
  2416. }
  2417. return flags;
  2418. }
  2419. /*
  2420. * Update curdir (the name of the current directory) in response to a
  2421. * cd command.
  2422. */
  2423. static const char *
  2424. updatepwd(const char *dir)
  2425. {
  2426. char *new;
  2427. char *p;
  2428. char *cdcomppath;
  2429. const char *lim;
  2430. cdcomppath = sstrdup(dir);
  2431. STARTSTACKSTR(new);
  2432. if (*dir != '/') {
  2433. if (curdir == nullstr)
  2434. return 0;
  2435. new = stack_putstr(curdir, new);
  2436. }
  2437. new = makestrspace(strlen(dir) + 2, new);
  2438. lim = (char *)stackblock() + 1;
  2439. if (*dir != '/') {
  2440. if (new[-1] != '/')
  2441. USTPUTC('/', new);
  2442. if (new > lim && *lim == '/')
  2443. lim++;
  2444. } else {
  2445. USTPUTC('/', new);
  2446. cdcomppath++;
  2447. if (dir[1] == '/' && dir[2] != '/') {
  2448. USTPUTC('/', new);
  2449. cdcomppath++;
  2450. lim++;
  2451. }
  2452. }
  2453. p = strtok(cdcomppath, "/");
  2454. while (p) {
  2455. switch (*p) {
  2456. case '.':
  2457. if (p[1] == '.' && p[2] == '\0') {
  2458. while (new > lim) {
  2459. STUNPUTC(new);
  2460. if (new[-1] == '/')
  2461. break;
  2462. }
  2463. break;
  2464. }
  2465. if (p[1] == '\0')
  2466. break;
  2467. /* fall through */
  2468. default:
  2469. new = stack_putstr(p, new);
  2470. USTPUTC('/', new);
  2471. }
  2472. p = strtok(NULL, "/");
  2473. }
  2474. if (new > lim)
  2475. STUNPUTC(new);
  2476. *new = 0;
  2477. return stackblock();
  2478. }
  2479. /*
  2480. * Find out what the current directory is. If we already know the current
  2481. * directory, this routine returns immediately.
  2482. */
  2483. static char *
  2484. getpwd(void)
  2485. {
  2486. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2487. return dir ? dir : nullstr;
  2488. }
  2489. static void
  2490. setpwd(const char *val, int setold)
  2491. {
  2492. char *oldcur, *dir;
  2493. oldcur = dir = curdir;
  2494. if (setold) {
  2495. setvar("OLDPWD", oldcur, VEXPORT);
  2496. }
  2497. INT_OFF;
  2498. if (physdir != nullstr) {
  2499. if (physdir != oldcur)
  2500. free(physdir);
  2501. physdir = nullstr;
  2502. }
  2503. if (oldcur == val || !val) {
  2504. char *s = getpwd();
  2505. physdir = s;
  2506. if (!val)
  2507. dir = s;
  2508. } else
  2509. dir = ckstrdup(val);
  2510. if (oldcur != dir && oldcur != nullstr) {
  2511. free(oldcur);
  2512. }
  2513. curdir = dir;
  2514. INT_ON;
  2515. setvar("PWD", dir, VEXPORT);
  2516. }
  2517. static void hashcd(void);
  2518. /*
  2519. * Actually do the chdir. We also call hashcd to let other routines
  2520. * know that the current directory has changed.
  2521. */
  2522. static int
  2523. docd(const char *dest, int flags)
  2524. {
  2525. const char *dir = NULL;
  2526. int err;
  2527. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2528. INT_OFF;
  2529. if (!(flags & CD_PHYSICAL)) {
  2530. dir = updatepwd(dest);
  2531. if (dir)
  2532. dest = dir;
  2533. }
  2534. err = chdir(dest);
  2535. if (err)
  2536. goto out;
  2537. setpwd(dir, 1);
  2538. hashcd();
  2539. out:
  2540. INT_ON;
  2541. return err;
  2542. }
  2543. static int FAST_FUNC
  2544. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2545. {
  2546. const char *dest;
  2547. const char *path;
  2548. const char *p;
  2549. char c;
  2550. struct stat statb;
  2551. int flags;
  2552. flags = cdopt();
  2553. dest = *argptr;
  2554. if (!dest)
  2555. dest = bltinlookup("HOME");
  2556. else if (LONE_DASH(dest)) {
  2557. dest = bltinlookup("OLDPWD");
  2558. flags |= CD_PRINT;
  2559. }
  2560. if (!dest)
  2561. dest = nullstr;
  2562. if (*dest == '/')
  2563. goto step6;
  2564. if (*dest == '.') {
  2565. c = dest[1];
  2566. dotdot:
  2567. switch (c) {
  2568. case '\0':
  2569. case '/':
  2570. goto step6;
  2571. case '.':
  2572. c = dest[2];
  2573. if (c != '.')
  2574. goto dotdot;
  2575. }
  2576. }
  2577. if (!*dest)
  2578. dest = ".";
  2579. path = bltinlookup("CDPATH");
  2580. while (path) {
  2581. c = *path;
  2582. p = path_advance(&path, dest);
  2583. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2584. if (c && c != ':')
  2585. flags |= CD_PRINT;
  2586. docd:
  2587. if (!docd(p, flags))
  2588. goto out;
  2589. goto err;
  2590. }
  2591. }
  2592. step6:
  2593. p = dest;
  2594. goto docd;
  2595. err:
  2596. ash_msg_and_raise_perror("can't cd to %s", dest);
  2597. /* NOTREACHED */
  2598. out:
  2599. if (flags & CD_PRINT)
  2600. out1fmt("%s\n", curdir);
  2601. return 0;
  2602. }
  2603. static int FAST_FUNC
  2604. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2605. {
  2606. int flags;
  2607. const char *dir = curdir;
  2608. flags = cdopt();
  2609. if (flags) {
  2610. if (physdir == nullstr)
  2611. setpwd(dir, 0);
  2612. dir = physdir;
  2613. }
  2614. out1fmt("%s\n", dir);
  2615. return 0;
  2616. }
  2617. /* ============ ... */
  2618. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2619. /* Syntax classes */
  2620. #define CWORD 0 /* character is nothing special */
  2621. #define CNL 1 /* newline character */
  2622. #define CBACK 2 /* a backslash character */
  2623. #define CSQUOTE 3 /* single quote */
  2624. #define CDQUOTE 4 /* double quote */
  2625. #define CENDQUOTE 5 /* a terminating quote */
  2626. #define CBQUOTE 6 /* backwards single quote */
  2627. #define CVAR 7 /* a dollar sign */
  2628. #define CENDVAR 8 /* a '}' character */
  2629. #define CLP 9 /* a left paren in arithmetic */
  2630. #define CRP 10 /* a right paren in arithmetic */
  2631. #define CENDFILE 11 /* end of file */
  2632. #define CCTL 12 /* like CWORD, except it must be escaped */
  2633. #define CSPCL 13 /* these terminate a word */
  2634. #define CIGN 14 /* character should be ignored */
  2635. #define PEOF 256
  2636. #if ENABLE_ASH_ALIAS
  2637. # define PEOA 257
  2638. #endif
  2639. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2640. #if ENABLE_FEATURE_SH_MATH
  2641. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2642. #else
  2643. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2644. #endif
  2645. static const uint16_t S_I_T[] ALIGN2 = {
  2646. #if ENABLE_ASH_ALIAS
  2647. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2648. #endif
  2649. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2650. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2651. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2652. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2653. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2654. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2655. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2656. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2657. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2658. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2659. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2660. #if !USE_SIT_FUNCTION
  2661. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2662. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2663. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2664. #endif
  2665. #undef SIT_ITEM
  2666. };
  2667. /* Constants below must match table above */
  2668. enum {
  2669. #if ENABLE_ASH_ALIAS
  2670. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2671. #endif
  2672. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2673. CNL_CNL_CNL_CNL , /* 2 */
  2674. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2675. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2676. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2677. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2678. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2679. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2680. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2681. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2682. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2683. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2684. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2685. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2686. };
  2687. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2688. * caller must ensure proper cast on it if c is *char_ptr!
  2689. */
  2690. #if USE_SIT_FUNCTION
  2691. static int
  2692. SIT(int c, int syntax)
  2693. {
  2694. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2695. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2696. /*
  2697. * This causes '/' to be prepended with CTLESC in dquoted string,
  2698. * making "./file"* treated incorrectly because we feed
  2699. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2700. * The "homegrown" glob implementation is okay with that,
  2701. * but glibc one isn't. With '/' always treated as CWORD,
  2702. * both work fine.
  2703. */
  2704. # if ENABLE_ASH_ALIAS
  2705. static const uint8_t syntax_index_table[] ALIGN1 = {
  2706. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2707. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2708. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2709. 11, 3 /* "}~" */
  2710. };
  2711. # else
  2712. static const uint8_t syntax_index_table[] ALIGN1 = {
  2713. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2714. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2715. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2716. 10, 2 /* "}~" */
  2717. };
  2718. # endif
  2719. const char *s;
  2720. int indx;
  2721. if (c == PEOF)
  2722. return CENDFILE;
  2723. # if ENABLE_ASH_ALIAS
  2724. if (c == PEOA)
  2725. indx = 0;
  2726. else
  2727. # endif
  2728. {
  2729. /* Cast is purely for paranoia here,
  2730. * just in case someone passed signed char to us */
  2731. if ((unsigned char)c >= CTL_FIRST
  2732. && (unsigned char)c <= CTL_LAST
  2733. ) {
  2734. return CCTL;
  2735. }
  2736. s = strchrnul(spec_symbls, c);
  2737. if (*s == '\0')
  2738. return CWORD;
  2739. indx = syntax_index_table[s - spec_symbls];
  2740. }
  2741. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2742. }
  2743. #else /* !USE_SIT_FUNCTION */
  2744. static const uint8_t syntax_index_table[] ALIGN1 = {
  2745. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2746. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2747. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2748. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2749. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2750. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2751. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2752. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2753. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2755. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2756. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2757. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2758. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2759. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2760. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2761. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2762. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2763. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2764. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2765. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2766. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2767. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2768. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2769. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2770. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2771. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2779. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2780. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2781. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2783. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2785. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2786. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2787. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2788. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2789. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2792. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2793. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2794. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2806. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2807. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2808. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2809. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2810. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2811. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2831. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2832. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2833. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2835. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2836. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2837. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2838. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2839. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2840. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2841. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2842. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2843. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2844. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2872. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2873. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2874. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2877. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2878. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2879. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2880. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2881. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2882. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2883. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2884. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2897. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2899. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2902. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2903. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2904. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2905. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2906. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2922. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2923. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2924. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2925. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2926. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2927. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2928. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2929. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2930. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2931. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2932. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2933. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2934. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2935. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2936. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2937. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2967. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2968. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2969. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2970. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2971. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2972. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2973. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2974. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2975. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2976. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2977. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2978. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2979. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2980. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2981. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2982. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2983. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2984. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2985. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2986. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2987. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2988. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2989. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2990. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2991. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2992. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2993. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2994. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2995. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2996. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2997. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2998. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2999. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  3000. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  3001. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  3002. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  3003. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  3004. # if ENABLE_ASH_ALIAS
  3005. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  3006. # endif
  3007. };
  3008. #if 1
  3009. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  3010. #else /* debug version, caught one signed char bug */
  3011. # define SIT(c, syntax) \
  3012. ({ \
  3013. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  3014. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3015. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  3016. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3017. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  3018. })
  3019. #endif
  3020. #endif /* !USE_SIT_FUNCTION */
  3021. /* ============ Alias handling */
  3022. #if ENABLE_ASH_ALIAS
  3023. #define ALIASINUSE 1
  3024. #define ALIASDEAD 2
  3025. struct alias {
  3026. struct alias *next;
  3027. char *name;
  3028. char *val;
  3029. int flag;
  3030. };
  3031. static struct alias **atab; // [ATABSIZE];
  3032. #define INIT_G_alias() do { \
  3033. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  3034. } while (0)
  3035. static struct alias **
  3036. __lookupalias(const char *name)
  3037. {
  3038. unsigned int hashval;
  3039. struct alias **app;
  3040. const char *p;
  3041. unsigned int ch;
  3042. p = name;
  3043. ch = (unsigned char)*p;
  3044. hashval = ch << 4;
  3045. while (ch) {
  3046. hashval += ch;
  3047. ch = (unsigned char)*++p;
  3048. }
  3049. app = &atab[hashval % ATABSIZE];
  3050. for (; *app; app = &(*app)->next) {
  3051. if (strcmp(name, (*app)->name) == 0) {
  3052. break;
  3053. }
  3054. }
  3055. return app;
  3056. }
  3057. static struct alias *
  3058. lookupalias(const char *name, int check)
  3059. {
  3060. struct alias *ap = *__lookupalias(name);
  3061. if (check && ap && (ap->flag & ALIASINUSE))
  3062. return NULL;
  3063. return ap;
  3064. }
  3065. static struct alias *
  3066. freealias(struct alias *ap)
  3067. {
  3068. struct alias *next;
  3069. if (ap->flag & ALIASINUSE) {
  3070. ap->flag |= ALIASDEAD;
  3071. return ap;
  3072. }
  3073. next = ap->next;
  3074. free(ap->name);
  3075. free(ap->val);
  3076. free(ap);
  3077. return next;
  3078. }
  3079. static void
  3080. setalias(const char *name, const char *val)
  3081. {
  3082. struct alias *ap, **app;
  3083. app = __lookupalias(name);
  3084. ap = *app;
  3085. INT_OFF;
  3086. if (ap) {
  3087. if (!(ap->flag & ALIASINUSE)) {
  3088. free(ap->val);
  3089. }
  3090. ap->val = ckstrdup(val);
  3091. ap->flag &= ~ALIASDEAD;
  3092. } else {
  3093. /* not found */
  3094. ap = ckzalloc(sizeof(struct alias));
  3095. ap->name = ckstrdup(name);
  3096. ap->val = ckstrdup(val);
  3097. /*ap->flag = 0; - ckzalloc did it */
  3098. /*ap->next = NULL;*/
  3099. *app = ap;
  3100. }
  3101. INT_ON;
  3102. }
  3103. static int
  3104. unalias(const char *name)
  3105. {
  3106. struct alias **app;
  3107. app = __lookupalias(name);
  3108. if (*app) {
  3109. INT_OFF;
  3110. *app = freealias(*app);
  3111. INT_ON;
  3112. return 0;
  3113. }
  3114. return 1;
  3115. }
  3116. static void
  3117. rmaliases(void)
  3118. {
  3119. struct alias *ap, **app;
  3120. int i;
  3121. INT_OFF;
  3122. for (i = 0; i < ATABSIZE; i++) {
  3123. app = &atab[i];
  3124. for (ap = *app; ap; ap = *app) {
  3125. *app = freealias(*app);
  3126. if (ap == *app) {
  3127. app = &ap->next;
  3128. }
  3129. }
  3130. }
  3131. INT_ON;
  3132. }
  3133. static void
  3134. printalias(const struct alias *ap)
  3135. {
  3136. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3137. }
  3138. /*
  3139. * TODO - sort output
  3140. */
  3141. static int FAST_FUNC
  3142. aliascmd(int argc UNUSED_PARAM, char **argv)
  3143. {
  3144. char *n, *v;
  3145. int ret = 0;
  3146. struct alias *ap;
  3147. if (!argv[1]) {
  3148. int i;
  3149. for (i = 0; i < ATABSIZE; i++) {
  3150. for (ap = atab[i]; ap; ap = ap->next) {
  3151. printalias(ap);
  3152. }
  3153. }
  3154. return 0;
  3155. }
  3156. while ((n = *++argv) != NULL) {
  3157. v = strchr(n+1, '=');
  3158. if (v == NULL) { /* n+1: funny ksh stuff */
  3159. ap = *__lookupalias(n);
  3160. if (ap == NULL) {
  3161. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3162. ret = 1;
  3163. } else
  3164. printalias(ap);
  3165. } else {
  3166. *v++ = '\0';
  3167. setalias(n, v);
  3168. }
  3169. }
  3170. return ret;
  3171. }
  3172. static int FAST_FUNC
  3173. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3174. {
  3175. int i;
  3176. while (nextopt("a") != '\0') {
  3177. rmaliases();
  3178. return 0;
  3179. }
  3180. for (i = 0; *argptr; argptr++) {
  3181. if (unalias(*argptr)) {
  3182. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3183. i = 1;
  3184. }
  3185. }
  3186. return i;
  3187. }
  3188. #endif /* ASH_ALIAS */
  3189. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3190. #define FORK_FG 0
  3191. #define FORK_BG 1
  3192. #define FORK_NOJOB 2
  3193. /* mode flags for showjob(s) */
  3194. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3195. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3196. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3197. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3198. /*
  3199. * A job structure contains information about a job. A job is either a
  3200. * single process or a set of processes contained in a pipeline. In the
  3201. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3202. * array of pids.
  3203. */
  3204. struct procstat {
  3205. pid_t ps_pid; /* process id */
  3206. int ps_status; /* last process status from wait() */
  3207. char *ps_cmd; /* text of command being run */
  3208. };
  3209. struct job {
  3210. struct procstat ps0; /* status of process */
  3211. struct procstat *ps; /* status of processes when more than one */
  3212. #if JOBS
  3213. int stopstatus; /* status of a stopped job */
  3214. #endif
  3215. unsigned nprocs; /* number of processes */
  3216. #define JOBRUNNING 0 /* at least one proc running */
  3217. #define JOBSTOPPED 1 /* all procs are stopped */
  3218. #define JOBDONE 2 /* all procs are completed */
  3219. unsigned
  3220. state: 8,
  3221. #if JOBS
  3222. sigint: 1, /* job was killed by SIGINT */
  3223. jobctl: 1, /* job running under job control */
  3224. #endif
  3225. waited: 1, /* true if this entry has been waited for */
  3226. used: 1, /* true if this entry is in used */
  3227. changed: 1; /* true if status has changed */
  3228. struct job *prev_job; /* previous job */
  3229. };
  3230. static struct job *makejob(/*union node *,*/ int);
  3231. static int forkshell(struct job *, union node *, int);
  3232. static int waitforjob(struct job *);
  3233. #if !JOBS
  3234. enum { doing_jobctl = 0 };
  3235. #define setjobctl(on) do {} while (0)
  3236. #else
  3237. static smallint doing_jobctl; //references:8
  3238. static void setjobctl(int);
  3239. #endif
  3240. /*
  3241. * Ignore a signal.
  3242. */
  3243. static void
  3244. ignoresig(int signo)
  3245. {
  3246. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3247. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3248. /* No, need to do it */
  3249. signal(signo, SIG_IGN);
  3250. }
  3251. sigmode[signo - 1] = S_HARD_IGN;
  3252. }
  3253. /*
  3254. * Only one usage site - in setsignal()
  3255. */
  3256. static void
  3257. signal_handler(int signo)
  3258. {
  3259. if (signo == SIGCHLD) {
  3260. got_sigchld = 1;
  3261. if (!trap[SIGCHLD])
  3262. return;
  3263. }
  3264. gotsig[signo - 1] = 1;
  3265. pending_sig = signo;
  3266. if (signo == SIGINT && !trap[SIGINT]) {
  3267. if (!suppress_int) {
  3268. pending_sig = 0;
  3269. raise_interrupt(); /* does not return */
  3270. }
  3271. pending_int = 1;
  3272. }
  3273. }
  3274. /*
  3275. * Set the signal handler for the specified signal. The routine figures
  3276. * out what it should be set to.
  3277. */
  3278. static void
  3279. setsignal(int signo)
  3280. {
  3281. char *t;
  3282. char cur_act, new_act;
  3283. struct sigaction act;
  3284. t = trap[signo];
  3285. new_act = S_DFL;
  3286. if (t != NULL) { /* trap for this sig is set */
  3287. new_act = S_CATCH;
  3288. if (t[0] == '\0') /* trap is "": ignore this sig */
  3289. new_act = S_IGN;
  3290. }
  3291. if (rootshell && new_act == S_DFL) {
  3292. switch (signo) {
  3293. case SIGINT:
  3294. if (iflag || minusc || sflag == 0)
  3295. new_act = S_CATCH;
  3296. break;
  3297. case SIGQUIT:
  3298. #if DEBUG
  3299. if (debug)
  3300. break;
  3301. #endif
  3302. /* man bash:
  3303. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3304. * commands run by bash have signal handlers
  3305. * set to the values inherited by the shell
  3306. * from its parent". */
  3307. new_act = S_IGN;
  3308. break;
  3309. case SIGTERM:
  3310. if (iflag)
  3311. new_act = S_IGN;
  3312. break;
  3313. #if JOBS
  3314. case SIGTSTP:
  3315. case SIGTTOU:
  3316. if (mflag)
  3317. new_act = S_IGN;
  3318. break;
  3319. #endif
  3320. }
  3321. }
  3322. /* if !rootshell, we reset SIGQUIT to DFL,
  3323. * whereas we have to restore it to what shell got on entry.
  3324. * This is handled by the fact that if signal was IGNored on entry,
  3325. * then cur_act is S_HARD_IGN and we never change its sigaction
  3326. * (see code below).
  3327. */
  3328. if (signo == SIGCHLD)
  3329. new_act = S_CATCH;
  3330. t = &sigmode[signo - 1];
  3331. cur_act = *t;
  3332. if (cur_act == 0) {
  3333. /* current setting is not yet known */
  3334. if (sigaction(signo, NULL, &act)) {
  3335. /* pretend it worked; maybe we should give a warning,
  3336. * but other shells don't. We don't alter sigmode,
  3337. * so we retry every time.
  3338. * btw, in Linux it never fails. --vda */
  3339. return;
  3340. }
  3341. if (act.sa_handler == SIG_IGN) {
  3342. cur_act = S_HARD_IGN;
  3343. if (mflag
  3344. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3345. ) {
  3346. cur_act = S_IGN; /* don't hard ignore these */
  3347. }
  3348. }
  3349. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3350. /* installing SIG_DFL over SIG_DFL is a no-op */
  3351. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3352. *t = S_DFL;
  3353. return;
  3354. }
  3355. }
  3356. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3357. return;
  3358. *t = new_act;
  3359. act.sa_handler = SIG_DFL;
  3360. switch (new_act) {
  3361. case S_CATCH:
  3362. act.sa_handler = signal_handler;
  3363. break;
  3364. case S_IGN:
  3365. act.sa_handler = SIG_IGN;
  3366. break;
  3367. }
  3368. /* flags and mask matter only if !DFL and !IGN, but we do it
  3369. * for all cases for more deterministic behavior:
  3370. */
  3371. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3372. sigfillset(&act.sa_mask);
  3373. sigaction_set(signo, &act);
  3374. }
  3375. /* mode flags for set_curjob */
  3376. #define CUR_DELETE 2
  3377. #define CUR_RUNNING 1
  3378. #define CUR_STOPPED 0
  3379. #if JOBS
  3380. /* pgrp of shell on invocation */
  3381. static int initialpgrp; //references:2
  3382. static int ttyfd = -1; //5
  3383. #endif
  3384. /* array of jobs */
  3385. static struct job *jobtab; //5
  3386. /* size of array */
  3387. static unsigned njobs; //4
  3388. /* current job */
  3389. static struct job *curjob; //lots
  3390. /* number of presumed living untracked jobs */
  3391. static int jobless; //4
  3392. #if 0
  3393. /* Bash has a feature: it restores termios after a successful wait for
  3394. * a foreground job which had at least one stopped or sigkilled member.
  3395. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3396. * properly restoring tty state. Should we do this too?
  3397. * A reproducer: ^Z an interactive python:
  3398. *
  3399. * # python
  3400. * Python 2.7.12 (...)
  3401. * >>> ^Z
  3402. * { python leaves tty in -icanon -echo state. We do survive that... }
  3403. * [1]+ Stopped python
  3404. * { ...however, next program (python #2) does not survive it well: }
  3405. * # python
  3406. * Python 2.7.12 (...)
  3407. * >>> Traceback (most recent call last):
  3408. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3409. * File "<stdin>", line 1, in <module>
  3410. * NameError: name 'qwerty' is not defined
  3411. *
  3412. * The implementation below is modeled on bash code and seems to work.
  3413. * However, I'm not sure we should do this. For one: what if I'd fg
  3414. * the stopped python instead? It'll be confused by "restored" tty state.
  3415. */
  3416. static struct termios shell_tty_info;
  3417. static void
  3418. get_tty_state(void)
  3419. {
  3420. if (rootshell && ttyfd >= 0)
  3421. tcgetattr(ttyfd, &shell_tty_info);
  3422. }
  3423. static void
  3424. set_tty_state(void)
  3425. {
  3426. /* if (rootshell) - caller ensures this */
  3427. if (ttyfd >= 0)
  3428. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3429. }
  3430. static int
  3431. job_signal_status(struct job *jp)
  3432. {
  3433. int status;
  3434. unsigned i;
  3435. struct procstat *ps = jp->ps;
  3436. for (i = 0; i < jp->nprocs; i++) {
  3437. status = ps[i].ps_status;
  3438. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3439. return status;
  3440. }
  3441. return 0;
  3442. }
  3443. static void
  3444. restore_tty_if_stopped_or_signaled(struct job *jp)
  3445. {
  3446. //TODO: check what happens if we come from waitforjob() in expbackq()
  3447. if (rootshell) {
  3448. int s = job_signal_status(jp);
  3449. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3450. set_tty_state();
  3451. }
  3452. }
  3453. #else
  3454. # define get_tty_state() ((void)0)
  3455. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3456. #endif
  3457. static void
  3458. set_curjob(struct job *jp, unsigned mode)
  3459. {
  3460. struct job *jp1;
  3461. struct job **jpp, **curp;
  3462. /* first remove from list */
  3463. jpp = curp = &curjob;
  3464. while (1) {
  3465. jp1 = *jpp;
  3466. if (jp1 == jp)
  3467. break;
  3468. jpp = &jp1->prev_job;
  3469. }
  3470. *jpp = jp1->prev_job;
  3471. /* Then re-insert in correct position */
  3472. jpp = curp;
  3473. switch (mode) {
  3474. default:
  3475. #if DEBUG
  3476. abort();
  3477. #endif
  3478. case CUR_DELETE:
  3479. /* job being deleted */
  3480. break;
  3481. case CUR_RUNNING:
  3482. /* newly created job or backgrounded job,
  3483. * put after all stopped jobs.
  3484. */
  3485. while (1) {
  3486. jp1 = *jpp;
  3487. #if JOBS
  3488. if (!jp1 || jp1->state != JOBSTOPPED)
  3489. #endif
  3490. break;
  3491. jpp = &jp1->prev_job;
  3492. }
  3493. /* FALLTHROUGH */
  3494. #if JOBS
  3495. case CUR_STOPPED:
  3496. #endif
  3497. /* newly stopped job - becomes curjob */
  3498. jp->prev_job = *jpp;
  3499. *jpp = jp;
  3500. break;
  3501. }
  3502. }
  3503. #if JOBS || DEBUG
  3504. static int
  3505. jobno(const struct job *jp)
  3506. {
  3507. return jp - jobtab + 1;
  3508. }
  3509. #endif
  3510. /*
  3511. * Convert a job name to a job structure.
  3512. */
  3513. #if !JOBS
  3514. #define getjob(name, getctl) getjob(name)
  3515. #endif
  3516. static struct job *
  3517. getjob(const char *name, int getctl)
  3518. {
  3519. struct job *jp;
  3520. struct job *found;
  3521. const char *err_msg = "%s: no such job";
  3522. unsigned num;
  3523. int c;
  3524. const char *p;
  3525. char *(*match)(const char *, const char *);
  3526. jp = curjob;
  3527. p = name;
  3528. if (!p)
  3529. goto currentjob;
  3530. if (*p != '%')
  3531. goto err;
  3532. c = *++p;
  3533. if (!c)
  3534. goto currentjob;
  3535. if (!p[1]) {
  3536. if (c == '+' || c == '%') {
  3537. currentjob:
  3538. err_msg = "No current job";
  3539. goto check;
  3540. }
  3541. if (c == '-') {
  3542. if (jp)
  3543. jp = jp->prev_job;
  3544. err_msg = "No previous job";
  3545. check:
  3546. if (!jp)
  3547. goto err;
  3548. goto gotit;
  3549. }
  3550. }
  3551. if (is_number(p)) {
  3552. num = atoi(p);
  3553. if (num > 0 && num <= njobs) {
  3554. jp = jobtab + num - 1;
  3555. if (jp->used)
  3556. goto gotit;
  3557. goto err;
  3558. }
  3559. }
  3560. match = prefix;
  3561. if (*p == '?') {
  3562. match = strstr;
  3563. p++;
  3564. }
  3565. found = NULL;
  3566. while (jp) {
  3567. if (match(jp->ps[0].ps_cmd, p)) {
  3568. if (found)
  3569. goto err;
  3570. found = jp;
  3571. err_msg = "%s: ambiguous";
  3572. }
  3573. jp = jp->prev_job;
  3574. }
  3575. if (!found)
  3576. goto err;
  3577. jp = found;
  3578. gotit:
  3579. #if JOBS
  3580. err_msg = "job %s not created under job control";
  3581. if (getctl && jp->jobctl == 0)
  3582. goto err;
  3583. #endif
  3584. return jp;
  3585. err:
  3586. ash_msg_and_raise_error(err_msg, name);
  3587. }
  3588. /*
  3589. * Mark a job structure as unused.
  3590. */
  3591. static void
  3592. freejob(struct job *jp)
  3593. {
  3594. struct procstat *ps;
  3595. int i;
  3596. INT_OFF;
  3597. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3598. if (ps->ps_cmd != nullstr)
  3599. free(ps->ps_cmd);
  3600. }
  3601. if (jp->ps != &jp->ps0)
  3602. free(jp->ps);
  3603. jp->used = 0;
  3604. set_curjob(jp, CUR_DELETE);
  3605. INT_ON;
  3606. }
  3607. #if JOBS
  3608. static void
  3609. xtcsetpgrp(int fd, pid_t pgrp)
  3610. {
  3611. if (tcsetpgrp(fd, pgrp))
  3612. ash_msg_and_raise_perror("can't set tty process group");
  3613. }
  3614. /*
  3615. * Turn job control on and off.
  3616. *
  3617. * Note: This code assumes that the third arg to ioctl is a character
  3618. * pointer, which is true on Berkeley systems but not System V. Since
  3619. * System V doesn't have job control yet, this isn't a problem now.
  3620. *
  3621. * Called with interrupts off.
  3622. */
  3623. static void
  3624. setjobctl(int on)
  3625. {
  3626. int fd;
  3627. int pgrp;
  3628. if (on == doing_jobctl || rootshell == 0)
  3629. return;
  3630. if (on) {
  3631. int ofd;
  3632. ofd = fd = open(_PATH_TTY, O_RDWR);
  3633. if (fd < 0) {
  3634. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3635. * That sometimes helps to acquire controlling tty.
  3636. * Obviously, a workaround for bugs when someone
  3637. * failed to provide a controlling tty to bash! :) */
  3638. fd = 2;
  3639. while (!isatty(fd))
  3640. if (--fd < 0)
  3641. goto out;
  3642. }
  3643. /* fd is a tty at this point */
  3644. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3645. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3646. close(ofd);
  3647. if (fd < 0)
  3648. goto out; /* F_DUPFD failed */
  3649. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3650. close_on_exec_on(fd);
  3651. while (1) { /* while we are in the background */
  3652. pgrp = tcgetpgrp(fd);
  3653. if (pgrp < 0) {
  3654. out:
  3655. ash_msg("can't access tty; job control turned off");
  3656. mflag = on = 0;
  3657. goto close;
  3658. }
  3659. if (pgrp == getpgrp())
  3660. break;
  3661. killpg(0, SIGTTIN);
  3662. }
  3663. initialpgrp = pgrp;
  3664. setsignal(SIGTSTP);
  3665. setsignal(SIGTTOU);
  3666. setsignal(SIGTTIN);
  3667. pgrp = rootpid;
  3668. setpgid(0, pgrp);
  3669. xtcsetpgrp(fd, pgrp);
  3670. } else {
  3671. /* turning job control off */
  3672. fd = ttyfd;
  3673. pgrp = initialpgrp;
  3674. /* was xtcsetpgrp, but this can make exiting ash
  3675. * loop forever if pty is already deleted */
  3676. tcsetpgrp(fd, pgrp);
  3677. setpgid(0, pgrp);
  3678. setsignal(SIGTSTP);
  3679. setsignal(SIGTTOU);
  3680. setsignal(SIGTTIN);
  3681. close:
  3682. if (fd >= 0)
  3683. close(fd);
  3684. fd = -1;
  3685. }
  3686. ttyfd = fd;
  3687. doing_jobctl = on;
  3688. }
  3689. static int FAST_FUNC
  3690. killcmd(int argc, char **argv)
  3691. {
  3692. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3693. int i = 1;
  3694. do {
  3695. if (argv[i][0] == '%') {
  3696. /*
  3697. * "kill %N" - job kill
  3698. * Converting to pgrp / pid kill
  3699. */
  3700. struct job *jp;
  3701. char *dst;
  3702. int j, n;
  3703. jp = getjob(argv[i], 0);
  3704. /*
  3705. * In jobs started under job control, we signal
  3706. * entire process group by kill -PGRP_ID.
  3707. * This happens, f.e., in interactive shell.
  3708. *
  3709. * Otherwise, we signal each child via
  3710. * kill PID1 PID2 PID3.
  3711. * Testcases:
  3712. * sh -c 'sleep 1|sleep 1 & kill %1'
  3713. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3714. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3715. */
  3716. n = jp->nprocs; /* can't be 0 (I hope) */
  3717. if (jp->jobctl)
  3718. n = 1;
  3719. dst = alloca(n * sizeof(int)*4);
  3720. argv[i] = dst;
  3721. for (j = 0; j < n; j++) {
  3722. struct procstat *ps = &jp->ps[j];
  3723. /* Skip non-running and not-stopped members
  3724. * (i.e. dead members) of the job
  3725. */
  3726. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3727. continue;
  3728. /*
  3729. * kill_main has matching code to expect
  3730. * leading space. Needed to not confuse
  3731. * negative pids with "kill -SIGNAL_NO" syntax
  3732. */
  3733. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3734. }
  3735. *dst = '\0';
  3736. }
  3737. } while (argv[++i]);
  3738. }
  3739. return kill_main(argc, argv);
  3740. }
  3741. static void
  3742. showpipe(struct job *jp /*, FILE *out*/)
  3743. {
  3744. struct procstat *ps;
  3745. struct procstat *psend;
  3746. psend = jp->ps + jp->nprocs;
  3747. for (ps = jp->ps + 1; ps < psend; ps++)
  3748. printf(" | %s", ps->ps_cmd);
  3749. newline_and_flush(stdout);
  3750. flush_stdout_stderr();
  3751. }
  3752. static int
  3753. restartjob(struct job *jp, int mode)
  3754. {
  3755. struct procstat *ps;
  3756. int i;
  3757. int status;
  3758. pid_t pgid;
  3759. INT_OFF;
  3760. if (jp->state == JOBDONE)
  3761. goto out;
  3762. jp->state = JOBRUNNING;
  3763. pgid = jp->ps[0].ps_pid;
  3764. if (mode == FORK_FG) {
  3765. get_tty_state();
  3766. xtcsetpgrp(ttyfd, pgid);
  3767. }
  3768. killpg(pgid, SIGCONT);
  3769. ps = jp->ps;
  3770. i = jp->nprocs;
  3771. do {
  3772. if (WIFSTOPPED(ps->ps_status)) {
  3773. ps->ps_status = -1;
  3774. }
  3775. ps++;
  3776. } while (--i);
  3777. out:
  3778. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3779. INT_ON;
  3780. return status;
  3781. }
  3782. static int FAST_FUNC
  3783. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3784. {
  3785. struct job *jp;
  3786. int mode;
  3787. int retval;
  3788. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3789. nextopt(nullstr);
  3790. argv = argptr;
  3791. do {
  3792. jp = getjob(*argv, 1);
  3793. if (mode == FORK_BG) {
  3794. set_curjob(jp, CUR_RUNNING);
  3795. printf("[%d] ", jobno(jp));
  3796. }
  3797. out1str(jp->ps[0].ps_cmd);
  3798. showpipe(jp /*, stdout*/);
  3799. retval = restartjob(jp, mode);
  3800. } while (*argv && *++argv);
  3801. return retval;
  3802. }
  3803. #endif
  3804. static int
  3805. sprint_status48(char *s, int status, int sigonly)
  3806. {
  3807. int col;
  3808. int st;
  3809. col = 0;
  3810. if (!WIFEXITED(status)) {
  3811. #if JOBS
  3812. if (WIFSTOPPED(status))
  3813. st = WSTOPSIG(status);
  3814. else
  3815. #endif
  3816. st = WTERMSIG(status);
  3817. if (sigonly) {
  3818. if (st == SIGINT || st == SIGPIPE)
  3819. goto out;
  3820. #if JOBS
  3821. if (WIFSTOPPED(status))
  3822. goto out;
  3823. #endif
  3824. }
  3825. st &= 0x7f;
  3826. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3827. col = fmtstr(s, 32, strsignal(st));
  3828. if (WCOREDUMP(status)) {
  3829. strcpy(s + col, " (core dumped)");
  3830. col += sizeof(" (core dumped)")-1;
  3831. }
  3832. } else if (!sigonly) {
  3833. st = WEXITSTATUS(status);
  3834. col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3835. }
  3836. out:
  3837. return col;
  3838. }
  3839. static int
  3840. wait_block_or_sig(int *status)
  3841. {
  3842. int pid;
  3843. do {
  3844. sigset_t mask;
  3845. /* Poll all children for changes in their state */
  3846. got_sigchld = 0;
  3847. /* if job control is active, accept stopped processes too */
  3848. pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
  3849. if (pid != 0)
  3850. break; /* Error (e.g. EINTR, ECHILD) or pid */
  3851. /* Children exist, but none are ready. Sleep until interesting signal */
  3852. #if 1
  3853. sigfillset(&mask);
  3854. sigprocmask2(SIG_SETMASK, &mask); /* mask is updated */
  3855. while (!got_sigchld && !pending_sig)
  3856. sigsuspend(&mask);
  3857. sigprocmask(SIG_SETMASK, &mask, NULL);
  3858. #else /* unsafe: a signal can set pending_sig after check, but before pause() */
  3859. while (!got_sigchld && !pending_sig)
  3860. pause();
  3861. #endif
  3862. /* If it was SIGCHLD, poll children again */
  3863. } while (got_sigchld);
  3864. return pid;
  3865. }
  3866. #define DOWAIT_NONBLOCK 0
  3867. #define DOWAIT_BLOCK 1
  3868. #define DOWAIT_BLOCK_OR_SIG 2
  3869. #if BASH_WAIT_N
  3870. # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
  3871. #endif
  3872. static int
  3873. dowait(int block, struct job *job)
  3874. {
  3875. int pid;
  3876. int status;
  3877. struct job *jp;
  3878. struct job *thisjob;
  3879. #if BASH_WAIT_N
  3880. bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
  3881. block = (block & ~DOWAIT_JOBSTATUS);
  3882. #endif
  3883. TRACE(("dowait(0x%x) called\n", block));
  3884. /* It's wrong to call waitpid() outside of INT_OFF region:
  3885. * signal can arrive just after syscall return and handler can
  3886. * longjmp away, losing stop/exit notification processing.
  3887. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3888. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3889. *
  3890. * However, for "wait" builtin it is wrong to simply call waitpid()
  3891. * in INT_OFF region: "wait" needs to wait for any running job
  3892. * to change state, but should exit on any trap too.
  3893. * In INT_OFF region, a signal just before syscall entry can set
  3894. * pending_sig variables, but we can't check them, and we would
  3895. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3896. *
  3897. * Because of this, we run inside INT_OFF, but use a special routine
  3898. * which combines waitpid() and sigsuspend().
  3899. * This is the reason why we need to have a handler for SIGCHLD:
  3900. * SIG_DFL handler does not wake sigsuspend().
  3901. */
  3902. INT_OFF;
  3903. if (block == DOWAIT_BLOCK_OR_SIG) {
  3904. pid = wait_block_or_sig(&status);
  3905. } else {
  3906. int wait_flags = 0;
  3907. if (block == DOWAIT_NONBLOCK)
  3908. wait_flags = WNOHANG;
  3909. /* if job control is active, accept stopped processes too */
  3910. if (doing_jobctl)
  3911. wait_flags |= WUNTRACED;
  3912. /* NB: _not_ safe_waitpid, we need to detect EINTR */
  3913. pid = waitpid(-1, &status, wait_flags);
  3914. }
  3915. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3916. pid, status, errno, strerror(errno)));
  3917. thisjob = NULL;
  3918. if (pid <= 0)
  3919. goto out;
  3920. for (jp = curjob; jp; jp = jp->prev_job) {
  3921. int jobstate;
  3922. struct procstat *ps;
  3923. struct procstat *psend;
  3924. if (jp->state == JOBDONE)
  3925. continue;
  3926. jobstate = JOBDONE;
  3927. ps = jp->ps;
  3928. psend = ps + jp->nprocs;
  3929. do {
  3930. if (ps->ps_pid == pid) {
  3931. TRACE(("Job %d: changing status of proc %d "
  3932. "from 0x%x to 0x%x\n",
  3933. jobno(jp), pid, ps->ps_status, status));
  3934. ps->ps_status = status;
  3935. thisjob = jp;
  3936. }
  3937. if (ps->ps_status == -1)
  3938. jobstate = JOBRUNNING;
  3939. #if JOBS
  3940. if (jobstate == JOBRUNNING)
  3941. continue;
  3942. if (WIFSTOPPED(ps->ps_status)) {
  3943. jp->stopstatus = ps->ps_status;
  3944. jobstate = JOBSTOPPED;
  3945. }
  3946. #endif
  3947. } while (++ps < psend);
  3948. if (!thisjob)
  3949. continue;
  3950. /* Found the job where one of its processes changed its state.
  3951. * Is there at least one live and running process in this job? */
  3952. if (jobstate != JOBRUNNING) {
  3953. /* No. All live processes in the job are stopped
  3954. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3955. */
  3956. thisjob->changed = 1;
  3957. if (thisjob->state != jobstate) {
  3958. TRACE(("Job %d: changing state from %d to %d\n",
  3959. jobno(thisjob), thisjob->state, jobstate));
  3960. thisjob->state = jobstate;
  3961. #if JOBS
  3962. if (jobstate == JOBSTOPPED)
  3963. set_curjob(thisjob, CUR_STOPPED);
  3964. #endif
  3965. }
  3966. }
  3967. goto out;
  3968. }
  3969. /* The process wasn't found in job list */
  3970. #if JOBS
  3971. if (!WIFSTOPPED(status))
  3972. jobless--;
  3973. #endif
  3974. out:
  3975. INT_ON;
  3976. #if BASH_WAIT_N
  3977. if (want_jobexitstatus) {
  3978. pid = -1;
  3979. if (thisjob && thisjob->state == JOBDONE)
  3980. pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
  3981. }
  3982. #endif
  3983. if (thisjob && thisjob == job) {
  3984. char s[48 + 1];
  3985. int len;
  3986. len = sprint_status48(s, status, 1);
  3987. if (len) {
  3988. s[len] = '\n';
  3989. s[len + 1] = '\0';
  3990. out2str(s);
  3991. }
  3992. }
  3993. return pid;
  3994. }
  3995. #if JOBS
  3996. static void
  3997. showjob(struct job *jp, int mode)
  3998. {
  3999. struct procstat *ps;
  4000. struct procstat *psend;
  4001. int col;
  4002. int indent_col;
  4003. char s[16 + 16 + 48];
  4004. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  4005. ps = jp->ps;
  4006. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  4007. /* just output process (group) id of pipeline */
  4008. fprintf(out, "%d\n", ps->ps_pid);
  4009. return;
  4010. }
  4011. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  4012. indent_col = col;
  4013. if (jp == curjob)
  4014. s[col - 3] = '+';
  4015. else if (curjob && jp == curjob->prev_job)
  4016. s[col - 3] = '-';
  4017. if (mode & SHOW_PIDS)
  4018. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  4019. psend = ps + jp->nprocs;
  4020. if (jp->state == JOBRUNNING) {
  4021. strcpy(s + col, "Running");
  4022. col += sizeof("Running") - 1;
  4023. } else {
  4024. int status = psend[-1].ps_status;
  4025. if (jp->state == JOBSTOPPED)
  4026. status = jp->stopstatus;
  4027. col += sprint_status48(s + col, status, 0);
  4028. }
  4029. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  4030. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  4031. * or prints several "PID | <cmdN>" lines,
  4032. * depending on SHOW_PIDS bit.
  4033. * We do not print status of individual processes
  4034. * between PID and <cmdN>. bash does it, but not very well:
  4035. * first line shows overall job status, not process status,
  4036. * making it impossible to know 1st process status.
  4037. */
  4038. goto start;
  4039. do {
  4040. /* for each process */
  4041. s[0] = '\0';
  4042. col = 33;
  4043. if (mode & SHOW_PIDS)
  4044. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  4045. start:
  4046. fprintf(out, "%s%*c%s%s",
  4047. s,
  4048. 33 - col >= 0 ? 33 - col : 0, ' ',
  4049. ps == jp->ps ? "" : "| ",
  4050. ps->ps_cmd
  4051. );
  4052. } while (++ps != psend);
  4053. newline_and_flush(out);
  4054. jp->changed = 0;
  4055. if (jp->state == JOBDONE) {
  4056. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4057. freejob(jp);
  4058. }
  4059. }
  4060. /*
  4061. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4062. * statuses have changed since the last call to showjobs.
  4063. */
  4064. static void
  4065. showjobs(int mode)
  4066. {
  4067. struct job *jp;
  4068. TRACE(("showjobs(0x%x) called\n", mode));
  4069. /* Handle all finished jobs */
  4070. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4071. continue;
  4072. for (jp = curjob; jp; jp = jp->prev_job) {
  4073. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4074. showjob(jp, mode);
  4075. }
  4076. }
  4077. }
  4078. static int FAST_FUNC
  4079. jobscmd(int argc UNUSED_PARAM, char **argv)
  4080. {
  4081. int mode, m;
  4082. mode = 0;
  4083. while ((m = nextopt("lp")) != '\0') {
  4084. if (m == 'l')
  4085. mode |= SHOW_PIDS;
  4086. else
  4087. mode |= SHOW_ONLY_PGID;
  4088. }
  4089. argv = argptr;
  4090. if (*argv) {
  4091. do
  4092. showjob(getjob(*argv, 0), mode);
  4093. while (*++argv);
  4094. } else {
  4095. showjobs(mode);
  4096. }
  4097. return 0;
  4098. }
  4099. #endif /* JOBS */
  4100. /* Called only on finished or stopped jobs (no members are running) */
  4101. static int
  4102. getstatus(struct job *job)
  4103. {
  4104. int status;
  4105. int retval;
  4106. struct procstat *ps;
  4107. /* Fetch last member's status */
  4108. ps = job->ps + job->nprocs - 1;
  4109. status = ps->ps_status;
  4110. if (pipefail) {
  4111. /* "set -o pipefail" mode: use last _nonzero_ status */
  4112. while (status == 0 && --ps >= job->ps)
  4113. status = ps->ps_status;
  4114. }
  4115. retval = WEXITSTATUS(status);
  4116. if (!WIFEXITED(status)) {
  4117. #if JOBS
  4118. retval = WSTOPSIG(status);
  4119. if (!WIFSTOPPED(status))
  4120. #endif
  4121. {
  4122. /* XXX: limits number of signals */
  4123. retval = WTERMSIG(status);
  4124. #if JOBS
  4125. if (retval == SIGINT)
  4126. job->sigint = 1;
  4127. #endif
  4128. }
  4129. retval += 128;
  4130. }
  4131. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4132. jobno(job), job->nprocs, status, retval));
  4133. return retval;
  4134. }
  4135. static int FAST_FUNC
  4136. waitcmd(int argc UNUSED_PARAM, char **argv)
  4137. {
  4138. struct job *job;
  4139. int retval;
  4140. struct job *jp;
  4141. #if BASH_WAIT_N
  4142. int status;
  4143. char one = nextopt("n");
  4144. #else
  4145. nextopt(nullstr);
  4146. #endif
  4147. retval = 0;
  4148. argv = argptr;
  4149. if (!argv[0]) {
  4150. /* wait for all jobs / one job if -n */
  4151. for (;;) {
  4152. jp = curjob;
  4153. #if BASH_WAIT_N
  4154. if (one && !jp)
  4155. /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
  4156. retval = 127;
  4157. #endif
  4158. while (1) {
  4159. if (!jp) /* no running procs */
  4160. goto ret;
  4161. if (jp->state == JOBRUNNING)
  4162. break;
  4163. jp->waited = 1;
  4164. jp = jp->prev_job;
  4165. }
  4166. /* man bash:
  4167. * "When bash is waiting for an asynchronous command via
  4168. * the wait builtin, the reception of a signal for which a trap
  4169. * has been set will cause the wait builtin to return immediately
  4170. * with an exit status greater than 128, immediately after which
  4171. * the trap is executed."
  4172. */
  4173. #if BASH_WAIT_N
  4174. status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
  4175. #else
  4176. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4177. #endif
  4178. /* if child sends us a signal *and immediately exits*,
  4179. * dowait() returns pid > 0. Check this case,
  4180. * not "if (dowait() < 0)"!
  4181. */
  4182. if (pending_sig)
  4183. goto sigout;
  4184. #if BASH_WAIT_N
  4185. if (one) {
  4186. /* wait -n waits for one _job_, not one _process_.
  4187. * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
  4188. * should wait for 2 seconds. Not 1 or 3.
  4189. */
  4190. if (status != -1 && !WIFSTOPPED(status)) {
  4191. retval = WEXITSTATUS(status);
  4192. if (WIFSIGNALED(status))
  4193. retval = WTERMSIG(status) + 128;
  4194. goto ret;
  4195. }
  4196. }
  4197. #endif
  4198. }
  4199. }
  4200. retval = 127;
  4201. do {
  4202. if (**argv != '%') {
  4203. pid_t pid = number(*argv);
  4204. job = curjob;
  4205. while (1) {
  4206. if (!job)
  4207. goto repeat;
  4208. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4209. break;
  4210. job = job->prev_job;
  4211. }
  4212. } else {
  4213. job = getjob(*argv, 0);
  4214. }
  4215. /* loop until process terminated or stopped */
  4216. while (job->state == JOBRUNNING) {
  4217. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4218. if (pending_sig)
  4219. goto sigout;
  4220. }
  4221. job->waited = 1;
  4222. retval = getstatus(job);
  4223. repeat: ;
  4224. } while (*++argv);
  4225. ret:
  4226. return retval;
  4227. sigout:
  4228. retval = 128 + pending_sig;
  4229. return retval;
  4230. }
  4231. static struct job *
  4232. growjobtab(void)
  4233. {
  4234. size_t len;
  4235. ptrdiff_t offset;
  4236. struct job *jp, *jq;
  4237. len = njobs * sizeof(*jp);
  4238. jq = jobtab;
  4239. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4240. offset = (char *)jp - (char *)jq;
  4241. if (offset) {
  4242. /* Relocate pointers */
  4243. size_t l = len;
  4244. jq = (struct job *)((char *)jq + l);
  4245. while (l) {
  4246. l -= sizeof(*jp);
  4247. jq--;
  4248. #define joff(p) ((struct job *)((char *)(p) + l))
  4249. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4250. if (joff(jp)->ps == &jq->ps0)
  4251. jmove(joff(jp)->ps);
  4252. if (joff(jp)->prev_job)
  4253. jmove(joff(jp)->prev_job);
  4254. }
  4255. if (curjob)
  4256. jmove(curjob);
  4257. #undef joff
  4258. #undef jmove
  4259. }
  4260. njobs += 4;
  4261. jobtab = jp;
  4262. jp = (struct job *)((char *)jp + len);
  4263. jq = jp + 3;
  4264. do {
  4265. jq->used = 0;
  4266. } while (--jq >= jp);
  4267. return jp;
  4268. }
  4269. /*
  4270. * Return a new job structure.
  4271. * Called with interrupts off.
  4272. */
  4273. static struct job *
  4274. makejob(/*union node *node,*/ int nprocs)
  4275. {
  4276. int i;
  4277. struct job *jp;
  4278. for (i = njobs, jp = jobtab; ; jp++) {
  4279. if (--i < 0) {
  4280. jp = growjobtab();
  4281. break;
  4282. }
  4283. if (jp->used == 0)
  4284. break;
  4285. if (jp->state != JOBDONE || !jp->waited)
  4286. continue;
  4287. #if JOBS
  4288. if (doing_jobctl)
  4289. continue;
  4290. #endif
  4291. freejob(jp);
  4292. break;
  4293. }
  4294. memset(jp, 0, sizeof(*jp));
  4295. #if JOBS
  4296. /* jp->jobctl is a bitfield.
  4297. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4298. if (doing_jobctl)
  4299. jp->jobctl = 1;
  4300. #endif
  4301. jp->prev_job = curjob;
  4302. curjob = jp;
  4303. jp->used = 1;
  4304. jp->ps = &jp->ps0;
  4305. if (nprocs > 1) {
  4306. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4307. }
  4308. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4309. jobno(jp)));
  4310. return jp;
  4311. }
  4312. #if JOBS
  4313. /*
  4314. * Return a string identifying a command (to be printed by the
  4315. * jobs command).
  4316. */
  4317. static char *cmdnextc;
  4318. static void
  4319. cmdputs(const char *s)
  4320. {
  4321. static const char vstype[VSTYPE + 1][3] = {
  4322. "", "}", "-", "+", "?", "=",
  4323. "%", "%%", "#", "##"
  4324. IF_BASH_SUBSTR(, ":")
  4325. IF_BASH_PATTERN_SUBST(, "/", "//")
  4326. };
  4327. const char *p, *str;
  4328. char cc[2];
  4329. char *nextc;
  4330. unsigned char c;
  4331. unsigned char subtype = 0;
  4332. int quoted = 0;
  4333. cc[1] = '\0';
  4334. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4335. p = s;
  4336. while ((c = *p++) != '\0') {
  4337. str = NULL;
  4338. switch (c) {
  4339. case CTLESC:
  4340. c = *p++;
  4341. break;
  4342. case CTLVAR:
  4343. subtype = *p++;
  4344. if ((subtype & VSTYPE) == VSLENGTH)
  4345. str = "${#";
  4346. else
  4347. str = "${";
  4348. goto dostr;
  4349. case CTLENDVAR:
  4350. str = "\"}" + !(quoted & 1);
  4351. quoted >>= 1;
  4352. subtype = 0;
  4353. goto dostr;
  4354. case CTLBACKQ:
  4355. str = "$(...)";
  4356. goto dostr;
  4357. #if ENABLE_FEATURE_SH_MATH
  4358. case CTLARI:
  4359. str = "$((";
  4360. goto dostr;
  4361. case CTLENDARI:
  4362. str = "))";
  4363. goto dostr;
  4364. #endif
  4365. case CTLQUOTEMARK:
  4366. quoted ^= 1;
  4367. c = '"';
  4368. break;
  4369. case '=':
  4370. if (subtype == 0)
  4371. break;
  4372. if ((subtype & VSTYPE) != VSNORMAL)
  4373. quoted <<= 1;
  4374. str = vstype[subtype & VSTYPE];
  4375. if (subtype & VSNUL)
  4376. c = ':';
  4377. else
  4378. goto checkstr;
  4379. break;
  4380. case '\'':
  4381. case '\\':
  4382. case '"':
  4383. case '$':
  4384. /* These can only happen inside quotes */
  4385. cc[0] = c;
  4386. str = cc;
  4387. //FIXME:
  4388. // $ true $$ &
  4389. // $ <cr>
  4390. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4391. c = '\\';
  4392. break;
  4393. default:
  4394. break;
  4395. }
  4396. USTPUTC(c, nextc);
  4397. checkstr:
  4398. if (!str)
  4399. continue;
  4400. dostr:
  4401. while ((c = *str++) != '\0') {
  4402. USTPUTC(c, nextc);
  4403. }
  4404. } /* while *p++ not NUL */
  4405. if (quoted & 1) {
  4406. USTPUTC('"', nextc);
  4407. }
  4408. *nextc = 0;
  4409. cmdnextc = nextc;
  4410. }
  4411. /* cmdtxt() and cmdlist() call each other */
  4412. static void cmdtxt(union node *n);
  4413. static void
  4414. cmdlist(union node *np, int sep)
  4415. {
  4416. for (; np; np = np->narg.next) {
  4417. if (!sep)
  4418. cmdputs(" ");
  4419. cmdtxt(np);
  4420. if (sep && np->narg.next)
  4421. cmdputs(" ");
  4422. }
  4423. }
  4424. static void
  4425. cmdtxt(union node *n)
  4426. {
  4427. union node *np;
  4428. struct nodelist *lp;
  4429. const char *p;
  4430. if (!n)
  4431. return;
  4432. switch (n->type) {
  4433. default:
  4434. #if DEBUG
  4435. abort();
  4436. #endif
  4437. case NPIPE:
  4438. lp = n->npipe.cmdlist;
  4439. for (;;) {
  4440. cmdtxt(lp->n);
  4441. lp = lp->next;
  4442. if (!lp)
  4443. break;
  4444. cmdputs(" | ");
  4445. }
  4446. break;
  4447. case NSEMI:
  4448. p = "; ";
  4449. goto binop;
  4450. case NAND:
  4451. p = " && ";
  4452. goto binop;
  4453. case NOR:
  4454. p = " || ";
  4455. binop:
  4456. cmdtxt(n->nbinary.ch1);
  4457. cmdputs(p);
  4458. n = n->nbinary.ch2;
  4459. goto donode;
  4460. case NREDIR:
  4461. case NBACKGND:
  4462. n = n->nredir.n;
  4463. goto donode;
  4464. case NNOT:
  4465. cmdputs("!");
  4466. n = n->nnot.com;
  4467. donode:
  4468. cmdtxt(n);
  4469. break;
  4470. case NIF:
  4471. cmdputs("if ");
  4472. cmdtxt(n->nif.test);
  4473. cmdputs("; then ");
  4474. if (n->nif.elsepart) {
  4475. cmdtxt(n->nif.ifpart);
  4476. cmdputs("; else ");
  4477. n = n->nif.elsepart;
  4478. } else {
  4479. n = n->nif.ifpart;
  4480. }
  4481. p = "; fi";
  4482. goto dotail;
  4483. case NSUBSHELL:
  4484. cmdputs("(");
  4485. n = n->nredir.n;
  4486. p = ")";
  4487. goto dotail;
  4488. case NWHILE:
  4489. p = "while ";
  4490. goto until;
  4491. case NUNTIL:
  4492. p = "until ";
  4493. until:
  4494. cmdputs(p);
  4495. cmdtxt(n->nbinary.ch1);
  4496. n = n->nbinary.ch2;
  4497. p = "; done";
  4498. dodo:
  4499. cmdputs("; do ");
  4500. dotail:
  4501. cmdtxt(n);
  4502. goto dotail2;
  4503. case NFOR:
  4504. cmdputs("for ");
  4505. cmdputs(n->nfor.var);
  4506. cmdputs(" in ");
  4507. cmdlist(n->nfor.args, 1);
  4508. n = n->nfor.body;
  4509. p = "; done";
  4510. goto dodo;
  4511. case NDEFUN:
  4512. cmdputs(n->ndefun.text);
  4513. p = "() { ... }";
  4514. goto dotail2;
  4515. case NCMD:
  4516. cmdlist(n->ncmd.args, 1);
  4517. cmdlist(n->ncmd.redirect, 0);
  4518. break;
  4519. case NARG:
  4520. p = n->narg.text;
  4521. dotail2:
  4522. cmdputs(p);
  4523. break;
  4524. case NHERE:
  4525. case NXHERE:
  4526. p = "<<...";
  4527. goto dotail2;
  4528. case NCASE:
  4529. cmdputs("case ");
  4530. cmdputs(n->ncase.expr->narg.text);
  4531. cmdputs(" in ");
  4532. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4533. cmdtxt(np->nclist.pattern);
  4534. cmdputs(") ");
  4535. cmdtxt(np->nclist.body);
  4536. cmdputs(";; ");
  4537. }
  4538. p = "esac";
  4539. goto dotail2;
  4540. case NTO:
  4541. p = ">";
  4542. goto redir;
  4543. case NCLOBBER:
  4544. p = ">|";
  4545. goto redir;
  4546. case NAPPEND:
  4547. p = ">>";
  4548. goto redir;
  4549. #if BASH_REDIR_OUTPUT
  4550. case NTO2:
  4551. #endif
  4552. case NTOFD:
  4553. p = ">&";
  4554. goto redir;
  4555. case NFROM:
  4556. p = "<";
  4557. goto redir;
  4558. case NFROMFD:
  4559. p = "<&";
  4560. goto redir;
  4561. case NFROMTO:
  4562. p = "<>";
  4563. redir:
  4564. cmdputs(utoa(n->nfile.fd));
  4565. cmdputs(p);
  4566. if (n->type == NTOFD || n->type == NFROMFD) {
  4567. if (n->ndup.dupfd >= 0)
  4568. cmdputs(utoa(n->ndup.dupfd));
  4569. else
  4570. cmdputs("-");
  4571. break;
  4572. }
  4573. n = n->nfile.fname;
  4574. goto donode;
  4575. }
  4576. }
  4577. static char *
  4578. commandtext(union node *n)
  4579. {
  4580. char *name;
  4581. STARTSTACKSTR(cmdnextc);
  4582. cmdtxt(n);
  4583. name = stackblock();
  4584. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4585. return ckstrdup(name);
  4586. }
  4587. #endif /* JOBS */
  4588. /*
  4589. * Fork off a subshell. If we are doing job control, give the subshell its
  4590. * own process group. Jp is a job structure that the job is to be added to.
  4591. * N is the command that will be evaluated by the child. Both jp and n may
  4592. * be NULL. The mode parameter can be one of the following:
  4593. * FORK_FG - Fork off a foreground process.
  4594. * FORK_BG - Fork off a background process.
  4595. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4596. * process group even if job control is on.
  4597. *
  4598. * When job control is turned off, background processes have their standard
  4599. * input redirected to /dev/null (except for the second and later processes
  4600. * in a pipeline).
  4601. *
  4602. * Called with interrupts off.
  4603. */
  4604. /*
  4605. * Clear traps on a fork.
  4606. */
  4607. static void
  4608. clear_traps(void)
  4609. {
  4610. char **tp;
  4611. INT_OFF;
  4612. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4613. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4614. if (trap_ptr == trap)
  4615. free(*tp);
  4616. /* else: it "belongs" to trap_ptr vector, don't free */
  4617. *tp = NULL;
  4618. if ((tp - trap) != 0)
  4619. setsignal(tp - trap);
  4620. }
  4621. }
  4622. may_have_traps = 0;
  4623. INT_ON;
  4624. }
  4625. /* Lives far away from here, needed for forkchild */
  4626. static void closescript(void);
  4627. /* Called after fork(), in child */
  4628. /* jp and n are NULL when called by openhere() for heredoc support */
  4629. static NOINLINE void
  4630. forkchild(struct job *jp, union node *n, int mode)
  4631. {
  4632. int oldlvl;
  4633. TRACE(("Child shell %d\n", getpid()));
  4634. oldlvl = shlvl;
  4635. shlvl++;
  4636. /* man bash: "Non-builtin commands run by bash have signal handlers
  4637. * set to the values inherited by the shell from its parent".
  4638. * Do we do it correctly? */
  4639. closescript();
  4640. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4641. && n && n->type == NCMD /* is it single cmd? */
  4642. /* && n->ncmd.args->type == NARG - always true? */
  4643. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4644. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4645. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4646. ) {
  4647. TRACE(("Trap hack\n"));
  4648. /* Awful hack for `trap` or $(trap).
  4649. *
  4650. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4651. * contains an example where "trap" is executed in a subshell:
  4652. *
  4653. * save_traps=$(trap)
  4654. * ...
  4655. * eval "$save_traps"
  4656. *
  4657. * Standard does not say that "trap" in subshell shall print
  4658. * parent shell's traps. It only says that its output
  4659. * must have suitable form, but then, in the above example
  4660. * (which is not supposed to be normative), it implies that.
  4661. *
  4662. * bash (and probably other shell) does implement it
  4663. * (traps are reset to defaults, but "trap" still shows them),
  4664. * but as a result, "trap" logic is hopelessly messed up:
  4665. *
  4666. * # trap
  4667. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4668. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4669. * # true | trap <--- trap is in subshell - no output (ditto)
  4670. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4671. * trap -- 'echo Ho' SIGWINCH
  4672. * # echo `(trap)` <--- in subshell in subshell - output
  4673. * trap -- 'echo Ho' SIGWINCH
  4674. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4675. * trap -- 'echo Ho' SIGWINCH
  4676. *
  4677. * The rules when to forget and when to not forget traps
  4678. * get really complex and nonsensical.
  4679. *
  4680. * Our solution: ONLY bare $(trap) or `trap` is special.
  4681. */
  4682. /* Save trap handler strings for trap builtin to print */
  4683. trap_ptr = xmemdup(trap, sizeof(trap));
  4684. /* Fall through into clearing traps */
  4685. }
  4686. clear_traps();
  4687. #if JOBS
  4688. /* do job control only in root shell */
  4689. doing_jobctl = 0;
  4690. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4691. pid_t pgrp;
  4692. if (jp->nprocs == 0)
  4693. pgrp = getpid();
  4694. else
  4695. pgrp = jp->ps[0].ps_pid;
  4696. /* this can fail because we are doing it in the parent also */
  4697. setpgid(0, pgrp);
  4698. if (mode == FORK_FG)
  4699. xtcsetpgrp(ttyfd, pgrp);
  4700. setsignal(SIGTSTP);
  4701. setsignal(SIGTTOU);
  4702. } else
  4703. #endif
  4704. if (mode == FORK_BG) {
  4705. /* man bash: "When job control is not in effect,
  4706. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4707. ignoresig(SIGINT);
  4708. ignoresig(SIGQUIT);
  4709. if (jp->nprocs == 0) {
  4710. close(0);
  4711. if (open(bb_dev_null, O_RDONLY) != 0)
  4712. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4713. }
  4714. }
  4715. if (oldlvl == 0) {
  4716. if (iflag) { /* why if iflag only? */
  4717. setsignal(SIGINT);
  4718. setsignal(SIGTERM);
  4719. }
  4720. /* man bash:
  4721. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4722. * commands run by bash have signal handlers
  4723. * set to the values inherited by the shell
  4724. * from its parent".
  4725. * Take care of the second rule: */
  4726. setsignal(SIGQUIT);
  4727. }
  4728. #if JOBS
  4729. if (n && n->type == NCMD
  4730. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4731. ) {
  4732. TRACE(("Job hack\n"));
  4733. /* "jobs": we do not want to clear job list for it,
  4734. * instead we remove only _its_ own_ job from job list.
  4735. * This makes "jobs .... | cat" more useful.
  4736. */
  4737. freejob(curjob);
  4738. return;
  4739. }
  4740. #endif
  4741. for (jp = curjob; jp; jp = jp->prev_job)
  4742. freejob(jp);
  4743. jobless = 0;
  4744. }
  4745. /* Called after fork(), in parent */
  4746. #if !JOBS
  4747. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4748. #endif
  4749. static void
  4750. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4751. {
  4752. TRACE(("In parent shell: child = %d\n", pid));
  4753. if (!jp) {
  4754. /* jp is NULL when called by openhere() for heredoc support */
  4755. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4756. continue;
  4757. jobless++;
  4758. return;
  4759. }
  4760. #if JOBS
  4761. if (mode != FORK_NOJOB && jp->jobctl) {
  4762. int pgrp;
  4763. if (jp->nprocs == 0)
  4764. pgrp = pid;
  4765. else
  4766. pgrp = jp->ps[0].ps_pid;
  4767. /* This can fail because we are doing it in the child also */
  4768. setpgid(pid, pgrp);
  4769. }
  4770. #endif
  4771. if (mode == FORK_BG) {
  4772. backgndpid = pid; /* set $! */
  4773. set_curjob(jp, CUR_RUNNING);
  4774. }
  4775. if (jp) {
  4776. struct procstat *ps = &jp->ps[jp->nprocs++];
  4777. ps->ps_pid = pid;
  4778. ps->ps_status = -1;
  4779. ps->ps_cmd = nullstr;
  4780. #if JOBS
  4781. if (doing_jobctl && n)
  4782. ps->ps_cmd = commandtext(n);
  4783. #endif
  4784. }
  4785. }
  4786. /* jp and n are NULL when called by openhere() for heredoc support */
  4787. static int
  4788. forkshell(struct job *jp, union node *n, int mode)
  4789. {
  4790. int pid;
  4791. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4792. pid = fork();
  4793. if (pid < 0) {
  4794. TRACE(("Fork failed, errno=%d", errno));
  4795. if (jp)
  4796. freejob(jp);
  4797. ash_msg_and_raise_perror("can't fork");
  4798. }
  4799. if (pid == 0) {
  4800. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4801. forkchild(jp, n, mode);
  4802. } else {
  4803. forkparent(jp, n, mode, pid);
  4804. }
  4805. return pid;
  4806. }
  4807. /*
  4808. * Wait for job to finish.
  4809. *
  4810. * Under job control we have the problem that while a child process
  4811. * is running interrupts generated by the user are sent to the child
  4812. * but not to the shell. This means that an infinite loop started by
  4813. * an interactive user may be hard to kill. With job control turned off,
  4814. * an interactive user may place an interactive program inside a loop.
  4815. * If the interactive program catches interrupts, the user doesn't want
  4816. * these interrupts to also abort the loop. The approach we take here
  4817. * is to have the shell ignore interrupt signals while waiting for a
  4818. * foreground process to terminate, and then send itself an interrupt
  4819. * signal if the child process was terminated by an interrupt signal.
  4820. * Unfortunately, some programs want to do a bit of cleanup and then
  4821. * exit on interrupt; unless these processes terminate themselves by
  4822. * sending a signal to themselves (instead of calling exit) they will
  4823. * confuse this approach.
  4824. *
  4825. * Called with interrupts off.
  4826. */
  4827. static int
  4828. waitforjob(struct job *jp)
  4829. {
  4830. int st;
  4831. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4832. INT_OFF;
  4833. while (jp->state == JOBRUNNING) {
  4834. /* In non-interactive shells, we _can_ get
  4835. * a keyboard signal here and be EINTRed,
  4836. * but we just loop back, waiting for command to complete.
  4837. *
  4838. * man bash:
  4839. * "If bash is waiting for a command to complete and receives
  4840. * a signal for which a trap has been set, the trap
  4841. * will not be executed until the command completes."
  4842. *
  4843. * Reality is that even if trap is not set, bash
  4844. * will not act on the signal until command completes.
  4845. * Try this. sleep5intoff.c:
  4846. * #include <signal.h>
  4847. * #include <unistd.h>
  4848. * int main() {
  4849. * sigset_t set;
  4850. * sigemptyset(&set);
  4851. * sigaddset(&set, SIGINT);
  4852. * sigaddset(&set, SIGQUIT);
  4853. * sigprocmask(SIG_BLOCK, &set, NULL);
  4854. * sleep(5);
  4855. * return 0;
  4856. * }
  4857. * $ bash -c './sleep5intoff; echo hi'
  4858. * ^C^C^C^C <--- pressing ^C once a second
  4859. * $ _
  4860. * $ bash -c './sleep5intoff; echo hi'
  4861. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4862. * $ _
  4863. */
  4864. dowait(DOWAIT_BLOCK, jp);
  4865. }
  4866. INT_ON;
  4867. st = getstatus(jp);
  4868. #if JOBS
  4869. if (jp->jobctl) {
  4870. xtcsetpgrp(ttyfd, rootpid);
  4871. restore_tty_if_stopped_or_signaled(jp);
  4872. /*
  4873. * This is truly gross.
  4874. * If we're doing job control, then we did a TIOCSPGRP which
  4875. * caused us (the shell) to no longer be in the controlling
  4876. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4877. * intuit from the subprocess exit status whether a SIGINT
  4878. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4879. */
  4880. if (jp->sigint) /* TODO: do the same with all signals */
  4881. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4882. }
  4883. if (jp->state == JOBDONE)
  4884. #endif
  4885. freejob(jp);
  4886. return st;
  4887. }
  4888. /*
  4889. * return 1 if there are stopped jobs, otherwise 0
  4890. */
  4891. static int
  4892. stoppedjobs(void)
  4893. {
  4894. struct job *jp;
  4895. int retval;
  4896. retval = 0;
  4897. if (job_warning)
  4898. goto out;
  4899. jp = curjob;
  4900. if (jp && jp->state == JOBSTOPPED) {
  4901. out2str("You have stopped jobs.\n");
  4902. job_warning = 2;
  4903. retval++;
  4904. }
  4905. out:
  4906. return retval;
  4907. }
  4908. /*
  4909. * Code for dealing with input/output redirection.
  4910. */
  4911. #undef EMPTY
  4912. #undef CLOSED
  4913. #define EMPTY -2 /* marks an unused slot in redirtab */
  4914. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4915. /*
  4916. * Handle here documents. Normally we fork off a process to write the
  4917. * data to a pipe. If the document is short, we can stuff the data in
  4918. * the pipe without forking.
  4919. */
  4920. /* openhere needs this forward reference */
  4921. static void expandhere(union node *arg, int fd);
  4922. static int
  4923. openhere(union node *redir)
  4924. {
  4925. int pip[2];
  4926. size_t len = 0;
  4927. if (pipe(pip) < 0)
  4928. ash_msg_and_raise_perror("can't create pipe");
  4929. if (redir->type == NHERE) {
  4930. len = strlen(redir->nhere.doc->narg.text);
  4931. if (len <= PIPE_BUF) {
  4932. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4933. goto out;
  4934. }
  4935. }
  4936. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4937. /* child */
  4938. close(pip[0]);
  4939. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4940. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4941. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4942. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4943. signal(SIGPIPE, SIG_DFL);
  4944. if (redir->type == NHERE)
  4945. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4946. else /* NXHERE */
  4947. expandhere(redir->nhere.doc, pip[1]);
  4948. _exit(EXIT_SUCCESS);
  4949. }
  4950. out:
  4951. close(pip[1]);
  4952. return pip[0];
  4953. }
  4954. static int
  4955. openredirect(union node *redir)
  4956. {
  4957. struct stat sb;
  4958. char *fname;
  4959. int f;
  4960. switch (redir->nfile.type) {
  4961. /* Can't happen, our single caller does this itself */
  4962. // case NTOFD:
  4963. // case NFROMFD:
  4964. // return -1;
  4965. case NHERE:
  4966. case NXHERE:
  4967. return openhere(redir);
  4968. }
  4969. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4970. * allocated space. Do it only when we know it is safe.
  4971. */
  4972. fname = redir->nfile.expfname;
  4973. switch (redir->nfile.type) {
  4974. default:
  4975. #if DEBUG
  4976. abort();
  4977. #endif
  4978. case NFROM:
  4979. f = open(fname, O_RDONLY);
  4980. if (f < 0)
  4981. goto eopen;
  4982. break;
  4983. case NFROMTO:
  4984. f = open(fname, O_RDWR|O_CREAT, 0666);
  4985. if (f < 0)
  4986. goto ecreate;
  4987. break;
  4988. case NTO:
  4989. #if BASH_REDIR_OUTPUT
  4990. case NTO2:
  4991. #endif
  4992. /* Take care of noclobber mode. */
  4993. if (Cflag) {
  4994. if (stat(fname, &sb) < 0) {
  4995. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4996. if (f < 0)
  4997. goto ecreate;
  4998. } else if (!S_ISREG(sb.st_mode)) {
  4999. f = open(fname, O_WRONLY, 0666);
  5000. if (f < 0)
  5001. goto ecreate;
  5002. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  5003. close(f);
  5004. errno = EEXIST;
  5005. goto ecreate;
  5006. }
  5007. } else {
  5008. errno = EEXIST;
  5009. goto ecreate;
  5010. }
  5011. break;
  5012. }
  5013. /* FALLTHROUGH */
  5014. case NCLOBBER:
  5015. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  5016. if (f < 0)
  5017. goto ecreate;
  5018. break;
  5019. case NAPPEND:
  5020. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  5021. if (f < 0)
  5022. goto ecreate;
  5023. break;
  5024. }
  5025. return f;
  5026. ecreate:
  5027. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  5028. eopen:
  5029. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  5030. }
  5031. /*
  5032. * Copy a file descriptor to be >= 10. Throws exception on error.
  5033. */
  5034. static int
  5035. savefd(int from)
  5036. {
  5037. int newfd;
  5038. int err;
  5039. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  5040. err = newfd < 0 ? errno : 0;
  5041. if (err != EBADF) {
  5042. if (err)
  5043. ash_msg_and_raise_perror("%d", from);
  5044. close(from);
  5045. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5046. close_on_exec_on(newfd);
  5047. }
  5048. return newfd;
  5049. }
  5050. static int
  5051. dup2_or_raise(int from, int to)
  5052. {
  5053. int newfd;
  5054. newfd = (from != to) ? dup2(from, to) : to;
  5055. if (newfd < 0) {
  5056. /* Happens when source fd is not open: try "echo >&99" */
  5057. ash_msg_and_raise_perror("%d", from);
  5058. }
  5059. return newfd;
  5060. }
  5061. static int
  5062. dup_CLOEXEC(int fd, int avoid_fd)
  5063. {
  5064. int newfd;
  5065. repeat:
  5066. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5067. if (newfd >= 0) {
  5068. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  5069. close_on_exec_on(newfd);
  5070. } else { /* newfd < 0 */
  5071. if (errno == EBUSY)
  5072. goto repeat;
  5073. if (errno == EINTR)
  5074. goto repeat;
  5075. }
  5076. return newfd;
  5077. }
  5078. static int
  5079. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5080. {
  5081. int newfd;
  5082. repeat:
  5083. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5084. if (newfd < 0) {
  5085. if (errno == EBUSY)
  5086. goto repeat;
  5087. if (errno == EINTR)
  5088. goto repeat;
  5089. /* fd was not open? */
  5090. if (errno == EBADF)
  5091. return fd;
  5092. ash_msg_and_raise_perror("%d", newfd);
  5093. }
  5094. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5095. close_on_exec_on(newfd);
  5096. close(fd);
  5097. return newfd;
  5098. }
  5099. /* Struct def and variable are moved down to the first usage site */
  5100. struct squirrel {
  5101. int orig_fd;
  5102. int moved_to;
  5103. };
  5104. struct redirtab {
  5105. struct redirtab *next;
  5106. int pair_count;
  5107. struct squirrel two_fd[];
  5108. };
  5109. #define redirlist (G_var.redirlist)
  5110. static void
  5111. add_squirrel_closed(struct redirtab *sq, int fd)
  5112. {
  5113. int i;
  5114. if (!sq)
  5115. return;
  5116. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5117. /* If we collide with an already moved fd... */
  5118. if (fd == sq->two_fd[i].orig_fd) {
  5119. /* Examples:
  5120. * "echo 3>FILE 3>&- 3>FILE"
  5121. * "echo 3>&- 3>FILE"
  5122. * No need for last redirect to insert
  5123. * another "need to close 3" indicator.
  5124. */
  5125. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5126. return;
  5127. }
  5128. }
  5129. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5130. sq->two_fd[i].orig_fd = fd;
  5131. sq->two_fd[i].moved_to = CLOSED;
  5132. }
  5133. static int
  5134. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5135. {
  5136. int i, new_fd;
  5137. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5138. avoid_fd = 9;
  5139. #if JOBS
  5140. if (fd == ttyfd) {
  5141. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5142. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5143. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5144. return 1; /* "we closed fd" */
  5145. }
  5146. #endif
  5147. /* Are we called from redirect(0)? E.g. redirect
  5148. * in a forked child. No need to save fds,
  5149. * we aren't going to use them anymore, ok to trash.
  5150. */
  5151. if (!sq)
  5152. return 0;
  5153. /* If this one of script's fds? */
  5154. if (fd != 0) {
  5155. struct parsefile *pf = g_parsefile;
  5156. while (pf) {
  5157. /* We skip fd == 0 case because of the following:
  5158. * $ ash # running ash interactively
  5159. * $ . ./script.sh
  5160. * and in script.sh: "exec 9>&0".
  5161. * Even though top-level pf_fd _is_ 0,
  5162. * it's still ok to use it: "read" builtin uses it,
  5163. * why should we cripple "exec" builtin?
  5164. */
  5165. if (fd == pf->pf_fd) {
  5166. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5167. return 1; /* "we closed fd" */
  5168. }
  5169. pf = pf->prev;
  5170. }
  5171. }
  5172. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5173. /* First: do we collide with some already moved fds? */
  5174. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5175. /* If we collide with an already moved fd... */
  5176. if (fd == sq->two_fd[i].moved_to) {
  5177. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5178. sq->two_fd[i].moved_to = new_fd;
  5179. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5180. if (new_fd < 0) /* what? */
  5181. xfunc_die();
  5182. return 0; /* "we did not close fd" */
  5183. }
  5184. if (fd == sq->two_fd[i].orig_fd) {
  5185. /* Example: echo Hello >/dev/null 1>&2 */
  5186. TRACE(("redirect_fd %d: already moved\n", fd));
  5187. return 0; /* "we did not close fd" */
  5188. }
  5189. }
  5190. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5191. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5192. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5193. if (new_fd < 0) {
  5194. if (errno != EBADF)
  5195. xfunc_die();
  5196. /* new_fd = CLOSED; - already is -1 */
  5197. }
  5198. sq->two_fd[i].moved_to = new_fd;
  5199. sq->two_fd[i].orig_fd = fd;
  5200. /* if we move stderr, let "set -x" code know */
  5201. if (fd == preverrout_fd)
  5202. preverrout_fd = new_fd;
  5203. return 0; /* "we did not close fd" */
  5204. }
  5205. static int
  5206. internally_opened_fd(int fd, struct redirtab *sq)
  5207. {
  5208. int i;
  5209. #if JOBS
  5210. if (fd == ttyfd)
  5211. return 1;
  5212. #endif
  5213. /* If this one of script's fds? */
  5214. if (fd != 0) {
  5215. struct parsefile *pf = g_parsefile;
  5216. while (pf) {
  5217. if (fd == pf->pf_fd)
  5218. return 1;
  5219. pf = pf->prev;
  5220. }
  5221. }
  5222. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5223. if (fd == sq->two_fd[i].moved_to)
  5224. return 1;
  5225. }
  5226. return 0;
  5227. }
  5228. /*
  5229. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5230. * old file descriptors are stashed away so that the redirection can be
  5231. * undone by calling popredir.
  5232. */
  5233. /* flags passed to redirect */
  5234. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5235. static void
  5236. redirect(union node *redir, int flags)
  5237. {
  5238. struct redirtab *sv;
  5239. if (!redir)
  5240. return;
  5241. sv = NULL;
  5242. INT_OFF;
  5243. if (flags & REDIR_PUSH)
  5244. sv = redirlist;
  5245. do {
  5246. int fd;
  5247. int newfd;
  5248. int close_fd;
  5249. int closed;
  5250. fd = redir->nfile.fd;
  5251. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5252. //bb_error_msg("doing %d > %d", fd, newfd);
  5253. newfd = redir->ndup.dupfd;
  5254. close_fd = -1;
  5255. } else {
  5256. newfd = openredirect(redir); /* always >= 0 */
  5257. if (fd == newfd) {
  5258. /* open() gave us precisely the fd we wanted.
  5259. * This means that this fd was not busy
  5260. * (not opened to anywhere).
  5261. * Remember to close it on restore:
  5262. */
  5263. add_squirrel_closed(sv, fd);
  5264. continue;
  5265. }
  5266. close_fd = newfd;
  5267. }
  5268. if (fd == newfd)
  5269. continue;
  5270. /* if "N>FILE": move newfd to fd */
  5271. /* if "N>&M": dup newfd to fd */
  5272. /* if "N>&-": close fd (newfd is -1) */
  5273. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5274. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5275. if (newfd == -1) {
  5276. /* "N>&-" means "close me" */
  5277. if (!closed) {
  5278. /* ^^^ optimization: saving may already
  5279. * have closed it. If not... */
  5280. close(fd);
  5281. }
  5282. } else {
  5283. /* if newfd is a script fd or saved fd, simulate EBADF */
  5284. if (internally_opened_fd(newfd, sv)) {
  5285. errno = EBADF;
  5286. ash_msg_and_raise_perror("%d", newfd);
  5287. }
  5288. dup2_or_raise(newfd, fd);
  5289. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5290. close(close_fd);
  5291. #if BASH_REDIR_OUTPUT
  5292. if (redir->nfile.type == NTO2 && fd == 1) {
  5293. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5294. fd = 2;
  5295. newfd = 1;
  5296. close_fd = -1;
  5297. goto redirect_more;
  5298. }
  5299. #endif
  5300. }
  5301. } while ((redir = redir->nfile.next) != NULL);
  5302. INT_ON;
  5303. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5304. #define REDIR_SAVEFD2 0
  5305. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5306. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5307. // not only for calls with flags containing REDIR_SAVEFD2.
  5308. // We do this unconditionally (see save_fd_on_redirect()).
  5309. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5310. // preverrout_fd = copied_fd2;
  5311. }
  5312. static int
  5313. redirectsafe(union node *redir, int flags)
  5314. {
  5315. int err;
  5316. volatile int saveint;
  5317. struct jmploc *volatile savehandler = exception_handler;
  5318. struct jmploc jmploc;
  5319. SAVE_INT(saveint);
  5320. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5321. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5322. if (!err) {
  5323. exception_handler = &jmploc;
  5324. redirect(redir, flags);
  5325. }
  5326. exception_handler = savehandler;
  5327. if (err && exception_type != EXERROR)
  5328. longjmp(exception_handler->loc, 1);
  5329. RESTORE_INT(saveint);
  5330. return err;
  5331. }
  5332. static struct redirtab*
  5333. pushredir(union node *redir)
  5334. {
  5335. struct redirtab *sv;
  5336. int i;
  5337. if (!redir)
  5338. return redirlist;
  5339. i = 0;
  5340. do {
  5341. i++;
  5342. #if BASH_REDIR_OUTPUT
  5343. if (redir->nfile.type == NTO2)
  5344. i++;
  5345. #endif
  5346. redir = redir->nfile.next;
  5347. } while (redir);
  5348. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5349. sv->pair_count = i;
  5350. while (--i >= 0)
  5351. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5352. sv->next = redirlist;
  5353. redirlist = sv;
  5354. return sv->next;
  5355. }
  5356. /*
  5357. * Undo the effects of the last redirection.
  5358. */
  5359. static void
  5360. popredir(int drop)
  5361. {
  5362. struct redirtab *rp;
  5363. int i;
  5364. if (redirlist == NULL)
  5365. return;
  5366. INT_OFF;
  5367. rp = redirlist;
  5368. for (i = 0; i < rp->pair_count; i++) {
  5369. int fd = rp->two_fd[i].orig_fd;
  5370. int copy = rp->two_fd[i].moved_to;
  5371. if (copy == CLOSED) {
  5372. if (!drop)
  5373. close(fd);
  5374. continue;
  5375. }
  5376. if (copy != EMPTY) {
  5377. if (!drop) {
  5378. /*close(fd);*/
  5379. dup2_or_raise(copy, fd);
  5380. }
  5381. close(copy);
  5382. }
  5383. }
  5384. redirlist = rp->next;
  5385. free(rp);
  5386. INT_ON;
  5387. }
  5388. static void
  5389. unwindredir(struct redirtab *stop)
  5390. {
  5391. while (redirlist != stop)
  5392. popredir(/*drop:*/ 0);
  5393. }
  5394. /* ============ Routines to expand arguments to commands
  5395. *
  5396. * We have to deal with backquotes, shell variables, and file metacharacters.
  5397. */
  5398. #if ENABLE_FEATURE_SH_MATH
  5399. static arith_t
  5400. ash_arith(const char *s)
  5401. {
  5402. arith_state_t math_state;
  5403. arith_t result;
  5404. math_state.lookupvar = lookupvar;
  5405. math_state.setvar = setvar0;
  5406. //math_state.endofname = endofname;
  5407. INT_OFF;
  5408. result = arith(&math_state, s);
  5409. if (math_state.errmsg)
  5410. ash_msg_and_raise_error(math_state.errmsg);
  5411. INT_ON;
  5412. return result;
  5413. }
  5414. #endif
  5415. #if BASH_SUBSTR
  5416. # if ENABLE_FEATURE_SH_MATH
  5417. static int substr_atoi(const char *s)
  5418. {
  5419. arith_t t = ash_arith(s);
  5420. if (sizeof(t) > sizeof(int)) {
  5421. /* clamp very large or very large negative nums for ${v:N:M}:
  5422. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5423. */
  5424. if (t > INT_MAX)
  5425. t = INT_MAX;
  5426. if (t < INT_MIN)
  5427. t = INT_MIN;
  5428. }
  5429. return t;
  5430. }
  5431. # else
  5432. # define substr_atoi(s) number(s)
  5433. # endif
  5434. #endif
  5435. /*
  5436. * expandarg flags
  5437. */
  5438. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5439. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5440. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5441. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5442. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5443. * POSIX says for this case:
  5444. * Pathname expansion shall not be performed on the word by a
  5445. * non-interactive shell; an interactive shell may perform it, but shall
  5446. * do so only when the expansion would result in one word.
  5447. * Currently, our code complies to the above rule by never globbing
  5448. * redirection filenames.
  5449. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5450. * (this means that on a typical Linux distro, bash almost always
  5451. * performs globbing, and thus diverges from what we do).
  5452. */
  5453. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5454. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5455. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5456. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5457. /*
  5458. * rmescape() flags
  5459. */
  5460. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5461. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5462. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5463. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5464. /* Add CTLESC when necessary. */
  5465. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5466. /* Do not skip NUL characters. */
  5467. #define QUOTES_KEEPNUL EXP_TILDE
  5468. /*
  5469. * Structure specifying which parts of the string should be searched
  5470. * for IFS characters.
  5471. */
  5472. struct ifsregion {
  5473. struct ifsregion *next; /* next region in list */
  5474. int begoff; /* offset of start of region */
  5475. int endoff; /* offset of end of region */
  5476. int nulonly; /* search for nul bytes only */
  5477. };
  5478. struct arglist {
  5479. struct strlist *list;
  5480. struct strlist **lastp;
  5481. };
  5482. /* output of current string */
  5483. static char *expdest;
  5484. /* list of back quote expressions */
  5485. static struct nodelist *argbackq;
  5486. /* first struct in list of ifs regions */
  5487. static struct ifsregion ifsfirst;
  5488. /* last struct in list */
  5489. static struct ifsregion *ifslastp;
  5490. /* holds expanded arg list */
  5491. static struct arglist exparg;
  5492. /*
  5493. * Our own itoa().
  5494. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5495. */
  5496. static int
  5497. cvtnum(arith_t num)
  5498. {
  5499. int len;
  5500. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5501. len = sizeof(arith_t) * 3;
  5502. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5503. if (sizeof(arith_t) < 4) len += 2;
  5504. expdest = makestrspace(len, expdest);
  5505. len = fmtstr(expdest, len, ARITH_FMT, num);
  5506. STADJUST(len, expdest);
  5507. return len;
  5508. }
  5509. /*
  5510. * Break the argument string into pieces based upon IFS and add the
  5511. * strings to the argument list. The regions of the string to be
  5512. * searched for IFS characters have been stored by recordregion.
  5513. */
  5514. static void
  5515. ifsbreakup(char *string, struct arglist *arglist)
  5516. {
  5517. struct ifsregion *ifsp;
  5518. struct strlist *sp;
  5519. char *start;
  5520. char *p;
  5521. char *q;
  5522. const char *ifs, *realifs;
  5523. int ifsspc;
  5524. int nulonly;
  5525. start = string;
  5526. if (ifslastp != NULL) {
  5527. ifsspc = 0;
  5528. nulonly = 0;
  5529. realifs = ifsset() ? ifsval() : defifs;
  5530. ifsp = &ifsfirst;
  5531. do {
  5532. int afternul;
  5533. p = string + ifsp->begoff;
  5534. afternul = nulonly;
  5535. nulonly = ifsp->nulonly;
  5536. ifs = nulonly ? nullstr : realifs;
  5537. ifsspc = 0;
  5538. while (p < string + ifsp->endoff) {
  5539. q = p;
  5540. if ((unsigned char)*p == CTLESC)
  5541. p++;
  5542. if (!strchr(ifs, *p)) {
  5543. p++;
  5544. continue;
  5545. }
  5546. if (!(afternul || nulonly))
  5547. ifsspc = (strchr(defifs, *p) != NULL);
  5548. /* Ignore IFS whitespace at start */
  5549. if (q == start && ifsspc) {
  5550. p++;
  5551. start = p;
  5552. continue;
  5553. }
  5554. *q = '\0';
  5555. sp = stzalloc(sizeof(*sp));
  5556. sp->text = start;
  5557. *arglist->lastp = sp;
  5558. arglist->lastp = &sp->next;
  5559. p++;
  5560. if (!nulonly) {
  5561. for (;;) {
  5562. if (p >= string + ifsp->endoff) {
  5563. break;
  5564. }
  5565. q = p;
  5566. if ((unsigned char)*p == CTLESC)
  5567. p++;
  5568. if (strchr(ifs, *p) == NULL) {
  5569. p = q;
  5570. break;
  5571. }
  5572. if (strchr(defifs, *p) == NULL) {
  5573. if (ifsspc) {
  5574. p++;
  5575. ifsspc = 0;
  5576. } else {
  5577. p = q;
  5578. break;
  5579. }
  5580. } else
  5581. p++;
  5582. }
  5583. }
  5584. start = p;
  5585. } /* while */
  5586. ifsp = ifsp->next;
  5587. } while (ifsp != NULL);
  5588. if (nulonly)
  5589. goto add;
  5590. }
  5591. if (!*start)
  5592. return;
  5593. add:
  5594. sp = stzalloc(sizeof(*sp));
  5595. sp->text = start;
  5596. *arglist->lastp = sp;
  5597. arglist->lastp = &sp->next;
  5598. }
  5599. static void
  5600. ifsfree(void)
  5601. {
  5602. struct ifsregion *p = ifsfirst.next;
  5603. if (!p)
  5604. goto out;
  5605. INT_OFF;
  5606. do {
  5607. struct ifsregion *ifsp;
  5608. ifsp = p->next;
  5609. free(p);
  5610. p = ifsp;
  5611. } while (p);
  5612. ifsfirst.next = NULL;
  5613. INT_ON;
  5614. out:
  5615. ifslastp = NULL;
  5616. }
  5617. static size_t
  5618. esclen(const char *start, const char *p)
  5619. {
  5620. size_t esc = 0;
  5621. while (p > start && (unsigned char)*--p == CTLESC) {
  5622. esc++;
  5623. }
  5624. return esc;
  5625. }
  5626. /*
  5627. * Remove any CTLESC characters from a string.
  5628. */
  5629. #if !BASH_PATTERN_SUBST
  5630. #define rmescapes(str, flag, slash_position) \
  5631. rmescapes(str, flag)
  5632. #endif
  5633. static char *
  5634. rmescapes(char *str, int flag, int *slash_position)
  5635. {
  5636. static const char qchars[] ALIGN1 = {
  5637. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5638. char *p, *q, *r;
  5639. unsigned protect_against_glob;
  5640. unsigned globbing;
  5641. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5642. if (!p)
  5643. return str;
  5644. q = p;
  5645. r = str;
  5646. if (flag & RMESCAPE_ALLOC) {
  5647. size_t len = p - str;
  5648. size_t fulllen = len + strlen(p) + 1;
  5649. if (flag & RMESCAPE_GROW) {
  5650. int strloc = str - (char *)stackblock();
  5651. r = makestrspace(fulllen, expdest);
  5652. /* p and str may be invalidated by makestrspace */
  5653. str = (char *)stackblock() + strloc;
  5654. p = str + len;
  5655. } else if (flag & RMESCAPE_HEAP) {
  5656. r = ckmalloc(fulllen);
  5657. } else {
  5658. r = stalloc(fulllen);
  5659. }
  5660. q = r;
  5661. if (len > 0) {
  5662. q = (char *)mempcpy(q, str, len);
  5663. }
  5664. }
  5665. globbing = flag & RMESCAPE_GLOB;
  5666. protect_against_glob = globbing;
  5667. while (*p) {
  5668. if ((unsigned char)*p == CTLQUOTEMARK) {
  5669. // Note: protect_against_glob only affect whether
  5670. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5671. p++;
  5672. protect_against_glob = globbing;
  5673. continue;
  5674. }
  5675. if (*p == '\\') {
  5676. /* naked back slash */
  5677. protect_against_glob = 0;
  5678. goto copy;
  5679. }
  5680. if ((unsigned char)*p == CTLESC) {
  5681. p++;
  5682. #if DEBUG
  5683. if (*p == '\0')
  5684. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5685. #endif
  5686. if (protect_against_glob) {
  5687. /*
  5688. * We used to trust glob() and fnmatch() to eat
  5689. * superfluous escapes (\z where z has no
  5690. * special meaning anyway). But this causes
  5691. * bugs such as string of one greek letter rho
  5692. * (unicode-encoded as two bytes "cf,81")
  5693. * getting encoded as "cf,CTLESC,81"
  5694. * and here, converted to "cf,\,81" -
  5695. * which does not go well with some flavors
  5696. * of fnmatch() in unicode locales
  5697. * (for example, glibc <= 2.22).
  5698. *
  5699. * Lets add "\" only on the chars which need it.
  5700. * Testcases for less obvious chars are shown.
  5701. */
  5702. if (*p == '*'
  5703. || *p == '?'
  5704. || *p == '['
  5705. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5706. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5707. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5708. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5709. /* Some libc support [^negate], that's why "^" also needs love */
  5710. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5711. ) {
  5712. *q++ = '\\';
  5713. }
  5714. }
  5715. }
  5716. #if BASH_PATTERN_SUBST
  5717. else if (slash_position && p == str + *slash_position) {
  5718. /* stop handling globbing */
  5719. globbing = 0;
  5720. *slash_position = q - r;
  5721. slash_position = NULL;
  5722. }
  5723. #endif
  5724. protect_against_glob = globbing;
  5725. copy:
  5726. *q++ = *p++;
  5727. }
  5728. *q = '\0';
  5729. if (flag & RMESCAPE_GROW) {
  5730. expdest = r;
  5731. STADJUST(q - r + 1, expdest);
  5732. }
  5733. return r;
  5734. }
  5735. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5736. /*
  5737. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5738. *
  5739. * Returns an stalloced string.
  5740. */
  5741. static char *
  5742. preglob(const char *pattern, int flag)
  5743. {
  5744. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5745. }
  5746. /*
  5747. * Put a string on the stack.
  5748. */
  5749. static void
  5750. memtodest(const char *p, size_t len, int syntax, int quotes)
  5751. {
  5752. char *q;
  5753. if (!len)
  5754. return;
  5755. q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
  5756. do {
  5757. unsigned char c = *p++;
  5758. if (c) {
  5759. if (quotes & QUOTES_ESC) {
  5760. int n = SIT(c, syntax);
  5761. if (n == CCTL
  5762. || (syntax != BASESYNTAX && n == CBACK)
  5763. ) {
  5764. USTPUTC(CTLESC, q);
  5765. }
  5766. }
  5767. } else if (!(quotes & QUOTES_KEEPNUL))
  5768. continue;
  5769. USTPUTC(c, q);
  5770. } while (--len);
  5771. expdest = q;
  5772. }
  5773. static size_t
  5774. strtodest(const char *p, int syntax, int quotes)
  5775. {
  5776. size_t len = strlen(p);
  5777. memtodest(p, len, syntax, quotes);
  5778. return len;
  5779. }
  5780. /*
  5781. * Record the fact that we have to scan this region of the
  5782. * string for IFS characters.
  5783. */
  5784. static void
  5785. recordregion(int start, int end, int nulonly)
  5786. {
  5787. struct ifsregion *ifsp;
  5788. if (ifslastp == NULL) {
  5789. ifsp = &ifsfirst;
  5790. } else {
  5791. INT_OFF;
  5792. ifsp = ckzalloc(sizeof(*ifsp));
  5793. /*ifsp->next = NULL; - ckzalloc did it */
  5794. ifslastp->next = ifsp;
  5795. INT_ON;
  5796. }
  5797. ifslastp = ifsp;
  5798. ifslastp->begoff = start;
  5799. ifslastp->endoff = end;
  5800. ifslastp->nulonly = nulonly;
  5801. }
  5802. static void
  5803. removerecordregions(int endoff)
  5804. {
  5805. if (ifslastp == NULL)
  5806. return;
  5807. if (ifsfirst.endoff > endoff) {
  5808. while (ifsfirst.next) {
  5809. struct ifsregion *ifsp;
  5810. INT_OFF;
  5811. ifsp = ifsfirst.next->next;
  5812. free(ifsfirst.next);
  5813. ifsfirst.next = ifsp;
  5814. INT_ON;
  5815. }
  5816. if (ifsfirst.begoff > endoff) {
  5817. ifslastp = NULL;
  5818. } else {
  5819. ifslastp = &ifsfirst;
  5820. ifsfirst.endoff = endoff;
  5821. }
  5822. return;
  5823. }
  5824. ifslastp = &ifsfirst;
  5825. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5826. ifslastp = ifslastp->next;
  5827. while (ifslastp->next) {
  5828. struct ifsregion *ifsp;
  5829. INT_OFF;
  5830. ifsp = ifslastp->next->next;
  5831. free(ifslastp->next);
  5832. ifslastp->next = ifsp;
  5833. INT_ON;
  5834. }
  5835. if (ifslastp->endoff > endoff)
  5836. ifslastp->endoff = endoff;
  5837. }
  5838. static char *
  5839. exptilde(char *startp, char *p, int flags)
  5840. {
  5841. unsigned char c;
  5842. char *name;
  5843. struct passwd *pw;
  5844. const char *home;
  5845. int quotes = flags & QUOTES_ESC;
  5846. name = p + 1;
  5847. while ((c = *++p) != '\0') {
  5848. switch (c) {
  5849. case CTLESC:
  5850. return startp;
  5851. case CTLQUOTEMARK:
  5852. return startp;
  5853. case ':':
  5854. if (flags & EXP_VARTILDE)
  5855. goto done;
  5856. break;
  5857. case '/':
  5858. case CTLENDVAR:
  5859. goto done;
  5860. }
  5861. }
  5862. done:
  5863. *p = '\0';
  5864. if (*name == '\0') {
  5865. home = lookupvar("HOME");
  5866. } else {
  5867. pw = getpwnam(name);
  5868. if (pw == NULL)
  5869. goto lose;
  5870. home = pw->pw_dir;
  5871. }
  5872. if (!home || !*home)
  5873. goto lose;
  5874. *p = c;
  5875. strtodest(home, SQSYNTAX, quotes);
  5876. return p;
  5877. lose:
  5878. *p = c;
  5879. return startp;
  5880. }
  5881. /*
  5882. * Execute a command inside back quotes. If it's a builtin command, we
  5883. * want to save its output in a block obtained from malloc. Otherwise
  5884. * we fork off a subprocess and get the output of the command via a pipe.
  5885. * Should be called with interrupts off.
  5886. */
  5887. struct backcmd { /* result of evalbackcmd */
  5888. int fd; /* file descriptor to read from */
  5889. int nleft; /* number of chars in buffer */
  5890. char *buf; /* buffer */
  5891. struct job *jp; /* job structure for command */
  5892. };
  5893. /* These forward decls are needed to use "eval" code for backticks handling: */
  5894. /* flags in argument to evaltree */
  5895. #define EV_EXIT 01 /* exit after evaluating tree */
  5896. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5897. static int evaltree(union node *, int);
  5898. /* An evaltree() which is known to never return.
  5899. * Used to use an alias:
  5900. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5901. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5902. */
  5903. static ALWAYS_INLINE NORETURN void
  5904. evaltreenr(union node *n, int flags)
  5905. {
  5906. evaltree(n, flags);
  5907. bb_unreachable(abort());
  5908. /* NOTREACHED */
  5909. }
  5910. static void FAST_FUNC
  5911. evalbackcmd(union node *n, struct backcmd *result)
  5912. {
  5913. int pip[2];
  5914. struct job *jp;
  5915. result->fd = -1;
  5916. result->buf = NULL;
  5917. result->nleft = 0;
  5918. result->jp = NULL;
  5919. if (n == NULL) {
  5920. goto out;
  5921. }
  5922. if (pipe(pip) < 0)
  5923. ash_msg_and_raise_perror("can't create pipe");
  5924. jp = makejob(/*n,*/ 1);
  5925. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5926. /* child */
  5927. FORCE_INT_ON;
  5928. close(pip[0]);
  5929. if (pip[1] != 1) {
  5930. /*close(1);*/
  5931. dup2_or_raise(pip[1], 1);
  5932. close(pip[1]);
  5933. }
  5934. /* TODO: eflag clearing makes the following not abort:
  5935. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5936. * which is what bash does (unless it is in POSIX mode).
  5937. * dash deleted "eflag = 0" line in the commit
  5938. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5939. * [EVAL] Don't clear eflag in evalbackcmd
  5940. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5941. */
  5942. eflag = 0;
  5943. ifsfree();
  5944. evaltreenr(n, EV_EXIT);
  5945. /* NOTREACHED */
  5946. }
  5947. /* parent */
  5948. close(pip[1]);
  5949. result->fd = pip[0];
  5950. result->jp = jp;
  5951. out:
  5952. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5953. result->fd, result->buf, result->nleft, result->jp));
  5954. }
  5955. /*
  5956. * Expand stuff in backwards quotes.
  5957. */
  5958. static void
  5959. expbackq(union node *cmd, int flag)
  5960. {
  5961. struct backcmd in;
  5962. int i;
  5963. char buf[128];
  5964. char *p;
  5965. char *dest;
  5966. int startloc;
  5967. int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5968. struct stackmark smark;
  5969. INT_OFF;
  5970. startloc = expdest - (char *)stackblock();
  5971. pushstackmark(&smark, startloc);
  5972. evalbackcmd(cmd, &in);
  5973. popstackmark(&smark);
  5974. p = in.buf;
  5975. i = in.nleft;
  5976. if (i == 0)
  5977. goto read;
  5978. for (;;) {
  5979. memtodest(p, i, syntax, flag & QUOTES_ESC);
  5980. read:
  5981. if (in.fd < 0)
  5982. break;
  5983. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  5984. TRACE(("expbackq: read returns %d\n", i));
  5985. if (i <= 0)
  5986. break;
  5987. p = buf;
  5988. }
  5989. free(in.buf);
  5990. if (in.fd >= 0) {
  5991. close(in.fd);
  5992. back_exitstatus = waitforjob(in.jp);
  5993. }
  5994. INT_ON;
  5995. /* Eat all trailing newlines */
  5996. dest = expdest;
  5997. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5998. STUNPUTC(dest);
  5999. expdest = dest;
  6000. if (!(flag & EXP_QUOTED))
  6001. recordregion(startloc, dest - (char *)stackblock(), 0);
  6002. TRACE(("evalbackq: size:%d:'%.*s'\n",
  6003. (int)((dest - (char *)stackblock()) - startloc),
  6004. (int)((dest - (char *)stackblock()) - startloc),
  6005. stackblock() + startloc));
  6006. }
  6007. #if ENABLE_FEATURE_SH_MATH
  6008. /*
  6009. * Expand arithmetic expression. Backup to start of expression,
  6010. * evaluate, place result in (backed up) result, adjust string position.
  6011. */
  6012. static void
  6013. expari(int flag)
  6014. {
  6015. char *p, *start;
  6016. int begoff;
  6017. int len;
  6018. /* ifsfree(); */
  6019. /*
  6020. * This routine is slightly over-complicated for
  6021. * efficiency. Next we scan backwards looking for the
  6022. * start of arithmetic.
  6023. */
  6024. start = stackblock();
  6025. p = expdest - 1;
  6026. *p = '\0';
  6027. p--;
  6028. while (1) {
  6029. int esc;
  6030. while ((unsigned char)*p != CTLARI) {
  6031. p--;
  6032. #if DEBUG
  6033. if (p < start) {
  6034. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  6035. }
  6036. #endif
  6037. }
  6038. esc = esclen(start, p);
  6039. if (!(esc % 2)) {
  6040. break;
  6041. }
  6042. p -= esc + 1;
  6043. }
  6044. begoff = p - start;
  6045. removerecordregions(begoff);
  6046. expdest = p;
  6047. if (flag & QUOTES_ESC)
  6048. rmescapes(p + 1, 0, NULL);
  6049. len = cvtnum(ash_arith(p + 1));
  6050. if (!(flag & EXP_QUOTED))
  6051. recordregion(begoff, begoff + len, 0);
  6052. }
  6053. #endif
  6054. /* argstr needs it */
  6055. static char *evalvar(char *p, int flags);
  6056. /*
  6057. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  6058. * characters to allow for further processing. Otherwise treat
  6059. * $@ like $* since no splitting will be performed.
  6060. */
  6061. static void
  6062. argstr(char *p, int flags)
  6063. {
  6064. static const char spclchars[] ALIGN1 = {
  6065. '=',
  6066. ':',
  6067. CTLQUOTEMARK,
  6068. CTLENDVAR,
  6069. CTLESC,
  6070. CTLVAR,
  6071. CTLBACKQ,
  6072. #if ENABLE_FEATURE_SH_MATH
  6073. CTLENDARI,
  6074. #endif
  6075. '\0'
  6076. };
  6077. const char *reject = spclchars;
  6078. int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6079. int inquotes;
  6080. size_t length;
  6081. int startloc;
  6082. if (!(flags & EXP_VARTILDE)) {
  6083. reject += 2;
  6084. } else if (flags & EXP_VARTILDE2) {
  6085. reject++;
  6086. }
  6087. inquotes = 0;
  6088. length = 0;
  6089. if (flags & EXP_TILDE) {
  6090. char *q;
  6091. flags &= ~EXP_TILDE;
  6092. tilde:
  6093. q = p;
  6094. if (*q == '~')
  6095. p = exptilde(p, q, flags);
  6096. }
  6097. start:
  6098. startloc = expdest - (char *)stackblock();
  6099. for (;;) {
  6100. unsigned char c;
  6101. length += strcspn(p + length, reject);
  6102. c = p[length];
  6103. if (c) {
  6104. if (!(c & 0x80)
  6105. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6106. ) {
  6107. /* c == '=' || c == ':' || c == CTLENDARI */
  6108. length++;
  6109. }
  6110. }
  6111. if (length > 0) {
  6112. int newloc;
  6113. expdest = stack_nputstr(p, length, expdest);
  6114. newloc = expdest - (char *)stackblock();
  6115. if (breakall && !inquotes && newloc > startloc) {
  6116. recordregion(startloc, newloc, 0);
  6117. }
  6118. startloc = newloc;
  6119. }
  6120. p += length + 1;
  6121. length = 0;
  6122. switch (c) {
  6123. case '\0':
  6124. goto breakloop;
  6125. case '=':
  6126. if (flags & EXP_VARTILDE2) {
  6127. p--;
  6128. continue;
  6129. }
  6130. flags |= EXP_VARTILDE2;
  6131. reject++;
  6132. /* fall through */
  6133. case ':':
  6134. /*
  6135. * sort of a hack - expand tildes in variable
  6136. * assignments (after the first '=' and after ':'s).
  6137. */
  6138. if (*--p == '~') {
  6139. goto tilde;
  6140. }
  6141. continue;
  6142. }
  6143. switch (c) {
  6144. case CTLENDVAR: /* ??? */
  6145. goto breakloop;
  6146. case CTLQUOTEMARK:
  6147. /* "$@" syntax adherence hack */
  6148. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6149. p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
  6150. goto start;
  6151. }
  6152. inquotes ^= EXP_QUOTED;
  6153. addquote:
  6154. if (flags & QUOTES_ESC) {
  6155. p--;
  6156. length++;
  6157. startloc++;
  6158. }
  6159. break;
  6160. case CTLESC:
  6161. startloc++;
  6162. length++;
  6163. goto addquote;
  6164. case CTLVAR:
  6165. TRACE(("argstr: evalvar('%s')\n", p));
  6166. p = evalvar(p, flags | inquotes);
  6167. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6168. goto start;
  6169. case CTLBACKQ:
  6170. expbackq(argbackq->n, flags | inquotes);
  6171. argbackq = argbackq->next;
  6172. goto start;
  6173. #if ENABLE_FEATURE_SH_MATH
  6174. case CTLENDARI:
  6175. p--;
  6176. expari(flags | inquotes);
  6177. goto start;
  6178. #endif
  6179. }
  6180. }
  6181. breakloop: ;
  6182. }
  6183. static char *
  6184. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6185. char *pattern, int quotes, int zero)
  6186. {
  6187. char *loc, *loc2;
  6188. char c;
  6189. loc = startp;
  6190. loc2 = rmesc;
  6191. do {
  6192. int match;
  6193. const char *s = loc2;
  6194. c = *loc2;
  6195. if (zero) {
  6196. *loc2 = '\0';
  6197. s = rmesc;
  6198. }
  6199. match = pmatch(pattern, s);
  6200. *loc2 = c;
  6201. if (match)
  6202. return loc;
  6203. if (quotes && (unsigned char)*loc == CTLESC)
  6204. loc++;
  6205. loc++;
  6206. loc2++;
  6207. } while (c);
  6208. return NULL;
  6209. }
  6210. static char *
  6211. scanright(char *startp, char *rmesc, char *rmescend,
  6212. char *pattern, int quotes, int match_at_start)
  6213. {
  6214. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6215. int try2optimize = match_at_start;
  6216. #endif
  6217. int esc = 0;
  6218. char *loc;
  6219. char *loc2;
  6220. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6221. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6222. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6223. * Logic:
  6224. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6225. * and on each iteration they go back two/one char until they reach the beginning.
  6226. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6227. */
  6228. /* TODO: document in what other circumstances we are called. */
  6229. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6230. int match;
  6231. char c = *loc2;
  6232. const char *s = loc2;
  6233. if (match_at_start) {
  6234. *loc2 = '\0';
  6235. s = rmesc;
  6236. }
  6237. match = pmatch(pattern, s);
  6238. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6239. *loc2 = c;
  6240. if (match)
  6241. return loc;
  6242. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6243. if (try2optimize) {
  6244. /* Maybe we can optimize this:
  6245. * if pattern ends with unescaped *, we can avoid checking
  6246. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6247. * it won't match truncated "raw_value_of_" strings too.
  6248. */
  6249. unsigned plen = strlen(pattern);
  6250. /* Does it end with "*"? */
  6251. if (plen != 0 && pattern[--plen] == '*') {
  6252. /* "xxxx*" is not escaped */
  6253. /* "xxx\*" is escaped */
  6254. /* "xx\\*" is not escaped */
  6255. /* "x\\\*" is escaped */
  6256. int slashes = 0;
  6257. while (plen != 0 && pattern[--plen] == '\\')
  6258. slashes++;
  6259. if (!(slashes & 1))
  6260. break; /* ends with unescaped "*" */
  6261. }
  6262. try2optimize = 0;
  6263. }
  6264. #endif
  6265. loc--;
  6266. if (quotes) {
  6267. if (--esc < 0) {
  6268. esc = esclen(startp, loc);
  6269. }
  6270. if (esc % 2) {
  6271. esc--;
  6272. loc--;
  6273. }
  6274. }
  6275. }
  6276. return NULL;
  6277. }
  6278. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6279. static void
  6280. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6281. {
  6282. const char *msg;
  6283. const char *tail;
  6284. tail = nullstr;
  6285. msg = "parameter not set";
  6286. if (umsg) {
  6287. if ((unsigned char)*end == CTLENDVAR) {
  6288. if (varflags & VSNUL)
  6289. tail = " or null";
  6290. } else {
  6291. msg = umsg;
  6292. }
  6293. }
  6294. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6295. }
  6296. static const char *
  6297. subevalvar(char *p, char *varname, int strloc, int subtype,
  6298. int startloc, int varflags, int flag)
  6299. {
  6300. struct nodelist *saveargbackq = argbackq;
  6301. int quotes = flag & QUOTES_ESC;
  6302. char *startp;
  6303. char *loc;
  6304. char *rmesc, *rmescend;
  6305. char *str;
  6306. int amount, resetloc;
  6307. int argstr_flags;
  6308. IF_BASH_PATTERN_SUBST(int workloc;)
  6309. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6310. IF_BASH_PATTERN_SUBST(char *repl;)
  6311. int zero;
  6312. char *(*scan)(char*, char*, char*, char*, int, int);
  6313. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  6314. // p, varname, strloc, subtype, startloc, varflags, quotes);
  6315. #if BASH_PATTERN_SUBST
  6316. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6317. * argstr() call expands possible variable references in pattern:
  6318. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6319. */
  6320. repl = NULL;
  6321. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6322. /* Find '/' and replace with NUL */
  6323. repl = p;
  6324. /* The pattern can't be empty.
  6325. * IOW: if the first char after "${v//" is a slash,
  6326. * it does not terminate the pattern - it's the first char of the pattern:
  6327. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6328. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6329. */
  6330. if (*repl == '/')
  6331. repl++;
  6332. for (;;) {
  6333. if (*repl == '\0') {
  6334. repl = NULL;
  6335. break;
  6336. }
  6337. if (*repl == '/') {
  6338. *repl = '\0';
  6339. break;
  6340. }
  6341. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6342. if ((unsigned char)*repl == CTLESC && repl[1])
  6343. repl++;
  6344. repl++;
  6345. }
  6346. }
  6347. #endif
  6348. argstr_flags = EXP_TILDE;
  6349. if (subtype != VSASSIGN
  6350. && subtype != VSQUESTION
  6351. #if BASH_SUBSTR
  6352. && subtype != VSSUBSTR
  6353. #endif
  6354. ) {
  6355. /* EXP_CASE keeps CTLESC's */
  6356. argstr_flags = EXP_TILDE | EXP_CASE;
  6357. }
  6358. argstr(p, argstr_flags);
  6359. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6360. #if BASH_PATTERN_SUBST
  6361. slash_pos = -1;
  6362. if (repl) {
  6363. slash_pos = expdest - ((char *)stackblock() + strloc);
  6364. STPUTC('/', expdest);
  6365. //bb_error_msg("repl+1:'%s'", repl + 1);
  6366. argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6367. *repl = '/';
  6368. }
  6369. #endif
  6370. STPUTC('\0', expdest);
  6371. argbackq = saveargbackq;
  6372. startp = (char *)stackblock() + startloc;
  6373. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6374. switch (subtype) {
  6375. case VSASSIGN:
  6376. setvar0(varname, startp);
  6377. amount = startp - expdest;
  6378. STADJUST(amount, expdest);
  6379. return startp;
  6380. case VSQUESTION:
  6381. varunset(p, varname, startp, varflags);
  6382. /* NOTREACHED */
  6383. #if BASH_SUBSTR
  6384. case VSSUBSTR: {
  6385. int pos, len, orig_len;
  6386. char *colon;
  6387. loc = str = stackblock() + strloc;
  6388. /* Read POS in ${var:POS:LEN} */
  6389. colon = strchr(loc, ':');
  6390. if (colon) *colon = '\0';
  6391. pos = substr_atoi(loc);
  6392. if (colon) *colon = ':';
  6393. /* Read LEN in ${var:POS:LEN} */
  6394. len = str - startp - 1;
  6395. /* *loc != '\0', guaranteed by parser */
  6396. if (quotes) {
  6397. char *ptr;
  6398. /* Adjust the length by the number of escapes */
  6399. for (ptr = startp; ptr < (str - 1); ptr++) {
  6400. if ((unsigned char)*ptr == CTLESC) {
  6401. len--;
  6402. ptr++;
  6403. }
  6404. }
  6405. }
  6406. orig_len = len;
  6407. if (*loc++ == ':') {
  6408. /* ${var::LEN} */
  6409. len = substr_atoi(loc);
  6410. } else {
  6411. /* Skip POS in ${var:POS:LEN} */
  6412. len = orig_len;
  6413. while (*loc && *loc != ':')
  6414. loc++;
  6415. if (*loc++ == ':')
  6416. len = substr_atoi(loc);
  6417. }
  6418. if (pos < 0) {
  6419. /* ${VAR:$((-n)):l} starts n chars from the end */
  6420. pos = orig_len + pos;
  6421. }
  6422. if ((unsigned)pos >= orig_len) {
  6423. /* apart from obvious ${VAR:999999:l},
  6424. * covers ${VAR:$((-9999999)):l} - result is ""
  6425. * (bash compat)
  6426. */
  6427. pos = 0;
  6428. len = 0;
  6429. }
  6430. if (len < 0) {
  6431. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6432. len = (orig_len - pos) + len;
  6433. }
  6434. if ((unsigned)len > (orig_len - pos))
  6435. len = orig_len - pos;
  6436. for (str = startp; pos; str++, pos--) {
  6437. if (quotes && (unsigned char)*str == CTLESC)
  6438. str++;
  6439. }
  6440. for (loc = startp; len; len--) {
  6441. if (quotes && (unsigned char)*str == CTLESC)
  6442. *loc++ = *str++;
  6443. *loc++ = *str++;
  6444. }
  6445. *loc = '\0';
  6446. amount = loc - expdest;
  6447. STADJUST(amount, expdest);
  6448. return loc;
  6449. }
  6450. #endif /* BASH_SUBSTR */
  6451. }
  6452. resetloc = expdest - (char *)stackblock();
  6453. #if BASH_PATTERN_SUBST
  6454. repl = NULL;
  6455. /* We'll comeback here if we grow the stack while handling
  6456. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6457. * stack will need rebasing, and we'll need to remove our work
  6458. * areas each time
  6459. */
  6460. restart:
  6461. #endif
  6462. amount = expdest - ((char *)stackblock() + resetloc);
  6463. STADJUST(-amount, expdest);
  6464. startp = (char *)stackblock() + startloc;
  6465. rmesc = startp;
  6466. rmescend = (char *)stackblock() + strloc;
  6467. //bb_error_msg("str7:'%s'", rmescend);
  6468. if (quotes) {
  6469. //TODO: how to handle slash_pos here if string changes (shortens?)
  6470. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6471. if (rmesc != startp) {
  6472. rmescend = expdest;
  6473. startp = (char *)stackblock() + startloc;
  6474. }
  6475. }
  6476. rmescend--;
  6477. str = (char *)stackblock() + strloc;
  6478. /*
  6479. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6480. * The result is a_\_z_c (not a\_\_z_c)!
  6481. *
  6482. * The search pattern and replace string treat backslashes differently!
  6483. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6484. * and string. It's only used on the first call.
  6485. */
  6486. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6487. rmescapes(str, RMESCAPE_GLOB,
  6488. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6489. );
  6490. #if BASH_PATTERN_SUBST
  6491. workloc = expdest - (char *)stackblock();
  6492. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6493. int len;
  6494. char *idx, *end;
  6495. if (!repl) {
  6496. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6497. repl = nullstr;
  6498. if (slash_pos >= 0) {
  6499. repl = str + slash_pos;
  6500. *repl++ = '\0';
  6501. }
  6502. }
  6503. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6504. /* If there's no pattern to match, return the expansion unmolested */
  6505. if (str[0] == '\0')
  6506. return NULL;
  6507. len = 0;
  6508. idx = startp;
  6509. end = str - 1;
  6510. while (idx < end) {
  6511. try_to_match:
  6512. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6513. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6514. if (!loc) {
  6515. /* No match, advance */
  6516. char *restart_detect = stackblock();
  6517. skip_matching:
  6518. STPUTC(*idx, expdest);
  6519. if (quotes && (unsigned char)*idx == CTLESC) {
  6520. idx++;
  6521. len++;
  6522. STPUTC(*idx, expdest);
  6523. }
  6524. if (stackblock() != restart_detect)
  6525. goto restart;
  6526. idx++;
  6527. len++;
  6528. rmesc++;
  6529. /* continue; - prone to quadratic behavior, smarter code: */
  6530. if (idx >= end)
  6531. break;
  6532. if (str[0] == '*') {
  6533. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6534. * it would never match "ong_string" etc, no point in trying.
  6535. */
  6536. goto skip_matching;
  6537. }
  6538. goto try_to_match;
  6539. }
  6540. if (subtype == VSREPLACEALL) {
  6541. while (idx < loc) {
  6542. if (quotes && (unsigned char)*idx == CTLESC)
  6543. idx++;
  6544. idx++;
  6545. rmesc++;
  6546. }
  6547. } else {
  6548. idx = loc;
  6549. }
  6550. //bb_error_msg("repl:'%s'", repl);
  6551. for (loc = (char*)repl; *loc; loc++) {
  6552. char *restart_detect = stackblock();
  6553. if (quotes && *loc == '\\') {
  6554. STPUTC(CTLESC, expdest);
  6555. len++;
  6556. }
  6557. STPUTC(*loc, expdest);
  6558. if (stackblock() != restart_detect)
  6559. goto restart;
  6560. len++;
  6561. }
  6562. if (subtype == VSREPLACE) {
  6563. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6564. while (*idx) {
  6565. char *restart_detect = stackblock();
  6566. STPUTC(*idx, expdest);
  6567. if (stackblock() != restart_detect)
  6568. goto restart;
  6569. len++;
  6570. idx++;
  6571. }
  6572. break;
  6573. }
  6574. }
  6575. /* We've put the replaced text into a buffer at workloc, now
  6576. * move it to the right place and adjust the stack.
  6577. */
  6578. STPUTC('\0', expdest);
  6579. startp = (char *)stackblock() + startloc;
  6580. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6581. //bb_error_msg("startp:'%s'", startp);
  6582. amount = expdest - (startp + len);
  6583. STADJUST(-amount, expdest);
  6584. return startp;
  6585. }
  6586. #endif /* BASH_PATTERN_SUBST */
  6587. subtype -= VSTRIMRIGHT;
  6588. #if DEBUG
  6589. if (subtype < 0 || subtype > 7)
  6590. abort();
  6591. #endif
  6592. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6593. zero = subtype >> 1;
  6594. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6595. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6596. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6597. if (loc) {
  6598. if (zero) {
  6599. memmove(startp, loc, str - loc);
  6600. loc = startp + (str - loc) - 1;
  6601. }
  6602. *loc = '\0';
  6603. amount = loc - expdest;
  6604. STADJUST(amount, expdest);
  6605. }
  6606. return loc;
  6607. }
  6608. /*
  6609. * Add the value of a specialized variable to the stack string.
  6610. * name parameter (examples):
  6611. * ash -c 'echo $1' name:'1='
  6612. * ash -c 'echo $qwe' name:'qwe='
  6613. * ash -c 'echo $$' name:'$='
  6614. * ash -c 'echo ${$}' name:'$='
  6615. * ash -c 'echo ${$##q}' name:'$=q'
  6616. * ash -c 'echo ${#$}' name:'$='
  6617. * note: examples with bad shell syntax:
  6618. * ash -c 'echo ${#$1}' name:'$=1'
  6619. * ash -c 'echo ${#1#}' name:'1=#'
  6620. */
  6621. static NOINLINE ssize_t
  6622. varvalue(char *name, int varflags, int flags, int quoted)
  6623. {
  6624. const char *p;
  6625. int num;
  6626. int i;
  6627. ssize_t len = 0;
  6628. int sep;
  6629. int subtype = varflags & VSTYPE;
  6630. int discard = subtype == VSPLUS || subtype == VSLENGTH;
  6631. int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
  6632. int syntax;
  6633. sep = (flags & EXP_FULL) << CHAR_BIT;
  6634. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  6635. switch (*name) {
  6636. case '$':
  6637. num = rootpid;
  6638. goto numvar;
  6639. case '?':
  6640. num = exitstatus;
  6641. goto numvar;
  6642. case '#':
  6643. num = shellparam.nparam;
  6644. goto numvar;
  6645. case '!':
  6646. num = backgndpid;
  6647. if (num == 0)
  6648. return -1;
  6649. numvar:
  6650. len = cvtnum(num);
  6651. goto check_1char_name;
  6652. case '-':
  6653. expdest = makestrspace(NOPTS, expdest);
  6654. for (i = NOPTS - 1; i >= 0; i--) {
  6655. if (optlist[i] && optletters(i)) {
  6656. USTPUTC(optletters(i), expdest);
  6657. len++;
  6658. }
  6659. }
  6660. check_1char_name:
  6661. #if 0
  6662. /* handles cases similar to ${#$1} */
  6663. if (name[2] != '\0')
  6664. raise_error_syntax("bad substitution");
  6665. #endif
  6666. break;
  6667. case '@':
  6668. if (quoted && sep)
  6669. goto param;
  6670. /* fall through */
  6671. case '*': {
  6672. char **ap;
  6673. char sepc;
  6674. char c;
  6675. /* We will set c to 0 or ~0 depending on whether
  6676. * we're doing field splitting. We won't do field
  6677. * splitting if either we're quoted or sep is zero.
  6678. *
  6679. * Instead of testing (quoted || !sep) the following
  6680. * trick optimises away any branches by using the
  6681. * fact that EXP_QUOTED (which is the only bit that
  6682. * can be set in quoted) is the same as EXP_FULL <<
  6683. * CHAR_BIT (which is the only bit that can be set
  6684. * in sep).
  6685. */
  6686. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6687. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6688. #endif
  6689. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6690. sep &= ~quoted;
  6691. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6692. param:
  6693. sepc = sep;
  6694. ap = shellparam.p;
  6695. if (!ap)
  6696. return -1;
  6697. while ((p = *ap++) != NULL) {
  6698. len += strtodest(p, syntax, quotes);
  6699. if (*ap && sep) {
  6700. len++;
  6701. memtodest(&sepc, 1, syntax, quotes);
  6702. }
  6703. }
  6704. break;
  6705. } /* case '*' */
  6706. case '0':
  6707. case '1':
  6708. case '2':
  6709. case '3':
  6710. case '4':
  6711. case '5':
  6712. case '6':
  6713. case '7':
  6714. case '8':
  6715. case '9':
  6716. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6717. if (num < 0 || num > shellparam.nparam)
  6718. return -1;
  6719. p = num ? shellparam.p[num - 1] : arg0;
  6720. goto value;
  6721. default:
  6722. /* NB: name has form "VAR=..." */
  6723. p = lookupvar(name);
  6724. value:
  6725. if (!p)
  6726. return -1;
  6727. len = strtodest(p, syntax, quotes);
  6728. #if ENABLE_UNICODE_SUPPORT
  6729. if (subtype == VSLENGTH && len > 0) {
  6730. reinit_unicode_for_ash();
  6731. if (unicode_status == UNICODE_ON) {
  6732. STADJUST(-len, expdest);
  6733. discard = 0;
  6734. len = unicode_strlen(p);
  6735. }
  6736. }
  6737. #endif
  6738. break;
  6739. }
  6740. if (discard)
  6741. STADJUST(-len, expdest);
  6742. return len;
  6743. }
  6744. /*
  6745. * Expand a variable, and return a pointer to the next character in the
  6746. * input string.
  6747. */
  6748. static char *
  6749. evalvar(char *p, int flag)
  6750. {
  6751. char varflags;
  6752. char subtype;
  6753. int quoted;
  6754. char *var;
  6755. int patloc;
  6756. int startloc;
  6757. ssize_t varlen;
  6758. varflags = (unsigned char) *p++;
  6759. subtype = varflags & VSTYPE;
  6760. if (!subtype)
  6761. raise_error_syntax("bad substitution");
  6762. quoted = flag & EXP_QUOTED;
  6763. var = p;
  6764. startloc = expdest - (char *)stackblock();
  6765. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6766. again:
  6767. varlen = varvalue(var, varflags, flag, quoted);
  6768. if (varflags & VSNUL)
  6769. varlen--;
  6770. if (subtype == VSPLUS) {
  6771. varlen = -1 - varlen;
  6772. goto vsplus;
  6773. }
  6774. if (subtype == VSMINUS) {
  6775. vsplus:
  6776. if (varlen < 0) {
  6777. argstr(
  6778. p,
  6779. flag | EXP_TILDE | EXP_WORD
  6780. );
  6781. goto end;
  6782. }
  6783. goto record;
  6784. }
  6785. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6786. if (varlen >= 0)
  6787. goto record;
  6788. subevalvar(p, var, 0, subtype, startloc, varflags,
  6789. flag & ~QUOTES_ESC);
  6790. varflags &= ~VSNUL;
  6791. /*
  6792. * Remove any recorded regions beyond
  6793. * start of variable
  6794. */
  6795. removerecordregions(startloc);
  6796. goto again;
  6797. }
  6798. if (varlen < 0 && uflag)
  6799. varunset(p, var, 0, 0);
  6800. if (subtype == VSLENGTH) {
  6801. cvtnum(varlen > 0 ? varlen : 0);
  6802. goto record;
  6803. }
  6804. if (subtype == VSNORMAL) {
  6805. record:
  6806. if (quoted) {
  6807. quoted = *var == '@' && shellparam.nparam;
  6808. if (!quoted)
  6809. goto end;
  6810. }
  6811. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6812. goto end;
  6813. }
  6814. #if DEBUG
  6815. switch (subtype) {
  6816. case VSTRIMLEFT:
  6817. case VSTRIMLEFTMAX:
  6818. case VSTRIMRIGHT:
  6819. case VSTRIMRIGHTMAX:
  6820. #if BASH_SUBSTR
  6821. case VSSUBSTR:
  6822. #endif
  6823. #if BASH_PATTERN_SUBST
  6824. case VSREPLACE:
  6825. case VSREPLACEALL:
  6826. #endif
  6827. break;
  6828. default:
  6829. abort();
  6830. }
  6831. #endif
  6832. if (varlen >= 0) {
  6833. /*
  6834. * Terminate the string and start recording the pattern
  6835. * right after it
  6836. */
  6837. STPUTC('\0', expdest);
  6838. patloc = expdest - (char *)stackblock();
  6839. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6840. startloc, varflags, flag)) {
  6841. int amount = expdest - (
  6842. (char *)stackblock() + patloc - 1
  6843. );
  6844. STADJUST(-amount, expdest);
  6845. }
  6846. /* Remove any recorded regions beyond start of variable */
  6847. removerecordregions(startloc);
  6848. goto record;
  6849. }
  6850. end:
  6851. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6852. int nesting = 1;
  6853. for (;;) {
  6854. unsigned char c = *p++;
  6855. if (c == CTLESC)
  6856. p++;
  6857. else if (c == CTLBACKQ) {
  6858. if (varlen >= 0)
  6859. argbackq = argbackq->next;
  6860. } else if (c == CTLVAR) {
  6861. if ((*p++ & VSTYPE) != VSNORMAL)
  6862. nesting++;
  6863. } else if (c == CTLENDVAR) {
  6864. if (--nesting == 0)
  6865. break;
  6866. }
  6867. }
  6868. }
  6869. return p;
  6870. }
  6871. /*
  6872. * Add a file name to the list.
  6873. */
  6874. static void
  6875. addfname(const char *name)
  6876. {
  6877. struct strlist *sp;
  6878. sp = stzalloc(sizeof(*sp));
  6879. sp->text = sstrdup(name);
  6880. *exparg.lastp = sp;
  6881. exparg.lastp = &sp->next;
  6882. }
  6883. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6884. static int
  6885. hasmeta(const char *p)
  6886. {
  6887. static const char chars[] ALIGN1 = {
  6888. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6889. };
  6890. for (;;) {
  6891. p = strpbrk(p, chars);
  6892. if (!p)
  6893. break;
  6894. switch ((unsigned char)*p) {
  6895. case CTLQUOTEMARK:
  6896. for (;;) {
  6897. p++;
  6898. if ((unsigned char)*p == CTLQUOTEMARK)
  6899. break;
  6900. if ((unsigned char)*p == CTLESC)
  6901. p++;
  6902. if (*p == '\0') /* huh? */
  6903. return 0;
  6904. }
  6905. break;
  6906. case '\\':
  6907. case CTLESC:
  6908. p++;
  6909. if (*p == '\0')
  6910. return 0;
  6911. break;
  6912. case '[':
  6913. if (!strchr(p + 1, ']')) {
  6914. /* It's not a properly closed [] pattern,
  6915. * but other metas may follow. Continue checking.
  6916. * my[file* _is_ globbed by bash
  6917. * and matches filenames like "my[file1".
  6918. */
  6919. break;
  6920. }
  6921. /* fallthrough */
  6922. default:
  6923. /* case '*': */
  6924. /* case '?': */
  6925. return 1;
  6926. }
  6927. p++;
  6928. }
  6929. return 0;
  6930. }
  6931. /* If we want to use glob() from libc... */
  6932. #if !ENABLE_ASH_INTERNAL_GLOB
  6933. /* Add the result of glob() to the list */
  6934. static void
  6935. addglob(const glob_t *pglob)
  6936. {
  6937. char **p = pglob->gl_pathv;
  6938. do {
  6939. addfname(*p);
  6940. } while (*++p);
  6941. }
  6942. static void
  6943. expandmeta(struct strlist *str /*, int flag*/)
  6944. {
  6945. /* TODO - EXP_REDIR */
  6946. while (str) {
  6947. char *p;
  6948. glob_t pglob;
  6949. int i;
  6950. if (fflag)
  6951. goto nometa;
  6952. if (!hasmeta(str->text))
  6953. goto nometa;
  6954. INT_OFF;
  6955. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6956. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6957. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6958. //
  6959. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6960. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6961. // Which means you need to unescape the string, right? Not so fast:
  6962. // if there _is_ a file named "file\?" (with backslash), it is returned
  6963. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6964. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6965. //
  6966. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6967. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6968. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6969. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6970. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6971. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6972. i = glob(p, 0, NULL, &pglob);
  6973. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6974. if (p != str->text)
  6975. free(p);
  6976. switch (i) {
  6977. case 0:
  6978. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6979. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6980. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6981. goto nometa2;
  6982. #endif
  6983. addglob(&pglob);
  6984. globfree(&pglob);
  6985. INT_ON;
  6986. break;
  6987. case GLOB_NOMATCH:
  6988. //nometa2:
  6989. globfree(&pglob);
  6990. INT_ON;
  6991. nometa:
  6992. *exparg.lastp = str;
  6993. rmescapes(str->text, 0, NULL);
  6994. exparg.lastp = &str->next;
  6995. break;
  6996. default: /* GLOB_NOSPACE */
  6997. globfree(&pglob);
  6998. INT_ON;
  6999. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  7000. }
  7001. str = str->next;
  7002. }
  7003. }
  7004. #else
  7005. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  7006. /*
  7007. * Do metacharacter (i.e. *, ?, [...]) expansion.
  7008. */
  7009. typedef struct exp_t {
  7010. char *dir;
  7011. unsigned dir_max;
  7012. } exp_t;
  7013. static void
  7014. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  7015. {
  7016. #define expdir exp->dir
  7017. #define expdir_max exp->dir_max
  7018. char *enddir = expdir + expdir_len;
  7019. char *p;
  7020. const char *cp;
  7021. char *start;
  7022. char *endname;
  7023. int metaflag;
  7024. struct stat statb;
  7025. DIR *dirp;
  7026. struct dirent *dp;
  7027. int atend;
  7028. int matchdot;
  7029. int esc;
  7030. metaflag = 0;
  7031. start = name;
  7032. for (p = name; esc = 0, *p; p += esc + 1) {
  7033. if (*p == '*' || *p == '?')
  7034. metaflag = 1;
  7035. else if (*p == '[') {
  7036. char *q = p + 1;
  7037. if (*q == '!')
  7038. q++;
  7039. for (;;) {
  7040. if (*q == '\\')
  7041. q++;
  7042. if (*q == '/' || *q == '\0')
  7043. break;
  7044. if (*++q == ']') {
  7045. metaflag = 1;
  7046. break;
  7047. }
  7048. }
  7049. } else {
  7050. if (*p == '\\' && p[1])
  7051. esc++;
  7052. if (p[esc] == '/') {
  7053. if (metaflag)
  7054. break;
  7055. start = p + esc + 1;
  7056. }
  7057. }
  7058. }
  7059. if (metaflag == 0) { /* we've reached the end of the file name */
  7060. if (!expdir_len)
  7061. return;
  7062. p = name;
  7063. do {
  7064. if (*p == '\\' && p[1])
  7065. p++;
  7066. *enddir++ = *p;
  7067. } while (*p++);
  7068. if (lstat(expdir, &statb) == 0)
  7069. addfname(expdir);
  7070. return;
  7071. }
  7072. endname = p;
  7073. if (name < start) {
  7074. p = name;
  7075. do {
  7076. if (*p == '\\' && p[1])
  7077. p++;
  7078. *enddir++ = *p++;
  7079. } while (p < start);
  7080. }
  7081. *enddir = '\0';
  7082. cp = expdir;
  7083. expdir_len = enddir - cp;
  7084. if (!expdir_len)
  7085. cp = ".";
  7086. dirp = opendir(cp);
  7087. if (dirp == NULL)
  7088. return;
  7089. if (*endname == 0) {
  7090. atend = 1;
  7091. } else {
  7092. atend = 0;
  7093. *endname = '\0';
  7094. endname += esc + 1;
  7095. }
  7096. name_len -= endname - name;
  7097. matchdot = 0;
  7098. p = start;
  7099. if (*p == '\\')
  7100. p++;
  7101. if (*p == '.')
  7102. matchdot++;
  7103. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7104. if (dp->d_name[0] == '.' && !matchdot)
  7105. continue;
  7106. if (pmatch(start, dp->d_name)) {
  7107. if (atend) {
  7108. strcpy(enddir, dp->d_name);
  7109. addfname(expdir);
  7110. } else {
  7111. unsigned offset;
  7112. unsigned len;
  7113. p = stpcpy(enddir, dp->d_name);
  7114. *p = '/';
  7115. offset = p - expdir + 1;
  7116. len = offset + name_len + NAME_MAX;
  7117. if (len > expdir_max) {
  7118. len += PATH_MAX;
  7119. expdir = ckrealloc(expdir, len);
  7120. expdir_max = len;
  7121. }
  7122. expmeta(exp, endname, name_len, offset);
  7123. enddir = expdir + expdir_len;
  7124. }
  7125. }
  7126. }
  7127. closedir(dirp);
  7128. if (!atend)
  7129. endname[-esc - 1] = esc ? '\\' : '/';
  7130. #undef expdir
  7131. #undef expdir_max
  7132. }
  7133. static struct strlist *
  7134. msort(struct strlist *list, int len)
  7135. {
  7136. struct strlist *p, *q = NULL;
  7137. struct strlist **lpp;
  7138. int half;
  7139. int n;
  7140. if (len <= 1)
  7141. return list;
  7142. half = len >> 1;
  7143. p = list;
  7144. for (n = half; --n >= 0;) {
  7145. q = p;
  7146. p = p->next;
  7147. }
  7148. q->next = NULL; /* terminate first half of list */
  7149. q = msort(list, half); /* sort first half of list */
  7150. p = msort(p, len - half); /* sort second half */
  7151. lpp = &list;
  7152. for (;;) {
  7153. #if ENABLE_LOCALE_SUPPORT
  7154. if (strcoll(p->text, q->text) < 0)
  7155. #else
  7156. if (strcmp(p->text, q->text) < 0)
  7157. #endif
  7158. {
  7159. *lpp = p;
  7160. lpp = &p->next;
  7161. p = *lpp;
  7162. if (p == NULL) {
  7163. *lpp = q;
  7164. break;
  7165. }
  7166. } else {
  7167. *lpp = q;
  7168. lpp = &q->next;
  7169. q = *lpp;
  7170. if (q == NULL) {
  7171. *lpp = p;
  7172. break;
  7173. }
  7174. }
  7175. }
  7176. return list;
  7177. }
  7178. /*
  7179. * Sort the results of file name expansion. It calculates the number of
  7180. * strings to sort and then calls msort (short for merge sort) to do the
  7181. * work.
  7182. */
  7183. static struct strlist *
  7184. expsort(struct strlist *str)
  7185. {
  7186. int len;
  7187. struct strlist *sp;
  7188. len = 0;
  7189. for (sp = str; sp; sp = sp->next)
  7190. len++;
  7191. return msort(str, len);
  7192. }
  7193. static void
  7194. expandmeta(struct strlist *str /*, int flag*/)
  7195. {
  7196. /* TODO - EXP_REDIR */
  7197. while (str) {
  7198. exp_t exp;
  7199. struct strlist **savelastp;
  7200. struct strlist *sp;
  7201. char *p;
  7202. unsigned len;
  7203. if (fflag)
  7204. goto nometa;
  7205. if (!hasmeta(str->text))
  7206. goto nometa;
  7207. savelastp = exparg.lastp;
  7208. INT_OFF;
  7209. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7210. len = strlen(p);
  7211. exp.dir_max = len + PATH_MAX;
  7212. exp.dir = ckmalloc(exp.dir_max);
  7213. expmeta(&exp, p, len, 0);
  7214. free(exp.dir);
  7215. if (p != str->text)
  7216. free(p);
  7217. INT_ON;
  7218. if (exparg.lastp == savelastp) {
  7219. /*
  7220. * no matches
  7221. */
  7222. nometa:
  7223. *exparg.lastp = str;
  7224. rmescapes(str->text, 0, NULL);
  7225. exparg.lastp = &str->next;
  7226. } else {
  7227. *exparg.lastp = NULL;
  7228. *savelastp = sp = expsort(*savelastp);
  7229. while (sp->next != NULL)
  7230. sp = sp->next;
  7231. exparg.lastp = &sp->next;
  7232. }
  7233. str = str->next;
  7234. }
  7235. }
  7236. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7237. /*
  7238. * Perform variable substitution and command substitution on an argument,
  7239. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7240. * perform splitting and file name expansion. When arglist is NULL, perform
  7241. * here document expansion.
  7242. */
  7243. static void
  7244. expandarg(union node *arg, struct arglist *arglist, int flag)
  7245. {
  7246. struct strlist *sp;
  7247. char *p;
  7248. argbackq = arg->narg.backquote;
  7249. STARTSTACKSTR(expdest);
  7250. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7251. argstr(arg->narg.text, flag);
  7252. p = _STPUTC('\0', expdest);
  7253. expdest = p - 1;
  7254. if (arglist == NULL) {
  7255. /* here document expanded */
  7256. goto out;
  7257. }
  7258. p = grabstackstr(p);
  7259. TRACE(("expandarg: p:'%s'\n", p));
  7260. exparg.lastp = &exparg.list;
  7261. /*
  7262. * TODO - EXP_REDIR
  7263. */
  7264. if (flag & EXP_FULL) {
  7265. ifsbreakup(p, &exparg);
  7266. *exparg.lastp = NULL;
  7267. exparg.lastp = &exparg.list;
  7268. expandmeta(exparg.list /*, flag*/);
  7269. } else {
  7270. sp = stzalloc(sizeof(*sp));
  7271. sp->text = p;
  7272. *exparg.lastp = sp;
  7273. exparg.lastp = &sp->next;
  7274. }
  7275. *exparg.lastp = NULL;
  7276. if (exparg.list) {
  7277. *arglist->lastp = exparg.list;
  7278. arglist->lastp = exparg.lastp;
  7279. }
  7280. out:
  7281. ifsfree();
  7282. }
  7283. /*
  7284. * Expand shell variables and backquotes inside a here document.
  7285. */
  7286. static void
  7287. expandhere(union node *arg, int fd)
  7288. {
  7289. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7290. full_write(fd, stackblock(), expdest - (char *)stackblock());
  7291. }
  7292. /*
  7293. * Returns true if the pattern matches the string.
  7294. */
  7295. static int
  7296. patmatch(char *pattern, const char *string)
  7297. {
  7298. char *p = preglob(pattern, 0);
  7299. int r = pmatch(p, string);
  7300. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7301. return r;
  7302. }
  7303. /*
  7304. * See if a pattern matches in a case statement.
  7305. */
  7306. static int
  7307. casematch(union node *pattern, char *val)
  7308. {
  7309. struct stackmark smark;
  7310. int result;
  7311. setstackmark(&smark);
  7312. argbackq = pattern->narg.backquote;
  7313. STARTSTACKSTR(expdest);
  7314. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7315. STACKSTRNUL(expdest);
  7316. ifsfree();
  7317. result = patmatch(stackblock(), val);
  7318. popstackmark(&smark);
  7319. return result;
  7320. }
  7321. /* ============ find_command */
  7322. struct builtincmd {
  7323. const char *name;
  7324. int (*builtin)(int, char **) FAST_FUNC;
  7325. /* unsigned flags; */
  7326. };
  7327. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7328. /* "regular" builtins always take precedence over commands,
  7329. * regardless of PATH=....%builtin... position */
  7330. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7331. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7332. struct cmdentry {
  7333. smallint cmdtype; /* CMDxxx */
  7334. union param {
  7335. int index;
  7336. /* index >= 0 for commands without path (slashes) */
  7337. /* (TODO: what exactly does the value mean? PATH position?) */
  7338. /* index == -1 for commands with slashes */
  7339. /* index == (-2 - applet_no) for NOFORK applets */
  7340. const struct builtincmd *cmd;
  7341. struct funcnode *func;
  7342. } u;
  7343. };
  7344. /* values of cmdtype */
  7345. #define CMDUNKNOWN -1 /* no entry in table for command */
  7346. #define CMDNORMAL 0 /* command is an executable program */
  7347. #define CMDFUNCTION 1 /* command is a shell function */
  7348. #define CMDBUILTIN 2 /* command is a shell builtin */
  7349. /* action to find_command() */
  7350. #define DO_ERR 0x01 /* prints errors */
  7351. #define DO_ABS 0x02 /* checks absolute paths */
  7352. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7353. #define DO_ALTPATH 0x08 /* using alternate path */
  7354. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  7355. static void find_command(char *, struct cmdentry *, int, const char *);
  7356. /* ============ Hashing commands */
  7357. /*
  7358. * When commands are first encountered, they are entered in a hash table.
  7359. * This ensures that a full path search will not have to be done for them
  7360. * on each invocation.
  7361. *
  7362. * We should investigate converting to a linear search, even though that
  7363. * would make the command name "hash" a misnomer.
  7364. */
  7365. struct tblentry {
  7366. struct tblentry *next; /* next entry in hash chain */
  7367. union param param; /* definition of builtin function */
  7368. smallint cmdtype; /* CMDxxx */
  7369. char rehash; /* if set, cd done since entry created */
  7370. char cmdname[1]; /* name of command */
  7371. };
  7372. static struct tblentry **cmdtable;
  7373. #define INIT_G_cmdtable() do { \
  7374. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7375. } while (0)
  7376. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7377. static void
  7378. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7379. {
  7380. #if ENABLE_FEATURE_SH_STANDALONE
  7381. if (applet_no >= 0) {
  7382. if (APPLET_IS_NOEXEC(applet_no)) {
  7383. clearenv();
  7384. while (*envp)
  7385. putenv(*envp++);
  7386. popredir(/*drop:*/ 1);
  7387. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7388. }
  7389. /* re-exec ourselves with the new arguments */
  7390. execve(bb_busybox_exec_path, argv, envp);
  7391. /* If they called chroot or otherwise made the binary no longer
  7392. * executable, fall through */
  7393. }
  7394. #endif
  7395. repeat:
  7396. #ifdef SYSV
  7397. do {
  7398. execve(cmd, argv, envp);
  7399. } while (errno == EINTR);
  7400. #else
  7401. execve(cmd, argv, envp);
  7402. #endif
  7403. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7404. /* Run "cmd" as a shell script:
  7405. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7406. * "If the execve() function fails with ENOEXEC, the shell
  7407. * shall execute a command equivalent to having a shell invoked
  7408. * with the command name as its first operand,
  7409. * with any remaining arguments passed to the new shell"
  7410. *
  7411. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7412. * just call ourselves.
  7413. *
  7414. * Note that bash reads ~80 chars of the file, and if it sees
  7415. * a zero byte before it sees newline, it doesn't try to
  7416. * interpret it, but fails with "cannot execute binary file"
  7417. * message and exit code 126. For one, this prevents attempts
  7418. * to interpret foreign ELF binaries as shell scripts.
  7419. */
  7420. argv[0] = (char*) cmd;
  7421. cmd = bb_busybox_exec_path;
  7422. /* NB: this is only possible because all callers of shellexec()
  7423. * ensure that the argv[-1] slot exists!
  7424. */
  7425. argv--;
  7426. argv[0] = (char*) "ash";
  7427. goto repeat;
  7428. }
  7429. }
  7430. /*
  7431. * Exec a program. Never returns. If you change this routine, you may
  7432. * have to change the find_command routine as well.
  7433. * argv[-1] must exist and be writable! See tryexec() for why.
  7434. */
  7435. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7436. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7437. {
  7438. char *cmdname;
  7439. int e;
  7440. char **envp;
  7441. int exerrno;
  7442. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7443. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7444. if (strchr(prog, '/') != NULL
  7445. #if ENABLE_FEATURE_SH_STANDALONE
  7446. || (applet_no = find_applet_by_name(prog)) >= 0
  7447. #endif
  7448. ) {
  7449. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7450. if (applet_no >= 0) {
  7451. /* We tried execing ourself, but it didn't work.
  7452. * Maybe /proc/self/exe doesn't exist?
  7453. * Try $PATH search.
  7454. */
  7455. goto try_PATH;
  7456. }
  7457. e = errno;
  7458. } else {
  7459. try_PATH:
  7460. e = ENOENT;
  7461. while ((cmdname = path_advance(&path, prog)) != NULL) {
  7462. if (--idx < 0 && pathopt == NULL) {
  7463. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7464. if (errno != ENOENT && errno != ENOTDIR)
  7465. e = errno;
  7466. }
  7467. stunalloc(cmdname);
  7468. }
  7469. }
  7470. /* Map to POSIX errors */
  7471. switch (e) {
  7472. default:
  7473. exerrno = 126;
  7474. break;
  7475. case ELOOP:
  7476. case ENAMETOOLONG:
  7477. case ENOENT:
  7478. case ENOTDIR:
  7479. exerrno = 127;
  7480. break;
  7481. }
  7482. exitstatus = exerrno;
  7483. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7484. prog, e, suppress_int));
  7485. ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
  7486. /* NOTREACHED */
  7487. }
  7488. static void
  7489. printentry(struct tblentry *cmdp)
  7490. {
  7491. int idx;
  7492. const char *path;
  7493. char *name;
  7494. idx = cmdp->param.index;
  7495. path = pathval();
  7496. do {
  7497. name = path_advance(&path, cmdp->cmdname);
  7498. stunalloc(name);
  7499. } while (--idx >= 0);
  7500. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7501. }
  7502. /*
  7503. * Clear out command entries. The argument specifies the first entry in
  7504. * PATH which has changed.
  7505. */
  7506. static void
  7507. clearcmdentry(int firstchange)
  7508. {
  7509. struct tblentry **tblp;
  7510. struct tblentry **pp;
  7511. struct tblentry *cmdp;
  7512. INT_OFF;
  7513. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7514. pp = tblp;
  7515. while ((cmdp = *pp) != NULL) {
  7516. if ((cmdp->cmdtype == CMDNORMAL &&
  7517. cmdp->param.index >= firstchange)
  7518. || (cmdp->cmdtype == CMDBUILTIN &&
  7519. builtinloc >= firstchange)
  7520. ) {
  7521. *pp = cmdp->next;
  7522. free(cmdp);
  7523. } else {
  7524. pp = &cmdp->next;
  7525. }
  7526. }
  7527. }
  7528. INT_ON;
  7529. }
  7530. /*
  7531. * Locate a command in the command hash table. If "add" is nonzero,
  7532. * add the command to the table if it is not already present. The
  7533. * variable "lastcmdentry" is set to point to the address of the link
  7534. * pointing to the entry, so that delete_cmd_entry can delete the
  7535. * entry.
  7536. *
  7537. * Interrupts must be off if called with add != 0.
  7538. */
  7539. static struct tblentry **lastcmdentry;
  7540. static struct tblentry *
  7541. cmdlookup(const char *name, int add)
  7542. {
  7543. unsigned int hashval;
  7544. const char *p;
  7545. struct tblentry *cmdp;
  7546. struct tblentry **pp;
  7547. p = name;
  7548. hashval = (unsigned char)*p << 4;
  7549. while (*p)
  7550. hashval += (unsigned char)*p++;
  7551. hashval &= 0x7FFF;
  7552. pp = &cmdtable[hashval % CMDTABLESIZE];
  7553. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7554. if (strcmp(cmdp->cmdname, name) == 0)
  7555. break;
  7556. pp = &cmdp->next;
  7557. }
  7558. if (add && cmdp == NULL) {
  7559. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7560. + strlen(name)
  7561. /* + 1 - already done because
  7562. * tblentry::cmdname is char[1] */);
  7563. /*cmdp->next = NULL; - ckzalloc did it */
  7564. cmdp->cmdtype = CMDUNKNOWN;
  7565. strcpy(cmdp->cmdname, name);
  7566. }
  7567. lastcmdentry = pp;
  7568. return cmdp;
  7569. }
  7570. /*
  7571. * Delete the command entry returned on the last lookup.
  7572. */
  7573. static void
  7574. delete_cmd_entry(void)
  7575. {
  7576. struct tblentry *cmdp;
  7577. INT_OFF;
  7578. cmdp = *lastcmdentry;
  7579. *lastcmdentry = cmdp->next;
  7580. if (cmdp->cmdtype == CMDFUNCTION)
  7581. freefunc(cmdp->param.func);
  7582. free(cmdp);
  7583. INT_ON;
  7584. }
  7585. /*
  7586. * Add a new command entry, replacing any existing command entry for
  7587. * the same name - except special builtins.
  7588. */
  7589. static void
  7590. addcmdentry(char *name, struct cmdentry *entry)
  7591. {
  7592. struct tblentry *cmdp;
  7593. cmdp = cmdlookup(name, 1);
  7594. if (cmdp->cmdtype == CMDFUNCTION) {
  7595. freefunc(cmdp->param.func);
  7596. }
  7597. cmdp->cmdtype = entry->cmdtype;
  7598. cmdp->param = entry->u;
  7599. cmdp->rehash = 0;
  7600. }
  7601. static int FAST_FUNC
  7602. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7603. {
  7604. struct tblentry **pp;
  7605. struct tblentry *cmdp;
  7606. int c;
  7607. struct cmdentry entry;
  7608. char *name;
  7609. if (nextopt("r") != '\0') {
  7610. clearcmdentry(0);
  7611. return 0;
  7612. }
  7613. if (*argptr == NULL) {
  7614. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7615. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7616. if (cmdp->cmdtype == CMDNORMAL)
  7617. printentry(cmdp);
  7618. }
  7619. }
  7620. return 0;
  7621. }
  7622. c = 0;
  7623. while ((name = *argptr) != NULL) {
  7624. cmdp = cmdlookup(name, 0);
  7625. if (cmdp != NULL
  7626. && (cmdp->cmdtype == CMDNORMAL
  7627. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  7628. ) {
  7629. delete_cmd_entry();
  7630. }
  7631. find_command(name, &entry, DO_ERR, pathval());
  7632. if (entry.cmdtype == CMDUNKNOWN)
  7633. c = 1;
  7634. argptr++;
  7635. }
  7636. return c;
  7637. }
  7638. /*
  7639. * Called when a cd is done. Marks all commands so the next time they
  7640. * are executed they will be rehashed.
  7641. */
  7642. static void
  7643. hashcd(void)
  7644. {
  7645. struct tblentry **pp;
  7646. struct tblentry *cmdp;
  7647. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7648. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7649. if (cmdp->cmdtype == CMDNORMAL
  7650. || (cmdp->cmdtype == CMDBUILTIN
  7651. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7652. && builtinloc > 0)
  7653. ) {
  7654. cmdp->rehash = 1;
  7655. }
  7656. }
  7657. }
  7658. }
  7659. /*
  7660. * Fix command hash table when PATH changed.
  7661. * Called before PATH is changed. The argument is the new value of PATH;
  7662. * pathval() still returns the old value at this point.
  7663. * Called with interrupts off.
  7664. */
  7665. static void FAST_FUNC
  7666. changepath(const char *new)
  7667. {
  7668. const char *old;
  7669. int firstchange;
  7670. int idx;
  7671. int idx_bltin;
  7672. old = pathval();
  7673. firstchange = 9999; /* assume no change */
  7674. idx = 0;
  7675. idx_bltin = -1;
  7676. for (;;) {
  7677. if (*old != *new) {
  7678. firstchange = idx;
  7679. if ((*old == '\0' && *new == ':')
  7680. || (*old == ':' && *new == '\0')
  7681. ) {
  7682. firstchange++;
  7683. }
  7684. old = new; /* ignore subsequent differences */
  7685. }
  7686. if (*new == '\0')
  7687. break;
  7688. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7689. idx_bltin = idx;
  7690. if (*new == ':')
  7691. idx++;
  7692. new++;
  7693. old++;
  7694. }
  7695. if (builtinloc < 0 && idx_bltin >= 0)
  7696. builtinloc = idx_bltin; /* zap builtins */
  7697. if (builtinloc >= 0 && idx_bltin < 0)
  7698. firstchange = 0;
  7699. clearcmdentry(firstchange);
  7700. builtinloc = idx_bltin;
  7701. }
  7702. enum {
  7703. TEOF,
  7704. TNL,
  7705. TREDIR,
  7706. TWORD,
  7707. TSEMI,
  7708. TBACKGND,
  7709. TAND,
  7710. TOR,
  7711. TPIPE,
  7712. TLP,
  7713. TRP,
  7714. TENDCASE,
  7715. TENDBQUOTE,
  7716. TNOT,
  7717. TCASE,
  7718. TDO,
  7719. TDONE,
  7720. TELIF,
  7721. TELSE,
  7722. TESAC,
  7723. TFI,
  7724. TFOR,
  7725. #if BASH_FUNCTION
  7726. TFUNCTION,
  7727. #endif
  7728. TIF,
  7729. TIN,
  7730. TTHEN,
  7731. TUNTIL,
  7732. TWHILE,
  7733. TBEGIN,
  7734. TEND
  7735. };
  7736. typedef smallint token_id_t;
  7737. /* Nth bit indicates if token marks the end of a list */
  7738. enum {
  7739. tokendlist = 0
  7740. /* 0 */ | (1u << TEOF)
  7741. /* 1 */ | (0u << TNL)
  7742. /* 2 */ | (0u << TREDIR)
  7743. /* 3 */ | (0u << TWORD)
  7744. /* 4 */ | (0u << TSEMI)
  7745. /* 5 */ | (0u << TBACKGND)
  7746. /* 6 */ | (0u << TAND)
  7747. /* 7 */ | (0u << TOR)
  7748. /* 8 */ | (0u << TPIPE)
  7749. /* 9 */ | (0u << TLP)
  7750. /* 10 */ | (1u << TRP)
  7751. /* 11 */ | (1u << TENDCASE)
  7752. /* 12 */ | (1u << TENDBQUOTE)
  7753. /* 13 */ | (0u << TNOT)
  7754. /* 14 */ | (0u << TCASE)
  7755. /* 15 */ | (1u << TDO)
  7756. /* 16 */ | (1u << TDONE)
  7757. /* 17 */ | (1u << TELIF)
  7758. /* 18 */ | (1u << TELSE)
  7759. /* 19 */ | (1u << TESAC)
  7760. /* 20 */ | (1u << TFI)
  7761. /* 21 */ | (0u << TFOR)
  7762. #if BASH_FUNCTION
  7763. /* 22 */ | (0u << TFUNCTION)
  7764. #endif
  7765. /* 23 */ | (0u << TIF)
  7766. /* 24 */ | (0u << TIN)
  7767. /* 25 */ | (1u << TTHEN)
  7768. /* 26 */ | (0u << TUNTIL)
  7769. /* 27 */ | (0u << TWHILE)
  7770. /* 28 */ | (0u << TBEGIN)
  7771. /* 29 */ | (1u << TEND)
  7772. , /* thus far 29 bits used */
  7773. };
  7774. static const char *const tokname_array[] = {
  7775. "end of file",
  7776. "newline",
  7777. "redirection",
  7778. "word",
  7779. ";",
  7780. "&",
  7781. "&&",
  7782. "||",
  7783. "|",
  7784. "(",
  7785. ")",
  7786. ";;",
  7787. "`",
  7788. #define KWDOFFSET 13
  7789. /* the following are keywords */
  7790. "!",
  7791. "case",
  7792. "do",
  7793. "done",
  7794. "elif",
  7795. "else",
  7796. "esac",
  7797. "fi",
  7798. "for",
  7799. #if BASH_FUNCTION
  7800. "function",
  7801. #endif
  7802. "if",
  7803. "in",
  7804. "then",
  7805. "until",
  7806. "while",
  7807. "{",
  7808. "}",
  7809. };
  7810. /* Wrapper around strcmp for qsort/bsearch/... */
  7811. static int
  7812. pstrcmp(const void *a, const void *b)
  7813. {
  7814. return strcmp((char*)a, *(char**)b);
  7815. }
  7816. static const char *const *
  7817. findkwd(const char *s)
  7818. {
  7819. return bsearch(s, tokname_array + KWDOFFSET,
  7820. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7821. sizeof(tokname_array[0]), pstrcmp);
  7822. }
  7823. /*
  7824. * Locate and print what a word is...
  7825. */
  7826. static int
  7827. describe_command(char *command, const char *path, int describe_command_verbose)
  7828. {
  7829. struct cmdentry entry;
  7830. #if ENABLE_ASH_ALIAS
  7831. const struct alias *ap;
  7832. #endif
  7833. path = path ? path : pathval();
  7834. if (describe_command_verbose) {
  7835. out1str(command);
  7836. }
  7837. /* First look at the keywords */
  7838. if (findkwd(command)) {
  7839. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7840. goto out;
  7841. }
  7842. #if ENABLE_ASH_ALIAS
  7843. /* Then look at the aliases */
  7844. ap = lookupalias(command, 0);
  7845. if (ap != NULL) {
  7846. if (!describe_command_verbose) {
  7847. out1str("alias ");
  7848. printalias(ap);
  7849. return 0;
  7850. }
  7851. out1fmt(" is an alias for %s", ap->val);
  7852. goto out;
  7853. }
  7854. #endif
  7855. /* Brute force */
  7856. find_command(command, &entry, DO_ABS, path);
  7857. switch (entry.cmdtype) {
  7858. case CMDNORMAL: {
  7859. int j = entry.u.index;
  7860. char *p;
  7861. if (j < 0) {
  7862. p = command;
  7863. } else {
  7864. do {
  7865. p = path_advance(&path, command);
  7866. stunalloc(p);
  7867. } while (--j >= 0);
  7868. }
  7869. if (describe_command_verbose) {
  7870. out1fmt(" is %s", p);
  7871. } else {
  7872. out1str(p);
  7873. }
  7874. break;
  7875. }
  7876. case CMDFUNCTION:
  7877. if (describe_command_verbose) {
  7878. /*out1str(" is a shell function");*/
  7879. out1str(" is a function"); /* bash says this */
  7880. } else {
  7881. out1str(command);
  7882. }
  7883. break;
  7884. case CMDBUILTIN:
  7885. if (describe_command_verbose) {
  7886. out1fmt(" is a %sshell builtin",
  7887. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7888. "special " : nullstr
  7889. );
  7890. } else {
  7891. out1str(command);
  7892. }
  7893. break;
  7894. default:
  7895. if (describe_command_verbose) {
  7896. out1str(": not found\n");
  7897. }
  7898. return 127;
  7899. }
  7900. out:
  7901. out1str("\n");
  7902. return 0;
  7903. }
  7904. static int FAST_FUNC
  7905. typecmd(int argc UNUSED_PARAM, char **argv)
  7906. {
  7907. int i = 1;
  7908. int err = 0;
  7909. int verbose = 1;
  7910. /* type -p ... ? (we don't bother checking for 'p') */
  7911. if (argv[1] && argv[1][0] == '-') {
  7912. i++;
  7913. verbose = 0;
  7914. }
  7915. while (argv[i]) {
  7916. err |= describe_command(argv[i++], NULL, verbose);
  7917. }
  7918. return err;
  7919. }
  7920. #if ENABLE_ASH_CMDCMD
  7921. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7922. static char **
  7923. parse_command_args(char **argv, const char **path)
  7924. {
  7925. char *cp, c;
  7926. for (;;) {
  7927. cp = *++argv;
  7928. if (!cp)
  7929. return NULL;
  7930. if (*cp++ != '-')
  7931. break;
  7932. c = *cp++;
  7933. if (!c)
  7934. break;
  7935. if (c == '-' && !*cp) {
  7936. if (!*++argv)
  7937. return NULL;
  7938. break;
  7939. }
  7940. do {
  7941. switch (c) {
  7942. case 'p':
  7943. *path = bb_default_path;
  7944. break;
  7945. default:
  7946. /* run 'typecmd' for other options */
  7947. return NULL;
  7948. }
  7949. c = *cp++;
  7950. } while (c);
  7951. }
  7952. return argv;
  7953. }
  7954. static int FAST_FUNC
  7955. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7956. {
  7957. char *cmd;
  7958. int c;
  7959. enum {
  7960. VERIFY_BRIEF = 1,
  7961. VERIFY_VERBOSE = 2,
  7962. } verify = 0;
  7963. const char *path = NULL;
  7964. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7965. * never reaches this function.
  7966. */
  7967. while ((c = nextopt("pvV")) != '\0')
  7968. if (c == 'V')
  7969. verify |= VERIFY_VERBOSE;
  7970. else if (c == 'v')
  7971. /*verify |= VERIFY_BRIEF*/;
  7972. #if DEBUG
  7973. else if (c != 'p')
  7974. abort();
  7975. #endif
  7976. else
  7977. path = bb_default_path;
  7978. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7979. cmd = *argptr;
  7980. if (/*verify && */ cmd)
  7981. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7982. return 0;
  7983. }
  7984. #endif
  7985. /*static int funcblocksize; // size of structures in function */
  7986. /*static int funcstringsize; // size of strings in node */
  7987. static void *funcblock; /* block to allocate function from */
  7988. static char *funcstring_end; /* end of block to allocate strings from */
  7989. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7990. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7991. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7992. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7993. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7994. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7995. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7996. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7997. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7998. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7999. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8000. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8001. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  8002. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  8003. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  8004. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  8005. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  8006. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8007. #if BASH_REDIR_OUTPUT
  8008. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  8009. #endif
  8010. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  8011. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  8012. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8013. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  8014. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8015. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8016. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8017. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8018. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  8019. };
  8020. static int calcsize(int funcblocksize, union node *n);
  8021. static int
  8022. sizenodelist(int funcblocksize, struct nodelist *lp)
  8023. {
  8024. while (lp) {
  8025. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  8026. funcblocksize = calcsize(funcblocksize, lp->n);
  8027. lp = lp->next;
  8028. }
  8029. return funcblocksize;
  8030. }
  8031. static int
  8032. calcsize(int funcblocksize, union node *n)
  8033. {
  8034. if (n == NULL)
  8035. return funcblocksize;
  8036. funcblocksize += nodesize[n->type];
  8037. switch (n->type) {
  8038. case NCMD:
  8039. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  8040. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  8041. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  8042. break;
  8043. case NPIPE:
  8044. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  8045. break;
  8046. case NREDIR:
  8047. case NBACKGND:
  8048. case NSUBSHELL:
  8049. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  8050. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  8051. break;
  8052. case NAND:
  8053. case NOR:
  8054. case NSEMI:
  8055. case NWHILE:
  8056. case NUNTIL:
  8057. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  8058. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  8059. break;
  8060. case NIF:
  8061. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  8062. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  8063. funcblocksize = calcsize(funcblocksize, n->nif.test);
  8064. break;
  8065. case NFOR:
  8066. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  8067. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  8068. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  8069. break;
  8070. case NCASE:
  8071. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  8072. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  8073. break;
  8074. case NCLIST:
  8075. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  8076. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  8077. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  8078. break;
  8079. case NDEFUN:
  8080. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8081. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8082. break;
  8083. case NARG:
  8084. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8085. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8086. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8087. break;
  8088. case NTO:
  8089. #if BASH_REDIR_OUTPUT
  8090. case NTO2:
  8091. #endif
  8092. case NCLOBBER:
  8093. case NFROM:
  8094. case NFROMTO:
  8095. case NAPPEND:
  8096. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8097. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8098. break;
  8099. case NTOFD:
  8100. case NFROMFD:
  8101. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8102. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8103. break;
  8104. case NHERE:
  8105. case NXHERE:
  8106. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8107. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8108. break;
  8109. case NNOT:
  8110. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8111. break;
  8112. };
  8113. return funcblocksize;
  8114. }
  8115. static char *
  8116. nodeckstrdup(char *s)
  8117. {
  8118. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8119. return strcpy(funcstring_end, s);
  8120. }
  8121. static union node *copynode(union node *);
  8122. static struct nodelist *
  8123. copynodelist(struct nodelist *lp)
  8124. {
  8125. struct nodelist *start;
  8126. struct nodelist **lpp;
  8127. lpp = &start;
  8128. while (lp) {
  8129. *lpp = funcblock;
  8130. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8131. (*lpp)->n = copynode(lp->n);
  8132. lp = lp->next;
  8133. lpp = &(*lpp)->next;
  8134. }
  8135. *lpp = NULL;
  8136. return start;
  8137. }
  8138. static union node *
  8139. copynode(union node *n)
  8140. {
  8141. union node *new;
  8142. if (n == NULL)
  8143. return NULL;
  8144. new = funcblock;
  8145. funcblock = (char *) funcblock + nodesize[n->type];
  8146. switch (n->type) {
  8147. case NCMD:
  8148. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8149. new->ncmd.args = copynode(n->ncmd.args);
  8150. new->ncmd.assign = copynode(n->ncmd.assign);
  8151. new->ncmd.linno = n->ncmd.linno;
  8152. break;
  8153. case NPIPE:
  8154. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8155. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8156. break;
  8157. case NREDIR:
  8158. case NBACKGND:
  8159. case NSUBSHELL:
  8160. new->nredir.redirect = copynode(n->nredir.redirect);
  8161. new->nredir.n = copynode(n->nredir.n);
  8162. new->nredir.linno = n->nredir.linno;
  8163. break;
  8164. case NAND:
  8165. case NOR:
  8166. case NSEMI:
  8167. case NWHILE:
  8168. case NUNTIL:
  8169. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8170. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8171. break;
  8172. case NIF:
  8173. new->nif.elsepart = copynode(n->nif.elsepart);
  8174. new->nif.ifpart = copynode(n->nif.ifpart);
  8175. new->nif.test = copynode(n->nif.test);
  8176. break;
  8177. case NFOR:
  8178. new->nfor.var = nodeckstrdup(n->nfor.var);
  8179. new->nfor.body = copynode(n->nfor.body);
  8180. new->nfor.args = copynode(n->nfor.args);
  8181. new->nfor.linno = n->nfor.linno;
  8182. break;
  8183. case NCASE:
  8184. new->ncase.cases = copynode(n->ncase.cases);
  8185. new->ncase.expr = copynode(n->ncase.expr);
  8186. new->ncase.linno = n->ncase.linno;
  8187. break;
  8188. case NCLIST:
  8189. new->nclist.body = copynode(n->nclist.body);
  8190. new->nclist.pattern = copynode(n->nclist.pattern);
  8191. new->nclist.next = copynode(n->nclist.next);
  8192. break;
  8193. case NDEFUN:
  8194. new->ndefun.body = copynode(n->ndefun.body);
  8195. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8196. new->ndefun.linno = n->ndefun.linno;
  8197. break;
  8198. case NARG:
  8199. new->narg.backquote = copynodelist(n->narg.backquote);
  8200. new->narg.text = nodeckstrdup(n->narg.text);
  8201. new->narg.next = copynode(n->narg.next);
  8202. break;
  8203. case NTO:
  8204. #if BASH_REDIR_OUTPUT
  8205. case NTO2:
  8206. #endif
  8207. case NCLOBBER:
  8208. case NFROM:
  8209. case NFROMTO:
  8210. case NAPPEND:
  8211. new->nfile.fname = copynode(n->nfile.fname);
  8212. new->nfile.fd = n->nfile.fd;
  8213. new->nfile.next = copynode(n->nfile.next);
  8214. break;
  8215. case NTOFD:
  8216. case NFROMFD:
  8217. new->ndup.vname = copynode(n->ndup.vname);
  8218. new->ndup.dupfd = n->ndup.dupfd;
  8219. new->ndup.fd = n->ndup.fd;
  8220. new->ndup.next = copynode(n->ndup.next);
  8221. break;
  8222. case NHERE:
  8223. case NXHERE:
  8224. new->nhere.doc = copynode(n->nhere.doc);
  8225. new->nhere.fd = n->nhere.fd;
  8226. new->nhere.next = copynode(n->nhere.next);
  8227. break;
  8228. case NNOT:
  8229. new->nnot.com = copynode(n->nnot.com);
  8230. break;
  8231. };
  8232. new->type = n->type;
  8233. return new;
  8234. }
  8235. /*
  8236. * Make a copy of a parse tree.
  8237. */
  8238. static struct funcnode *
  8239. copyfunc(union node *n)
  8240. {
  8241. struct funcnode *f;
  8242. size_t blocksize;
  8243. /*funcstringsize = 0;*/
  8244. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8245. f = ckzalloc(blocksize /* + funcstringsize */);
  8246. funcblock = (char *) f + offsetof(struct funcnode, n);
  8247. funcstring_end = (char *) f + blocksize;
  8248. copynode(n);
  8249. /* f->count = 0; - ckzalloc did it */
  8250. return f;
  8251. }
  8252. /*
  8253. * Define a shell function.
  8254. */
  8255. static void
  8256. defun(union node *func)
  8257. {
  8258. struct cmdentry entry;
  8259. INT_OFF;
  8260. entry.cmdtype = CMDFUNCTION;
  8261. entry.u.func = copyfunc(func);
  8262. addcmdentry(func->ndefun.text, &entry);
  8263. INT_ON;
  8264. }
  8265. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8266. #define SKIPBREAK (1 << 0)
  8267. #define SKIPCONT (1 << 1)
  8268. #define SKIPFUNC (1 << 2)
  8269. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8270. static int skipcount; /* number of levels to skip */
  8271. static int loopnest; /* current loop nesting level */
  8272. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8273. /* Forward decl way out to parsing code - dotrap needs it */
  8274. static int evalstring(char *s, int flags);
  8275. /* Called to execute a trap.
  8276. * Single callsite - at the end of evaltree().
  8277. * If we return non-zero, evaltree raises EXEXIT exception.
  8278. *
  8279. * Perhaps we should avoid entering new trap handlers
  8280. * while we are executing a trap handler. [is it a TODO?]
  8281. */
  8282. static void
  8283. dotrap(void)
  8284. {
  8285. uint8_t *g;
  8286. int sig;
  8287. uint8_t last_status;
  8288. if (!pending_sig)
  8289. return;
  8290. last_status = exitstatus;
  8291. pending_sig = 0;
  8292. barrier();
  8293. TRACE(("dotrap entered\n"));
  8294. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8295. char *p;
  8296. if (!*g)
  8297. continue;
  8298. if (evalskip) {
  8299. pending_sig = sig;
  8300. break;
  8301. }
  8302. p = trap[sig];
  8303. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8304. * don't upset it by resetting gotsig[SIGINT-1] */
  8305. if (sig == SIGINT && !p)
  8306. continue;
  8307. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8308. *g = 0;
  8309. if (!p)
  8310. continue;
  8311. evalstring(p, 0);
  8312. }
  8313. exitstatus = last_status;
  8314. TRACE(("dotrap returns\n"));
  8315. }
  8316. /* forward declarations - evaluation is fairly recursive business... */
  8317. static int evalloop(union node *, int);
  8318. static int evalfor(union node *, int);
  8319. static int evalcase(union node *, int);
  8320. static int evalsubshell(union node *, int);
  8321. static void expredir(union node *);
  8322. static int evalpipe(union node *, int);
  8323. static int evalcommand(union node *, int);
  8324. static int evalbltin(const struct builtincmd *, int, char **, int);
  8325. static void prehash(union node *);
  8326. /*
  8327. * Evaluate a parse tree. The value is left in the global variable
  8328. * exitstatus.
  8329. */
  8330. static int
  8331. evaltree(union node *n, int flags)
  8332. {
  8333. int checkexit = 0;
  8334. int (*evalfn)(union node *, int);
  8335. struct stackmark smark;
  8336. int status = 0;
  8337. setstackmark(&smark);
  8338. if (n == NULL) {
  8339. TRACE(("evaltree(NULL) called\n"));
  8340. goto out;
  8341. }
  8342. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8343. dotrap();
  8344. switch (n->type) {
  8345. default:
  8346. #if DEBUG
  8347. out1fmt("Node type = %d\n", n->type);
  8348. fflush_all();
  8349. break;
  8350. #endif
  8351. case NNOT:
  8352. status = !evaltree(n->nnot.com, EV_TESTED);
  8353. goto setstatus;
  8354. case NREDIR:
  8355. errlinno = lineno = n->nredir.linno;
  8356. if (funcline)
  8357. lineno -= funcline - 1;
  8358. expredir(n->nredir.redirect);
  8359. pushredir(n->nredir.redirect);
  8360. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8361. if (!status) {
  8362. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8363. }
  8364. if (n->nredir.redirect)
  8365. popredir(/*drop:*/ 0);
  8366. goto setstatus;
  8367. case NCMD:
  8368. evalfn = evalcommand;
  8369. checkexit:
  8370. if (eflag && !(flags & EV_TESTED))
  8371. checkexit = ~0;
  8372. goto calleval;
  8373. case NFOR:
  8374. evalfn = evalfor;
  8375. goto calleval;
  8376. case NWHILE:
  8377. case NUNTIL:
  8378. evalfn = evalloop;
  8379. goto calleval;
  8380. case NSUBSHELL:
  8381. case NBACKGND:
  8382. evalfn = evalsubshell;
  8383. goto checkexit;
  8384. case NPIPE:
  8385. evalfn = evalpipe;
  8386. goto checkexit;
  8387. case NCASE:
  8388. evalfn = evalcase;
  8389. goto calleval;
  8390. case NAND:
  8391. case NOR:
  8392. case NSEMI: {
  8393. #if NAND + 1 != NOR
  8394. #error NAND + 1 != NOR
  8395. #endif
  8396. #if NOR + 1 != NSEMI
  8397. #error NOR + 1 != NSEMI
  8398. #endif
  8399. unsigned is_or = n->type - NAND;
  8400. status = evaltree(
  8401. n->nbinary.ch1,
  8402. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8403. );
  8404. if ((!status) == is_or || evalskip)
  8405. break;
  8406. n = n->nbinary.ch2;
  8407. evaln:
  8408. evalfn = evaltree;
  8409. calleval:
  8410. status = evalfn(n, flags);
  8411. goto setstatus;
  8412. }
  8413. case NIF:
  8414. status = evaltree(n->nif.test, EV_TESTED);
  8415. if (evalskip)
  8416. break;
  8417. if (!status) {
  8418. n = n->nif.ifpart;
  8419. goto evaln;
  8420. }
  8421. if (n->nif.elsepart) {
  8422. n = n->nif.elsepart;
  8423. goto evaln;
  8424. }
  8425. status = 0;
  8426. goto setstatus;
  8427. case NDEFUN:
  8428. defun(n);
  8429. /* Not necessary. To test it:
  8430. * "false; f() { qwerty; }; echo $?" should print 0.
  8431. */
  8432. /* status = 0; */
  8433. setstatus:
  8434. exitstatus = status;
  8435. break;
  8436. }
  8437. out:
  8438. /* Order of checks below is important:
  8439. * signal handlers trigger before exit caused by "set -e".
  8440. */
  8441. dotrap();
  8442. if (checkexit & status)
  8443. raise_exception(EXEXIT);
  8444. if (flags & EV_EXIT)
  8445. raise_exception(EXEXIT);
  8446. popstackmark(&smark);
  8447. TRACE(("leaving evaltree (no interrupts)\n"));
  8448. return exitstatus;
  8449. }
  8450. static int
  8451. skiploop(void)
  8452. {
  8453. int skip = evalskip;
  8454. switch (skip) {
  8455. case 0:
  8456. break;
  8457. case SKIPBREAK:
  8458. case SKIPCONT:
  8459. if (--skipcount <= 0) {
  8460. evalskip = 0;
  8461. break;
  8462. }
  8463. skip = SKIPBREAK;
  8464. break;
  8465. }
  8466. return skip;
  8467. }
  8468. static int
  8469. evalloop(union node *n, int flags)
  8470. {
  8471. int skip;
  8472. int status;
  8473. loopnest++;
  8474. status = 0;
  8475. flags &= EV_TESTED;
  8476. do {
  8477. int i;
  8478. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8479. skip = skiploop();
  8480. if (skip == SKIPFUNC)
  8481. status = i;
  8482. if (skip)
  8483. continue;
  8484. if (n->type != NWHILE)
  8485. i = !i;
  8486. if (i != 0)
  8487. break;
  8488. status = evaltree(n->nbinary.ch2, flags);
  8489. skip = skiploop();
  8490. } while (!(skip & ~SKIPCONT));
  8491. loopnest--;
  8492. return status;
  8493. }
  8494. static int
  8495. evalfor(union node *n, int flags)
  8496. {
  8497. struct arglist arglist;
  8498. union node *argp;
  8499. struct strlist *sp;
  8500. int status = 0;
  8501. errlinno = lineno = n->ncase.linno;
  8502. if (funcline)
  8503. lineno -= funcline - 1;
  8504. arglist.list = NULL;
  8505. arglist.lastp = &arglist.list;
  8506. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8507. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8508. }
  8509. *arglist.lastp = NULL;
  8510. loopnest++;
  8511. flags &= EV_TESTED;
  8512. for (sp = arglist.list; sp; sp = sp->next) {
  8513. setvar0(n->nfor.var, sp->text);
  8514. status = evaltree(n->nfor.body, flags);
  8515. if (skiploop() & ~SKIPCONT)
  8516. break;
  8517. }
  8518. loopnest--;
  8519. return status;
  8520. }
  8521. static int
  8522. evalcase(union node *n, int flags)
  8523. {
  8524. union node *cp;
  8525. union node *patp;
  8526. struct arglist arglist;
  8527. int status = 0;
  8528. errlinno = lineno = n->ncase.linno;
  8529. if (funcline)
  8530. lineno -= funcline - 1;
  8531. arglist.list = NULL;
  8532. arglist.lastp = &arglist.list;
  8533. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8534. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8535. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8536. if (casematch(patp, arglist.list->text)) {
  8537. /* Ensure body is non-empty as otherwise
  8538. * EV_EXIT may prevent us from setting the
  8539. * exit status.
  8540. */
  8541. if (evalskip == 0 && cp->nclist.body) {
  8542. status = evaltree(cp->nclist.body, flags);
  8543. }
  8544. goto out;
  8545. }
  8546. }
  8547. }
  8548. out:
  8549. return status;
  8550. }
  8551. /*
  8552. * Kick off a subshell to evaluate a tree.
  8553. */
  8554. static int
  8555. evalsubshell(union node *n, int flags)
  8556. {
  8557. struct job *jp;
  8558. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8559. int status;
  8560. errlinno = lineno = n->nredir.linno;
  8561. if (funcline)
  8562. lineno -= funcline - 1;
  8563. expredir(n->nredir.redirect);
  8564. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8565. goto nofork;
  8566. INT_OFF;
  8567. if (backgnd == FORK_FG)
  8568. get_tty_state();
  8569. jp = makejob(/*n,*/ 1);
  8570. if (forkshell(jp, n, backgnd) == 0) {
  8571. /* child */
  8572. INT_ON;
  8573. flags |= EV_EXIT;
  8574. if (backgnd)
  8575. flags &= ~EV_TESTED;
  8576. nofork:
  8577. redirect(n->nredir.redirect, 0);
  8578. evaltreenr(n->nredir.n, flags);
  8579. /* never returns */
  8580. }
  8581. /* parent */
  8582. status = 0;
  8583. if (backgnd == FORK_FG)
  8584. status = waitforjob(jp);
  8585. INT_ON;
  8586. return status;
  8587. }
  8588. /*
  8589. * Compute the names of the files in a redirection list.
  8590. */
  8591. static void fixredir(union node *, const char *, int);
  8592. static void
  8593. expredir(union node *n)
  8594. {
  8595. union node *redir;
  8596. for (redir = n; redir; redir = redir->nfile.next) {
  8597. struct arglist fn;
  8598. fn.list = NULL;
  8599. fn.lastp = &fn.list;
  8600. switch (redir->type) {
  8601. case NFROMTO:
  8602. case NFROM:
  8603. case NTO:
  8604. #if BASH_REDIR_OUTPUT
  8605. case NTO2:
  8606. #endif
  8607. case NCLOBBER:
  8608. case NAPPEND:
  8609. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8610. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8611. #if BASH_REDIR_OUTPUT
  8612. store_expfname:
  8613. #endif
  8614. #if 0
  8615. // By the design of stack allocator, the loop of this kind:
  8616. // while true; do while true; do break; done </dev/null; done
  8617. // will look like a memory leak: ash plans to free expfname's
  8618. // of "/dev/null" as soon as it finishes running the loop
  8619. // (in this case, never).
  8620. // This "fix" is wrong:
  8621. if (redir->nfile.expfname)
  8622. stunalloc(redir->nfile.expfname);
  8623. // It results in corrupted state of stacked allocations.
  8624. #endif
  8625. redir->nfile.expfname = fn.list->text;
  8626. break;
  8627. case NFROMFD:
  8628. case NTOFD: /* >& */
  8629. if (redir->ndup.vname) {
  8630. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  8631. if (fn.list == NULL)
  8632. ash_msg_and_raise_error("redir error");
  8633. #if BASH_REDIR_OUTPUT
  8634. //FIXME: we used expandarg with different args!
  8635. if (!isdigit_str9(fn.list->text)) {
  8636. /* >&file, not >&fd */
  8637. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8638. ash_msg_and_raise_error("redir error");
  8639. redir->type = NTO2;
  8640. goto store_expfname;
  8641. }
  8642. #endif
  8643. fixredir(redir, fn.list->text, 1);
  8644. }
  8645. break;
  8646. }
  8647. }
  8648. }
  8649. /*
  8650. * Evaluate a pipeline. All the processes in the pipeline are children
  8651. * of the process creating the pipeline. (This differs from some versions
  8652. * of the shell, which make the last process in a pipeline the parent
  8653. * of all the rest.)
  8654. */
  8655. static int
  8656. evalpipe(union node *n, int flags)
  8657. {
  8658. struct job *jp;
  8659. struct nodelist *lp;
  8660. int pipelen;
  8661. int prevfd;
  8662. int pip[2];
  8663. int status = 0;
  8664. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8665. pipelen = 0;
  8666. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8667. pipelen++;
  8668. flags |= EV_EXIT;
  8669. INT_OFF;
  8670. if (n->npipe.pipe_backgnd == 0)
  8671. get_tty_state();
  8672. jp = makejob(/*n,*/ pipelen);
  8673. prevfd = -1;
  8674. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8675. prehash(lp->n);
  8676. pip[1] = -1;
  8677. if (lp->next) {
  8678. if (pipe(pip) < 0) {
  8679. close(prevfd);
  8680. ash_msg_and_raise_perror("can't create pipe");
  8681. }
  8682. }
  8683. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8684. /* child */
  8685. INT_ON;
  8686. if (pip[1] >= 0) {
  8687. close(pip[0]);
  8688. }
  8689. if (prevfd > 0) {
  8690. dup2(prevfd, 0);
  8691. close(prevfd);
  8692. }
  8693. if (pip[1] > 1) {
  8694. dup2(pip[1], 1);
  8695. close(pip[1]);
  8696. }
  8697. evaltreenr(lp->n, flags);
  8698. /* never returns */
  8699. }
  8700. /* parent */
  8701. if (prevfd >= 0)
  8702. close(prevfd);
  8703. prevfd = pip[0];
  8704. /* Don't want to trigger debugging */
  8705. if (pip[1] != -1)
  8706. close(pip[1]);
  8707. }
  8708. if (n->npipe.pipe_backgnd == 0) {
  8709. status = waitforjob(jp);
  8710. TRACE(("evalpipe: job done exit status %d\n", status));
  8711. }
  8712. INT_ON;
  8713. return status;
  8714. }
  8715. /*
  8716. * Controls whether the shell is interactive or not.
  8717. */
  8718. static void
  8719. setinteractive(int on)
  8720. {
  8721. static smallint is_interactive;
  8722. if (++on == is_interactive)
  8723. return;
  8724. is_interactive = on;
  8725. setsignal(SIGINT);
  8726. setsignal(SIGQUIT);
  8727. setsignal(SIGTERM);
  8728. if (is_interactive > 1) {
  8729. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8730. /* Looks like they want an interactive shell */
  8731. static smallint did_banner;
  8732. if (!did_banner) {
  8733. /* note: ash and hush share this string */
  8734. out1fmt("\n\n%s %s\n"
  8735. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8736. "\n",
  8737. bb_banner,
  8738. "built-in shell (ash)"
  8739. );
  8740. did_banner = 1;
  8741. }
  8742. #endif
  8743. #if ENABLE_FEATURE_EDITING
  8744. if (!line_input_state)
  8745. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  8746. #endif
  8747. }
  8748. }
  8749. static void
  8750. optschanged(void)
  8751. {
  8752. #if DEBUG
  8753. opentrace();
  8754. #endif
  8755. setinteractive(iflag);
  8756. setjobctl(mflag);
  8757. #if ENABLE_FEATURE_EDITING_VI
  8758. if (line_input_state) {
  8759. if (viflag)
  8760. line_input_state->flags |= VI_MODE;
  8761. else
  8762. line_input_state->flags &= ~VI_MODE;
  8763. }
  8764. #else
  8765. viflag = 0; /* forcibly keep the option off */
  8766. #endif
  8767. }
  8768. struct localvar_list {
  8769. struct localvar_list *next;
  8770. struct localvar *lv;
  8771. };
  8772. static struct localvar_list *localvar_stack;
  8773. /*
  8774. * Called after a function returns.
  8775. * Interrupts must be off.
  8776. */
  8777. static void
  8778. poplocalvars(int keep)
  8779. {
  8780. struct localvar_list *ll;
  8781. struct localvar *lvp, *next;
  8782. struct var *vp;
  8783. INT_OFF;
  8784. ll = localvar_stack;
  8785. localvar_stack = ll->next;
  8786. next = ll->lv;
  8787. free(ll);
  8788. while ((lvp = next) != NULL) {
  8789. next = lvp->next;
  8790. vp = lvp->vp;
  8791. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8792. if (keep) {
  8793. int bits = VSTRFIXED;
  8794. if (lvp->flags != VUNSET) {
  8795. if (vp->var_text == lvp->text)
  8796. bits |= VTEXTFIXED;
  8797. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8798. free((char*)lvp->text);
  8799. }
  8800. vp->flags &= ~bits;
  8801. vp->flags |= (lvp->flags & bits);
  8802. if ((vp->flags &
  8803. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8804. unsetvar(vp->var_text);
  8805. } else if (vp == NULL) { /* $- saved */
  8806. memcpy(optlist, lvp->text, sizeof(optlist));
  8807. free((char*)lvp->text);
  8808. optschanged();
  8809. } else if (lvp->flags == VUNSET) {
  8810. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8811. unsetvar(vp->var_text);
  8812. } else {
  8813. if (vp->var_func)
  8814. vp->var_func(var_end(lvp->text));
  8815. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8816. free((char*)vp->var_text);
  8817. vp->flags = lvp->flags;
  8818. vp->var_text = lvp->text;
  8819. }
  8820. free(lvp);
  8821. }
  8822. INT_ON;
  8823. }
  8824. /*
  8825. * Create a new localvar environment.
  8826. */
  8827. static struct localvar_list *
  8828. pushlocalvars(void)
  8829. {
  8830. struct localvar_list *ll;
  8831. INT_OFF;
  8832. ll = ckzalloc(sizeof(*ll));
  8833. /*ll->lv = NULL; - zalloc did it */
  8834. ll->next = localvar_stack;
  8835. localvar_stack = ll;
  8836. INT_ON;
  8837. return ll->next;
  8838. }
  8839. static void
  8840. unwindlocalvars(struct localvar_list *stop)
  8841. {
  8842. while (localvar_stack != stop)
  8843. poplocalvars(0);
  8844. }
  8845. static int
  8846. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8847. {
  8848. volatile struct shparam saveparam;
  8849. struct jmploc *volatile savehandler;
  8850. struct jmploc jmploc;
  8851. int e;
  8852. int savefuncline;
  8853. saveparam = shellparam;
  8854. savefuncline = funcline;
  8855. savehandler = exception_handler;
  8856. e = setjmp(jmploc.loc);
  8857. if (e) {
  8858. goto funcdone;
  8859. }
  8860. INT_OFF;
  8861. exception_handler = &jmploc;
  8862. shellparam.malloced = 0;
  8863. func->count++;
  8864. funcline = func->n.ndefun.linno;
  8865. INT_ON;
  8866. shellparam.nparam = argc - 1;
  8867. shellparam.p = argv + 1;
  8868. #if ENABLE_ASH_GETOPTS
  8869. shellparam.optind = 1;
  8870. shellparam.optoff = -1;
  8871. #endif
  8872. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  8873. funcdone:
  8874. INT_OFF;
  8875. funcline = savefuncline;
  8876. freefunc(func);
  8877. freeparam(&shellparam);
  8878. shellparam = saveparam;
  8879. exception_handler = savehandler;
  8880. INT_ON;
  8881. evalskip &= ~SKIPFUNC;
  8882. return e;
  8883. }
  8884. /*
  8885. * Make a variable a local variable. When a variable is made local, it's
  8886. * value and flags are saved in a localvar structure. The saved values
  8887. * will be restored when the shell function returns. We handle the name
  8888. * "-" as a special case: it makes changes to "set +-options" local
  8889. * (options will be restored on return from the function).
  8890. */
  8891. static void
  8892. mklocal(char *name)
  8893. {
  8894. struct localvar *lvp;
  8895. struct var **vpp;
  8896. struct var *vp;
  8897. char *eq = strchr(name, '=');
  8898. INT_OFF;
  8899. /* Cater for duplicate "local". Examples:
  8900. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8901. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8902. */
  8903. lvp = localvar_stack->lv;
  8904. while (lvp) {
  8905. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8906. if (eq)
  8907. setvareq(name, 0);
  8908. /* else:
  8909. * it's a duplicate "local VAR" declaration, do nothing
  8910. */
  8911. goto ret;
  8912. }
  8913. lvp = lvp->next;
  8914. }
  8915. lvp = ckzalloc(sizeof(*lvp));
  8916. if (LONE_DASH(name)) {
  8917. char *p;
  8918. p = ckmalloc(sizeof(optlist));
  8919. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8920. vp = NULL;
  8921. } else {
  8922. vpp = hashvar(name);
  8923. vp = *findvar(vpp, name);
  8924. if (vp == NULL) {
  8925. /* variable did not exist yet */
  8926. if (eq)
  8927. vp = setvareq(name, VSTRFIXED);
  8928. else
  8929. vp = setvar(name, NULL, VSTRFIXED);
  8930. lvp->flags = VUNSET;
  8931. } else {
  8932. lvp->text = vp->var_text;
  8933. lvp->flags = vp->flags;
  8934. /* make sure neither "struct var" nor string gets freed
  8935. * during (un)setting:
  8936. */
  8937. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8938. if (eq)
  8939. setvareq(name, 0);
  8940. else
  8941. /* "local VAR" unsets VAR: */
  8942. setvar0(name, NULL);
  8943. }
  8944. }
  8945. lvp->vp = vp;
  8946. lvp->next = localvar_stack->lv;
  8947. localvar_stack->lv = lvp;
  8948. ret:
  8949. INT_ON;
  8950. }
  8951. /*
  8952. * The "local" command.
  8953. */
  8954. static int FAST_FUNC
  8955. localcmd(int argc UNUSED_PARAM, char **argv)
  8956. {
  8957. char *name;
  8958. if (!localvar_stack)
  8959. ash_msg_and_raise_error("not in a function");
  8960. argv = argptr;
  8961. while ((name = *argv++) != NULL) {
  8962. mklocal(name);
  8963. }
  8964. return 0;
  8965. }
  8966. static int FAST_FUNC
  8967. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8968. {
  8969. return 1;
  8970. }
  8971. static int FAST_FUNC
  8972. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8973. {
  8974. return 0;
  8975. }
  8976. static int FAST_FUNC
  8977. execcmd(int argc UNUSED_PARAM, char **argv)
  8978. {
  8979. optionarg = NULL;
  8980. while (nextopt("a:") != '\0')
  8981. /* nextopt() sets optionarg to "-a ARGV0" */;
  8982. argv = argptr;
  8983. if (argv[0]) {
  8984. char *prog;
  8985. iflag = 0; /* exit on error */
  8986. mflag = 0;
  8987. optschanged();
  8988. /* We should set up signals for "exec CMD"
  8989. * the same way as for "CMD" without "exec".
  8990. * But optschanged->setinteractive->setsignal
  8991. * still thought we are a root shell. Therefore, for example,
  8992. * SIGQUIT is still set to IGN. Fix it:
  8993. */
  8994. shlvl++;
  8995. setsignal(SIGQUIT);
  8996. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  8997. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  8998. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  8999. prog = argv[0];
  9000. if (optionarg)
  9001. argv[0] = optionarg;
  9002. shellexec(prog, argv, pathval(), 0);
  9003. /* NOTREACHED */
  9004. }
  9005. return 0;
  9006. }
  9007. /*
  9008. * The return command.
  9009. */
  9010. static int FAST_FUNC
  9011. returncmd(int argc UNUSED_PARAM, char **argv)
  9012. {
  9013. /*
  9014. * If called outside a function, do what ksh does;
  9015. * skip the rest of the file.
  9016. */
  9017. evalskip = SKIPFUNC;
  9018. return argv[1] ? number(argv[1]) : exitstatus;
  9019. }
  9020. /* Forward declarations for builtintab[] */
  9021. static int breakcmd(int, char **) FAST_FUNC;
  9022. static int dotcmd(int, char **) FAST_FUNC;
  9023. static int evalcmd(int, char **, int) FAST_FUNC;
  9024. static int exitcmd(int, char **) FAST_FUNC;
  9025. static int exportcmd(int, char **) FAST_FUNC;
  9026. #if ENABLE_ASH_GETOPTS
  9027. static int getoptscmd(int, char **) FAST_FUNC;
  9028. #endif
  9029. #if ENABLE_ASH_HELP
  9030. static int helpcmd(int, char **) FAST_FUNC;
  9031. #endif
  9032. #if MAX_HISTORY
  9033. static int historycmd(int, char **) FAST_FUNC;
  9034. #endif
  9035. #if ENABLE_FEATURE_SH_MATH
  9036. static int letcmd(int, char **) FAST_FUNC;
  9037. #endif
  9038. static int readcmd(int, char **) FAST_FUNC;
  9039. static int setcmd(int, char **) FAST_FUNC;
  9040. static int shiftcmd(int, char **) FAST_FUNC;
  9041. static int timescmd(int, char **) FAST_FUNC;
  9042. static int trapcmd(int, char **) FAST_FUNC;
  9043. static int umaskcmd(int, char **) FAST_FUNC;
  9044. static int unsetcmd(int, char **) FAST_FUNC;
  9045. static int ulimitcmd(int, char **) FAST_FUNC;
  9046. #define BUILTIN_NOSPEC "0"
  9047. #define BUILTIN_SPECIAL "1"
  9048. #define BUILTIN_REGULAR "2"
  9049. #define BUILTIN_SPEC_REG "3"
  9050. #define BUILTIN_ASSIGN "4"
  9051. #define BUILTIN_SPEC_ASSG "5"
  9052. #define BUILTIN_REG_ASSG "6"
  9053. #define BUILTIN_SPEC_REG_ASSG "7"
  9054. /* Stubs for calling non-FAST_FUNC's */
  9055. #if ENABLE_ASH_ECHO
  9056. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  9057. #endif
  9058. #if ENABLE_ASH_PRINTF
  9059. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  9060. #endif
  9061. #if ENABLE_ASH_TEST || BASH_TEST2
  9062. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  9063. #endif
  9064. /* Keep these in proper order since it is searched via bsearch() */
  9065. static const struct builtincmd builtintab[] = {
  9066. { BUILTIN_SPEC_REG "." , dotcmd },
  9067. { BUILTIN_SPEC_REG ":" , truecmd },
  9068. #if ENABLE_ASH_TEST
  9069. { BUILTIN_REGULAR "[" , testcmd },
  9070. #endif
  9071. #if BASH_TEST2
  9072. { BUILTIN_REGULAR "[[" , testcmd },
  9073. #endif
  9074. #if ENABLE_ASH_ALIAS
  9075. { BUILTIN_REG_ASSG "alias" , aliascmd },
  9076. #endif
  9077. #if JOBS
  9078. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  9079. #endif
  9080. { BUILTIN_SPEC_REG "break" , breakcmd },
  9081. { BUILTIN_REGULAR "cd" , cdcmd },
  9082. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9083. #if ENABLE_ASH_CMDCMD
  9084. { BUILTIN_REGULAR "command" , commandcmd },
  9085. #endif
  9086. { BUILTIN_SPEC_REG "continue", breakcmd },
  9087. #if ENABLE_ASH_ECHO
  9088. { BUILTIN_REGULAR "echo" , echocmd },
  9089. #endif
  9090. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9091. { BUILTIN_SPEC_REG "exec" , execcmd },
  9092. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9093. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9094. { BUILTIN_REGULAR "false" , falsecmd },
  9095. #if JOBS
  9096. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9097. #endif
  9098. #if ENABLE_ASH_GETOPTS
  9099. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9100. #endif
  9101. { BUILTIN_NOSPEC "hash" , hashcmd },
  9102. #if ENABLE_ASH_HELP
  9103. { BUILTIN_NOSPEC "help" , helpcmd },
  9104. #endif
  9105. #if MAX_HISTORY
  9106. { BUILTIN_NOSPEC "history" , historycmd },
  9107. #endif
  9108. #if JOBS
  9109. { BUILTIN_REGULAR "jobs" , jobscmd },
  9110. { BUILTIN_REGULAR "kill" , killcmd },
  9111. #endif
  9112. #if ENABLE_FEATURE_SH_MATH
  9113. { BUILTIN_NOSPEC "let" , letcmd },
  9114. #endif
  9115. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9116. #if ENABLE_ASH_PRINTF
  9117. { BUILTIN_REGULAR "printf" , printfcmd },
  9118. #endif
  9119. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  9120. { BUILTIN_REGULAR "read" , readcmd },
  9121. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9122. { BUILTIN_SPEC_REG "return" , returncmd },
  9123. { BUILTIN_SPEC_REG "set" , setcmd },
  9124. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9125. #if BASH_SOURCE
  9126. { BUILTIN_SPEC_REG "source" , dotcmd },
  9127. #endif
  9128. #if ENABLE_ASH_TEST
  9129. { BUILTIN_REGULAR "test" , testcmd },
  9130. #endif
  9131. { BUILTIN_SPEC_REG "times" , timescmd },
  9132. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9133. { BUILTIN_REGULAR "true" , truecmd },
  9134. { BUILTIN_NOSPEC "type" , typecmd },
  9135. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  9136. { BUILTIN_REGULAR "umask" , umaskcmd },
  9137. #if ENABLE_ASH_ALIAS
  9138. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9139. #endif
  9140. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9141. { BUILTIN_REGULAR "wait" , waitcmd },
  9142. };
  9143. /* Should match the above table! */
  9144. #define COMMANDCMD (builtintab + \
  9145. /* . : */ 2 + \
  9146. /* [ */ 1 * ENABLE_ASH_TEST + \
  9147. /* [[ */ 1 * BASH_TEST2 + \
  9148. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9149. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9150. /* break cd cddir */ 3)
  9151. #define EVALCMD (COMMANDCMD + \
  9152. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9153. /* continue */ 1 + \
  9154. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9155. 0)
  9156. #define EXECCMD (EVALCMD + \
  9157. /* eval */ 1)
  9158. /*
  9159. * Search the table of builtin commands.
  9160. */
  9161. static int
  9162. pstrcmp1(const void *a, const void *b)
  9163. {
  9164. return strcmp((char*)a, *(char**)b + 1);
  9165. }
  9166. static struct builtincmd *
  9167. find_builtin(const char *name)
  9168. {
  9169. struct builtincmd *bp;
  9170. bp = bsearch(
  9171. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9172. pstrcmp1
  9173. );
  9174. return bp;
  9175. }
  9176. /*
  9177. * Execute a simple command.
  9178. */
  9179. static void unwindfiles(struct parsefile *stop);
  9180. static int
  9181. isassignment(const char *p)
  9182. {
  9183. const char *q = endofname(p);
  9184. if (p == q)
  9185. return 0;
  9186. return *q == '=';
  9187. }
  9188. static int FAST_FUNC
  9189. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9190. {
  9191. /* Preserve exitstatus of a previous possible redirection
  9192. * as POSIX mandates */
  9193. return back_exitstatus;
  9194. }
  9195. static int
  9196. evalcommand(union node *cmd, int flags)
  9197. {
  9198. static const struct builtincmd null_bltin = {
  9199. "\0\0", bltincmd /* why three NULs? */
  9200. };
  9201. struct localvar_list *localvar_stop;
  9202. struct parsefile *file_stop;
  9203. struct redirtab *redir_stop;
  9204. union node *argp;
  9205. struct arglist arglist;
  9206. struct arglist varlist;
  9207. char **argv;
  9208. int argc;
  9209. const struct strlist *sp;
  9210. struct cmdentry cmdentry;
  9211. struct job *jp;
  9212. char *lastarg;
  9213. const char *path;
  9214. int spclbltin;
  9215. int status;
  9216. char **nargv;
  9217. smallint cmd_is_exec;
  9218. errlinno = lineno = cmd->ncmd.linno;
  9219. if (funcline)
  9220. lineno -= funcline - 1;
  9221. /* First expand the arguments. */
  9222. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9223. localvar_stop = pushlocalvars();
  9224. file_stop = g_parsefile;
  9225. back_exitstatus = 0;
  9226. cmdentry.cmdtype = CMDBUILTIN;
  9227. cmdentry.u.cmd = &null_bltin;
  9228. varlist.lastp = &varlist.list;
  9229. *varlist.lastp = NULL;
  9230. arglist.lastp = &arglist.list;
  9231. *arglist.lastp = NULL;
  9232. argc = 0;
  9233. if (cmd->ncmd.args) {
  9234. struct builtincmd *bcmd;
  9235. smallint pseudovarflag;
  9236. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  9237. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  9238. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  9239. struct strlist **spp;
  9240. spp = arglist.lastp;
  9241. if (pseudovarflag && isassignment(argp->narg.text))
  9242. expandarg(argp, &arglist, EXP_VARTILDE);
  9243. else
  9244. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  9245. for (sp = *spp; sp; sp = sp->next)
  9246. argc++;
  9247. }
  9248. }
  9249. /* Reserve one extra spot at the front for shellexec. */
  9250. nargv = stalloc(sizeof(char *) * (argc + 2));
  9251. argv = ++nargv;
  9252. for (sp = arglist.list; sp; sp = sp->next) {
  9253. TRACE(("evalcommand arg: %s\n", sp->text));
  9254. *nargv++ = sp->text;
  9255. }
  9256. *nargv = NULL;
  9257. lastarg = NULL;
  9258. if (iflag && funcline == 0 && argc > 0)
  9259. lastarg = nargv[-1];
  9260. expredir(cmd->ncmd.redirect);
  9261. redir_stop = pushredir(cmd->ncmd.redirect);
  9262. preverrout_fd = 2;
  9263. if (BASH_XTRACEFD && xflag) {
  9264. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9265. * we do not emulate this. We only use its value.
  9266. */
  9267. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9268. if (xtracefd && is_number(xtracefd))
  9269. preverrout_fd = atoi(xtracefd);
  9270. }
  9271. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9272. path = vpath.var_text;
  9273. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9274. struct strlist **spp;
  9275. char *p;
  9276. spp = varlist.lastp;
  9277. expandarg(argp, &varlist, EXP_VARTILDE);
  9278. mklocal((*spp)->text);
  9279. /*
  9280. * Modify the command lookup path, if a PATH= assignment
  9281. * is present
  9282. */
  9283. p = (*spp)->text;
  9284. if (varcmp(p, path) == 0)
  9285. path = p;
  9286. }
  9287. /* Print the command if xflag is set. */
  9288. if (xflag) {
  9289. const char *pfx = "";
  9290. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9291. sp = varlist.list;
  9292. while (sp) {
  9293. char *varval = sp->text;
  9294. char *eq = strchrnul(varval, '=');
  9295. if (*eq)
  9296. eq++;
  9297. fdprintf(preverrout_fd, "%s%.*s%s",
  9298. pfx,
  9299. (int)(eq - varval), varval,
  9300. maybe_single_quote(eq)
  9301. );
  9302. sp = sp->next;
  9303. pfx = " ";
  9304. }
  9305. sp = arglist.list;
  9306. while (sp) {
  9307. fdprintf(preverrout_fd, "%s%s",
  9308. pfx,
  9309. /* always quote if matches reserved word: */
  9310. findkwd(sp->text)
  9311. ? single_quote(sp->text)
  9312. : maybe_single_quote(sp->text)
  9313. );
  9314. sp = sp->next;
  9315. pfx = " ";
  9316. }
  9317. safe_write(preverrout_fd, "\n", 1);
  9318. }
  9319. cmd_is_exec = 0;
  9320. spclbltin = -1;
  9321. /* Now locate the command. */
  9322. if (argc) {
  9323. int cmd_flag = DO_ERR;
  9324. #if ENABLE_ASH_CMDCMD
  9325. const char *oldpath = path + 5;
  9326. #endif
  9327. path += 5;
  9328. for (;;) {
  9329. find_command(argv[0], &cmdentry, cmd_flag, path);
  9330. if (cmdentry.cmdtype == CMDUNKNOWN) {
  9331. flush_stdout_stderr();
  9332. status = 127;
  9333. goto bail;
  9334. }
  9335. /* implement bltin and command here */
  9336. if (cmdentry.cmdtype != CMDBUILTIN)
  9337. break;
  9338. if (spclbltin < 0)
  9339. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9340. if (cmdentry.u.cmd == EXECCMD)
  9341. cmd_is_exec = 1;
  9342. #if ENABLE_ASH_CMDCMD
  9343. if (cmdentry.u.cmd == COMMANDCMD) {
  9344. path = oldpath;
  9345. nargv = parse_command_args(argv, &path);
  9346. if (!nargv)
  9347. break;
  9348. /* It's "command [-p] PROG ARGS" (that is, no -Vv).
  9349. * nargv => "PROG". path is updated if -p.
  9350. */
  9351. argc -= nargv - argv;
  9352. argv = nargv;
  9353. cmd_flag |= DO_NOFUNC;
  9354. } else
  9355. #endif
  9356. break;
  9357. }
  9358. }
  9359. if (status) {
  9360. bail:
  9361. exitstatus = status;
  9362. /* We have a redirection error. */
  9363. if (spclbltin > 0)
  9364. raise_exception(EXERROR);
  9365. goto out;
  9366. }
  9367. /* Execute the command. */
  9368. switch (cmdentry.cmdtype) {
  9369. default: {
  9370. #if ENABLE_FEATURE_SH_STANDALONE \
  9371. && ENABLE_FEATURE_SH_NOFORK \
  9372. && NUM_APPLETS > 1
  9373. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9374. * around run_nofork_applet() call.
  9375. * (2) Should this check also be done in forkshell()?
  9376. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9377. */
  9378. /* find_command() encodes applet_no as (-2 - applet_no) */
  9379. int applet_no = (- cmdentry.u.index - 2);
  9380. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9381. char **sv_environ;
  9382. INT_OFF;
  9383. sv_environ = environ;
  9384. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9385. /*
  9386. * Run <applet>_main().
  9387. * Signals (^C) can't interrupt here.
  9388. * Otherwise we can mangle stdio or malloc internal state.
  9389. * This makes applets which can run for a long time
  9390. * and/or wait for user input ineligible for NOFORK:
  9391. * for example, "yes" or "rm" (rm -i waits for input).
  9392. */
  9393. status = run_nofork_applet(applet_no, argv);
  9394. environ = sv_environ;
  9395. /*
  9396. * Try enabling NOFORK for "yes" applet.
  9397. * ^C _will_ stop it (write returns EINTR),
  9398. * but this causes stdout FILE to be stuck
  9399. * and needing clearerr(). What if other applets
  9400. * also can get EINTRs? Do we need to switch
  9401. * our signals to SA_RESTART?
  9402. */
  9403. /*clearerr(stdout);*/
  9404. INT_ON;
  9405. break;
  9406. }
  9407. #endif
  9408. /* Can we avoid forking? For example, very last command
  9409. * in a script or a subshell does not need forking,
  9410. * we can just exec it.
  9411. */
  9412. if (!(flags & EV_EXIT) || may_have_traps) {
  9413. /* No, forking off a child is necessary */
  9414. INT_OFF;
  9415. get_tty_state();
  9416. jp = makejob(/*cmd,*/ 1);
  9417. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9418. /* parent */
  9419. status = waitforjob(jp);
  9420. INT_ON;
  9421. TRACE(("forked child exited with %d\n", status));
  9422. break;
  9423. }
  9424. /* child */
  9425. FORCE_INT_ON;
  9426. /* fall through to exec'ing external program */
  9427. }
  9428. listsetvar(varlist.list, VEXPORT|VSTACK);
  9429. shellexec(argv[0], argv, path, cmdentry.u.index);
  9430. /* NOTREACHED */
  9431. } /* default */
  9432. case CMDBUILTIN:
  9433. if (spclbltin > 0 || argc == 0) {
  9434. poplocalvars(1);
  9435. if (cmd_is_exec && argc > 1)
  9436. listsetvar(varlist.list, VEXPORT);
  9437. }
  9438. /* Tight loop with builtins only:
  9439. * "while kill -0 $child; do true; done"
  9440. * will never exit even if $child died, unless we do this
  9441. * to reap the zombie and make kill detect that it's gone: */
  9442. dowait(DOWAIT_NONBLOCK, NULL);
  9443. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
  9444. if (exception_type == EXERROR && spclbltin <= 0) {
  9445. FORCE_INT_ON;
  9446. goto readstatus;
  9447. }
  9448. raise:
  9449. longjmp(exception_handler->loc, 1);
  9450. }
  9451. goto readstatus;
  9452. case CMDFUNCTION:
  9453. /* See above for the rationale */
  9454. dowait(DOWAIT_NONBLOCK, NULL);
  9455. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9456. goto raise;
  9457. readstatus:
  9458. status = exitstatus;
  9459. break;
  9460. } /* switch */
  9461. out:
  9462. if (cmd->ncmd.redirect)
  9463. popredir(/*drop:*/ cmd_is_exec);
  9464. unwindredir(redir_stop);
  9465. unwindfiles(file_stop);
  9466. unwindlocalvars(localvar_stop);
  9467. if (lastarg) {
  9468. /* dsl: I think this is intended to be used to support
  9469. * '_' in 'vi' command mode during line editing...
  9470. * However I implemented that within libedit itself.
  9471. */
  9472. setvar0("_", lastarg);
  9473. }
  9474. return status;
  9475. }
  9476. static int
  9477. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9478. {
  9479. char *volatile savecmdname;
  9480. struct jmploc *volatile savehandler;
  9481. struct jmploc jmploc;
  9482. int status;
  9483. int i;
  9484. savecmdname = commandname;
  9485. savehandler = exception_handler;
  9486. i = setjmp(jmploc.loc);
  9487. if (i)
  9488. goto cmddone;
  9489. exception_handler = &jmploc;
  9490. commandname = argv[0];
  9491. argptr = argv + 1;
  9492. optptr = NULL; /* initialize nextopt */
  9493. if (cmd == EVALCMD)
  9494. status = evalcmd(argc, argv, flags);
  9495. else
  9496. status = (*cmd->builtin)(argc, argv);
  9497. flush_stdout_stderr();
  9498. status |= ferror(stdout);
  9499. exitstatus = status;
  9500. cmddone:
  9501. clearerr(stdout);
  9502. commandname = savecmdname;
  9503. exception_handler = savehandler;
  9504. return i;
  9505. }
  9506. static int
  9507. goodname(const char *p)
  9508. {
  9509. return endofname(p)[0] == '\0';
  9510. }
  9511. /*
  9512. * Search for a command. This is called before we fork so that the
  9513. * location of the command will be available in the parent as well as
  9514. * the child. The check for "goodname" is an overly conservative
  9515. * check that the name will not be subject to expansion.
  9516. */
  9517. static void
  9518. prehash(union node *n)
  9519. {
  9520. struct cmdentry entry;
  9521. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9522. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9523. }
  9524. /* ============ Builtin commands
  9525. *
  9526. * Builtin commands whose functions are closely tied to evaluation
  9527. * are implemented here.
  9528. */
  9529. /*
  9530. * Handle break and continue commands. Break, continue, and return are
  9531. * all handled by setting the evalskip flag. The evaluation routines
  9532. * above all check this flag, and if it is set they start skipping
  9533. * commands rather than executing them. The variable skipcount is
  9534. * the number of loops to break/continue, or the number of function
  9535. * levels to return. (The latter is always 1.) It should probably
  9536. * be an error to break out of more loops than exist, but it isn't
  9537. * in the standard shell so we don't make it one here.
  9538. */
  9539. static int FAST_FUNC
  9540. breakcmd(int argc UNUSED_PARAM, char **argv)
  9541. {
  9542. int n = argv[1] ? number(argv[1]) : 1;
  9543. if (n <= 0)
  9544. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9545. if (n > loopnest)
  9546. n = loopnest;
  9547. if (n > 0) {
  9548. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9549. skipcount = n;
  9550. }
  9551. return 0;
  9552. }
  9553. /*
  9554. * This implements the input routines used by the parser.
  9555. */
  9556. enum {
  9557. INPUT_PUSH_FILE = 1,
  9558. INPUT_NOFILE_OK = 2,
  9559. };
  9560. static smallint checkkwd;
  9561. /* values of checkkwd variable */
  9562. #define CHKALIAS 0x1
  9563. #define CHKKWD 0x2
  9564. #define CHKNL 0x4
  9565. #define CHKEOFMARK 0x8
  9566. /*
  9567. * Push a string back onto the input at this current parsefile level.
  9568. * We handle aliases this way.
  9569. */
  9570. #if !ENABLE_ASH_ALIAS
  9571. #define pushstring(s, ap) pushstring(s)
  9572. #endif
  9573. static void
  9574. pushstring(char *s, struct alias *ap)
  9575. {
  9576. struct strpush *sp;
  9577. int len;
  9578. len = strlen(s);
  9579. INT_OFF;
  9580. if (g_parsefile->strpush) {
  9581. sp = ckzalloc(sizeof(*sp));
  9582. sp->prev = g_parsefile->strpush;
  9583. } else {
  9584. sp = &(g_parsefile->basestrpush);
  9585. }
  9586. g_parsefile->strpush = sp;
  9587. sp->prev_string = g_parsefile->next_to_pgetc;
  9588. sp->prev_left_in_line = g_parsefile->left_in_line;
  9589. sp->unget = g_parsefile->unget;
  9590. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9591. #if ENABLE_ASH_ALIAS
  9592. sp->ap = ap;
  9593. if (ap) {
  9594. ap->flag |= ALIASINUSE;
  9595. sp->string = s;
  9596. }
  9597. #endif
  9598. g_parsefile->next_to_pgetc = s;
  9599. g_parsefile->left_in_line = len;
  9600. g_parsefile->unget = 0;
  9601. INT_ON;
  9602. }
  9603. static void
  9604. popstring(void)
  9605. {
  9606. struct strpush *sp = g_parsefile->strpush;
  9607. INT_OFF;
  9608. #if ENABLE_ASH_ALIAS
  9609. if (sp->ap) {
  9610. if (g_parsefile->next_to_pgetc[-1] == ' '
  9611. || g_parsefile->next_to_pgetc[-1] == '\t'
  9612. ) {
  9613. checkkwd |= CHKALIAS;
  9614. }
  9615. if (sp->string != sp->ap->val) {
  9616. free(sp->string);
  9617. }
  9618. sp->ap->flag &= ~ALIASINUSE;
  9619. if (sp->ap->flag & ALIASDEAD) {
  9620. unalias(sp->ap->name);
  9621. }
  9622. }
  9623. #endif
  9624. g_parsefile->next_to_pgetc = sp->prev_string;
  9625. g_parsefile->left_in_line = sp->prev_left_in_line;
  9626. g_parsefile->unget = sp->unget;
  9627. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9628. g_parsefile->strpush = sp->prev;
  9629. if (sp != &(g_parsefile->basestrpush))
  9630. free(sp);
  9631. INT_ON;
  9632. }
  9633. static int
  9634. preadfd(void)
  9635. {
  9636. int nr;
  9637. char *buf = g_parsefile->buf;
  9638. g_parsefile->next_to_pgetc = buf;
  9639. #if ENABLE_FEATURE_EDITING
  9640. retry:
  9641. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9642. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9643. else {
  9644. # if ENABLE_ASH_IDLE_TIMEOUT
  9645. int timeout = -1;
  9646. const char *tmout_var = lookupvar("TMOUT");
  9647. if (tmout_var) {
  9648. timeout = atoi(tmout_var) * 1000;
  9649. if (timeout <= 0)
  9650. timeout = -1;
  9651. }
  9652. line_input_state->timeout = timeout;
  9653. # endif
  9654. # if ENABLE_FEATURE_TAB_COMPLETION
  9655. line_input_state->path_lookup = pathval();
  9656. # endif
  9657. reinit_unicode_for_ash();
  9658. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9659. if (nr == 0) {
  9660. /* ^C pressed, "convert" to SIGINT */
  9661. write(STDOUT_FILENO, "^C", 2);
  9662. if (trap[SIGINT]) {
  9663. buf[0] = '\n';
  9664. buf[1] = '\0';
  9665. raise(SIGINT);
  9666. return 1;
  9667. }
  9668. exitstatus = 128 + SIGINT;
  9669. bb_putchar('\n');
  9670. goto retry;
  9671. }
  9672. if (nr < 0) {
  9673. if (errno == 0) {
  9674. /* Ctrl+D pressed */
  9675. nr = 0;
  9676. }
  9677. # if ENABLE_ASH_IDLE_TIMEOUT
  9678. else if (errno == EAGAIN && timeout > 0) {
  9679. puts("\007timed out waiting for input: auto-logout");
  9680. exitshell();
  9681. }
  9682. # endif
  9683. }
  9684. }
  9685. #else
  9686. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9687. #endif
  9688. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9689. if (nr < 0) {
  9690. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9691. int flags = fcntl(0, F_GETFL);
  9692. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9693. flags &= ~O_NONBLOCK;
  9694. if (fcntl(0, F_SETFL, flags) >= 0) {
  9695. out2str("sh: turning off NDELAY mode\n");
  9696. goto retry;
  9697. }
  9698. }
  9699. }
  9700. }
  9701. #endif
  9702. return nr;
  9703. }
  9704. /*
  9705. * Refill the input buffer and return the next input character:
  9706. *
  9707. * 1) If a string was pushed back on the input, pop it;
  9708. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9709. * or we are reading from a string so we can't refill the buffer,
  9710. * return EOF.
  9711. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9712. * 4) Process input up to the next newline, deleting nul characters.
  9713. */
  9714. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9715. #define pgetc_debug(...) ((void)0)
  9716. static int pgetc(void);
  9717. static int
  9718. preadbuffer(void)
  9719. {
  9720. char *q;
  9721. int more;
  9722. if (g_parsefile->strpush) {
  9723. #if ENABLE_ASH_ALIAS
  9724. if (g_parsefile->left_in_line == -1
  9725. && g_parsefile->strpush->ap
  9726. && g_parsefile->next_to_pgetc[-1] != ' '
  9727. && g_parsefile->next_to_pgetc[-1] != '\t'
  9728. ) {
  9729. pgetc_debug("preadbuffer PEOA");
  9730. return PEOA;
  9731. }
  9732. #endif
  9733. popstring();
  9734. return pgetc();
  9735. }
  9736. /* on both branches above g_parsefile->left_in_line < 0.
  9737. * "pgetc" needs refilling.
  9738. */
  9739. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9740. * pungetc() may increment it a few times.
  9741. * Assuming it won't increment it to less than -90.
  9742. */
  9743. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9744. pgetc_debug("preadbuffer PEOF1");
  9745. /* even in failure keep left_in_line and next_to_pgetc
  9746. * in lock step, for correct multi-layer pungetc.
  9747. * left_in_line was decremented before preadbuffer(),
  9748. * must inc next_to_pgetc: */
  9749. g_parsefile->next_to_pgetc++;
  9750. return PEOF;
  9751. }
  9752. more = g_parsefile->left_in_buffer;
  9753. if (more <= 0) {
  9754. flush_stdout_stderr();
  9755. again:
  9756. more = preadfd();
  9757. if (more <= 0) {
  9758. /* don't try reading again */
  9759. g_parsefile->left_in_line = -99;
  9760. pgetc_debug("preadbuffer PEOF2");
  9761. g_parsefile->next_to_pgetc++;
  9762. return PEOF;
  9763. }
  9764. }
  9765. /* Find out where's the end of line.
  9766. * Set g_parsefile->left_in_line
  9767. * and g_parsefile->left_in_buffer acordingly.
  9768. * NUL chars are deleted.
  9769. */
  9770. q = g_parsefile->next_to_pgetc;
  9771. for (;;) {
  9772. char c;
  9773. more--;
  9774. c = *q;
  9775. if (c == '\0') {
  9776. memmove(q, q + 1, more);
  9777. } else {
  9778. q++;
  9779. if (c == '\n') {
  9780. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9781. break;
  9782. }
  9783. }
  9784. if (more <= 0) {
  9785. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9786. if (g_parsefile->left_in_line < 0)
  9787. goto again;
  9788. break;
  9789. }
  9790. }
  9791. g_parsefile->left_in_buffer = more;
  9792. if (vflag) {
  9793. char save = *q;
  9794. *q = '\0';
  9795. out2str(g_parsefile->next_to_pgetc);
  9796. *q = save;
  9797. }
  9798. pgetc_debug("preadbuffer at %d:%p'%s'",
  9799. g_parsefile->left_in_line,
  9800. g_parsefile->next_to_pgetc,
  9801. g_parsefile->next_to_pgetc);
  9802. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9803. }
  9804. static void
  9805. nlprompt(void)
  9806. {
  9807. g_parsefile->linno++;
  9808. setprompt_if(doprompt, 2);
  9809. }
  9810. static void
  9811. nlnoprompt(void)
  9812. {
  9813. g_parsefile->linno++;
  9814. needprompt = doprompt;
  9815. }
  9816. static int
  9817. pgetc(void)
  9818. {
  9819. int c;
  9820. pgetc_debug("pgetc at %d:%p'%s'",
  9821. g_parsefile->left_in_line,
  9822. g_parsefile->next_to_pgetc,
  9823. g_parsefile->next_to_pgetc);
  9824. if (g_parsefile->unget)
  9825. return g_parsefile->lastc[--g_parsefile->unget];
  9826. if (--g_parsefile->left_in_line >= 0)
  9827. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9828. else
  9829. c = preadbuffer();
  9830. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9831. g_parsefile->lastc[0] = c;
  9832. return c;
  9833. }
  9834. #if ENABLE_ASH_ALIAS
  9835. static int
  9836. pgetc_without_PEOA(void)
  9837. {
  9838. int c;
  9839. do {
  9840. pgetc_debug("pgetc at %d:%p'%s'",
  9841. g_parsefile->left_in_line,
  9842. g_parsefile->next_to_pgetc,
  9843. g_parsefile->next_to_pgetc);
  9844. c = pgetc();
  9845. } while (c == PEOA);
  9846. return c;
  9847. }
  9848. #else
  9849. # define pgetc_without_PEOA() pgetc()
  9850. #endif
  9851. /*
  9852. * Undo a call to pgetc. Only two characters may be pushed back.
  9853. * PEOF may be pushed back.
  9854. */
  9855. static void
  9856. pungetc(void)
  9857. {
  9858. g_parsefile->unget++;
  9859. }
  9860. /* This one eats backslash+newline */
  9861. static int
  9862. pgetc_eatbnl(void)
  9863. {
  9864. int c;
  9865. while ((c = pgetc()) == '\\') {
  9866. if (pgetc() != '\n') {
  9867. pungetc();
  9868. break;
  9869. }
  9870. nlprompt();
  9871. }
  9872. return c;
  9873. }
  9874. struct synstack {
  9875. smalluint syntax;
  9876. uint8_t innerdq :1;
  9877. uint8_t varpushed :1;
  9878. uint8_t dblquote :1;
  9879. int varnest; /* levels of variables expansion */
  9880. int dqvarnest; /* levels of variables expansion within double quotes */
  9881. int parenlevel; /* levels of parens in arithmetic */
  9882. struct synstack *prev;
  9883. struct synstack *next;
  9884. };
  9885. static void
  9886. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  9887. {
  9888. memset(next, 0, sizeof(*next));
  9889. next->syntax = syntax;
  9890. next->next = *stack;
  9891. (*stack)->prev = next;
  9892. *stack = next;
  9893. }
  9894. static ALWAYS_INLINE void
  9895. synstack_pop(struct synstack **stack)
  9896. {
  9897. *stack = (*stack)->next;
  9898. }
  9899. /*
  9900. * To handle the "." command, a stack of input files is used. Pushfile
  9901. * adds a new entry to the stack and popfile restores the previous level.
  9902. */
  9903. static void
  9904. pushfile(void)
  9905. {
  9906. struct parsefile *pf;
  9907. pf = ckzalloc(sizeof(*pf));
  9908. pf->prev = g_parsefile;
  9909. pf->pf_fd = -1;
  9910. /*pf->strpush = NULL; - ckzalloc did it */
  9911. /*pf->basestrpush.prev = NULL;*/
  9912. /*pf->unget = 0;*/
  9913. g_parsefile = pf;
  9914. }
  9915. static void
  9916. popfile(void)
  9917. {
  9918. struct parsefile *pf = g_parsefile;
  9919. if (pf == &basepf)
  9920. return;
  9921. INT_OFF;
  9922. if (pf->pf_fd >= 0)
  9923. close(pf->pf_fd);
  9924. free(pf->buf);
  9925. while (pf->strpush)
  9926. popstring();
  9927. g_parsefile = pf->prev;
  9928. free(pf);
  9929. INT_ON;
  9930. }
  9931. static void
  9932. unwindfiles(struct parsefile *stop)
  9933. {
  9934. while (g_parsefile != stop)
  9935. popfile();
  9936. }
  9937. /*
  9938. * Return to top level.
  9939. */
  9940. static void
  9941. popallfiles(void)
  9942. {
  9943. unwindfiles(&basepf);
  9944. }
  9945. /*
  9946. * Close the file(s) that the shell is reading commands from. Called
  9947. * after a fork is done.
  9948. */
  9949. static void
  9950. closescript(void)
  9951. {
  9952. popallfiles();
  9953. if (g_parsefile->pf_fd > 0) {
  9954. close(g_parsefile->pf_fd);
  9955. g_parsefile->pf_fd = 0;
  9956. }
  9957. }
  9958. /*
  9959. * Like setinputfile, but takes an open file descriptor. Call this with
  9960. * interrupts off.
  9961. */
  9962. static void
  9963. setinputfd(int fd, int push)
  9964. {
  9965. if (push) {
  9966. pushfile();
  9967. g_parsefile->buf = NULL;
  9968. }
  9969. g_parsefile->pf_fd = fd;
  9970. if (g_parsefile->buf == NULL)
  9971. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9972. g_parsefile->left_in_buffer = 0;
  9973. g_parsefile->left_in_line = 0;
  9974. g_parsefile->linno = 1;
  9975. }
  9976. /*
  9977. * Set the input to take input from a file. If push is set, push the
  9978. * old input onto the stack first.
  9979. */
  9980. static int
  9981. setinputfile(const char *fname, int flags)
  9982. {
  9983. int fd;
  9984. INT_OFF;
  9985. fd = open(fname, O_RDONLY | O_CLOEXEC);
  9986. if (fd < 0) {
  9987. if (flags & INPUT_NOFILE_OK)
  9988. goto out;
  9989. exitstatus = 127;
  9990. ash_msg_and_raise_perror("can't open '%s'", fname);
  9991. }
  9992. if (fd < 10)
  9993. fd = savefd(fd);
  9994. else if (O_CLOEXEC == 0) /* old libc */
  9995. close_on_exec_on(fd);
  9996. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9997. out:
  9998. INT_ON;
  9999. return fd;
  10000. }
  10001. /*
  10002. * Like setinputfile, but takes input from a string.
  10003. */
  10004. static void
  10005. setinputstring(char *string)
  10006. {
  10007. INT_OFF;
  10008. pushfile();
  10009. g_parsefile->next_to_pgetc = string;
  10010. g_parsefile->left_in_line = strlen(string);
  10011. g_parsefile->buf = NULL;
  10012. g_parsefile->linno = 1;
  10013. INT_ON;
  10014. }
  10015. /*
  10016. * Routines to check for mail.
  10017. */
  10018. #if ENABLE_ASH_MAIL
  10019. /* Hash of mtimes of mailboxes */
  10020. static unsigned mailtime_hash;
  10021. /* Set if MAIL or MAILPATH is changed. */
  10022. static smallint mail_var_path_changed;
  10023. /*
  10024. * Print appropriate message(s) if mail has arrived.
  10025. * If mail_var_path_changed is set,
  10026. * then the value of MAIL has mail_var_path_changed,
  10027. * so we just update the values.
  10028. */
  10029. static void
  10030. chkmail(void)
  10031. {
  10032. const char *mpath;
  10033. char *p;
  10034. char *q;
  10035. unsigned new_hash;
  10036. struct stackmark smark;
  10037. struct stat statb;
  10038. setstackmark(&smark);
  10039. mpath = mpathset() ? mpathval() : mailval();
  10040. new_hash = 0;
  10041. for (;;) {
  10042. p = path_advance(&mpath, nullstr);
  10043. if (p == NULL)
  10044. break;
  10045. if (*p == '\0')
  10046. continue;
  10047. for (q = p; *q; q++)
  10048. continue;
  10049. #if DEBUG
  10050. if (q[-1] != '/')
  10051. abort();
  10052. #endif
  10053. q[-1] = '\0'; /* delete trailing '/' */
  10054. if (stat(p, &statb) < 0) {
  10055. continue;
  10056. }
  10057. /* Very simplistic "hash": just a sum of all mtimes */
  10058. new_hash += (unsigned)statb.st_mtime;
  10059. }
  10060. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  10061. if (mailtime_hash != 0)
  10062. out2str("you have mail\n");
  10063. mailtime_hash = new_hash;
  10064. }
  10065. mail_var_path_changed = 0;
  10066. popstackmark(&smark);
  10067. }
  10068. static void FAST_FUNC
  10069. changemail(const char *val UNUSED_PARAM)
  10070. {
  10071. mail_var_path_changed = 1;
  10072. }
  10073. #endif /* ASH_MAIL */
  10074. /* ============ ??? */
  10075. /*
  10076. * Set the shell parameters.
  10077. */
  10078. static void
  10079. setparam(char **argv)
  10080. {
  10081. char **newparam;
  10082. char **ap;
  10083. int nparam;
  10084. for (nparam = 0; argv[nparam]; nparam++)
  10085. continue;
  10086. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10087. while (*argv) {
  10088. *ap++ = ckstrdup(*argv++);
  10089. }
  10090. *ap = NULL;
  10091. freeparam(&shellparam);
  10092. shellparam.malloced = 1;
  10093. shellparam.nparam = nparam;
  10094. shellparam.p = newparam;
  10095. #if ENABLE_ASH_GETOPTS
  10096. shellparam.optind = 1;
  10097. shellparam.optoff = -1;
  10098. #endif
  10099. }
  10100. /*
  10101. * Process shell options. The global variable argptr contains a pointer
  10102. * to the argument list; we advance it past the options.
  10103. *
  10104. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10105. * For a non-interactive shell, an error condition encountered
  10106. * by a special built-in ... shall cause the shell to write a diagnostic message
  10107. * to standard error and exit as shown in the following table:
  10108. * Error Special Built-In
  10109. * ...
  10110. * Utility syntax error (option or operand error) Shall exit
  10111. * ...
  10112. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10113. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10114. * and shell continues), and people rely on this behavior!
  10115. * Testcase:
  10116. * set -o barfoo 2>/dev/null
  10117. * echo $?
  10118. *
  10119. * Oh well. Let's mimic that.
  10120. */
  10121. static int
  10122. plus_minus_o(char *name, int val)
  10123. {
  10124. int i;
  10125. if (name) {
  10126. for (i = 0; i < NOPTS; i++) {
  10127. if (strcmp(name, optnames(i)) == 0) {
  10128. optlist[i] = val;
  10129. return 0;
  10130. }
  10131. }
  10132. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10133. return 1;
  10134. }
  10135. for (i = 0; i < NOPTS; i++) {
  10136. if (optnames(i)[0] == '\0')
  10137. continue;
  10138. if (val) {
  10139. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10140. } else {
  10141. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10142. }
  10143. }
  10144. return 0;
  10145. }
  10146. static void
  10147. setoption(int flag, int val)
  10148. {
  10149. int i;
  10150. for (i = 0; i < NOPTS; i++) {
  10151. if (optletters(i) == flag && optnames(i)[0] != '\0') {
  10152. optlist[i] = val;
  10153. return;
  10154. }
  10155. }
  10156. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10157. /* NOTREACHED */
  10158. }
  10159. /* If login_sh is not NULL, we are called to parse command line opts,
  10160. * not "set -opts"
  10161. */
  10162. static int
  10163. options(int *login_sh)
  10164. {
  10165. char *p;
  10166. int val;
  10167. int c;
  10168. if (login_sh)
  10169. minusc = NULL;
  10170. while ((p = *argptr) != NULL) {
  10171. c = *p++;
  10172. if (c != '-' && c != '+')
  10173. break;
  10174. argptr++;
  10175. val = 0; /* val = 0 if c == '+' */
  10176. if (c == '-') {
  10177. val = 1;
  10178. if (p[0] == '\0' || LONE_DASH(p)) {
  10179. if (!login_sh) {
  10180. /* "-" means turn off -x and -v */
  10181. if (p[0] == '\0')
  10182. xflag = vflag = 0;
  10183. /* "--" means reset params */
  10184. else if (*argptr == NULL)
  10185. setparam(argptr);
  10186. }
  10187. break; /* "-" or "--" terminates options */
  10188. }
  10189. }
  10190. /* first char was + or - */
  10191. while ((c = *p++) != '\0') {
  10192. if (login_sh) {
  10193. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10194. if (c == 'c') {
  10195. minusc = p; /* command is after shell args */
  10196. cflag = 1;
  10197. continue;
  10198. }
  10199. if (c == 's') { /* -s, +s */
  10200. sflag = 1;
  10201. continue;
  10202. }
  10203. if (c == 'i') { /* -i, +i */
  10204. iflag = 1;
  10205. continue;
  10206. }
  10207. if (c == 'l') {
  10208. *login_sh = 1; /* -l or +l == --login */
  10209. continue;
  10210. }
  10211. /* bash does not accept +-login, we also won't */
  10212. if (val && (c == '-')) { /* long options */
  10213. if (strcmp(p, "login") == 0) {
  10214. *login_sh = 1;
  10215. }
  10216. break;
  10217. }
  10218. }
  10219. if (c == 'o') {
  10220. if (plus_minus_o(*argptr, val)) {
  10221. /* it already printed err message */
  10222. return 1; /* error */
  10223. }
  10224. if (*argptr)
  10225. argptr++;
  10226. } else {
  10227. setoption(c, val);
  10228. }
  10229. }
  10230. }
  10231. return 0;
  10232. }
  10233. /*
  10234. * The shift builtin command.
  10235. */
  10236. static int FAST_FUNC
  10237. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10238. {
  10239. int n;
  10240. char **ap1, **ap2;
  10241. n = 1;
  10242. if (argv[1])
  10243. n = number(argv[1]);
  10244. if (n > shellparam.nparam)
  10245. return 1;
  10246. INT_OFF;
  10247. shellparam.nparam -= n;
  10248. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10249. if (shellparam.malloced)
  10250. free(*ap1);
  10251. }
  10252. ap2 = shellparam.p;
  10253. while ((*ap2++ = *ap1++) != NULL)
  10254. continue;
  10255. #if ENABLE_ASH_GETOPTS
  10256. shellparam.optind = 1;
  10257. shellparam.optoff = -1;
  10258. #endif
  10259. INT_ON;
  10260. return 0;
  10261. }
  10262. /*
  10263. * POSIX requires that 'set' (but not export or readonly) output the
  10264. * variables in lexicographic order - by the locale's collating order (sigh).
  10265. * Maybe we could keep them in an ordered balanced binary tree
  10266. * instead of hashed lists.
  10267. * For now just roll 'em through qsort for printing...
  10268. */
  10269. static int
  10270. showvars(const char *sep_prefix, int on, int off)
  10271. {
  10272. const char *sep;
  10273. char **ep, **epend;
  10274. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10275. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10276. sep = *sep_prefix ? " " : sep_prefix;
  10277. for (; ep < epend; ep++) {
  10278. const char *p;
  10279. const char *q;
  10280. p = endofname(*ep);
  10281. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10282. * makes "export -p" to have output not suitable for "eval":
  10283. * import os
  10284. * os.environ["test-test"]="test"
  10285. * if os.fork() == 0:
  10286. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10287. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10288. */
  10289. q = nullstr;
  10290. if (*p == '=')
  10291. q = single_quote(++p);
  10292. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10293. }
  10294. return 0;
  10295. }
  10296. /*
  10297. * The set command builtin.
  10298. */
  10299. static int FAST_FUNC
  10300. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10301. {
  10302. int retval;
  10303. if (!argv[1])
  10304. return showvars(nullstr, 0, VUNSET);
  10305. INT_OFF;
  10306. retval = options(/*login_sh:*/ NULL);
  10307. if (retval == 0) { /* if no parse error... */
  10308. optschanged();
  10309. if (*argptr != NULL) {
  10310. setparam(argptr);
  10311. }
  10312. }
  10313. INT_ON;
  10314. return retval;
  10315. }
  10316. #if ENABLE_ASH_RANDOM_SUPPORT
  10317. static void FAST_FUNC
  10318. change_random(const char *value)
  10319. {
  10320. uint32_t t;
  10321. if (value == NULL) {
  10322. /* "get", generate */
  10323. t = next_random(&random_gen);
  10324. /* set without recursion */
  10325. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10326. vrandom.flags &= ~VNOFUNC;
  10327. } else {
  10328. /* set/reset */
  10329. t = strtoul(value, NULL, 10);
  10330. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10331. }
  10332. }
  10333. #endif
  10334. #if BASH_EPOCH_VARS
  10335. static void FAST_FUNC
  10336. change_epoch(struct var *vepoch, const char *fmt)
  10337. {
  10338. struct timeval tv;
  10339. char buffer[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  10340. gettimeofday(&tv, NULL);
  10341. sprintf(buffer, fmt, (unsigned long)tv.tv_sec, (unsigned)tv.tv_usec);
  10342. setvar(vepoch->var_text, buffer, VNOFUNC);
  10343. vepoch->flags &= ~VNOFUNC;
  10344. }
  10345. static void FAST_FUNC
  10346. change_seconds(const char *value UNUSED_PARAM)
  10347. {
  10348. change_epoch(&vepochs, "%lu");
  10349. }
  10350. static void FAST_FUNC
  10351. change_realtime(const char *value UNUSED_PARAM)
  10352. {
  10353. change_epoch(&vepochr, "%lu.%06u");
  10354. }
  10355. #endif
  10356. #if ENABLE_ASH_GETOPTS
  10357. static int
  10358. getopts(char *optstr, char *optvar, char **optfirst)
  10359. {
  10360. char *p, *q;
  10361. char c = '?';
  10362. int done = 0;
  10363. char sbuf[2];
  10364. char **optnext;
  10365. int ind = shellparam.optind;
  10366. int off = shellparam.optoff;
  10367. sbuf[1] = '\0';
  10368. shellparam.optind = -1;
  10369. optnext = optfirst + ind - 1;
  10370. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10371. p = NULL;
  10372. else
  10373. p = optnext[-1] + off;
  10374. if (p == NULL || *p == '\0') {
  10375. /* Current word is done, advance */
  10376. p = *optnext;
  10377. if (p == NULL || *p != '-' || *++p == '\0') {
  10378. atend:
  10379. unsetvar("OPTARG");
  10380. p = NULL;
  10381. done = 1;
  10382. goto out;
  10383. }
  10384. optnext++;
  10385. if (LONE_DASH(p)) /* check for "--" */
  10386. goto atend;
  10387. }
  10388. c = *p++;
  10389. for (q = optstr; *q != c;) {
  10390. if (*q == '\0') {
  10391. /* OPTERR is a bashism */
  10392. const char *cp = lookupvar("OPTERR");
  10393. if ((cp && LONE_CHAR(cp, '0'))
  10394. || (optstr[0] == ':')
  10395. ) {
  10396. sbuf[0] = c;
  10397. /*sbuf[1] = '\0'; - already is */
  10398. setvar0("OPTARG", sbuf);
  10399. } else {
  10400. fprintf(stderr, "Illegal option -%c\n", c);
  10401. unsetvar("OPTARG");
  10402. }
  10403. c = '?';
  10404. goto out;
  10405. }
  10406. if (*++q == ':')
  10407. q++;
  10408. }
  10409. if (*++q == ':') {
  10410. if (*p == '\0' && (p = *optnext) == NULL) {
  10411. /* OPTERR is a bashism */
  10412. const char *cp = lookupvar("OPTERR");
  10413. if ((cp && LONE_CHAR(cp, '0'))
  10414. || (optstr[0] == ':')
  10415. ) {
  10416. sbuf[0] = c;
  10417. /*sbuf[1] = '\0'; - already is */
  10418. setvar0("OPTARG", sbuf);
  10419. c = ':';
  10420. } else {
  10421. fprintf(stderr, "No arg for -%c option\n", c);
  10422. unsetvar("OPTARG");
  10423. c = '?';
  10424. }
  10425. goto out;
  10426. }
  10427. if (p == *optnext)
  10428. optnext++;
  10429. setvar0("OPTARG", p);
  10430. p = NULL;
  10431. } else
  10432. setvar0("OPTARG", nullstr);
  10433. out:
  10434. ind = optnext - optfirst + 1;
  10435. setvar("OPTIND", itoa(ind), VNOFUNC);
  10436. sbuf[0] = c;
  10437. /*sbuf[1] = '\0'; - already is */
  10438. setvar0(optvar, sbuf);
  10439. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10440. shellparam.optind = ind;
  10441. return done;
  10442. }
  10443. /*
  10444. * The getopts builtin. Shellparam.optnext points to the next argument
  10445. * to be processed. Shellparam.optptr points to the next character to
  10446. * be processed in the current argument. If shellparam.optnext is NULL,
  10447. * then it's the first time getopts has been called.
  10448. */
  10449. static int FAST_FUNC
  10450. getoptscmd(int argc, char **argv)
  10451. {
  10452. char **optbase;
  10453. if (argc < 3)
  10454. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10455. if (argc == 3) {
  10456. optbase = shellparam.p;
  10457. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10458. shellparam.optind = 1;
  10459. shellparam.optoff = -1;
  10460. }
  10461. } else {
  10462. optbase = &argv[3];
  10463. if ((unsigned)shellparam.optind > argc - 2) {
  10464. shellparam.optind = 1;
  10465. shellparam.optoff = -1;
  10466. }
  10467. }
  10468. return getopts(argv[1], argv[2], optbase);
  10469. }
  10470. #endif /* ASH_GETOPTS */
  10471. /* ============ Shell parser */
  10472. struct heredoc {
  10473. struct heredoc *next; /* next here document in list */
  10474. union node *here; /* redirection node */
  10475. char *eofmark; /* string indicating end of input */
  10476. smallint striptabs; /* if set, strip leading tabs */
  10477. };
  10478. static smallint tokpushback; /* last token pushed back */
  10479. static smallint quoteflag; /* set if (part of) last token was quoted */
  10480. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10481. static struct heredoc *heredoclist; /* list of here documents to read */
  10482. static char *wordtext; /* text of last word returned by readtoken */
  10483. static struct nodelist *backquotelist;
  10484. static union node *redirnode;
  10485. static struct heredoc *heredoc;
  10486. static const char *
  10487. tokname(char *buf, int tok)
  10488. {
  10489. if (tok < TSEMI)
  10490. return tokname_array[tok];
  10491. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10492. return buf;
  10493. }
  10494. /* raise_error_unexpected_syntax:
  10495. * Called when an unexpected token is read during the parse. The argument
  10496. * is the token that is expected, or -1 if more than one type of token can
  10497. * occur at this point.
  10498. */
  10499. static void raise_error_unexpected_syntax(int) NORETURN;
  10500. static void
  10501. raise_error_unexpected_syntax(int token)
  10502. {
  10503. char msg[64];
  10504. char buf[16];
  10505. int l;
  10506. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10507. if (token >= 0)
  10508. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10509. raise_error_syntax(msg);
  10510. /* NOTREACHED */
  10511. }
  10512. /* parsing is heavily cross-recursive, need these forward decls */
  10513. static union node *andor(void);
  10514. static union node *pipeline(void);
  10515. static union node *parse_command(void);
  10516. static void parseheredoc(void);
  10517. static int peektoken(void);
  10518. static int readtoken(void);
  10519. static union node *
  10520. list(int nlflag)
  10521. {
  10522. union node *n1, *n2, *n3;
  10523. int tok;
  10524. n1 = NULL;
  10525. for (;;) {
  10526. switch (peektoken()) {
  10527. case TNL:
  10528. if (!(nlflag & 1))
  10529. break;
  10530. parseheredoc();
  10531. return n1;
  10532. case TEOF:
  10533. if (!n1 && (nlflag & 1))
  10534. n1 = NODE_EOF;
  10535. parseheredoc();
  10536. return n1;
  10537. }
  10538. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10539. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10540. return n1;
  10541. nlflag |= 2;
  10542. n2 = andor();
  10543. tok = readtoken();
  10544. if (tok == TBACKGND) {
  10545. if (n2->type == NPIPE) {
  10546. n2->npipe.pipe_backgnd = 1;
  10547. } else {
  10548. if (n2->type != NREDIR) {
  10549. n3 = stzalloc(sizeof(struct nredir));
  10550. n3->nredir.n = n2;
  10551. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10552. n2 = n3;
  10553. }
  10554. n2->type = NBACKGND;
  10555. }
  10556. }
  10557. if (n1 == NULL) {
  10558. n1 = n2;
  10559. } else {
  10560. n3 = stzalloc(sizeof(struct nbinary));
  10561. n3->type = NSEMI;
  10562. n3->nbinary.ch1 = n1;
  10563. n3->nbinary.ch2 = n2;
  10564. n1 = n3;
  10565. }
  10566. switch (tok) {
  10567. case TNL:
  10568. case TEOF:
  10569. tokpushback = 1;
  10570. /* fall through */
  10571. case TBACKGND:
  10572. case TSEMI:
  10573. break;
  10574. default:
  10575. if ((nlflag & 1))
  10576. raise_error_unexpected_syntax(-1);
  10577. tokpushback = 1;
  10578. return n1;
  10579. }
  10580. }
  10581. }
  10582. static union node *
  10583. andor(void)
  10584. {
  10585. union node *n1, *n2, *n3;
  10586. int t;
  10587. n1 = pipeline();
  10588. for (;;) {
  10589. t = readtoken();
  10590. if (t == TAND) {
  10591. t = NAND;
  10592. } else if (t == TOR) {
  10593. t = NOR;
  10594. } else {
  10595. tokpushback = 1;
  10596. return n1;
  10597. }
  10598. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10599. n2 = pipeline();
  10600. n3 = stzalloc(sizeof(struct nbinary));
  10601. n3->type = t;
  10602. n3->nbinary.ch1 = n1;
  10603. n3->nbinary.ch2 = n2;
  10604. n1 = n3;
  10605. }
  10606. }
  10607. static union node *
  10608. pipeline(void)
  10609. {
  10610. union node *n1, *n2, *pipenode;
  10611. struct nodelist *lp, *prev;
  10612. int negate;
  10613. negate = 0;
  10614. TRACE(("pipeline: entered\n"));
  10615. if (readtoken() == TNOT) {
  10616. negate = !negate;
  10617. checkkwd = CHKKWD | CHKALIAS;
  10618. } else
  10619. tokpushback = 1;
  10620. n1 = parse_command();
  10621. if (readtoken() == TPIPE) {
  10622. pipenode = stzalloc(sizeof(struct npipe));
  10623. pipenode->type = NPIPE;
  10624. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10625. lp = stzalloc(sizeof(struct nodelist));
  10626. pipenode->npipe.cmdlist = lp;
  10627. lp->n = n1;
  10628. do {
  10629. prev = lp;
  10630. lp = stzalloc(sizeof(struct nodelist));
  10631. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10632. lp->n = parse_command();
  10633. prev->next = lp;
  10634. } while (readtoken() == TPIPE);
  10635. lp->next = NULL;
  10636. n1 = pipenode;
  10637. }
  10638. tokpushback = 1;
  10639. if (negate) {
  10640. n2 = stzalloc(sizeof(struct nnot));
  10641. n2->type = NNOT;
  10642. n2->nnot.com = n1;
  10643. return n2;
  10644. }
  10645. return n1;
  10646. }
  10647. static union node *
  10648. makename(void)
  10649. {
  10650. union node *n;
  10651. n = stzalloc(sizeof(struct narg));
  10652. n->type = NARG;
  10653. /*n->narg.next = NULL; - stzalloc did it */
  10654. n->narg.text = wordtext;
  10655. n->narg.backquote = backquotelist;
  10656. return n;
  10657. }
  10658. static void
  10659. fixredir(union node *n, const char *text, int err)
  10660. {
  10661. int fd;
  10662. TRACE(("Fix redir %s %d\n", text, err));
  10663. if (!err)
  10664. n->ndup.vname = NULL;
  10665. fd = bb_strtou(text, NULL, 10);
  10666. if (!errno && fd >= 0)
  10667. n->ndup.dupfd = fd;
  10668. else if (LONE_DASH(text))
  10669. n->ndup.dupfd = -1;
  10670. else {
  10671. if (err)
  10672. raise_error_syntax("bad fd number");
  10673. n->ndup.vname = makename();
  10674. }
  10675. }
  10676. static void
  10677. parsefname(void)
  10678. {
  10679. union node *n = redirnode;
  10680. if (n->type == NHERE)
  10681. checkkwd = CHKEOFMARK;
  10682. if (readtoken() != TWORD)
  10683. raise_error_unexpected_syntax(-1);
  10684. if (n->type == NHERE) {
  10685. struct heredoc *here = heredoc;
  10686. struct heredoc *p;
  10687. if (quoteflag == 0)
  10688. n->type = NXHERE;
  10689. TRACE(("Here document %d\n", n->type));
  10690. rmescapes(wordtext, 0, NULL);
  10691. here->eofmark = wordtext;
  10692. here->next = NULL;
  10693. if (heredoclist == NULL)
  10694. heredoclist = here;
  10695. else {
  10696. for (p = heredoclist; p->next; p = p->next)
  10697. continue;
  10698. p->next = here;
  10699. }
  10700. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10701. fixredir(n, wordtext, 0);
  10702. } else {
  10703. n->nfile.fname = makename();
  10704. }
  10705. }
  10706. static union node *
  10707. simplecmd(void)
  10708. {
  10709. union node *args, **app;
  10710. union node *n = NULL;
  10711. union node *vars, **vpp;
  10712. union node **rpp, *redir;
  10713. int savecheckkwd;
  10714. int savelinno;
  10715. #if BASH_TEST2
  10716. smallint double_brackets_flag = 0;
  10717. #endif
  10718. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10719. args = NULL;
  10720. app = &args;
  10721. vars = NULL;
  10722. vpp = &vars;
  10723. redir = NULL;
  10724. rpp = &redir;
  10725. savecheckkwd = CHKALIAS;
  10726. savelinno = g_parsefile->linno;
  10727. for (;;) {
  10728. int t;
  10729. checkkwd = savecheckkwd;
  10730. t = readtoken();
  10731. switch (t) {
  10732. #if BASH_FUNCTION
  10733. case TFUNCTION:
  10734. if (peektoken() != TWORD)
  10735. raise_error_unexpected_syntax(TWORD);
  10736. function_flag = 1;
  10737. break;
  10738. #endif
  10739. #if BASH_TEST2
  10740. case TAND: /* "&&" */
  10741. case TOR: /* "||" */
  10742. if (!double_brackets_flag) {
  10743. tokpushback = 1;
  10744. goto out;
  10745. }
  10746. wordtext = (char *) (t == TAND ? "-a" : "-o");
  10747. #endif
  10748. case TWORD:
  10749. n = stzalloc(sizeof(struct narg));
  10750. n->type = NARG;
  10751. /*n->narg.next = NULL; - stzalloc did it */
  10752. n->narg.text = wordtext;
  10753. #if BASH_TEST2
  10754. if (strcmp("[[", wordtext) == 0)
  10755. double_brackets_flag = 1;
  10756. else if (strcmp("]]", wordtext) == 0)
  10757. double_brackets_flag = 0;
  10758. #endif
  10759. n->narg.backquote = backquotelist;
  10760. if (savecheckkwd && isassignment(wordtext)) {
  10761. *vpp = n;
  10762. vpp = &n->narg.next;
  10763. } else {
  10764. *app = n;
  10765. app = &n->narg.next;
  10766. savecheckkwd = 0;
  10767. }
  10768. #if BASH_FUNCTION
  10769. if (function_flag) {
  10770. checkkwd = CHKNL | CHKKWD;
  10771. switch (peektoken()) {
  10772. case TBEGIN:
  10773. case TIF:
  10774. case TCASE:
  10775. case TUNTIL:
  10776. case TWHILE:
  10777. case TFOR:
  10778. goto do_func;
  10779. case TLP:
  10780. function_flag = 0;
  10781. break;
  10782. # if BASH_TEST2
  10783. case TWORD:
  10784. if (strcmp("[[", wordtext) == 0)
  10785. goto do_func;
  10786. /* fall through */
  10787. # endif
  10788. default:
  10789. raise_error_unexpected_syntax(-1);
  10790. }
  10791. }
  10792. #endif
  10793. break;
  10794. case TREDIR:
  10795. *rpp = n = redirnode;
  10796. rpp = &n->nfile.next;
  10797. parsefname(); /* read name of redirection file */
  10798. break;
  10799. case TLP:
  10800. IF_BASH_FUNCTION(do_func:)
  10801. if (args && app == &args->narg.next
  10802. && !vars && !redir
  10803. ) {
  10804. struct builtincmd *bcmd;
  10805. const char *name;
  10806. /* We have a function */
  10807. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10808. raise_error_unexpected_syntax(TRP);
  10809. name = n->narg.text;
  10810. if (!goodname(name)
  10811. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10812. ) {
  10813. raise_error_syntax("bad function name");
  10814. }
  10815. n->type = NDEFUN;
  10816. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10817. n->ndefun.text = n->narg.text;
  10818. n->ndefun.linno = g_parsefile->linno;
  10819. n->ndefun.body = parse_command();
  10820. return n;
  10821. }
  10822. IF_BASH_FUNCTION(function_flag = 0;)
  10823. /* fall through */
  10824. default:
  10825. tokpushback = 1;
  10826. goto out;
  10827. }
  10828. }
  10829. out:
  10830. *app = NULL;
  10831. *vpp = NULL;
  10832. *rpp = NULL;
  10833. n = stzalloc(sizeof(struct ncmd));
  10834. if (NCMD != 0)
  10835. n->type = NCMD;
  10836. n->ncmd.linno = savelinno;
  10837. n->ncmd.args = args;
  10838. n->ncmd.assign = vars;
  10839. n->ncmd.redirect = redir;
  10840. return n;
  10841. }
  10842. static union node *
  10843. parse_command(void)
  10844. {
  10845. union node *n1, *n2;
  10846. union node *ap, **app;
  10847. union node *cp, **cpp;
  10848. union node *redir, **rpp;
  10849. union node **rpp2;
  10850. int t;
  10851. int savelinno;
  10852. redir = NULL;
  10853. rpp2 = &redir;
  10854. savelinno = g_parsefile->linno;
  10855. switch (readtoken()) {
  10856. default:
  10857. raise_error_unexpected_syntax(-1);
  10858. /* NOTREACHED */
  10859. case TIF:
  10860. n1 = stzalloc(sizeof(struct nif));
  10861. n1->type = NIF;
  10862. n1->nif.test = list(0);
  10863. if (readtoken() != TTHEN)
  10864. raise_error_unexpected_syntax(TTHEN);
  10865. n1->nif.ifpart = list(0);
  10866. n2 = n1;
  10867. while (readtoken() == TELIF) {
  10868. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10869. n2 = n2->nif.elsepart;
  10870. n2->type = NIF;
  10871. n2->nif.test = list(0);
  10872. if (readtoken() != TTHEN)
  10873. raise_error_unexpected_syntax(TTHEN);
  10874. n2->nif.ifpart = list(0);
  10875. }
  10876. if (lasttoken == TELSE)
  10877. n2->nif.elsepart = list(0);
  10878. else {
  10879. n2->nif.elsepart = NULL;
  10880. tokpushback = 1;
  10881. }
  10882. t = TFI;
  10883. break;
  10884. case TWHILE:
  10885. case TUNTIL: {
  10886. int got;
  10887. n1 = stzalloc(sizeof(struct nbinary));
  10888. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10889. n1->nbinary.ch1 = list(0);
  10890. got = readtoken();
  10891. if (got != TDO) {
  10892. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10893. got == TWORD ? wordtext : ""));
  10894. raise_error_unexpected_syntax(TDO);
  10895. }
  10896. n1->nbinary.ch2 = list(0);
  10897. t = TDONE;
  10898. break;
  10899. }
  10900. case TFOR:
  10901. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10902. raise_error_syntax("bad for loop variable");
  10903. n1 = stzalloc(sizeof(struct nfor));
  10904. n1->type = NFOR;
  10905. n1->nfor.linno = savelinno;
  10906. n1->nfor.var = wordtext;
  10907. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10908. if (readtoken() == TIN) {
  10909. app = &ap;
  10910. while (readtoken() == TWORD) {
  10911. n2 = stzalloc(sizeof(struct narg));
  10912. n2->type = NARG;
  10913. /*n2->narg.next = NULL; - stzalloc did it */
  10914. n2->narg.text = wordtext;
  10915. n2->narg.backquote = backquotelist;
  10916. *app = n2;
  10917. app = &n2->narg.next;
  10918. }
  10919. *app = NULL;
  10920. n1->nfor.args = ap;
  10921. if (lasttoken != TNL && lasttoken != TSEMI)
  10922. raise_error_unexpected_syntax(-1);
  10923. } else {
  10924. n2 = stzalloc(sizeof(struct narg));
  10925. n2->type = NARG;
  10926. /*n2->narg.next = NULL; - stzalloc did it */
  10927. n2->narg.text = (char *)dolatstr;
  10928. /*n2->narg.backquote = NULL;*/
  10929. n1->nfor.args = n2;
  10930. /*
  10931. * Newline or semicolon here is optional (but note
  10932. * that the original Bourne shell only allowed NL).
  10933. */
  10934. if (lasttoken != TSEMI)
  10935. tokpushback = 1;
  10936. }
  10937. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10938. if (readtoken() != TDO)
  10939. raise_error_unexpected_syntax(TDO);
  10940. n1->nfor.body = list(0);
  10941. t = TDONE;
  10942. break;
  10943. case TCASE:
  10944. n1 = stzalloc(sizeof(struct ncase));
  10945. n1->type = NCASE;
  10946. n1->ncase.linno = savelinno;
  10947. if (readtoken() != TWORD)
  10948. raise_error_unexpected_syntax(TWORD);
  10949. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10950. n2->type = NARG;
  10951. /*n2->narg.next = NULL; - stzalloc did it */
  10952. n2->narg.text = wordtext;
  10953. n2->narg.backquote = backquotelist;
  10954. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10955. if (readtoken() != TIN)
  10956. raise_error_unexpected_syntax(TIN);
  10957. cpp = &n1->ncase.cases;
  10958. next_case:
  10959. checkkwd = CHKNL | CHKKWD;
  10960. t = readtoken();
  10961. while (t != TESAC) {
  10962. if (lasttoken == TLP)
  10963. readtoken();
  10964. *cpp = cp = stzalloc(sizeof(struct nclist));
  10965. cp->type = NCLIST;
  10966. app = &cp->nclist.pattern;
  10967. for (;;) {
  10968. *app = ap = stzalloc(sizeof(struct narg));
  10969. ap->type = NARG;
  10970. /*ap->narg.next = NULL; - stzalloc did it */
  10971. ap->narg.text = wordtext;
  10972. ap->narg.backquote = backquotelist;
  10973. if (readtoken() != TPIPE)
  10974. break;
  10975. app = &ap->narg.next;
  10976. readtoken();
  10977. }
  10978. //ap->narg.next = NULL;
  10979. if (lasttoken != TRP)
  10980. raise_error_unexpected_syntax(TRP);
  10981. cp->nclist.body = list(2);
  10982. cpp = &cp->nclist.next;
  10983. checkkwd = CHKNL | CHKKWD;
  10984. t = readtoken();
  10985. if (t != TESAC) {
  10986. if (t != TENDCASE)
  10987. raise_error_unexpected_syntax(TENDCASE);
  10988. goto next_case;
  10989. }
  10990. }
  10991. *cpp = NULL;
  10992. goto redir;
  10993. case TLP:
  10994. n1 = stzalloc(sizeof(struct nredir));
  10995. n1->type = NSUBSHELL;
  10996. n1->nredir.linno = savelinno;
  10997. n1->nredir.n = list(0);
  10998. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10999. t = TRP;
  11000. break;
  11001. case TBEGIN:
  11002. n1 = list(0);
  11003. t = TEND;
  11004. break;
  11005. IF_BASH_FUNCTION(case TFUNCTION:)
  11006. case TWORD:
  11007. case TREDIR:
  11008. tokpushback = 1;
  11009. return simplecmd();
  11010. }
  11011. if (readtoken() != t)
  11012. raise_error_unexpected_syntax(t);
  11013. redir:
  11014. /* Now check for redirection which may follow command */
  11015. checkkwd = CHKKWD | CHKALIAS;
  11016. rpp = rpp2;
  11017. while (readtoken() == TREDIR) {
  11018. *rpp = n2 = redirnode;
  11019. rpp = &n2->nfile.next;
  11020. parsefname();
  11021. }
  11022. tokpushback = 1;
  11023. *rpp = NULL;
  11024. if (redir) {
  11025. if (n1->type != NSUBSHELL) {
  11026. n2 = stzalloc(sizeof(struct nredir));
  11027. n2->type = NREDIR;
  11028. n2->nredir.linno = savelinno;
  11029. n2->nredir.n = n1;
  11030. n1 = n2;
  11031. }
  11032. n1->nredir.redirect = redir;
  11033. }
  11034. return n1;
  11035. }
  11036. #if BASH_DOLLAR_SQUOTE
  11037. static int
  11038. decode_dollar_squote(void)
  11039. {
  11040. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  11041. int c, cnt;
  11042. char *p;
  11043. char buf[4];
  11044. c = pgetc();
  11045. p = strchr(C_escapes, c);
  11046. if (p) {
  11047. buf[0] = c;
  11048. p = buf;
  11049. cnt = 3;
  11050. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  11051. do {
  11052. c = pgetc();
  11053. *++p = c;
  11054. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  11055. pungetc();
  11056. } else if (c == 'x') { /* \xHH */
  11057. do {
  11058. c = pgetc();
  11059. *++p = c;
  11060. } while (isxdigit(c) && --cnt);
  11061. pungetc();
  11062. if (cnt == 3) { /* \x but next char is "bad" */
  11063. c = 'x';
  11064. goto unrecognized;
  11065. }
  11066. } else { /* simple seq like \\ or \t */
  11067. p++;
  11068. }
  11069. *p = '\0';
  11070. p = buf;
  11071. c = bb_process_escape_sequence((void*)&p);
  11072. } else { /* unrecognized "\z": print both chars unless ' or " */
  11073. if (c != '\'' && c != '"') {
  11074. unrecognized:
  11075. c |= 0x100; /* "please encode \, then me" */
  11076. }
  11077. }
  11078. return c;
  11079. }
  11080. #endif
  11081. /* Used by expandstr to get here-doc like behaviour. */
  11082. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  11083. static ALWAYS_INLINE int
  11084. realeofmark(const char *eofmark)
  11085. {
  11086. return eofmark && eofmark != FAKEEOFMARK;
  11087. }
  11088. /*
  11089. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  11090. * is not NULL, read a here document. In the latter case, eofmark is the
  11091. * word which marks the end of the document and striptabs is true if
  11092. * leading tabs should be stripped from the document. The argument c
  11093. * is the first character of the input token or document.
  11094. *
  11095. * Because C does not have internal subroutines, I have simulated them
  11096. * using goto's to implement the subroutine linkage. The following macros
  11097. * will run code that appears at the end of readtoken1.
  11098. */
  11099. #define CHECKEND() {goto checkend; checkend_return:;}
  11100. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  11101. #define PARSESUB() {goto parsesub; parsesub_return:;}
  11102. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  11103. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  11104. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  11105. static int
  11106. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  11107. {
  11108. /* NB: syntax parameter fits into smallint */
  11109. /* c parameter is an unsigned char or PEOF or PEOA */
  11110. char *out;
  11111. size_t len;
  11112. struct nodelist *bqlist;
  11113. smallint quotef;
  11114. smallint oldstyle;
  11115. smallint pssyntax; /* we are expanding a prompt string */
  11116. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  11117. /* syntax stack */
  11118. struct synstack synbase = { };
  11119. struct synstack *synstack = &synbase;
  11120. #if ENABLE_ASH_EXPAND_PRMT
  11121. pssyntax = (syntax == PSSYNTAX);
  11122. if (pssyntax)
  11123. syntax = DQSYNTAX;
  11124. #else
  11125. pssyntax = 0; /* constant */
  11126. #endif
  11127. synstack->syntax = syntax;
  11128. if (syntax == DQSYNTAX)
  11129. synstack->dblquote = 1;
  11130. quotef = 0;
  11131. bqlist = NULL;
  11132. STARTSTACKSTR(out);
  11133. loop:
  11134. /* For each line, until end of word */
  11135. CHECKEND(); /* set c to PEOF if at end of here document */
  11136. for (;;) { /* until end of line or end of word */
  11137. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11138. switch (SIT(c, synstack->syntax)) {
  11139. case CNL: /* '\n' */
  11140. if (synstack->syntax == BASESYNTAX
  11141. && !synstack->varnest
  11142. ) {
  11143. goto endword; /* exit outer loop */
  11144. }
  11145. USTPUTC(c, out);
  11146. nlprompt();
  11147. c = pgetc();
  11148. goto loop; /* continue outer loop */
  11149. case CWORD:
  11150. USTPUTC(c, out);
  11151. break;
  11152. case CCTL:
  11153. #if BASH_DOLLAR_SQUOTE
  11154. if (c == '\\' && bash_dollar_squote) {
  11155. c = decode_dollar_squote();
  11156. if (c == '\0') {
  11157. /* skip $'\000', $'\x00' (like bash) */
  11158. break;
  11159. }
  11160. if (c & 0x100) {
  11161. /* Unknown escape. Encode as '\z' */
  11162. c = (unsigned char)c;
  11163. if (eofmark == NULL || synstack->dblquote)
  11164. USTPUTC(CTLESC, out);
  11165. USTPUTC('\\', out);
  11166. }
  11167. }
  11168. #endif
  11169. if (!eofmark || synstack->dblquote || synstack->varnest)
  11170. USTPUTC(CTLESC, out);
  11171. USTPUTC(c, out);
  11172. break;
  11173. case CBACK: /* backslash */
  11174. c = pgetc_without_PEOA();
  11175. if (c == PEOF) {
  11176. USTPUTC(CTLESC, out);
  11177. USTPUTC('\\', out);
  11178. pungetc();
  11179. } else if (c == '\n') {
  11180. nlprompt();
  11181. } else {
  11182. if (pssyntax && c == '$') {
  11183. USTPUTC(CTLESC, out);
  11184. USTPUTC('\\', out);
  11185. }
  11186. /* Backslash is retained if we are in "str"
  11187. * and next char isn't dquote-special.
  11188. */
  11189. if (synstack->dblquote
  11190. && c != '\\'
  11191. && c != '`'
  11192. && c != '$'
  11193. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11194. && (c != '}' || !synstack->varnest)
  11195. ) {
  11196. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11197. USTPUTC('\\', out);
  11198. }
  11199. USTPUTC(CTLESC, out);
  11200. USTPUTC(c, out);
  11201. quotef = 1;
  11202. }
  11203. break;
  11204. case CSQUOTE:
  11205. synstack->syntax = SQSYNTAX;
  11206. quotemark:
  11207. if (eofmark == NULL) {
  11208. USTPUTC(CTLQUOTEMARK, out);
  11209. }
  11210. break;
  11211. case CDQUOTE:
  11212. synstack->syntax = DQSYNTAX;
  11213. synstack->dblquote = 1;
  11214. toggledq:
  11215. if (synstack->varnest)
  11216. synstack->innerdq ^= 1;
  11217. goto quotemark;
  11218. case CENDQUOTE:
  11219. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11220. if (eofmark != NULL && synstack->varnest == 0) {
  11221. USTPUTC(c, out);
  11222. break;
  11223. }
  11224. if (synstack->dqvarnest == 0) {
  11225. synstack->syntax = BASESYNTAX;
  11226. synstack->dblquote = 0;
  11227. }
  11228. quotef = 1;
  11229. if (c == '"')
  11230. goto toggledq;
  11231. goto quotemark;
  11232. case CVAR: /* '$' */
  11233. PARSESUB(); /* parse substitution */
  11234. break;
  11235. case CENDVAR: /* '}' */
  11236. if (!synstack->innerdq && synstack->varnest > 0) {
  11237. if (!--synstack->varnest && synstack->varpushed)
  11238. synstack_pop(&synstack);
  11239. else if (synstack->dqvarnest > 0)
  11240. synstack->dqvarnest--;
  11241. c = CTLENDVAR;
  11242. }
  11243. USTPUTC(c, out);
  11244. break;
  11245. #if ENABLE_FEATURE_SH_MATH
  11246. case CLP: /* '(' in arithmetic */
  11247. synstack->parenlevel++;
  11248. USTPUTC(c, out);
  11249. break;
  11250. case CRP: /* ')' in arithmetic */
  11251. if (synstack->parenlevel > 0) {
  11252. synstack->parenlevel--;
  11253. } else {
  11254. if (pgetc_eatbnl() == ')') {
  11255. c = CTLENDARI;
  11256. synstack_pop(&synstack);
  11257. } else {
  11258. /*
  11259. * unbalanced parens
  11260. * (don't 2nd guess - no error)
  11261. */
  11262. pungetc();
  11263. }
  11264. }
  11265. USTPUTC(c, out);
  11266. break;
  11267. #endif
  11268. case CBQUOTE: /* '`' */
  11269. if (checkkwd & CHKEOFMARK) {
  11270. quotef = 1;
  11271. USTPUTC('`', out);
  11272. break;
  11273. }
  11274. PARSEBACKQOLD();
  11275. break;
  11276. case CENDFILE:
  11277. goto endword; /* exit outer loop */
  11278. case CIGN:
  11279. break;
  11280. default:
  11281. if (synstack->varnest == 0) {
  11282. #if BASH_REDIR_OUTPUT
  11283. if (c == '&') {
  11284. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11285. if (pgetc() == '>')
  11286. c = 0x100 + '>'; /* flag &> */
  11287. pungetc();
  11288. }
  11289. #endif
  11290. goto endword; /* exit outer loop */
  11291. }
  11292. IF_ASH_ALIAS(if (c != PEOA))
  11293. USTPUTC(c, out);
  11294. }
  11295. c = pgetc();
  11296. } /* for (;;) */
  11297. endword:
  11298. #if ENABLE_FEATURE_SH_MATH
  11299. if (synstack->syntax == ARISYNTAX)
  11300. raise_error_syntax("missing '))'");
  11301. #endif
  11302. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11303. raise_error_syntax("unterminated quoted string");
  11304. if (synstack->varnest != 0) {
  11305. /* { */
  11306. raise_error_syntax("missing '}'");
  11307. }
  11308. USTPUTC('\0', out);
  11309. len = out - (char *)stackblock();
  11310. out = stackblock();
  11311. if (eofmark == NULL) {
  11312. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11313. && quotef == 0
  11314. ) {
  11315. if (isdigit_str9(out)) {
  11316. PARSEREDIR(); /* passed as params: out, c */
  11317. lasttoken = TREDIR;
  11318. return lasttoken;
  11319. }
  11320. /* else: non-number X seen, interpret it
  11321. * as "NNNX>file" = "NNNX >file" */
  11322. }
  11323. pungetc();
  11324. }
  11325. quoteflag = quotef;
  11326. backquotelist = bqlist;
  11327. grabstackblock(len);
  11328. wordtext = out;
  11329. lasttoken = TWORD;
  11330. return lasttoken;
  11331. /* end of readtoken routine */
  11332. /*
  11333. * Check to see whether we are at the end of the here document. When this
  11334. * is called, c is set to the first character of the next input line. If
  11335. * we are at the end of the here document, this routine sets the c to PEOF.
  11336. */
  11337. checkend: {
  11338. if (realeofmark(eofmark)) {
  11339. int markloc;
  11340. char *p;
  11341. #if ENABLE_ASH_ALIAS
  11342. if (c == PEOA)
  11343. c = pgetc_without_PEOA();
  11344. #endif
  11345. if (striptabs) {
  11346. while (c == '\t') {
  11347. c = pgetc_without_PEOA();
  11348. }
  11349. }
  11350. markloc = out - (char *)stackblock();
  11351. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11352. if (c != *p)
  11353. goto more_heredoc;
  11354. c = pgetc_without_PEOA();
  11355. }
  11356. if (c == '\n' || c == PEOF) {
  11357. c = PEOF;
  11358. g_parsefile->linno++;
  11359. needprompt = doprompt;
  11360. } else {
  11361. int len_here;
  11362. more_heredoc:
  11363. p = (char *)stackblock() + markloc + 1;
  11364. len_here = out - p;
  11365. if (len_here) {
  11366. len_here -= (c >= PEOF);
  11367. c = p[-1];
  11368. if (len_here) {
  11369. char *str;
  11370. str = alloca(len_here + 1);
  11371. *(char *)mempcpy(str, p, len_here) = '\0';
  11372. pushstring(str, NULL);
  11373. }
  11374. }
  11375. }
  11376. STADJUST((char *)stackblock() + markloc - out, out);
  11377. }
  11378. goto checkend_return;
  11379. }
  11380. /*
  11381. * Parse a redirection operator. The variable "out" points to a string
  11382. * specifying the fd to be redirected. The variable "c" contains the
  11383. * first character of the redirection operator.
  11384. */
  11385. parseredir: {
  11386. /* out is already checked to be a valid number or "" */
  11387. int fd = (*out == '\0' ? -1 : atoi(out));
  11388. union node *np;
  11389. np = stzalloc(sizeof(struct nfile));
  11390. if (c == '>') {
  11391. np->nfile.fd = 1;
  11392. c = pgetc_eatbnl();
  11393. if (c == '>')
  11394. np->type = NAPPEND;
  11395. else if (c == '|')
  11396. np->type = NCLOBBER;
  11397. else if (c == '&')
  11398. np->type = NTOFD;
  11399. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11400. else {
  11401. np->type = NTO;
  11402. pungetc();
  11403. }
  11404. }
  11405. #if BASH_REDIR_OUTPUT
  11406. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11407. np->nfile.fd = 1;
  11408. pgetc(); /* this is '>', no need to check */
  11409. np->type = NTO2;
  11410. }
  11411. #endif
  11412. else { /* c == '<' */
  11413. /*np->nfile.fd = 0; - stzalloc did it */
  11414. c = pgetc_eatbnl();
  11415. switch (c) {
  11416. case '<':
  11417. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11418. np = stzalloc(sizeof(struct nhere));
  11419. /*np->nfile.fd = 0; - stzalloc did it */
  11420. }
  11421. np->type = NHERE;
  11422. heredoc = stzalloc(sizeof(struct heredoc));
  11423. heredoc->here = np;
  11424. c = pgetc_eatbnl();
  11425. if (c == '-') {
  11426. heredoc->striptabs = 1;
  11427. } else {
  11428. /*heredoc->striptabs = 0; - stzalloc did it */
  11429. pungetc();
  11430. }
  11431. break;
  11432. case '&':
  11433. np->type = NFROMFD;
  11434. break;
  11435. case '>':
  11436. np->type = NFROMTO;
  11437. break;
  11438. default:
  11439. np->type = NFROM;
  11440. pungetc();
  11441. break;
  11442. }
  11443. }
  11444. if (fd >= 0)
  11445. np->nfile.fd = fd;
  11446. redirnode = np;
  11447. goto parseredir_return;
  11448. }
  11449. /*
  11450. * Parse a substitution. At this point, we have read the dollar sign
  11451. * and nothing else.
  11452. */
  11453. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11454. * (assuming ascii char codes, as the original implementation did) */
  11455. #define is_special(c) \
  11456. (((unsigned)(c) - 33 < 32) \
  11457. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11458. parsesub: {
  11459. unsigned char subtype;
  11460. int typeloc;
  11461. c = pgetc_eatbnl();
  11462. if ((checkkwd & CHKEOFMARK)
  11463. || c > 255 /* PEOA or PEOF */
  11464. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11465. ) {
  11466. #if BASH_DOLLAR_SQUOTE
  11467. if (synstack->syntax != DQSYNTAX && c == '\'')
  11468. bash_dollar_squote = 1;
  11469. else
  11470. #endif
  11471. USTPUTC('$', out);
  11472. pungetc();
  11473. } else if (c == '(') {
  11474. /* $(command) or $((arith)) */
  11475. if (pgetc_eatbnl() == '(') {
  11476. #if ENABLE_FEATURE_SH_MATH
  11477. PARSEARITH();
  11478. #else
  11479. raise_error_syntax("support for $((arith)) is disabled");
  11480. #endif
  11481. } else {
  11482. pungetc();
  11483. PARSEBACKQNEW();
  11484. }
  11485. } else {
  11486. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11487. smalluint newsyn = synstack->syntax;
  11488. USTPUTC(CTLVAR, out);
  11489. typeloc = out - (char *)stackblock();
  11490. STADJUST(1, out);
  11491. subtype = VSNORMAL;
  11492. if (c == '{') {
  11493. c = pgetc_eatbnl();
  11494. subtype = 0;
  11495. }
  11496. varname:
  11497. if (is_name(c)) {
  11498. /* $[{[#]]NAME[}] */
  11499. do {
  11500. STPUTC(c, out);
  11501. c = pgetc_eatbnl();
  11502. } while (is_in_name(c));
  11503. } else if (isdigit(c)) {
  11504. /* $[{[#]]NUM[}] */
  11505. do {
  11506. STPUTC(c, out);
  11507. c = pgetc_eatbnl();
  11508. } while (isdigit(c));
  11509. } else if (c != '}') {
  11510. /* $[{[#]]<specialchar>[}] */
  11511. int cc = c;
  11512. c = pgetc_eatbnl();
  11513. if (!subtype && cc == '#') {
  11514. subtype = VSLENGTH;
  11515. if (c == '_' || isalnum(c))
  11516. goto varname;
  11517. cc = c;
  11518. c = pgetc_eatbnl();
  11519. if (cc == '}' || c != '}') {
  11520. pungetc();
  11521. subtype = 0;
  11522. c = cc;
  11523. cc = '#';
  11524. }
  11525. }
  11526. if (!is_special(cc)) {
  11527. if (subtype == VSLENGTH)
  11528. subtype = 0;
  11529. goto badsub;
  11530. }
  11531. USTPUTC(cc, out);
  11532. } else
  11533. goto badsub;
  11534. if (c != '}' && subtype == VSLENGTH) {
  11535. /* ${#VAR didn't end with } */
  11536. goto badsub;
  11537. }
  11538. if (subtype == 0) {
  11539. static const char types[] ALIGN1 = "}-+?=";
  11540. /* ${VAR...} but not $VAR or ${#VAR} */
  11541. /* c == first char after VAR */
  11542. int cc = c;
  11543. switch (c) {
  11544. case ':':
  11545. c = pgetc_eatbnl();
  11546. #if BASH_SUBSTR
  11547. /* This check is only needed to not misinterpret
  11548. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11549. * constructs.
  11550. */
  11551. if (!strchr(types, c)) {
  11552. subtype = VSSUBSTR;
  11553. pungetc();
  11554. break; /* "goto badsub" is bigger (!) */
  11555. }
  11556. #endif
  11557. subtype = VSNUL;
  11558. /*FALLTHROUGH*/
  11559. default: {
  11560. const char *p = strchr(types, c);
  11561. if (p == NULL)
  11562. break;
  11563. subtype |= p - types + VSNORMAL;
  11564. break;
  11565. }
  11566. case '%':
  11567. case '#':
  11568. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11569. c = pgetc_eatbnl();
  11570. if (c == cc)
  11571. subtype++;
  11572. else
  11573. pungetc();
  11574. newsyn = BASESYNTAX;
  11575. break;
  11576. #if BASH_PATTERN_SUBST
  11577. case '/':
  11578. /* ${v/[/]pattern/repl} */
  11579. //TODO: encode pattern and repl separately.
  11580. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11581. // are broken (should print "ONE")
  11582. subtype = VSREPLACE;
  11583. newsyn = BASESYNTAX;
  11584. c = pgetc_eatbnl();
  11585. if (c != '/')
  11586. goto badsub;
  11587. subtype++; /* VSREPLACEALL */
  11588. break;
  11589. #endif
  11590. }
  11591. } else {
  11592. badsub:
  11593. pungetc();
  11594. }
  11595. if (newsyn == ARISYNTAX)
  11596. newsyn = DQSYNTAX;
  11597. if ((newsyn != synstack->syntax || synstack->innerdq)
  11598. && subtype != VSNORMAL
  11599. ) {
  11600. synstack_push(&synstack,
  11601. synstack->prev ?: alloca(sizeof(*synstack)),
  11602. newsyn);
  11603. synstack->varpushed = 1;
  11604. synstack->dblquote = newsyn != BASESYNTAX;
  11605. }
  11606. ((unsigned char *)stackblock())[typeloc] = subtype;
  11607. if (subtype != VSNORMAL) {
  11608. synstack->varnest++;
  11609. if (synstack->dblquote)
  11610. synstack->dqvarnest++;
  11611. }
  11612. STPUTC('=', out);
  11613. }
  11614. goto parsesub_return;
  11615. }
  11616. /*
  11617. * Called to parse command substitutions. Newstyle is set if the command
  11618. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11619. * list of commands (passed by reference), and savelen is the number of
  11620. * characters on the top of the stack which must be preserved.
  11621. */
  11622. parsebackq: {
  11623. struct nodelist **nlpp;
  11624. union node *n;
  11625. char *str;
  11626. size_t savelen;
  11627. smallint saveprompt = 0;
  11628. str = NULL;
  11629. savelen = out - (char *)stackblock();
  11630. if (savelen > 0) {
  11631. /*
  11632. * FIXME: this can allocate very large block on stack and SEGV.
  11633. * Example:
  11634. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11635. * allocates 100kb for every command subst. With about
  11636. * a hundred command substitutions stack overflows.
  11637. * With larger prepended string, SEGV happens sooner.
  11638. */
  11639. str = alloca(savelen);
  11640. memcpy(str, stackblock(), savelen);
  11641. }
  11642. if (oldstyle) {
  11643. /* We must read until the closing backquote, giving special
  11644. * treatment to some slashes, and then push the string and
  11645. * reread it as input, interpreting it normally.
  11646. */
  11647. char *pout;
  11648. size_t psavelen;
  11649. char *pstr;
  11650. STARTSTACKSTR(pout);
  11651. for (;;) {
  11652. int pc;
  11653. setprompt_if(needprompt, 2);
  11654. pc = pgetc_eatbnl();
  11655. switch (pc) {
  11656. case '`':
  11657. goto done;
  11658. case '\\':
  11659. pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
  11660. if (pc != '\\' && pc != '`' && pc != '$'
  11661. && (!synstack->dblquote || pc != '"')
  11662. ) {
  11663. STPUTC('\\', pout);
  11664. }
  11665. if (pc <= 255 /* not PEOA or PEOF */) {
  11666. break;
  11667. }
  11668. /* fall through */
  11669. case PEOF:
  11670. IF_ASH_ALIAS(case PEOA:)
  11671. raise_error_syntax("EOF in backquote substitution");
  11672. case '\n':
  11673. nlnoprompt();
  11674. break;
  11675. default:
  11676. break;
  11677. }
  11678. STPUTC(pc, pout);
  11679. }
  11680. done:
  11681. STPUTC('\0', pout);
  11682. psavelen = pout - (char *)stackblock();
  11683. if (psavelen > 0) {
  11684. pstr = grabstackstr(pout);
  11685. setinputstring(pstr);
  11686. }
  11687. }
  11688. nlpp = &bqlist;
  11689. while (*nlpp)
  11690. nlpp = &(*nlpp)->next;
  11691. *nlpp = stzalloc(sizeof(**nlpp));
  11692. /* (*nlpp)->next = NULL; - stzalloc did it */
  11693. if (oldstyle) {
  11694. saveprompt = doprompt;
  11695. doprompt = 0;
  11696. }
  11697. n = list(2);
  11698. if (oldstyle)
  11699. doprompt = saveprompt;
  11700. else if (readtoken() != TRP)
  11701. raise_error_unexpected_syntax(TRP);
  11702. (*nlpp)->n = n;
  11703. if (oldstyle) {
  11704. /*
  11705. * Start reading from old file again, ignoring any pushed back
  11706. * tokens left from the backquote parsing
  11707. */
  11708. popfile();
  11709. tokpushback = 0;
  11710. }
  11711. while (stackblocksize() <= savelen)
  11712. growstackblock();
  11713. STARTSTACKSTR(out);
  11714. if (str) {
  11715. memcpy(out, str, savelen);
  11716. STADJUST(savelen, out);
  11717. }
  11718. USTPUTC(CTLBACKQ, out);
  11719. if (oldstyle)
  11720. goto parsebackq_oldreturn;
  11721. goto parsebackq_newreturn;
  11722. }
  11723. #if ENABLE_FEATURE_SH_MATH
  11724. /*
  11725. * Parse an arithmetic expansion (indicate start of one and set state)
  11726. */
  11727. parsearith: {
  11728. synstack_push(&synstack,
  11729. synstack->prev ?: alloca(sizeof(*synstack)),
  11730. ARISYNTAX);
  11731. synstack->dblquote = 1;
  11732. USTPUTC(CTLARI, out);
  11733. goto parsearith_return;
  11734. }
  11735. #endif
  11736. } /* end of readtoken */
  11737. /*
  11738. * Read the next input token.
  11739. * If the token is a word, we set backquotelist to the list of cmds in
  11740. * backquotes. We set quoteflag to true if any part of the word was
  11741. * quoted.
  11742. * If the token is TREDIR, then we set redirnode to a structure containing
  11743. * the redirection.
  11744. *
  11745. * [Change comment: here documents and internal procedures]
  11746. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11747. * word parsing code into a separate routine. In this case, readtoken
  11748. * doesn't need to have any internal procedures, but parseword does.
  11749. * We could also make parseoperator in essence the main routine, and
  11750. * have parseword (readtoken1?) handle both words and redirection.]
  11751. */
  11752. #define NEW_xxreadtoken
  11753. #ifdef NEW_xxreadtoken
  11754. /* singles must be first! */
  11755. static const char xxreadtoken_chars[7] ALIGN1 = {
  11756. '\n', '(', ')', /* singles */
  11757. '&', '|', ';', /* doubles */
  11758. 0
  11759. };
  11760. #define xxreadtoken_singles 3
  11761. #define xxreadtoken_doubles 3
  11762. static const char xxreadtoken_tokens[] ALIGN1 = {
  11763. TNL, TLP, TRP, /* only single occurrence allowed */
  11764. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11765. TEOF, /* corresponds to trailing nul */
  11766. TAND, TOR, TENDCASE /* if double occurrence */
  11767. };
  11768. static int
  11769. xxreadtoken(void)
  11770. {
  11771. int c;
  11772. if (tokpushback) {
  11773. tokpushback = 0;
  11774. return lasttoken;
  11775. }
  11776. setprompt_if(needprompt, 2);
  11777. for (;;) { /* until token or start of word found */
  11778. c = pgetc_eatbnl();
  11779. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11780. continue;
  11781. if (c == '#') {
  11782. while ((c = pgetc()) != '\n' && c != PEOF)
  11783. continue;
  11784. pungetc();
  11785. } else if (c == '\\') {
  11786. break; /* return readtoken1(...) */
  11787. } else {
  11788. const char *p;
  11789. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11790. if (c != PEOF) {
  11791. if (c == '\n') {
  11792. nlnoprompt();
  11793. }
  11794. p = strchr(xxreadtoken_chars, c);
  11795. if (p == NULL)
  11796. break; /* return readtoken1(...) */
  11797. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11798. int cc = pgetc_eatbnl();
  11799. if (cc == c) { /* double occurrence? */
  11800. p += xxreadtoken_doubles + 1;
  11801. } else {
  11802. pungetc();
  11803. #if BASH_REDIR_OUTPUT
  11804. if (c == '&' && cc == '>') /* &> */
  11805. break; /* return readtoken1(...) */
  11806. #endif
  11807. }
  11808. }
  11809. }
  11810. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11811. return lasttoken;
  11812. }
  11813. } /* for (;;) */
  11814. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11815. }
  11816. #else /* old xxreadtoken */
  11817. #define RETURN(token) return lasttoken = token
  11818. static int
  11819. xxreadtoken(void)
  11820. {
  11821. int c;
  11822. if (tokpushback) {
  11823. tokpushback = 0;
  11824. return lasttoken;
  11825. }
  11826. setprompt_if(needprompt, 2);
  11827. for (;;) { /* until token or start of word found */
  11828. c = pgetc_eatbnl();
  11829. switch (c) {
  11830. case ' ': case '\t':
  11831. IF_ASH_ALIAS(case PEOA:)
  11832. continue;
  11833. case '#':
  11834. while ((c = pgetc()) != '\n' && c != PEOF)
  11835. continue;
  11836. pungetc();
  11837. continue;
  11838. case '\n':
  11839. nlnoprompt();
  11840. RETURN(TNL);
  11841. case PEOF:
  11842. RETURN(TEOF);
  11843. case '&':
  11844. if (pgetc_eatbnl() == '&')
  11845. RETURN(TAND);
  11846. pungetc();
  11847. RETURN(TBACKGND);
  11848. case '|':
  11849. if (pgetc_eatbnl() == '|')
  11850. RETURN(TOR);
  11851. pungetc();
  11852. RETURN(TPIPE);
  11853. case ';':
  11854. if (pgetc_eatbnl() == ';')
  11855. RETURN(TENDCASE);
  11856. pungetc();
  11857. RETURN(TSEMI);
  11858. case '(':
  11859. RETURN(TLP);
  11860. case ')':
  11861. RETURN(TRP);
  11862. }
  11863. break;
  11864. }
  11865. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11866. #undef RETURN
  11867. }
  11868. #endif /* old xxreadtoken */
  11869. static int
  11870. readtoken(void)
  11871. {
  11872. int t;
  11873. int kwd = checkkwd;
  11874. #if DEBUG
  11875. smallint alreadyseen = tokpushback;
  11876. #endif
  11877. #if ENABLE_ASH_ALIAS
  11878. top:
  11879. #endif
  11880. t = xxreadtoken();
  11881. /*
  11882. * eat newlines
  11883. */
  11884. if (kwd & CHKNL) {
  11885. while (t == TNL) {
  11886. parseheredoc();
  11887. t = xxreadtoken();
  11888. }
  11889. }
  11890. if (t != TWORD || quoteflag) {
  11891. goto out;
  11892. }
  11893. /*
  11894. * check for keywords
  11895. */
  11896. if (kwd & CHKKWD) {
  11897. const char *const *pp;
  11898. pp = findkwd(wordtext);
  11899. if (pp) {
  11900. lasttoken = t = pp - tokname_array;
  11901. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11902. goto out;
  11903. }
  11904. }
  11905. if (checkkwd & CHKALIAS) {
  11906. #if ENABLE_ASH_ALIAS
  11907. struct alias *ap;
  11908. ap = lookupalias(wordtext, 1);
  11909. if (ap != NULL) {
  11910. if (*ap->val) {
  11911. pushstring(ap->val, ap);
  11912. }
  11913. goto top;
  11914. }
  11915. #endif
  11916. }
  11917. out:
  11918. checkkwd = 0;
  11919. #if DEBUG
  11920. if (!alreadyseen)
  11921. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11922. else
  11923. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11924. #endif
  11925. return t;
  11926. }
  11927. static int
  11928. peektoken(void)
  11929. {
  11930. int t;
  11931. t = readtoken();
  11932. tokpushback = 1;
  11933. return t;
  11934. }
  11935. /*
  11936. * Read and parse a command. Returns NODE_EOF on end of file.
  11937. * (NULL is a valid parse tree indicating a blank line.)
  11938. */
  11939. static union node *
  11940. parsecmd(int interact)
  11941. {
  11942. tokpushback = 0;
  11943. checkkwd = 0;
  11944. heredoclist = 0;
  11945. doprompt = interact;
  11946. setprompt_if(doprompt, doprompt);
  11947. needprompt = 0;
  11948. return list(1);
  11949. }
  11950. /*
  11951. * Input any here documents.
  11952. */
  11953. static void
  11954. parseheredoc(void)
  11955. {
  11956. struct heredoc *here;
  11957. union node *n;
  11958. here = heredoclist;
  11959. heredoclist = NULL;
  11960. while (here) {
  11961. tokpushback = 0;
  11962. setprompt_if(needprompt, 2);
  11963. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11964. here->eofmark, here->striptabs);
  11965. n = stzalloc(sizeof(struct narg));
  11966. n->narg.type = NARG;
  11967. /*n->narg.next = NULL; - stzalloc did it */
  11968. n->narg.text = wordtext;
  11969. n->narg.backquote = backquotelist;
  11970. here->here->nhere.doc = n;
  11971. here = here->next;
  11972. }
  11973. }
  11974. static const char *
  11975. expandstr(const char *ps, int syntax_type)
  11976. {
  11977. union node n;
  11978. int saveprompt;
  11979. struct parsefile *file_stop = g_parsefile;
  11980. volatile int saveint;
  11981. struct jmploc *volatile savehandler = exception_handler;
  11982. struct jmploc jmploc;
  11983. /* XXX Fix (char *) cast. */
  11984. setinputstring((char *)ps);
  11985. saveprompt = doprompt;
  11986. doprompt = 0;
  11987. /* readtoken1() might die horribly.
  11988. * Try a prompt with syntactically wrong command:
  11989. * PS1='$(date "+%H:%M:%S) > '
  11990. */
  11991. SAVE_INT(saveint);
  11992. if (setjmp(jmploc.loc) == 0) {
  11993. exception_handler = &jmploc;
  11994. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  11995. }
  11996. exception_handler = savehandler;
  11997. RESTORE_INT(saveint);
  11998. doprompt = saveprompt;
  11999. /* Try: PS1='`xxx(`' */
  12000. unwindfiles(file_stop);
  12001. n.narg.type = NARG;
  12002. n.narg.next = NULL;
  12003. n.narg.text = wordtext;
  12004. n.narg.backquote = backquotelist;
  12005. /* expandarg() might fail too:
  12006. * PS1='$((123+))'
  12007. */
  12008. SAVE_INT(saveint);
  12009. if (setjmp(jmploc.loc) == 0) {
  12010. exception_handler = &jmploc;
  12011. expandarg(&n, NULL, EXP_QUOTED);
  12012. } else if (exception_type == EXEXIT) {
  12013. exitshell();
  12014. }
  12015. exception_handler = savehandler;
  12016. RESTORE_INT(saveint);
  12017. return stackblock();
  12018. }
  12019. static inline int
  12020. parser_eof(void)
  12021. {
  12022. return tokpushback && lasttoken == TEOF;
  12023. }
  12024. /*
  12025. * Execute a command or commands contained in a string.
  12026. */
  12027. static int
  12028. evalstring(char *s, int flags)
  12029. {
  12030. struct jmploc *volatile savehandler;
  12031. struct jmploc jmploc;
  12032. int ex;
  12033. union node *n;
  12034. struct stackmark smark;
  12035. int status;
  12036. s = sstrdup(s);
  12037. setinputstring(s);
  12038. setstackmark(&smark);
  12039. status = 0;
  12040. /* On exception inside execution loop, we must popfile().
  12041. * Try interactively:
  12042. * readonly a=a
  12043. * command eval "a=b" # throws "is read only" error
  12044. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  12045. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  12046. */
  12047. savehandler = exception_handler;
  12048. ex = setjmp(jmploc.loc);
  12049. if (ex)
  12050. goto out;
  12051. exception_handler = &jmploc;
  12052. while ((n = parsecmd(0)) != NODE_EOF) {
  12053. int i;
  12054. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  12055. if (n)
  12056. status = i;
  12057. popstackmark(&smark);
  12058. if (evalskip)
  12059. break;
  12060. }
  12061. out:
  12062. popstackmark(&smark);
  12063. popfile();
  12064. stunalloc(s);
  12065. exception_handler = savehandler;
  12066. if (ex)
  12067. longjmp(exception_handler->loc, ex);
  12068. return status;
  12069. }
  12070. /*
  12071. * The eval command.
  12072. */
  12073. static int FAST_FUNC
  12074. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  12075. {
  12076. char *p;
  12077. char *concat;
  12078. if (argv[1]) {
  12079. p = argv[1];
  12080. argv += 2;
  12081. if (argv[0]) {
  12082. STARTSTACKSTR(concat);
  12083. for (;;) {
  12084. concat = stack_putstr(p, concat);
  12085. p = *argv++;
  12086. if (p == NULL)
  12087. break;
  12088. STPUTC(' ', concat);
  12089. }
  12090. STPUTC('\0', concat);
  12091. p = grabstackstr(concat);
  12092. }
  12093. return evalstring(p, flags & EV_TESTED);
  12094. }
  12095. return 0;
  12096. }
  12097. /*
  12098. * Read and execute commands.
  12099. * "Top" is nonzero for the top level command loop;
  12100. * it turns on prompting if the shell is interactive.
  12101. */
  12102. static int
  12103. cmdloop(int top)
  12104. {
  12105. union node *n;
  12106. struct stackmark smark;
  12107. int inter;
  12108. int status = 0;
  12109. int numeof = 0;
  12110. TRACE(("cmdloop(%d) called\n", top));
  12111. for (;;) {
  12112. int skip;
  12113. setstackmark(&smark);
  12114. #if JOBS
  12115. if (doing_jobctl)
  12116. showjobs(SHOW_CHANGED|SHOW_STDERR);
  12117. #endif
  12118. inter = 0;
  12119. if (iflag && top) {
  12120. inter++;
  12121. chkmail();
  12122. }
  12123. n = parsecmd(inter);
  12124. #if DEBUG
  12125. if (DEBUG > 2 && debug && (n != NODE_EOF))
  12126. showtree(n);
  12127. #endif
  12128. if (n == NODE_EOF) {
  12129. if (!top || numeof >= 50)
  12130. break;
  12131. if (!stoppedjobs()) {
  12132. if (!Iflag)
  12133. break;
  12134. out2str("\nUse \"exit\" to leave shell.\n");
  12135. }
  12136. numeof++;
  12137. } else if (nflag == 0) {
  12138. int i;
  12139. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12140. job_warning >>= 1;
  12141. numeof = 0;
  12142. i = evaltree(n, 0);
  12143. if (n)
  12144. status = i;
  12145. }
  12146. popstackmark(&smark);
  12147. skip = evalskip;
  12148. if (skip) {
  12149. evalskip &= ~SKIPFUNC;
  12150. break;
  12151. }
  12152. }
  12153. return status;
  12154. }
  12155. /*
  12156. * Take commands from a file. To be compatible we should do a path
  12157. * search for the file, which is necessary to find sub-commands.
  12158. */
  12159. static char *
  12160. find_dot_file(char *name)
  12161. {
  12162. char *fullname;
  12163. const char *path = pathval();
  12164. struct stat statb;
  12165. /* don't try this for absolute or relative paths */
  12166. if (strchr(name, '/'))
  12167. return name;
  12168. while ((fullname = path_advance(&path, name)) != NULL) {
  12169. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  12170. /*
  12171. * Don't bother freeing here, since it will
  12172. * be freed by the caller.
  12173. */
  12174. return fullname;
  12175. }
  12176. if (fullname != name)
  12177. stunalloc(fullname);
  12178. }
  12179. /* not found in PATH */
  12180. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12181. return name;
  12182. #else
  12183. ash_msg_and_raise_error("%s: not found", name);
  12184. /* NOTREACHED */
  12185. #endif
  12186. }
  12187. static int FAST_FUNC
  12188. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12189. {
  12190. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12191. int status = 0;
  12192. char *fullname;
  12193. char **argv;
  12194. char *args_need_save;
  12195. volatile struct shparam saveparam;
  12196. //???
  12197. // struct strlist *sp;
  12198. // for (sp = cmdenviron; sp; sp = sp->next)
  12199. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12200. nextopt(nullstr); /* handle possible "--" */
  12201. argv = argptr;
  12202. if (!argv[0]) {
  12203. /* bash says: "bash: .: filename argument required" */
  12204. return 2; /* bash compat */
  12205. }
  12206. /* This aborts if file isn't found, which is POSIXly correct.
  12207. * bash returns exitcode 1 instead.
  12208. */
  12209. fullname = find_dot_file(argv[0]);
  12210. argv++;
  12211. args_need_save = argv[0];
  12212. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12213. int argc;
  12214. saveparam = shellparam;
  12215. shellparam.malloced = 0;
  12216. argc = 1;
  12217. while (argv[argc])
  12218. argc++;
  12219. shellparam.nparam = argc;
  12220. shellparam.p = argv;
  12221. };
  12222. /* This aborts if file can't be opened, which is POSIXly correct.
  12223. * bash returns exitcode 1 instead.
  12224. */
  12225. setinputfile(fullname, INPUT_PUSH_FILE);
  12226. commandname = fullname;
  12227. status = cmdloop(0);
  12228. popfile();
  12229. if (args_need_save) {
  12230. freeparam(&shellparam);
  12231. shellparam = saveparam;
  12232. };
  12233. return status;
  12234. }
  12235. static int FAST_FUNC
  12236. exitcmd(int argc UNUSED_PARAM, char **argv)
  12237. {
  12238. if (stoppedjobs())
  12239. return 0;
  12240. if (argv[1])
  12241. exitstatus = number(argv[1]);
  12242. raise_exception(EXEXIT);
  12243. /* NOTREACHED */
  12244. }
  12245. /*
  12246. * Read a file containing shell functions.
  12247. */
  12248. static void
  12249. readcmdfile(char *name)
  12250. {
  12251. setinputfile(name, INPUT_PUSH_FILE);
  12252. cmdloop(0);
  12253. popfile();
  12254. }
  12255. /* ============ find_command inplementation */
  12256. /*
  12257. * Resolve a command name. If you change this routine, you may have to
  12258. * change the shellexec routine as well.
  12259. */
  12260. static void
  12261. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12262. {
  12263. struct tblentry *cmdp;
  12264. int idx;
  12265. int prev;
  12266. char *fullname;
  12267. struct stat statb;
  12268. int e;
  12269. int updatetbl;
  12270. struct builtincmd *bcmd;
  12271. /* If name contains a slash, don't use PATH or hash table */
  12272. if (strchr(name, '/') != NULL) {
  12273. entry->u.index = -1;
  12274. if (act & DO_ABS) {
  12275. while (stat(name, &statb) < 0) {
  12276. #ifdef SYSV
  12277. if (errno == EINTR)
  12278. continue;
  12279. #endif
  12280. entry->cmdtype = CMDUNKNOWN;
  12281. return;
  12282. }
  12283. }
  12284. entry->cmdtype = CMDNORMAL;
  12285. return;
  12286. }
  12287. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12288. updatetbl = (path == pathval());
  12289. if (!updatetbl) {
  12290. act |= DO_ALTPATH;
  12291. if (strstr(path, "%builtin") != NULL)
  12292. act |= DO_ALTBLTIN;
  12293. }
  12294. /* If name is in the table, check answer will be ok */
  12295. cmdp = cmdlookup(name, 0);
  12296. if (cmdp != NULL) {
  12297. int bit;
  12298. switch (cmdp->cmdtype) {
  12299. default:
  12300. #if DEBUG
  12301. abort();
  12302. #endif
  12303. case CMDNORMAL:
  12304. bit = DO_ALTPATH;
  12305. break;
  12306. case CMDFUNCTION:
  12307. bit = DO_NOFUNC;
  12308. break;
  12309. case CMDBUILTIN:
  12310. bit = DO_ALTBLTIN;
  12311. break;
  12312. }
  12313. if (act & bit) {
  12314. updatetbl = 0;
  12315. cmdp = NULL;
  12316. } else if (cmdp->rehash == 0)
  12317. /* if not invalidated by cd, we're done */
  12318. goto success;
  12319. }
  12320. /* If %builtin not in path, check for builtin next */
  12321. bcmd = find_builtin(name);
  12322. if (bcmd) {
  12323. if (IS_BUILTIN_REGULAR(bcmd))
  12324. goto builtin_success;
  12325. if (act & DO_ALTPATH) {
  12326. if (!(act & DO_ALTBLTIN))
  12327. goto builtin_success;
  12328. } else if (builtinloc <= 0) {
  12329. goto builtin_success;
  12330. }
  12331. }
  12332. #if ENABLE_FEATURE_SH_STANDALONE
  12333. {
  12334. int applet_no = find_applet_by_name(name);
  12335. if (applet_no >= 0) {
  12336. entry->cmdtype = CMDNORMAL;
  12337. entry->u.index = -2 - applet_no;
  12338. return;
  12339. }
  12340. }
  12341. #endif
  12342. /* We have to search path. */
  12343. prev = -1; /* where to start */
  12344. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12345. if (cmdp->cmdtype == CMDBUILTIN)
  12346. prev = builtinloc;
  12347. else
  12348. prev = cmdp->param.index;
  12349. }
  12350. e = ENOENT;
  12351. idx = -1;
  12352. loop:
  12353. while ((fullname = path_advance(&path, name)) != NULL) {
  12354. stunalloc(fullname);
  12355. /* NB: code below will still use fullname
  12356. * despite it being "unallocated" */
  12357. idx++;
  12358. if (pathopt) {
  12359. if (prefix(pathopt, "builtin")) {
  12360. if (bcmd)
  12361. goto builtin_success;
  12362. continue;
  12363. }
  12364. if ((act & DO_NOFUNC)
  12365. || !prefix(pathopt, "func")
  12366. ) { /* ignore unimplemented options */
  12367. continue;
  12368. }
  12369. }
  12370. /* if rehash, don't redo absolute path names */
  12371. if (fullname[0] == '/' && idx <= prev) {
  12372. if (idx < prev)
  12373. continue;
  12374. TRACE(("searchexec \"%s\": no change\n", name));
  12375. goto success;
  12376. }
  12377. while (stat(fullname, &statb) < 0) {
  12378. #ifdef SYSV
  12379. if (errno == EINTR)
  12380. continue;
  12381. #endif
  12382. if (errno != ENOENT && errno != ENOTDIR)
  12383. e = errno;
  12384. goto loop;
  12385. }
  12386. e = EACCES; /* if we fail, this will be the error */
  12387. if (!S_ISREG(statb.st_mode))
  12388. continue;
  12389. if (pathopt) { /* this is a %func directory */
  12390. stalloc(strlen(fullname) + 1);
  12391. /* NB: stalloc will return space pointed by fullname
  12392. * (because we don't have any intervening allocations
  12393. * between stunalloc above and this stalloc) */
  12394. readcmdfile(fullname);
  12395. cmdp = cmdlookup(name, 0);
  12396. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12397. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12398. stunalloc(fullname);
  12399. goto success;
  12400. }
  12401. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12402. if (!updatetbl) {
  12403. entry->cmdtype = CMDNORMAL;
  12404. entry->u.index = idx;
  12405. return;
  12406. }
  12407. INT_OFF;
  12408. cmdp = cmdlookup(name, 1);
  12409. cmdp->cmdtype = CMDNORMAL;
  12410. cmdp->param.index = idx;
  12411. INT_ON;
  12412. goto success;
  12413. }
  12414. /* We failed. If there was an entry for this command, delete it */
  12415. if (cmdp && updatetbl)
  12416. delete_cmd_entry();
  12417. if (act & DO_ERR) {
  12418. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12419. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12420. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12421. char *argv[3];
  12422. argv[0] = (char*) "command_not_found_handle";
  12423. argv[1] = name;
  12424. argv[2] = NULL;
  12425. evalfun(hookp->param.func, 2, argv, 0);
  12426. entry->cmdtype = CMDUNKNOWN;
  12427. return;
  12428. }
  12429. #endif
  12430. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12431. }
  12432. entry->cmdtype = CMDUNKNOWN;
  12433. return;
  12434. builtin_success:
  12435. if (!updatetbl) {
  12436. entry->cmdtype = CMDBUILTIN;
  12437. entry->u.cmd = bcmd;
  12438. return;
  12439. }
  12440. INT_OFF;
  12441. cmdp = cmdlookup(name, 1);
  12442. cmdp->cmdtype = CMDBUILTIN;
  12443. cmdp->param.cmd = bcmd;
  12444. INT_ON;
  12445. success:
  12446. cmdp->rehash = 0;
  12447. entry->cmdtype = cmdp->cmdtype;
  12448. entry->u = cmdp->param;
  12449. }
  12450. /*
  12451. * The trap builtin.
  12452. */
  12453. static int FAST_FUNC
  12454. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12455. {
  12456. char *action;
  12457. char **ap;
  12458. int signo, exitcode;
  12459. nextopt(nullstr);
  12460. ap = argptr;
  12461. if (!*ap) {
  12462. for (signo = 0; signo < NSIG; signo++) {
  12463. char *tr = trap_ptr[signo];
  12464. if (tr) {
  12465. /* note: bash adds "SIG", but only if invoked
  12466. * as "bash". If called as "sh", or if set -o posix,
  12467. * then it prints short signal names.
  12468. * We are printing short names: */
  12469. out1fmt("trap -- %s %s\n",
  12470. single_quote(tr),
  12471. get_signame(signo));
  12472. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12473. * In this case, we will exit very soon, no need to free(). */
  12474. /* if (trap_ptr != trap && tp[0]) */
  12475. /* free(tr); */
  12476. }
  12477. }
  12478. /*
  12479. if (trap_ptr != trap) {
  12480. free(trap_ptr);
  12481. trap_ptr = trap;
  12482. }
  12483. */
  12484. return 0;
  12485. }
  12486. /* Why the second check?
  12487. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12488. * In this case, NUM is signal no, not an action.
  12489. */
  12490. action = NULL;
  12491. if (ap[1] && !is_number(ap[0]))
  12492. action = *ap++;
  12493. exitcode = 0;
  12494. while (*ap) {
  12495. signo = get_signum(*ap);
  12496. if (signo < 0) {
  12497. /* Mimic bash message exactly */
  12498. ash_msg("%s: invalid signal specification", *ap);
  12499. exitcode = 1;
  12500. goto next;
  12501. }
  12502. INT_OFF;
  12503. if (action) {
  12504. if (LONE_DASH(action))
  12505. action = NULL;
  12506. else {
  12507. if (action[0]) /* not NULL and not "" and not "-" */
  12508. may_have_traps = 1;
  12509. action = ckstrdup(action);
  12510. }
  12511. }
  12512. free(trap[signo]);
  12513. trap[signo] = action;
  12514. if (signo != 0)
  12515. setsignal(signo);
  12516. INT_ON;
  12517. next:
  12518. ap++;
  12519. }
  12520. return exitcode;
  12521. }
  12522. /* ============ Builtins */
  12523. #if ENABLE_ASH_HELP
  12524. static int FAST_FUNC
  12525. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12526. {
  12527. unsigned col;
  12528. unsigned i;
  12529. out1fmt(
  12530. "Built-in commands:\n"
  12531. "------------------\n");
  12532. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12533. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12534. builtintab[i].name + 1);
  12535. if (col > 60) {
  12536. out1fmt("\n");
  12537. col = 0;
  12538. }
  12539. }
  12540. # if ENABLE_FEATURE_SH_STANDALONE
  12541. {
  12542. const char *a = applet_names;
  12543. while (*a) {
  12544. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12545. if (col > 60) {
  12546. out1fmt("\n");
  12547. col = 0;
  12548. }
  12549. while (*a++ != '\0')
  12550. continue;
  12551. }
  12552. }
  12553. # endif
  12554. newline_and_flush(stdout);
  12555. return EXIT_SUCCESS;
  12556. }
  12557. #endif
  12558. #if MAX_HISTORY
  12559. static int FAST_FUNC
  12560. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12561. {
  12562. if (line_input_state)
  12563. show_history(line_input_state);
  12564. return EXIT_SUCCESS;
  12565. }
  12566. #endif
  12567. /*
  12568. * The export and readonly commands.
  12569. */
  12570. static int FAST_FUNC
  12571. exportcmd(int argc UNUSED_PARAM, char **argv)
  12572. {
  12573. struct var *vp;
  12574. char *name;
  12575. const char *p;
  12576. char **aptr;
  12577. char opt;
  12578. int flag;
  12579. int flag_off;
  12580. /* "readonly" in bash accepts, but ignores -n.
  12581. * We do the same: it saves a conditional in nextopt's param.
  12582. */
  12583. flag_off = 0;
  12584. while ((opt = nextopt("np")) != '\0') {
  12585. if (opt == 'n')
  12586. flag_off = VEXPORT;
  12587. }
  12588. flag = VEXPORT;
  12589. if (argv[0][0] == 'r') {
  12590. flag = VREADONLY;
  12591. flag_off = 0; /* readonly ignores -n */
  12592. }
  12593. flag_off = ~flag_off;
  12594. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12595. {
  12596. aptr = argptr;
  12597. name = *aptr;
  12598. if (name) {
  12599. do {
  12600. p = strchr(name, '=');
  12601. if (p != NULL) {
  12602. p++;
  12603. } else {
  12604. vp = *findvar(hashvar(name), name);
  12605. if (vp) {
  12606. vp->flags = ((vp->flags | flag) & flag_off);
  12607. continue;
  12608. }
  12609. }
  12610. setvar(name, p, (flag & flag_off));
  12611. } while ((name = *++aptr) != NULL);
  12612. return 0;
  12613. }
  12614. }
  12615. /* No arguments. Show the list of exported or readonly vars.
  12616. * -n is ignored.
  12617. */
  12618. showvars(argv[0], flag, 0);
  12619. return 0;
  12620. }
  12621. /*
  12622. * Delete a function if it exists.
  12623. */
  12624. static void
  12625. unsetfunc(const char *name)
  12626. {
  12627. struct tblentry *cmdp;
  12628. cmdp = cmdlookup(name, 0);
  12629. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12630. delete_cmd_entry();
  12631. }
  12632. /*
  12633. * The unset builtin command. We unset the function before we unset the
  12634. * variable to allow a function to be unset when there is a readonly variable
  12635. * with the same name.
  12636. */
  12637. static int FAST_FUNC
  12638. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12639. {
  12640. char **ap;
  12641. int i;
  12642. int flag = 0;
  12643. while ((i = nextopt("vf")) != 0) {
  12644. flag = i;
  12645. }
  12646. for (ap = argptr; *ap; ap++) {
  12647. if (flag != 'f') {
  12648. unsetvar(*ap);
  12649. continue;
  12650. }
  12651. if (flag != 'v')
  12652. unsetfunc(*ap);
  12653. }
  12654. return 0;
  12655. }
  12656. static const unsigned char timescmd_str[] ALIGN1 = {
  12657. ' ', offsetof(struct tms, tms_utime),
  12658. '\n', offsetof(struct tms, tms_stime),
  12659. ' ', offsetof(struct tms, tms_cutime),
  12660. '\n', offsetof(struct tms, tms_cstime),
  12661. 0
  12662. };
  12663. static int FAST_FUNC
  12664. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12665. {
  12666. unsigned clk_tck;
  12667. const unsigned char *p;
  12668. struct tms buf;
  12669. clk_tck = bb_clk_tck();
  12670. times(&buf);
  12671. p = timescmd_str;
  12672. do {
  12673. unsigned sec, frac;
  12674. unsigned long t;
  12675. t = *(clock_t *)(((char *) &buf) + p[1]);
  12676. sec = t / clk_tck;
  12677. frac = t % clk_tck;
  12678. out1fmt("%um%u.%03us%c",
  12679. sec / 60, sec % 60,
  12680. (frac * 1000) / clk_tck,
  12681. p[0]);
  12682. p += 2;
  12683. } while (*p);
  12684. return 0;
  12685. }
  12686. #if ENABLE_FEATURE_SH_MATH
  12687. /*
  12688. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12689. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12690. *
  12691. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12692. */
  12693. static int FAST_FUNC
  12694. letcmd(int argc UNUSED_PARAM, char **argv)
  12695. {
  12696. arith_t i;
  12697. argv++;
  12698. if (!*argv)
  12699. ash_msg_and_raise_error("expression expected");
  12700. do {
  12701. i = ash_arith(*argv);
  12702. } while (*++argv);
  12703. return !i;
  12704. }
  12705. #endif
  12706. /*
  12707. * The read builtin. Options:
  12708. * -r Do not interpret '\' specially
  12709. * -s Turn off echo (tty only)
  12710. * -n NCHARS Read NCHARS max
  12711. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12712. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12713. * -u FD Read from given FD instead of fd 0
  12714. * -d DELIM End on DELIM char, not newline
  12715. * This uses unbuffered input, which may be avoidable in some cases.
  12716. * TODO: bash also has:
  12717. * -a ARRAY Read into array[0],[1],etc
  12718. * -e Use line editing (tty only)
  12719. */
  12720. static int FAST_FUNC
  12721. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12722. {
  12723. struct builtin_read_params params;
  12724. const char *r;
  12725. int i;
  12726. memset(&params, 0, sizeof(params));
  12727. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12728. switch (i) {
  12729. case 'p':
  12730. params.opt_p = optionarg;
  12731. break;
  12732. case 'n':
  12733. params.opt_n = optionarg;
  12734. break;
  12735. case 's':
  12736. params.read_flags |= BUILTIN_READ_SILENT;
  12737. break;
  12738. case 't':
  12739. params.opt_t = optionarg;
  12740. break;
  12741. case 'r':
  12742. params.read_flags |= BUILTIN_READ_RAW;
  12743. break;
  12744. case 'u':
  12745. params.opt_u = optionarg;
  12746. break;
  12747. #if BASH_READ_D
  12748. case 'd':
  12749. params.opt_d = optionarg;
  12750. break;
  12751. #endif
  12752. default:
  12753. break;
  12754. }
  12755. }
  12756. params.argv = argptr;
  12757. params.setvar = setvar0;
  12758. params.ifs = bltinlookup("IFS"); /* can be NULL */
  12759. /* "read -s" needs to save/restore termios, can't allow ^C
  12760. * to jump out of it.
  12761. */
  12762. again:
  12763. INT_OFF;
  12764. r = shell_builtin_read(&params);
  12765. INT_ON;
  12766. if ((uintptr_t)r == 1 && errno == EINTR) {
  12767. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12768. * Correct behavior is to not exit "read"
  12769. */
  12770. if (pending_sig == 0)
  12771. goto again;
  12772. }
  12773. if ((uintptr_t)r > 1)
  12774. ash_msg_and_raise_error(r);
  12775. return (uintptr_t)r;
  12776. }
  12777. static int FAST_FUNC
  12778. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12779. {
  12780. static const char permuser[3] ALIGN1 = "ogu";
  12781. mode_t mask;
  12782. int symbolic_mode = 0;
  12783. while (nextopt("S") != '\0') {
  12784. symbolic_mode = 1;
  12785. }
  12786. INT_OFF;
  12787. mask = umask(0);
  12788. umask(mask);
  12789. INT_ON;
  12790. if (*argptr == NULL) {
  12791. if (symbolic_mode) {
  12792. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12793. char *p = buf;
  12794. int i;
  12795. i = 2;
  12796. for (;;) {
  12797. *p++ = ',';
  12798. *p++ = permuser[i];
  12799. *p++ = '=';
  12800. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12801. if (!(mask & 0400)) *p++ = 'r';
  12802. if (!(mask & 0200)) *p++ = 'w';
  12803. if (!(mask & 0100)) *p++ = 'x';
  12804. mask <<= 3;
  12805. if (--i < 0)
  12806. break;
  12807. }
  12808. *p = '\0';
  12809. puts(buf + 1);
  12810. } else {
  12811. out1fmt("%04o\n", mask);
  12812. }
  12813. } else {
  12814. char *modestr = *argptr;
  12815. /* numeric umasks are taken as-is */
  12816. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12817. if (!isdigit(modestr[0]))
  12818. mask ^= 0777;
  12819. mask = bb_parse_mode(modestr, mask);
  12820. if ((unsigned)mask > 0777) {
  12821. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12822. }
  12823. if (!isdigit(modestr[0]))
  12824. mask ^= 0777;
  12825. umask(mask);
  12826. }
  12827. return 0;
  12828. }
  12829. static int FAST_FUNC
  12830. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12831. {
  12832. return shell_builtin_ulimit(argv);
  12833. }
  12834. /* ============ main() and helpers */
  12835. /*
  12836. * Called to exit the shell.
  12837. */
  12838. static void
  12839. exitshell(void)
  12840. {
  12841. struct jmploc loc;
  12842. char *p;
  12843. int status;
  12844. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12845. if (line_input_state)
  12846. save_history(line_input_state);
  12847. #endif
  12848. status = exitstatus;
  12849. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  12850. if (setjmp(loc.loc)) {
  12851. if (exception_type == EXEXIT)
  12852. status = exitstatus;
  12853. goto out;
  12854. }
  12855. exception_handler = &loc;
  12856. p = trap[0];
  12857. if (p) {
  12858. trap[0] = NULL;
  12859. evalskip = 0;
  12860. evalstring(p, 0);
  12861. /*free(p); - we'll exit soon */
  12862. }
  12863. out:
  12864. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12865. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12866. */
  12867. setjobctl(0);
  12868. flush_stdout_stderr();
  12869. _exit(status);
  12870. /* NOTREACHED */
  12871. }
  12872. /* Don't inline: conserve stack of caller from having our locals too */
  12873. static NOINLINE void
  12874. init(void)
  12875. {
  12876. /* we will never free this */
  12877. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12878. basepf.linno = 1;
  12879. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  12880. setsignal(SIGCHLD);
  12881. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  12882. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  12883. */
  12884. signal(SIGHUP, SIG_DFL);
  12885. {
  12886. char **envp;
  12887. const char *p;
  12888. initvar();
  12889. for (envp = environ; envp && *envp; envp++) {
  12890. /* Used to have
  12891. * p = endofname(*envp);
  12892. * if (p != *envp && *p == '=') {
  12893. * here to weed out badly-named variables, but this breaks
  12894. * scenarios where people do want them passed to children:
  12895. * import os
  12896. * os.environ["test-test"]="test"
  12897. * if os.fork() == 0:
  12898. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  12899. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  12900. */
  12901. if (strchr(*envp, '=')) {
  12902. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12903. }
  12904. }
  12905. setvareq((char*)defifsvar, VTEXTFIXED);
  12906. setvareq((char*)defoptindvar, VTEXTFIXED);
  12907. setvar0("PPID", utoa(getppid()));
  12908. #if BASH_SHLVL_VAR
  12909. p = lookupvar("SHLVL");
  12910. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12911. #endif
  12912. #if BASH_HOSTNAME_VAR
  12913. if (!lookupvar("HOSTNAME")) {
  12914. struct utsname uts;
  12915. uname(&uts);
  12916. setvar0("HOSTNAME", uts.nodename);
  12917. }
  12918. #endif
  12919. p = lookupvar("PWD");
  12920. if (p) {
  12921. struct stat st1, st2;
  12922. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12923. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12924. ) {
  12925. p = NULL;
  12926. }
  12927. }
  12928. setpwd(p, 0);
  12929. }
  12930. }
  12931. //usage:#define ash_trivial_usage
  12932. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  12933. //usage:#define ash_full_usage "\n\n"
  12934. //usage: "Unix shell interpreter"
  12935. /*
  12936. * Process the shell command line arguments.
  12937. */
  12938. static int
  12939. procargs(char **argv)
  12940. {
  12941. int i;
  12942. const char *xminusc;
  12943. char **xargv;
  12944. int login_sh;
  12945. xargv = argv;
  12946. login_sh = xargv[0] && xargv[0][0] == '-';
  12947. #if NUM_SCRIPTS > 0
  12948. if (minusc)
  12949. goto setarg0;
  12950. #endif
  12951. arg0 = xargv[0];
  12952. /* if (xargv[0]) - mmm, this is always true! */
  12953. xargv++;
  12954. argptr = xargv;
  12955. for (i = 0; i < NOPTS; i++)
  12956. optlist[i] = 2;
  12957. if (options(&login_sh)) {
  12958. /* it already printed err message */
  12959. raise_exception(EXERROR);
  12960. }
  12961. xargv = argptr;
  12962. xminusc = minusc;
  12963. if (*xargv == NULL) {
  12964. if (xminusc)
  12965. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  12966. sflag = 1;
  12967. }
  12968. if (iflag == 2 /* no explicit -i given */
  12969. && sflag == 1 /* -s given (or implied) */
  12970. && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
  12971. && isatty(0) && isatty(1) /* we are on tty */
  12972. ) {
  12973. iflag = 1;
  12974. }
  12975. if (mflag == 2)
  12976. mflag = iflag;
  12977. for (i = 0; i < NOPTS; i++)
  12978. if (optlist[i] == 2)
  12979. optlist[i] = 0;
  12980. #if DEBUG == 2
  12981. debug = 1;
  12982. #endif
  12983. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  12984. if (xminusc) {
  12985. minusc = *xargv++;
  12986. if (*xargv)
  12987. goto setarg0;
  12988. } else if (!sflag) {
  12989. setinputfile(*xargv, 0);
  12990. setarg0:
  12991. arg0 = *xargv++;
  12992. commandname = arg0;
  12993. }
  12994. shellparam.p = xargv;
  12995. #if ENABLE_ASH_GETOPTS
  12996. shellparam.optind = 1;
  12997. shellparam.optoff = -1;
  12998. #endif
  12999. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  13000. while (*xargv) {
  13001. shellparam.nparam++;
  13002. xargv++;
  13003. }
  13004. optschanged();
  13005. return login_sh;
  13006. }
  13007. /*
  13008. * Read /etc/profile, ~/.profile, $ENV.
  13009. */
  13010. static void
  13011. read_profile(const char *name)
  13012. {
  13013. name = expandstr(name, DQSYNTAX);
  13014. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  13015. return;
  13016. cmdloop(0);
  13017. popfile();
  13018. }
  13019. /*
  13020. * This routine is called when an error or an interrupt occurs in an
  13021. * interactive shell and control is returned to the main command loop.
  13022. * (In dash, this function is auto-generated by build machinery).
  13023. */
  13024. static void
  13025. reset(void)
  13026. {
  13027. /* from eval.c: */
  13028. evalskip = 0;
  13029. loopnest = 0;
  13030. /* from expand.c: */
  13031. ifsfree();
  13032. /* from input.c: */
  13033. g_parsefile->left_in_buffer = 0;
  13034. g_parsefile->left_in_line = 0; /* clear input buffer */
  13035. popallfiles();
  13036. /* from redir.c: */
  13037. unwindredir(NULL);
  13038. /* from var.c: */
  13039. unwindlocalvars(NULL);
  13040. }
  13041. #if PROFILE
  13042. static short profile_buf[16384];
  13043. extern int etext();
  13044. #endif
  13045. /*
  13046. * Main routine. We initialize things, parse the arguments, execute
  13047. * profiles if we're a login shell, and then call cmdloop to execute
  13048. * commands. The setjmp call sets up the location to jump to when an
  13049. * exception occurs. When an exception occurs the variable "state"
  13050. * is used to figure out how far we had gotten.
  13051. */
  13052. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13053. #if NUM_SCRIPTS > 0
  13054. int ash_main(int argc, char **argv)
  13055. #else
  13056. int ash_main(int argc UNUSED_PARAM, char **argv)
  13057. #endif
  13058. /* note: 'argc' is used only if embedded scripts are enabled */
  13059. {
  13060. volatile smallint state;
  13061. struct jmploc jmploc;
  13062. struct stackmark smark;
  13063. int login_sh;
  13064. /* Initialize global data */
  13065. INIT_G_misc();
  13066. INIT_G_memstack();
  13067. INIT_G_var();
  13068. #if ENABLE_ASH_ALIAS
  13069. INIT_G_alias();
  13070. #endif
  13071. INIT_G_cmdtable();
  13072. #if PROFILE
  13073. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  13074. #endif
  13075. state = 0;
  13076. if (setjmp(jmploc.loc)) {
  13077. smallint e;
  13078. smallint s;
  13079. reset();
  13080. e = exception_type;
  13081. s = state;
  13082. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  13083. exitshell();
  13084. }
  13085. if (e == EXINT) {
  13086. newline_and_flush(stderr);
  13087. }
  13088. popstackmark(&smark);
  13089. FORCE_INT_ON; /* enable interrupts */
  13090. if (s == 1)
  13091. goto state1;
  13092. if (s == 2)
  13093. goto state2;
  13094. if (s == 3)
  13095. goto state3;
  13096. goto state4;
  13097. }
  13098. exception_handler = &jmploc;
  13099. rootpid = getpid();
  13100. init();
  13101. setstackmark(&smark);
  13102. #if NUM_SCRIPTS > 0
  13103. if (argc < 0)
  13104. /* Non-NULL minusc tells procargs that an embedded script is being run */
  13105. minusc = get_script_content(-argc - 1);
  13106. #endif
  13107. login_sh = procargs(argv);
  13108. #if DEBUG
  13109. TRACE(("Shell args: "));
  13110. trace_puts_args(argv);
  13111. #endif
  13112. if (login_sh) {
  13113. const char *hp;
  13114. state = 1;
  13115. read_profile("/etc/profile");
  13116. state1:
  13117. state = 2;
  13118. hp = lookupvar("HOME");
  13119. if (hp)
  13120. read_profile("$HOME/.profile");
  13121. }
  13122. state2:
  13123. state = 3;
  13124. if (
  13125. #ifndef linux
  13126. getuid() == geteuid() && getgid() == getegid() &&
  13127. #endif
  13128. iflag
  13129. ) {
  13130. const char *shinit = lookupvar("ENV");
  13131. if (shinit != NULL && *shinit != '\0')
  13132. read_profile(shinit);
  13133. }
  13134. popstackmark(&smark);
  13135. state3:
  13136. state = 4;
  13137. if (minusc) {
  13138. /* evalstring pushes parsefile stack.
  13139. * Ensure we don't falsely claim that 0 (stdin)
  13140. * is one of stacked source fds.
  13141. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13142. // if (!sflag) g_parsefile->pf_fd = -1;
  13143. // ^^ not necessary since now we special-case fd 0
  13144. // in save_fd_on_redirect()
  13145. // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
  13146. // The above makes
  13147. // ash -sc 'echo $-'
  13148. // continue reading input from stdin after running 'echo'.
  13149. // bash does not do this: it prints "hBcs" and exits.
  13150. evalstring(minusc, EV_EXIT);
  13151. }
  13152. if (sflag || minusc == NULL) {
  13153. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13154. if (iflag) {
  13155. const char *hp = lookupvar("HISTFILE");
  13156. if (!hp) {
  13157. hp = lookupvar("HOME");
  13158. if (hp) {
  13159. INT_OFF;
  13160. hp = concat_path_file(hp, ".ash_history");
  13161. setvar0("HISTFILE", hp);
  13162. free((char*)hp);
  13163. INT_ON;
  13164. hp = lookupvar("HISTFILE");
  13165. }
  13166. }
  13167. if (hp)
  13168. line_input_state->hist_file = hp;
  13169. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13170. hp = lookupvar("HISTFILESIZE");
  13171. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13172. # endif
  13173. }
  13174. #endif
  13175. state4: /* XXX ??? - why isn't this before the "if" statement */
  13176. cmdloop(1);
  13177. }
  13178. #if PROFILE
  13179. monitor(0);
  13180. #endif
  13181. #ifdef GPROF
  13182. {
  13183. extern void _mcleanup(void);
  13184. _mcleanup();
  13185. }
  13186. #endif
  13187. TRACE(("End of main reached\n"));
  13188. exitshell();
  13189. /* NOTREACHED */
  13190. }
  13191. /*-
  13192. * Copyright (c) 1989, 1991, 1993, 1994
  13193. * The Regents of the University of California. All rights reserved.
  13194. *
  13195. * This code is derived from software contributed to Berkeley by
  13196. * Kenneth Almquist.
  13197. *
  13198. * Redistribution and use in source and binary forms, with or without
  13199. * modification, are permitted provided that the following conditions
  13200. * are met:
  13201. * 1. Redistributions of source code must retain the above copyright
  13202. * notice, this list of conditions and the following disclaimer.
  13203. * 2. Redistributions in binary form must reproduce the above copyright
  13204. * notice, this list of conditions and the following disclaimer in the
  13205. * documentation and/or other materials provided with the distribution.
  13206. * 3. Neither the name of the University nor the names of its contributors
  13207. * may be used to endorse or promote products derived from this software
  13208. * without specific prior written permission.
  13209. *
  13210. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13211. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13212. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13213. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13214. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13215. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13216. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13217. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13218. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13219. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13220. * SUCH DAMAGE.
  13221. */