ash.c 325 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567
  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 SHELL_ASH
  19. //config: bool #hidden option
  20. //config: depends on !NOMMU
  21. //config:
  22. //config:config ASH
  23. //config: bool "ash (78 kb)"
  24. //config: default y
  25. //config: depends on !NOMMU
  26. //config: select SHELL_ASH
  27. //config: help
  28. //config: The most complete and most pedantically correct shell included with
  29. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  30. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  31. //config: (written by Kenneth Almquist) from NetBSD.
  32. //config:
  33. //config:# ash options
  34. //config:# note: Don't remove !NOMMU part in the next line; it would break
  35. //config:# menuconfig's indenting.
  36. //config:if !NOMMU && (SHELL_ASH || ASH || SH_IS_ASH || BASH_IS_ASH)
  37. //config:
  38. //config:config ASH_OPTIMIZE_FOR_SIZE
  39. //config: bool "Optimize for size instead of speed"
  40. //config: default y
  41. //config: depends on SHELL_ASH
  42. //config:
  43. //config:config ASH_INTERNAL_GLOB
  44. //config: bool "Use internal glob() implementation"
  45. //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
  46. //config: depends on SHELL_ASH
  47. //config: help
  48. //config: Do not use glob() function from libc, use internal implementation.
  49. //config: Use this if you are getting "glob.h: No such file or directory"
  50. //config: or similar build errors.
  51. //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
  52. //config: which would break ash if you select N here.
  53. //config:
  54. //config:config ASH_BASH_COMPAT
  55. //config: bool "bash-compatible extensions"
  56. //config: default y
  57. //config: depends on SHELL_ASH
  58. //config:
  59. //config:config ASH_BASH_SOURCE_CURDIR
  60. //config: bool "'source' and '.' builtins search current directory after $PATH"
  61. //config: default n # do not encourage non-standard behavior
  62. //config: depends on ASH_BASH_COMPAT
  63. //config: help
  64. //config: This is not compliant with standards. Avoid if possible.
  65. //config:
  66. //config:config ASH_BASH_NOT_FOUND_HOOK
  67. //config: bool "command_not_found_handle hook support"
  68. //config: default y
  69. //config: depends on ASH_BASH_COMPAT
  70. //config: help
  71. //config: Enable support for the 'command_not_found_handle' hook function,
  72. //config: from GNU bash, which allows for alternative command not found
  73. //config: handling.
  74. //config:
  75. //config:config ASH_JOB_CONTROL
  76. //config: bool "Job control"
  77. //config: default y
  78. //config: depends on SHELL_ASH
  79. //config:
  80. //config:config ASH_ALIAS
  81. //config: bool "Alias support"
  82. //config: default y
  83. //config: depends on SHELL_ASH
  84. //config:
  85. //config:config ASH_RANDOM_SUPPORT
  86. //config: bool "Pseudorandom generator and $RANDOM variable"
  87. //config: default y
  88. //config: depends on SHELL_ASH
  89. //config: help
  90. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  91. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  92. //config: You can reset the generator by using a specified start value.
  93. //config: After "unset RANDOM" the generator will switch off and this
  94. //config: variable will no longer have special treatment.
  95. //config:
  96. //config:config ASH_EXPAND_PRMT
  97. //config: bool "Expand prompt string"
  98. //config: default y
  99. //config: depends on SHELL_ASH
  100. //config: help
  101. //config: $PS# may contain volatile content, such as backquote commands.
  102. //config: This option recreates the prompt string from the environment
  103. //config: variable each time it is displayed.
  104. //config:
  105. //config:config ASH_IDLE_TIMEOUT
  106. //config: bool "Idle timeout variable $TMOUT"
  107. //config: default y
  108. //config: depends on SHELL_ASH
  109. //config: help
  110. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  111. //config:
  112. //config:config ASH_MAIL
  113. //config: bool "Check for new mail in interactive shell"
  114. //config: default y
  115. //config: depends on SHELL_ASH
  116. //config: help
  117. //config: Enable "check for new mail" function:
  118. //config: if set, $MAIL file and $MAILPATH list of files
  119. //config: are checked for mtime changes, and "you have mail"
  120. //config: message is printed if change is detected.
  121. //config:
  122. //config:config ASH_ECHO
  123. //config: bool "echo builtin"
  124. //config: default y
  125. //config: depends on SHELL_ASH
  126. //config:
  127. //config:config ASH_PRINTF
  128. //config: bool "printf builtin"
  129. //config: default y
  130. //config: depends on SHELL_ASH
  131. //config:
  132. //config:config ASH_TEST
  133. //config: bool "test builtin"
  134. //config: default y
  135. //config: depends on SHELL_ASH
  136. //config:
  137. //config:config ASH_HELP
  138. //config: bool "help builtin"
  139. //config: default y
  140. //config: depends on SHELL_ASH
  141. //config:
  142. //config:config ASH_GETOPTS
  143. //config: bool "getopts builtin"
  144. //config: default y
  145. //config: depends on SHELL_ASH
  146. //config:
  147. //config:config ASH_CMDCMD
  148. //config: bool "command builtin"
  149. //config: default y
  150. //config: depends on SHELL_ASH
  151. //config: help
  152. //config: Enable support for the 'command' builtin, which allows
  153. //config: you to run the specified command or builtin,
  154. //config: even when there is a function with the same name.
  155. //config:
  156. //config:endif # ash options
  157. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  158. // APPLET_ODDNAME:name main location suid_type help
  159. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  160. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  161. //kbuild:lib-$(CONFIG_SHELL_ASH) += ash.o ash_ptr_hack.o shell_common.o
  162. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  163. /*
  164. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  165. * DEBUG=2 to compile in and turn on debugging.
  166. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  167. * debugging info is written to ./trace, quit signal generates core dump.
  168. */
  169. #define DEBUG 0
  170. /* Tweak debug output verbosity here */
  171. #define DEBUG_TIME 0
  172. #define DEBUG_PID 1
  173. #define DEBUG_SIG 1
  174. #define DEBUG_INTONOFF 0
  175. #define PROFILE 0
  176. #define JOBS ENABLE_ASH_JOB_CONTROL
  177. #include <fnmatch.h>
  178. #include <sys/times.h>
  179. #include <sys/utsname.h> /* for setting $HOSTNAME */
  180. #include "busybox.h" /* for applet_names */
  181. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
  182. # include "embedded_scripts.h"
  183. #else
  184. # define NUM_SCRIPTS 0
  185. #endif
  186. /* So far, all bash compat is controlled by one config option */
  187. /* Separate defines document which part of code implements what */
  188. /* function keyword */
  189. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  190. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  191. /* &>file */
  192. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  193. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  194. /* $'...' */
  195. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  196. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  197. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  198. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  199. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  200. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  201. /* BASH_TEST2: [[ EXPR ]]
  202. * Status of [[ support:
  203. * We replace && and || with -a and -o
  204. * TODO:
  205. * singleword+noglob expansion:
  206. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  207. * [[ /bin/n* ]]; echo 0:$?
  208. * -a/-o are not AND/OR ops! (they are just strings)
  209. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  210. * = is glob match operator, not equality operator: STR = GLOB
  211. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  212. * == same as =
  213. * add =~ regex match operator: STR =~ REGEX
  214. */
  215. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  216. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  217. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  218. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  219. #define BASH_EPOCH_VARS ENABLE_ASH_BASH_COMPAT
  220. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  221. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  222. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  223. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  224. #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
  225. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  226. /* Bionic at least up to version 24 has no glob() */
  227. # undef ENABLE_ASH_INTERNAL_GLOB
  228. # define ENABLE_ASH_INTERNAL_GLOB 1
  229. #endif
  230. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  231. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  232. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  233. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  234. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  235. # error fails to match dirname, subsequently not expanding <pattern> in it.
  236. // Testcase:
  237. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  238. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  239. #endif
  240. #if !ENABLE_ASH_INTERNAL_GLOB
  241. # include <glob.h>
  242. #endif
  243. #include "unicode.h"
  244. #include "shell_common.h"
  245. #if ENABLE_FEATURE_SH_MATH
  246. # include "math.h"
  247. #else
  248. typedef long arith_t;
  249. # define ARITH_FMT "%ld"
  250. #endif
  251. #if ENABLE_ASH_RANDOM_SUPPORT
  252. # include "random.h"
  253. #else
  254. # define CLEAR_RANDOM_T(rnd) ((void)0)
  255. #endif
  256. #include "NUM_APPLETS.h"
  257. #if NUM_APPLETS == 1
  258. /* STANDALONE does not make sense, and won't compile */
  259. # undef CONFIG_FEATURE_SH_STANDALONE
  260. # undef ENABLE_FEATURE_SH_STANDALONE
  261. # undef IF_FEATURE_SH_STANDALONE
  262. # undef IF_NOT_FEATURE_SH_STANDALONE
  263. # define ENABLE_FEATURE_SH_STANDALONE 0
  264. # define IF_FEATURE_SH_STANDALONE(...)
  265. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  266. #endif
  267. #ifndef F_DUPFD_CLOEXEC
  268. # define F_DUPFD_CLOEXEC F_DUPFD
  269. #endif
  270. #ifndef O_CLOEXEC
  271. # define O_CLOEXEC 0
  272. #endif
  273. #ifndef PIPE_BUF
  274. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  275. #endif
  276. #if !BB_MMU
  277. # error "Do not even bother, ash will not run on NOMMU machine"
  278. #endif
  279. /* We use a trick to have more optimized code (fewer pointer reloads):
  280. * ash.c: extern struct globals *const ash_ptr_to_globals;
  281. * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
  282. * This way, compiler in ash.c knows the pointer can not change.
  283. *
  284. * However, this may break on weird arches or toolchains. In this case,
  285. * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
  286. * this optimization.
  287. */
  288. #ifndef BB_GLOBAL_CONST
  289. # define BB_GLOBAL_CONST const
  290. #endif
  291. /* ============ Hash table sizes. Configurable. */
  292. #define VTABSIZE 39
  293. #define ATABSIZE 39
  294. #define CMDTABLESIZE 31 /* should be prime */
  295. /* ============ Shell options */
  296. static const char *const optletters_optnames[] = {
  297. "e" "errexit",
  298. "f" "noglob",
  299. "I" "ignoreeof",
  300. /* The below allowed this invocation:
  301. * ash -c 'set -i; echo $-; sleep 5; echo $-'
  302. * to be ^C-ed and get to interactive ash prompt.
  303. * bash does not support such "set -i".
  304. * In our code, this is denoted by empty long name:
  305. */
  306. "i" "",
  307. "m" "monitor",
  308. "n" "noexec",
  309. /* Ditto: bash has no "set -s" */
  310. "s" "",
  311. "c" "",
  312. "x" "xtrace",
  313. "v" "verbose",
  314. "C" "noclobber",
  315. "a" "allexport",
  316. "b" "notify",
  317. "u" "nounset",
  318. "\0" "vi"
  319. #if BASH_PIPEFAIL
  320. ,"\0" "pipefail"
  321. #endif
  322. #if DEBUG
  323. ,"\0" "nolog"
  324. ,"\0" "debug"
  325. #endif
  326. };
  327. //bash 4.4.23 also has these opts (with these defaults):
  328. //braceexpand on
  329. //emacs on
  330. //errtrace off
  331. //functrace off
  332. //hashall on
  333. //histexpand off
  334. //history on
  335. //interactive-comments on
  336. //keyword off
  337. //onecmd off
  338. //physical off
  339. //posix off
  340. //privileged off
  341. #define optletters(n) optletters_optnames[n][0]
  342. #define optnames(n) (optletters_optnames[n] + 1)
  343. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  344. /* ============ Misc data */
  345. #define msg_illnum "Illegal number: %s"
  346. /*
  347. * We enclose jmp_buf in a structure so that we can declare pointers to
  348. * jump locations. The global variable handler contains the location to
  349. * jump to when an exception occurs, and the global variable exception_type
  350. * contains a code identifying the exception. To implement nested
  351. * exception handlers, the user should save the value of handler on entry
  352. * to an inner scope, set handler to point to a jmploc structure for the
  353. * inner scope, and restore handler on exit from the scope.
  354. */
  355. struct jmploc {
  356. jmp_buf loc;
  357. };
  358. struct globals_misc {
  359. uint8_t exitstatus; /* exit status of last command */
  360. uint8_t back_exitstatus;/* exit status of backquoted command */
  361. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  362. int savestatus; /* exit status of last command outside traps */
  363. int rootpid; /* pid of main shell */
  364. /* shell level: 0 for the main shell, 1 for its children, and so on */
  365. int shlvl;
  366. #define rootshell (!shlvl)
  367. int errlinno;
  368. char *minusc; /* argument to -c option */
  369. char *curdir; // = nullstr; /* current working directory */
  370. char *physdir; // = nullstr; /* physical working directory */
  371. char *arg0; /* value of $0 */
  372. struct jmploc *exception_handler;
  373. volatile int suppress_int; /* counter */
  374. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  375. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  376. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  377. smallint exception_type; /* kind of exception: */
  378. #define EXINT 0 /* SIGINT received */
  379. #define EXERROR 1 /* a generic error */
  380. #define EXEND 3 /* exit the shell */
  381. #define EXEXIT 4 /* exit the shell via exitcmd */
  382. char nullstr[1]; /* zero length string */
  383. char optlist[NOPTS];
  384. #define eflag optlist[0]
  385. #define fflag optlist[1]
  386. #define Iflag optlist[2]
  387. #define iflag optlist[3]
  388. #define mflag optlist[4]
  389. #define nflag optlist[5]
  390. #define sflag optlist[6]
  391. #define cflag optlist[7]
  392. #define xflag optlist[8]
  393. #define vflag optlist[9]
  394. #define Cflag optlist[10]
  395. #define aflag optlist[11]
  396. #define bflag optlist[12]
  397. #define uflag optlist[13]
  398. #define viflag optlist[14]
  399. #if BASH_PIPEFAIL
  400. # define pipefail optlist[15]
  401. #else
  402. # define pipefail 0
  403. #endif
  404. #if DEBUG
  405. # define nolog optlist[15 + BASH_PIPEFAIL]
  406. # define debug optlist[16 + BASH_PIPEFAIL]
  407. #endif
  408. /* trap handler commands */
  409. /*
  410. * Sigmode records the current value of the signal handlers for the various
  411. * modes. A value of zero means that the current handler is not known.
  412. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  413. */
  414. char sigmode[NSIG - 1];
  415. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  416. #define S_CATCH 2 /* signal is caught */
  417. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  418. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  419. /* indicates specified signal received */
  420. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  421. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  422. char *trap[NSIG];
  423. char **trap_ptr; /* used only by "trap hack" */
  424. /* Rarely referenced stuff */
  425. #if ENABLE_ASH_RANDOM_SUPPORT
  426. random_t random_gen;
  427. #endif
  428. pid_t backgndpid; /* pid of last background process */
  429. };
  430. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  431. #define G_misc (*ash_ptr_to_globals_misc)
  432. #define exitstatus (G_misc.exitstatus )
  433. #define back_exitstatus (G_misc.back_exitstatus )
  434. #define job_warning (G_misc.job_warning)
  435. #define savestatus (G_misc.savestatus )
  436. #define rootpid (G_misc.rootpid )
  437. #define shlvl (G_misc.shlvl )
  438. #define errlinno (G_misc.errlinno )
  439. #define minusc (G_misc.minusc )
  440. #define curdir (G_misc.curdir )
  441. #define physdir (G_misc.physdir )
  442. #define arg0 (G_misc.arg0 )
  443. #define exception_handler (G_misc.exception_handler)
  444. #define exception_type (G_misc.exception_type )
  445. #define suppress_int (G_misc.suppress_int )
  446. #define pending_int (G_misc.pending_int )
  447. #define got_sigchld (G_misc.got_sigchld )
  448. #define pending_sig (G_misc.pending_sig )
  449. #define nullstr (G_misc.nullstr )
  450. #define optlist (G_misc.optlist )
  451. #define sigmode (G_misc.sigmode )
  452. #define gotsig (G_misc.gotsig )
  453. #define may_have_traps (G_misc.may_have_traps )
  454. #define trap (G_misc.trap )
  455. #define trap_ptr (G_misc.trap_ptr )
  456. #define random_gen (G_misc.random_gen )
  457. #define backgndpid (G_misc.backgndpid )
  458. #define INIT_G_misc() do { \
  459. (*(struct globals_misc**)not_const_pp(&ash_ptr_to_globals_misc)) = xzalloc(sizeof(G_misc)); \
  460. barrier(); \
  461. savestatus = -1; \
  462. curdir = nullstr; \
  463. physdir = nullstr; \
  464. trap_ptr = trap; \
  465. } while (0)
  466. /* ============ DEBUG */
  467. #if DEBUG
  468. static void trace_printf(const char *fmt, ...);
  469. static void trace_vprintf(const char *fmt, va_list va);
  470. # define TRACE(param) trace_printf param
  471. # define TRACEV(param) trace_vprintf param
  472. # define close(fd) do { \
  473. int dfd = (fd); \
  474. if (close(dfd) < 0) \
  475. bb_error_msg("bug on %d: closing %d(0x%x)", \
  476. __LINE__, dfd, dfd); \
  477. } while (0)
  478. #else
  479. # define TRACE(param)
  480. # define TRACEV(param)
  481. #endif
  482. /* ============ Utility functions */
  483. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  484. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  485. static int
  486. isdigit_str9(const char *str)
  487. {
  488. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  489. while (--maxlen && isdigit(*str))
  490. str++;
  491. return (*str == '\0');
  492. }
  493. static const char *
  494. var_end(const char *var)
  495. {
  496. while (*var)
  497. if (*var++ == '=')
  498. break;
  499. return var;
  500. }
  501. /* ============ Interrupts / exceptions */
  502. static void exitshell(void) NORETURN;
  503. /*
  504. * These macros allow the user to suspend the handling of interrupt signals
  505. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  506. * much more efficient and portable. (But hacking the kernel is so much
  507. * more fun than worrying about efficiency and portability. :-))
  508. */
  509. #if DEBUG_INTONOFF
  510. # define INT_OFF do { \
  511. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  512. suppress_int++; \
  513. barrier(); \
  514. } while (0)
  515. #else
  516. # define INT_OFF do { \
  517. suppress_int++; \
  518. barrier(); \
  519. } while (0)
  520. #endif
  521. /*
  522. * Called to raise an exception. Since C doesn't include exceptions, we
  523. * just do a longjmp to the exception handler. The type of exception is
  524. * stored in the global variable "exception_type".
  525. */
  526. static void raise_exception(int) NORETURN;
  527. static void
  528. raise_exception(int e)
  529. {
  530. #if DEBUG
  531. if (exception_handler == NULL)
  532. abort();
  533. #endif
  534. INT_OFF;
  535. exception_type = e;
  536. longjmp(exception_handler->loc, 1);
  537. }
  538. #if DEBUG
  539. #define raise_exception(e) do { \
  540. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  541. raise_exception(e); \
  542. } while (0)
  543. #endif
  544. /*
  545. * Called when a SIGINT is received. (If the user specifies
  546. * that SIGINT is to be trapped or ignored using the trap builtin, then
  547. * this routine is not called.) Suppressint is nonzero when interrupts
  548. * are held using the INT_OFF macro. (The test for iflag is just
  549. * defensive programming.)
  550. */
  551. static void raise_interrupt(void) NORETURN;
  552. static void
  553. raise_interrupt(void)
  554. {
  555. pending_int = 0;
  556. /* Signal is not automatically unmasked after it is raised,
  557. * do it ourself - unmask all signals */
  558. sigprocmask_allsigs(SIG_UNBLOCK);
  559. /* pending_sig = 0; - now done in signal_handler() */
  560. if (!(rootshell && iflag)) {
  561. /* Kill ourself with SIGINT */
  562. signal(SIGINT, SIG_DFL);
  563. raise(SIGINT);
  564. }
  565. /* bash: ^C even on empty command line sets $? */
  566. exitstatus = SIGINT + 128;
  567. raise_exception(EXINT);
  568. /* NOTREACHED */
  569. }
  570. #if DEBUG
  571. #define raise_interrupt() do { \
  572. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  573. raise_interrupt(); \
  574. } while (0)
  575. #endif
  576. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  577. int_on(void)
  578. {
  579. barrier();
  580. if (--suppress_int == 0 && pending_int) {
  581. raise_interrupt();
  582. }
  583. }
  584. #if DEBUG_INTONOFF
  585. # define INT_ON do { \
  586. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  587. int_on(); \
  588. } while (0)
  589. #else
  590. # define INT_ON int_on()
  591. #endif
  592. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  593. force_int_on(void)
  594. {
  595. barrier();
  596. suppress_int = 0;
  597. if (pending_int)
  598. raise_interrupt();
  599. }
  600. #define FORCE_INT_ON force_int_on()
  601. #define SAVE_INT(v) ((v) = suppress_int)
  602. #define RESTORE_INT(v) do { \
  603. barrier(); \
  604. suppress_int = (v); \
  605. if (suppress_int == 0 && pending_int) \
  606. raise_interrupt(); \
  607. } while (0)
  608. /* ============ Stdout/stderr output */
  609. static void
  610. outstr(const char *p, FILE *file)
  611. {
  612. INT_OFF;
  613. fputs(p, file);
  614. INT_ON;
  615. }
  616. static void
  617. flush_stdout_stderr(void)
  618. {
  619. INT_OFF;
  620. fflush_all();
  621. INT_ON;
  622. }
  623. /* Was called outcslow(c,FILE*), but c was always '\n' */
  624. static void
  625. newline_and_flush(FILE *dest)
  626. {
  627. INT_OFF;
  628. putc('\n', dest);
  629. fflush(dest);
  630. INT_ON;
  631. }
  632. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  633. static int
  634. out1fmt(const char *fmt, ...)
  635. {
  636. va_list ap;
  637. int r;
  638. INT_OFF;
  639. va_start(ap, fmt);
  640. r = vprintf(fmt, ap);
  641. va_end(ap);
  642. INT_ON;
  643. return r;
  644. }
  645. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  646. static int
  647. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  648. {
  649. va_list ap;
  650. int ret;
  651. INT_OFF;
  652. va_start(ap, fmt);
  653. ret = vsnprintf(outbuf, length, fmt, ap);
  654. va_end(ap);
  655. INT_ON;
  656. return ret > (int)length ? length : ret;
  657. }
  658. static void
  659. out1str(const char *p)
  660. {
  661. outstr(p, stdout);
  662. }
  663. static void
  664. out2str(const char *p)
  665. {
  666. outstr(p, stderr);
  667. flush_stdout_stderr();
  668. }
  669. /* ============ Parser structures */
  670. /* control characters in argument strings */
  671. #define CTL_FIRST CTLESC
  672. #define CTLESC ((unsigned char)'\201') /* escape next character */
  673. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  674. #define CTLENDVAR ((unsigned char)'\203')
  675. #define CTLBACKQ ((unsigned char)'\204')
  676. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  677. #define CTLENDARI ((unsigned char)'\207')
  678. #define CTLQUOTEMARK ((unsigned char)'\210')
  679. #define CTL_LAST CTLQUOTEMARK
  680. /* variable substitution byte (follows CTLVAR) */
  681. #define VSTYPE 0x0f /* type of variable substitution */
  682. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  683. /* values of VSTYPE field */
  684. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  685. #define VSMINUS 0x2 /* ${var-text} */
  686. #define VSPLUS 0x3 /* ${var+text} */
  687. #define VSQUESTION 0x4 /* ${var?message} */
  688. #define VSASSIGN 0x5 /* ${var=text} */
  689. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  690. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  691. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  692. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  693. #define VSLENGTH 0xa /* ${#var} */
  694. #if BASH_SUBSTR
  695. #define VSSUBSTR 0xc /* ${var:position:length} */
  696. #endif
  697. #if BASH_PATTERN_SUBST
  698. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  699. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  700. #endif
  701. static const char dolatstr[] ALIGN1 = {
  702. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  703. };
  704. #define DOLATSTRLEN 6
  705. #define NCMD 0
  706. #define NPIPE 1
  707. #define NREDIR 2
  708. #define NBACKGND 3
  709. #define NSUBSHELL 4
  710. #define NAND 5
  711. #define NOR 6
  712. #define NSEMI 7
  713. #define NIF 8
  714. #define NWHILE 9
  715. #define NUNTIL 10
  716. #define NFOR 11
  717. #define NCASE 12
  718. #define NCLIST 13
  719. #define NDEFUN 14
  720. #define NARG 15
  721. #define NTO 16
  722. #if BASH_REDIR_OUTPUT
  723. #define NTO2 17
  724. #endif
  725. #define NCLOBBER 18
  726. #define NFROM 19
  727. #define NFROMTO 20
  728. #define NAPPEND 21
  729. #define NTOFD 22
  730. #define NFROMFD 23
  731. #define NHERE 24
  732. #define NXHERE 25
  733. #define NNOT 26
  734. #define N_NUMBER 27
  735. union node;
  736. struct ncmd {
  737. smallint type; /* Nxxxx */
  738. int linno;
  739. union node *assign;
  740. union node *args;
  741. union node *redirect;
  742. };
  743. struct npipe {
  744. smallint type;
  745. smallint pipe_backgnd;
  746. struct nodelist *cmdlist;
  747. };
  748. struct nredir {
  749. smallint type;
  750. int linno;
  751. union node *n;
  752. union node *redirect;
  753. };
  754. struct nbinary {
  755. smallint type;
  756. union node *ch1;
  757. union node *ch2;
  758. };
  759. struct nif {
  760. smallint type;
  761. union node *test;
  762. union node *ifpart;
  763. union node *elsepart;
  764. };
  765. struct nfor {
  766. smallint type;
  767. int linno;
  768. union node *args;
  769. union node *body;
  770. char *var;
  771. };
  772. struct ncase {
  773. smallint type;
  774. int linno;
  775. union node *expr;
  776. union node *cases;
  777. };
  778. struct nclist {
  779. smallint type;
  780. union node *next;
  781. union node *pattern;
  782. union node *body;
  783. };
  784. struct ndefun {
  785. smallint type;
  786. int linno;
  787. char *text;
  788. union node *body;
  789. };
  790. struct narg {
  791. smallint type;
  792. union node *next;
  793. char *text;
  794. struct nodelist *backquote;
  795. };
  796. /* nfile and ndup layout must match!
  797. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  798. * that it is actually NTO2 (>&file), and change its type.
  799. */
  800. struct nfile {
  801. smallint type;
  802. union node *next;
  803. int fd;
  804. int _unused_dupfd;
  805. union node *fname;
  806. char *expfname;
  807. };
  808. struct ndup {
  809. smallint type;
  810. union node *next;
  811. int fd;
  812. int dupfd;
  813. union node *vname;
  814. char *_unused_expfname;
  815. };
  816. struct nhere {
  817. smallint type;
  818. union node *next;
  819. int fd;
  820. union node *doc;
  821. };
  822. struct nnot {
  823. smallint type;
  824. union node *com;
  825. };
  826. union node {
  827. smallint type;
  828. struct ncmd ncmd;
  829. struct npipe npipe;
  830. struct nredir nredir;
  831. struct nbinary nbinary;
  832. struct nif nif;
  833. struct nfor nfor;
  834. struct ncase ncase;
  835. struct nclist nclist;
  836. struct ndefun ndefun;
  837. struct narg narg;
  838. struct nfile nfile;
  839. struct ndup ndup;
  840. struct nhere nhere;
  841. struct nnot nnot;
  842. };
  843. /*
  844. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  845. * It must be distinct from NULL.
  846. */
  847. #define NODE_EOF ((union node *) -1L)
  848. struct nodelist {
  849. struct nodelist *next;
  850. union node *n;
  851. };
  852. struct funcnode {
  853. int count;
  854. union node n;
  855. };
  856. /*
  857. * Free a parse tree.
  858. */
  859. static void
  860. freefunc(struct funcnode *f)
  861. {
  862. if (f && --f->count < 0)
  863. free(f);
  864. }
  865. /* ============ Debugging output */
  866. #if DEBUG
  867. static FILE *tracefile;
  868. static void
  869. trace_printf(const char *fmt, ...)
  870. {
  871. va_list va;
  872. if (debug != 1)
  873. return;
  874. if (DEBUG_TIME)
  875. fprintf(tracefile, "%u ", (int) time(NULL));
  876. if (DEBUG_PID)
  877. fprintf(tracefile, "[%u] ", (int) getpid());
  878. if (DEBUG_SIG)
  879. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  880. va_start(va, fmt);
  881. vfprintf(tracefile, fmt, va);
  882. va_end(va);
  883. }
  884. static void
  885. trace_vprintf(const char *fmt, va_list va)
  886. {
  887. if (debug != 1)
  888. return;
  889. vfprintf(tracefile, fmt, va);
  890. fprintf(tracefile, "\n");
  891. }
  892. static void
  893. trace_puts(const char *s)
  894. {
  895. if (debug != 1)
  896. return;
  897. fputs(s, tracefile);
  898. }
  899. static void
  900. trace_puts_quoted(char *s)
  901. {
  902. char *p;
  903. char c;
  904. if (debug != 1)
  905. return;
  906. putc('"', tracefile);
  907. for (p = s; *p; p++) {
  908. switch ((unsigned char)*p) {
  909. case '\n': c = 'n'; goto backslash;
  910. case '\t': c = 't'; goto backslash;
  911. case '\r': c = 'r'; goto backslash;
  912. case '\"': c = '\"'; goto backslash;
  913. case '\\': c = '\\'; goto backslash;
  914. case CTLESC: c = 'e'; goto backslash;
  915. case CTLVAR: c = 'v'; goto backslash;
  916. case CTLBACKQ: c = 'q'; goto backslash;
  917. backslash:
  918. putc('\\', tracefile);
  919. putc(c, tracefile);
  920. break;
  921. default:
  922. if (*p >= ' ' && *p <= '~')
  923. putc(*p, tracefile);
  924. else {
  925. putc('\\', tracefile);
  926. putc((*p >> 6) & 03, tracefile);
  927. putc((*p >> 3) & 07, tracefile);
  928. putc(*p & 07, tracefile);
  929. }
  930. break;
  931. }
  932. }
  933. putc('"', tracefile);
  934. }
  935. static void
  936. trace_puts_args(char **ap)
  937. {
  938. if (debug != 1)
  939. return;
  940. if (!*ap)
  941. return;
  942. while (1) {
  943. trace_puts_quoted(*ap);
  944. if (!*++ap) {
  945. putc('\n', tracefile);
  946. break;
  947. }
  948. putc(' ', tracefile);
  949. }
  950. }
  951. static void
  952. opentrace(void)
  953. {
  954. char s[100];
  955. #ifdef O_APPEND
  956. int flags;
  957. #endif
  958. if (debug != 1) {
  959. if (tracefile)
  960. fflush(tracefile);
  961. /* leave open because libedit might be using it */
  962. return;
  963. }
  964. strcpy(s, "./trace");
  965. if (tracefile) {
  966. if (!freopen(s, "a", tracefile)) {
  967. fprintf(stderr, "Can't re-open %s\n", s);
  968. debug = 0;
  969. return;
  970. }
  971. } else {
  972. tracefile = fopen(s, "a");
  973. if (tracefile == NULL) {
  974. fprintf(stderr, "Can't open %s\n", s);
  975. debug = 0;
  976. return;
  977. }
  978. }
  979. #ifdef O_APPEND
  980. flags = fcntl(fileno(tracefile), F_GETFL);
  981. if (flags >= 0)
  982. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  983. #endif
  984. setlinebuf(tracefile);
  985. fputs("\nTracing started.\n", tracefile);
  986. }
  987. static void
  988. indent(int amount, char *pfx, FILE *fp)
  989. {
  990. int i;
  991. for (i = 0; i < amount; i++) {
  992. if (pfx && i == amount - 1)
  993. fputs(pfx, fp);
  994. putc('\t', fp);
  995. }
  996. }
  997. /* little circular references here... */
  998. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  999. static void
  1000. sharg(union node *arg, FILE *fp)
  1001. {
  1002. char *p;
  1003. struct nodelist *bqlist;
  1004. unsigned char subtype;
  1005. if (arg->type != NARG) {
  1006. out1fmt("<node type %d>\n", arg->type);
  1007. abort();
  1008. }
  1009. bqlist = arg->narg.backquote;
  1010. for (p = arg->narg.text; *p; p++) {
  1011. switch ((unsigned char)*p) {
  1012. case CTLESC:
  1013. p++;
  1014. putc(*p, fp);
  1015. break;
  1016. case CTLVAR:
  1017. putc('$', fp);
  1018. putc('{', fp);
  1019. subtype = *++p;
  1020. if (subtype == VSLENGTH)
  1021. putc('#', fp);
  1022. while (*p != '=') {
  1023. putc(*p, fp);
  1024. p++;
  1025. }
  1026. if (subtype & VSNUL)
  1027. putc(':', fp);
  1028. switch (subtype & VSTYPE) {
  1029. case VSNORMAL:
  1030. putc('}', fp);
  1031. break;
  1032. case VSMINUS:
  1033. putc('-', fp);
  1034. break;
  1035. case VSPLUS:
  1036. putc('+', fp);
  1037. break;
  1038. case VSQUESTION:
  1039. putc('?', fp);
  1040. break;
  1041. case VSASSIGN:
  1042. putc('=', fp);
  1043. break;
  1044. case VSTRIMLEFT:
  1045. putc('#', fp);
  1046. break;
  1047. case VSTRIMLEFTMAX:
  1048. putc('#', fp);
  1049. putc('#', fp);
  1050. break;
  1051. case VSTRIMRIGHT:
  1052. putc('%', fp);
  1053. break;
  1054. case VSTRIMRIGHTMAX:
  1055. putc('%', fp);
  1056. putc('%', fp);
  1057. break;
  1058. case VSLENGTH:
  1059. break;
  1060. default:
  1061. out1fmt("<subtype %d>", subtype);
  1062. }
  1063. break;
  1064. case CTLENDVAR:
  1065. putc('}', fp);
  1066. break;
  1067. case CTLBACKQ:
  1068. putc('$', fp);
  1069. putc('(', fp);
  1070. shtree(bqlist->n, -1, NULL, fp);
  1071. putc(')', fp);
  1072. break;
  1073. default:
  1074. putc(*p, fp);
  1075. break;
  1076. }
  1077. }
  1078. }
  1079. static void
  1080. shcmd(union node *cmd, FILE *fp)
  1081. {
  1082. union node *np;
  1083. int first;
  1084. const char *s;
  1085. int dftfd;
  1086. first = 1;
  1087. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1088. if (!first)
  1089. putc(' ', fp);
  1090. sharg(np, fp);
  1091. first = 0;
  1092. }
  1093. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1094. if (!first)
  1095. putc(' ', fp);
  1096. dftfd = 0;
  1097. switch (np->nfile.type) {
  1098. case NTO: s = ">>"+1; dftfd = 1; break;
  1099. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1100. case NAPPEND: s = ">>"; dftfd = 1; break;
  1101. #if BASH_REDIR_OUTPUT
  1102. case NTO2:
  1103. #endif
  1104. case NTOFD: s = ">&"; dftfd = 1; break;
  1105. case NFROM: s = "<"; break;
  1106. case NFROMFD: s = "<&"; break;
  1107. case NFROMTO: s = "<>"; break;
  1108. default: s = "*error*"; break;
  1109. }
  1110. if (np->nfile.fd != dftfd)
  1111. fprintf(fp, "%d", np->nfile.fd);
  1112. fputs(s, fp);
  1113. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1114. fprintf(fp, "%d", np->ndup.dupfd);
  1115. } else {
  1116. sharg(np->nfile.fname, fp);
  1117. }
  1118. first = 0;
  1119. }
  1120. }
  1121. static void
  1122. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1123. {
  1124. struct nodelist *lp;
  1125. const char *s;
  1126. if (n == NULL)
  1127. return;
  1128. indent(ind, pfx, fp);
  1129. if (n == NODE_EOF) {
  1130. fputs("<EOF>", fp);
  1131. return;
  1132. }
  1133. switch (n->type) {
  1134. case NSEMI:
  1135. s = "; ";
  1136. goto binop;
  1137. case NAND:
  1138. s = " && ";
  1139. goto binop;
  1140. case NOR:
  1141. s = " || ";
  1142. binop:
  1143. shtree(n->nbinary.ch1, ind, NULL, fp);
  1144. /* if (ind < 0) */
  1145. fputs(s, fp);
  1146. shtree(n->nbinary.ch2, ind, NULL, fp);
  1147. break;
  1148. case NCMD:
  1149. shcmd(n, fp);
  1150. if (ind >= 0)
  1151. putc('\n', fp);
  1152. break;
  1153. case NPIPE:
  1154. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1155. shtree(lp->n, 0, NULL, fp);
  1156. if (lp->next)
  1157. fputs(" | ", fp);
  1158. }
  1159. if (n->npipe.pipe_backgnd)
  1160. fputs(" &", fp);
  1161. if (ind >= 0)
  1162. putc('\n', fp);
  1163. break;
  1164. default:
  1165. fprintf(fp, "<node type %d>", n->type);
  1166. if (ind >= 0)
  1167. putc('\n', fp);
  1168. break;
  1169. }
  1170. }
  1171. static void
  1172. showtree(union node *n)
  1173. {
  1174. trace_puts("showtree called\n");
  1175. shtree(n, 1, NULL, stderr);
  1176. }
  1177. #endif /* DEBUG */
  1178. /* ============ Parser data */
  1179. /*
  1180. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1181. */
  1182. struct strlist {
  1183. struct strlist *next;
  1184. char *text;
  1185. };
  1186. struct alias;
  1187. struct strpush {
  1188. struct strpush *prev; /* preceding string on stack */
  1189. char *prev_string;
  1190. int prev_left_in_line;
  1191. #if ENABLE_ASH_ALIAS
  1192. struct alias *ap; /* if push was associated with an alias */
  1193. #endif
  1194. char *string; /* remember the string since it may change */
  1195. /* Remember last two characters for pungetc. */
  1196. int lastc[2];
  1197. /* Number of outstanding calls to pungetc. */
  1198. int unget;
  1199. };
  1200. /*
  1201. * The parsefile structure pointed to by the global variable parsefile
  1202. * contains information about the current file being read.
  1203. */
  1204. struct parsefile {
  1205. struct parsefile *prev; /* preceding file on stack */
  1206. int linno; /* current line */
  1207. int pf_fd; /* file descriptor (or -1 if string) */
  1208. int left_in_line; /* number of chars left in this line */
  1209. int left_in_buffer; /* number of chars left in this buffer past the line */
  1210. char *next_to_pgetc; /* next char in buffer */
  1211. char *buf; /* input buffer */
  1212. struct strpush *strpush; /* for pushing strings at this level */
  1213. struct strpush basestrpush; /* so pushing one is fast */
  1214. /* Remember last two characters for pungetc. */
  1215. int lastc[2];
  1216. /* Number of outstanding calls to pungetc. */
  1217. int unget;
  1218. };
  1219. static struct parsefile basepf; /* top level input file */
  1220. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1221. static char *commandname; /* currently executing command */
  1222. /* ============ Message printing */
  1223. static void
  1224. ash_vmsg(const char *msg, va_list ap)
  1225. {
  1226. fprintf(stderr, "%s: ", arg0);
  1227. if (commandname) {
  1228. if (strcmp(arg0, commandname))
  1229. fprintf(stderr, "%s: ", commandname);
  1230. if (!iflag || g_parsefile->pf_fd > 0)
  1231. fprintf(stderr, "line %d: ", errlinno);
  1232. }
  1233. vfprintf(stderr, msg, ap);
  1234. newline_and_flush(stderr);
  1235. }
  1236. /*
  1237. * Exverror is called to raise the error exception. If the second argument
  1238. * is not NULL then error prints an error message using printf style
  1239. * formatting. It then raises the error exception.
  1240. */
  1241. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1242. static void
  1243. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1244. {
  1245. #if DEBUG
  1246. if (msg) {
  1247. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1248. TRACEV((msg, ap));
  1249. } else
  1250. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1251. if (msg)
  1252. #endif
  1253. ash_vmsg(msg, ap);
  1254. flush_stdout_stderr();
  1255. raise_exception(cond);
  1256. /* NOTREACHED */
  1257. }
  1258. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1259. static void
  1260. ash_msg_and_raise_error(const char *msg, ...)
  1261. {
  1262. va_list ap;
  1263. exitstatus = 2;
  1264. va_start(ap, msg);
  1265. ash_vmsg_and_raise(EXERROR, msg, ap);
  1266. /* NOTREACHED */
  1267. va_end(ap);
  1268. }
  1269. /*
  1270. * 'fmt' must be a string literal.
  1271. */
  1272. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1273. static void raise_error_syntax(const char *) NORETURN;
  1274. static void
  1275. raise_error_syntax(const char *msg)
  1276. {
  1277. errlinno = g_parsefile->linno;
  1278. ash_msg_and_raise_error("syntax error: %s", msg);
  1279. /* NOTREACHED */
  1280. }
  1281. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1282. static void
  1283. ash_msg_and_raise(int cond, const char *msg, ...)
  1284. {
  1285. va_list ap;
  1286. va_start(ap, msg);
  1287. ash_vmsg_and_raise(cond, msg, ap);
  1288. /* NOTREACHED */
  1289. va_end(ap);
  1290. }
  1291. /*
  1292. * error/warning routines for external builtins
  1293. */
  1294. static void
  1295. ash_msg(const char *fmt, ...)
  1296. {
  1297. va_list ap;
  1298. va_start(ap, fmt);
  1299. ash_vmsg(fmt, ap);
  1300. va_end(ap);
  1301. }
  1302. /*
  1303. * Return a string describing an error. The returned string may be a
  1304. * pointer to a static buffer that will be overwritten on the next call.
  1305. * Action describes the operation that got the error.
  1306. */
  1307. static const char *
  1308. errmsg(int e, const char *em)
  1309. {
  1310. if (e == ENOENT || e == ENOTDIR) {
  1311. return em;
  1312. }
  1313. return strerror(e);
  1314. }
  1315. /* ============ Memory allocation */
  1316. #if 0
  1317. /* I consider these wrappers nearly useless:
  1318. * ok, they return you to nearest exception handler, but
  1319. * how much memory do you leak in the process, making
  1320. * memory starvation worse?
  1321. */
  1322. static void *
  1323. ckrealloc(void * p, size_t nbytes)
  1324. {
  1325. p = realloc(p, nbytes);
  1326. if (!p)
  1327. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1328. return p;
  1329. }
  1330. static void *
  1331. ckmalloc(size_t nbytes)
  1332. {
  1333. return ckrealloc(NULL, nbytes);
  1334. }
  1335. static void *
  1336. ckzalloc(size_t nbytes)
  1337. {
  1338. return memset(ckmalloc(nbytes), 0, nbytes);
  1339. }
  1340. static char *
  1341. ckstrdup(const char *s)
  1342. {
  1343. char *p = strdup(s);
  1344. if (!p)
  1345. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1346. return p;
  1347. }
  1348. #else
  1349. /* Using bbox equivalents. They exit if out of memory */
  1350. # define ckrealloc xrealloc
  1351. # define ckmalloc xmalloc
  1352. # define ckzalloc xzalloc
  1353. # define ckstrdup xstrdup
  1354. #endif
  1355. /*
  1356. * It appears that grabstackstr() will barf with such alignments
  1357. * because stalloc() will return a string allocated in a new stackblock.
  1358. */
  1359. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1360. enum {
  1361. /* Most machines require the value returned from malloc to be aligned
  1362. * in some way. The following macro will get this right
  1363. * on many machines. */
  1364. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1365. /* Minimum size of a block */
  1366. MINSIZE = SHELL_ALIGN(504),
  1367. };
  1368. struct stack_block {
  1369. struct stack_block *prev;
  1370. char space[MINSIZE];
  1371. };
  1372. struct stackmark {
  1373. struct stack_block *stackp;
  1374. char *stacknxt;
  1375. size_t stacknleft;
  1376. };
  1377. struct globals_memstack {
  1378. struct stack_block *g_stackp; // = &stackbase;
  1379. char *g_stacknxt; // = stackbase.space;
  1380. char *sstrend; // = stackbase.space + MINSIZE;
  1381. size_t g_stacknleft; // = MINSIZE;
  1382. struct stack_block stackbase;
  1383. };
  1384. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1385. #define G_memstack (*ash_ptr_to_globals_memstack)
  1386. #define g_stackp (G_memstack.g_stackp )
  1387. #define g_stacknxt (G_memstack.g_stacknxt )
  1388. #define sstrend (G_memstack.sstrend )
  1389. #define g_stacknleft (G_memstack.g_stacknleft)
  1390. #define stackbase (G_memstack.stackbase )
  1391. #define INIT_G_memstack() do { \
  1392. (*(struct globals_memstack**)not_const_pp(&ash_ptr_to_globals_memstack)) = xzalloc(sizeof(G_memstack)); \
  1393. barrier(); \
  1394. g_stackp = &stackbase; \
  1395. g_stacknxt = stackbase.space; \
  1396. g_stacknleft = MINSIZE; \
  1397. sstrend = stackbase.space + MINSIZE; \
  1398. } while (0)
  1399. #define stackblock() ((void *)g_stacknxt)
  1400. #define stackblocksize() g_stacknleft
  1401. /*
  1402. * Parse trees for commands are allocated in lifo order, so we use a stack
  1403. * to make this more efficient, and also to avoid all sorts of exception
  1404. * handling code to handle interrupts in the middle of a parse.
  1405. *
  1406. * The size 504 was chosen because the Ultrix malloc handles that size
  1407. * well.
  1408. */
  1409. static void *
  1410. stalloc(size_t nbytes)
  1411. {
  1412. char *p;
  1413. size_t aligned;
  1414. aligned = SHELL_ALIGN(nbytes);
  1415. if (aligned > g_stacknleft) {
  1416. size_t len;
  1417. size_t blocksize;
  1418. struct stack_block *sp;
  1419. blocksize = aligned;
  1420. if (blocksize < MINSIZE)
  1421. blocksize = MINSIZE;
  1422. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1423. if (len < blocksize)
  1424. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1425. INT_OFF;
  1426. sp = ckmalloc(len);
  1427. sp->prev = g_stackp;
  1428. g_stacknxt = sp->space;
  1429. g_stacknleft = blocksize;
  1430. sstrend = g_stacknxt + blocksize;
  1431. g_stackp = sp;
  1432. INT_ON;
  1433. }
  1434. p = g_stacknxt;
  1435. g_stacknxt += aligned;
  1436. g_stacknleft -= aligned;
  1437. return p;
  1438. }
  1439. static void *
  1440. stzalloc(size_t nbytes)
  1441. {
  1442. return memset(stalloc(nbytes), 0, nbytes);
  1443. }
  1444. static void
  1445. stunalloc(void *p)
  1446. {
  1447. #if DEBUG
  1448. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1449. write(STDERR_FILENO, "stunalloc\n", 10);
  1450. abort();
  1451. }
  1452. #endif
  1453. g_stacknleft += g_stacknxt - (char *)p;
  1454. g_stacknxt = p;
  1455. }
  1456. /*
  1457. * Like strdup but works with the ash stack.
  1458. */
  1459. static char *
  1460. sstrdup(const char *p)
  1461. {
  1462. size_t len = strlen(p) + 1;
  1463. return memcpy(stalloc(len), p, len);
  1464. }
  1465. static ALWAYS_INLINE void
  1466. grabstackblock(size_t len)
  1467. {
  1468. stalloc(len);
  1469. }
  1470. static void
  1471. pushstackmark(struct stackmark *mark, size_t len)
  1472. {
  1473. mark->stackp = g_stackp;
  1474. mark->stacknxt = g_stacknxt;
  1475. mark->stacknleft = g_stacknleft;
  1476. grabstackblock(len);
  1477. }
  1478. static void
  1479. setstackmark(struct stackmark *mark)
  1480. {
  1481. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1482. }
  1483. static void
  1484. popstackmark(struct stackmark *mark)
  1485. {
  1486. struct stack_block *sp;
  1487. if (!mark->stackp)
  1488. return;
  1489. INT_OFF;
  1490. while (g_stackp != mark->stackp) {
  1491. sp = g_stackp;
  1492. g_stackp = sp->prev;
  1493. free(sp);
  1494. }
  1495. g_stacknxt = mark->stacknxt;
  1496. g_stacknleft = mark->stacknleft;
  1497. sstrend = mark->stacknxt + mark->stacknleft;
  1498. INT_ON;
  1499. }
  1500. /*
  1501. * When the parser reads in a string, it wants to stick the string on the
  1502. * stack and only adjust the stack pointer when it knows how big the
  1503. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1504. * of space on top of the stack and stackblocklen returns the length of
  1505. * this block. Growstackblock will grow this space by at least one byte,
  1506. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1507. * part of the block that has been used.
  1508. */
  1509. static void
  1510. growstackblock(size_t min)
  1511. {
  1512. size_t newlen;
  1513. newlen = g_stacknleft * 2;
  1514. if (newlen < g_stacknleft)
  1515. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1516. min = SHELL_ALIGN(min | 128);
  1517. if (newlen < min)
  1518. newlen += min;
  1519. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1520. struct stack_block *sp;
  1521. struct stack_block *prevstackp;
  1522. size_t grosslen;
  1523. INT_OFF;
  1524. sp = g_stackp;
  1525. prevstackp = sp->prev;
  1526. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1527. sp = ckrealloc(sp, grosslen);
  1528. sp->prev = prevstackp;
  1529. g_stackp = sp;
  1530. g_stacknxt = sp->space;
  1531. g_stacknleft = newlen;
  1532. sstrend = sp->space + newlen;
  1533. INT_ON;
  1534. } else {
  1535. char *oldspace = g_stacknxt;
  1536. size_t oldlen = g_stacknleft;
  1537. char *p = stalloc(newlen);
  1538. /* free the space we just allocated */
  1539. g_stacknxt = memcpy(p, oldspace, oldlen);
  1540. g_stacknleft += newlen;
  1541. }
  1542. }
  1543. /*
  1544. * The following routines are somewhat easier to use than the above.
  1545. * The user declares a variable of type STACKSTR, which may be declared
  1546. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1547. * the user uses the macro STPUTC to add characters to the string. In
  1548. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1549. * grown as necessary. When the user is done, she can just leave the
  1550. * string there and refer to it using stackblock(). Or she can allocate
  1551. * the space for it using grabstackstr(). If it is necessary to allow
  1552. * someone else to use the stack temporarily and then continue to grow
  1553. * the string, the user should use grabstack to allocate the space, and
  1554. * then call ungrabstr(p) to return to the previous mode of operation.
  1555. *
  1556. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1557. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1558. * is space for at least one character.
  1559. */
  1560. static void *
  1561. growstackstr(void)
  1562. {
  1563. size_t len = stackblocksize();
  1564. growstackblock(0);
  1565. return (char *)stackblock() + len;
  1566. }
  1567. static char *
  1568. growstackto(size_t len)
  1569. {
  1570. if (stackblocksize() < len)
  1571. growstackblock(len);
  1572. return stackblock();
  1573. }
  1574. /*
  1575. * Called from CHECKSTRSPACE.
  1576. */
  1577. static char *
  1578. makestrspace(size_t newlen, char *p)
  1579. {
  1580. size_t len = p - g_stacknxt;
  1581. return growstackto(len + newlen) + len;
  1582. }
  1583. static char *
  1584. stnputs(const char *s, size_t n, char *p)
  1585. {
  1586. p = makestrspace(n, p);
  1587. p = (char *)mempcpy(p, s, n);
  1588. return p;
  1589. }
  1590. static char *
  1591. stack_putstr(const char *s, char *p)
  1592. {
  1593. return stnputs(s, strlen(s), p);
  1594. }
  1595. static char *
  1596. _STPUTC(int c, char *p)
  1597. {
  1598. if (p == sstrend)
  1599. p = growstackstr();
  1600. *p++ = c;
  1601. return p;
  1602. }
  1603. #define STARTSTACKSTR(p) ((p) = stackblock())
  1604. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1605. #define CHECKSTRSPACE(n, p) do { \
  1606. char *q = (p); \
  1607. size_t l = (n); \
  1608. size_t m = sstrend - q; \
  1609. if (l > m) \
  1610. (p) = makestrspace(l, q); \
  1611. } while (0)
  1612. #define USTPUTC(c, p) (*(p)++ = (c))
  1613. #define STACKSTRNUL(p) do { \
  1614. if ((p) == sstrend) \
  1615. (p) = growstackstr(); \
  1616. *(p) = '\0'; \
  1617. } while (0)
  1618. #define STUNPUTC(p) (--(p))
  1619. #define STTOPC(p) ((p)[-1])
  1620. #define STADJUST(amount, p) ((p) += (amount))
  1621. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1622. #define ungrabstackstr(s, p) stunalloc(s)
  1623. #define stackstrend() ((void *)sstrend)
  1624. /* ============ String helpers */
  1625. /*
  1626. * prefix -- see if pfx is a prefix of string.
  1627. */
  1628. static char *
  1629. prefix(const char *string, const char *pfx)
  1630. {
  1631. while (*pfx) {
  1632. if (*pfx++ != *string++)
  1633. return NULL;
  1634. }
  1635. return (char *) string;
  1636. }
  1637. /*
  1638. * Check for a valid number. This should be elsewhere.
  1639. */
  1640. static int
  1641. is_number(const char *p)
  1642. {
  1643. do {
  1644. if (!isdigit(*p))
  1645. return 0;
  1646. } while (*++p != '\0');
  1647. return 1;
  1648. }
  1649. /*
  1650. * Convert a string of digits to an integer, printing an error message on
  1651. * failure.
  1652. */
  1653. static int
  1654. number(const char *s)
  1655. {
  1656. if (!is_number(s))
  1657. ash_msg_and_raise_error(msg_illnum, s);
  1658. return atoi(s);
  1659. }
  1660. /*
  1661. * Produce a single quoted string suitable as input to the shell.
  1662. * The return string is allocated on the stack.
  1663. */
  1664. static char *
  1665. single_quote(const char *s)
  1666. {
  1667. char *p;
  1668. STARTSTACKSTR(p);
  1669. do {
  1670. char *q;
  1671. size_t len;
  1672. len = strchrnul(s, '\'') - s;
  1673. q = p = makestrspace(len + 3, p);
  1674. *q++ = '\'';
  1675. q = (char *)mempcpy(q, s, len);
  1676. *q++ = '\'';
  1677. s += len;
  1678. STADJUST(q - p, p);
  1679. if (*s != '\'')
  1680. break;
  1681. len = 0;
  1682. do len++; while (*++s == '\'');
  1683. q = p = makestrspace(len + 3, p);
  1684. *q++ = '"';
  1685. q = (char *)mempcpy(q, s - len, len);
  1686. *q++ = '"';
  1687. STADJUST(q - p, p);
  1688. } while (*s);
  1689. USTPUTC('\0', p);
  1690. return stackblock();
  1691. }
  1692. /*
  1693. * Produce a possibly single quoted string suitable as input to the shell.
  1694. * If quoting was done, the return string is allocated on the stack,
  1695. * otherwise a pointer to the original string is returned.
  1696. */
  1697. static const char *
  1698. maybe_single_quote(const char *s)
  1699. {
  1700. const char *p = s;
  1701. while (*p) {
  1702. /* Assuming ACSII */
  1703. /* quote ctrl_chars space !"#$%&'()* */
  1704. if (*p < '+')
  1705. goto need_quoting;
  1706. /* quote ;<=>? */
  1707. if (*p >= ';' && *p <= '?')
  1708. goto need_quoting;
  1709. /* quote `[\ */
  1710. if (*p == '`')
  1711. goto need_quoting;
  1712. if (*p == '[')
  1713. goto need_quoting;
  1714. if (*p == '\\')
  1715. goto need_quoting;
  1716. /* quote {|}~ DEL and high bytes */
  1717. if (*p > 'z')
  1718. goto need_quoting;
  1719. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1720. /* TODO: maybe avoid quoting % */
  1721. p++;
  1722. }
  1723. return s;
  1724. need_quoting:
  1725. return single_quote(s);
  1726. }
  1727. /* ============ nextopt */
  1728. static char **argptr; /* argument list for builtin commands */
  1729. static char *optionarg; /* set by nextopt (like getopt) */
  1730. static char *optptr; /* used by nextopt */
  1731. /*
  1732. * XXX - should get rid of. Have all builtins use getopt(3).
  1733. * The library getopt must have the BSD extension static variable
  1734. * "optreset", otherwise it can't be used within the shell safely.
  1735. *
  1736. * Standard option processing (a la getopt) for builtin routines.
  1737. * The only argument that is passed to nextopt is the option string;
  1738. * the other arguments are unnecessary. It returns the character,
  1739. * or '\0' on end of input.
  1740. */
  1741. static int
  1742. nextopt(const char *optstring)
  1743. {
  1744. char *p;
  1745. const char *q;
  1746. char c;
  1747. p = optptr;
  1748. if (p == NULL || *p == '\0') {
  1749. /* We ate entire "-param", take next one */
  1750. p = *argptr;
  1751. if (p == NULL)
  1752. return '\0';
  1753. if (*p != '-')
  1754. return '\0';
  1755. if (*++p == '\0') /* just "-" ? */
  1756. return '\0';
  1757. argptr++;
  1758. if (LONE_DASH(p)) /* "--" ? */
  1759. return '\0';
  1760. /* p => next "-param" */
  1761. }
  1762. /* p => some option char in the middle of a "-param" */
  1763. c = *p++;
  1764. for (q = optstring; *q != c;) {
  1765. if (*q == '\0')
  1766. ash_msg_and_raise_error("illegal option -%c", c);
  1767. if (*++q == ':')
  1768. q++;
  1769. }
  1770. if (*++q == ':') {
  1771. if (*p == '\0') {
  1772. p = *argptr++;
  1773. if (p == NULL)
  1774. ash_msg_and_raise_error("no arg for -%c option", c);
  1775. }
  1776. optionarg = p;
  1777. p = NULL;
  1778. }
  1779. optptr = p;
  1780. return c;
  1781. }
  1782. /* ============ Shell variables */
  1783. struct shparam {
  1784. int nparam; /* # of positional parameters (without $0) */
  1785. #if ENABLE_ASH_GETOPTS
  1786. int optind; /* next parameter to be processed by getopts */
  1787. int optoff; /* used by getopts */
  1788. #endif
  1789. unsigned char malloced; /* if parameter list dynamically allocated */
  1790. char **p; /* parameter list */
  1791. };
  1792. /*
  1793. * Free the list of positional parameters.
  1794. */
  1795. static void
  1796. freeparam(volatile struct shparam *param)
  1797. {
  1798. if (param->malloced) {
  1799. char **ap, **ap1;
  1800. ap = ap1 = param->p;
  1801. while (*ap)
  1802. free(*ap++);
  1803. free(ap1);
  1804. }
  1805. }
  1806. #if ENABLE_ASH_GETOPTS
  1807. static void FAST_FUNC getoptsreset(const char *value);
  1808. #endif
  1809. struct var {
  1810. struct var *next; /* next entry in hash list */
  1811. int flags; /* flags are defined above */
  1812. const char *var_text; /* name=value */
  1813. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1814. /* the variable gets set/unset */
  1815. };
  1816. struct localvar {
  1817. struct localvar *next; /* next local variable in list */
  1818. struct var *vp; /* the variable that was made local */
  1819. int flags; /* saved flags */
  1820. const char *text; /* saved text */
  1821. };
  1822. /* flags */
  1823. #define VEXPORT 0x01 /* variable is exported */
  1824. #define VREADONLY 0x02 /* variable cannot be modified */
  1825. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1826. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1827. #define VSTACK 0x10 /* text is allocated on the stack */
  1828. #define VUNSET 0x20 /* the variable is not set */
  1829. #define VNOFUNC 0x40 /* don't call the callback function */
  1830. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1831. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1832. #if ENABLE_ASH_RANDOM_SUPPORT
  1833. # define VDYNAMIC 0x200 /* dynamic variable */
  1834. #else
  1835. # define VDYNAMIC 0
  1836. #endif
  1837. /* Need to be before varinit_data[] */
  1838. #if ENABLE_LOCALE_SUPPORT
  1839. static void FAST_FUNC
  1840. change_lc_all(const char *value)
  1841. {
  1842. if (value && *value != '\0')
  1843. setlocale(LC_ALL, value);
  1844. }
  1845. static void FAST_FUNC
  1846. change_lc_ctype(const char *value)
  1847. {
  1848. if (value && *value != '\0')
  1849. setlocale(LC_CTYPE, value);
  1850. }
  1851. #endif
  1852. #if ENABLE_ASH_MAIL
  1853. static void chkmail(void);
  1854. static void changemail(const char *var_value) FAST_FUNC;
  1855. #else
  1856. # define chkmail() ((void)0)
  1857. #endif
  1858. static void changepath(const char *) FAST_FUNC;
  1859. #if ENABLE_ASH_RANDOM_SUPPORT
  1860. static void change_random(const char *) FAST_FUNC;
  1861. #endif
  1862. #if BASH_EPOCH_VARS
  1863. static void change_seconds(const char *) FAST_FUNC;
  1864. static void change_realtime(const char *) FAST_FUNC;
  1865. #endif
  1866. static const struct {
  1867. int flags;
  1868. const char *var_text;
  1869. void (*var_func)(const char *) FAST_FUNC;
  1870. } varinit_data[] = {
  1871. /*
  1872. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1873. * some environment strings may be constant.
  1874. */
  1875. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1876. #if ENABLE_ASH_MAIL
  1877. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1878. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1879. #endif
  1880. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1881. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1882. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1883. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1884. #if ENABLE_ASH_GETOPTS
  1885. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1886. #endif
  1887. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1888. #if ENABLE_ASH_RANDOM_SUPPORT
  1889. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1890. #endif
  1891. #if BASH_EPOCH_VARS
  1892. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
  1893. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
  1894. #endif
  1895. #if ENABLE_LOCALE_SUPPORT
  1896. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1897. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1898. #endif
  1899. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1900. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1901. #endif
  1902. };
  1903. struct redirtab;
  1904. struct globals_var {
  1905. struct shparam shellparam; /* $@ current positional parameters */
  1906. struct redirtab *redirlist;
  1907. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1908. struct var *vartab[VTABSIZE];
  1909. struct var varinit[ARRAY_SIZE(varinit_data)];
  1910. int lineno;
  1911. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1912. };
  1913. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1914. #define G_var (*ash_ptr_to_globals_var)
  1915. #define shellparam (G_var.shellparam )
  1916. //#define redirlist (G_var.redirlist )
  1917. #define preverrout_fd (G_var.preverrout_fd)
  1918. #define vartab (G_var.vartab )
  1919. #define varinit (G_var.varinit )
  1920. #define lineno (G_var.lineno )
  1921. #define linenovar (G_var.linenovar )
  1922. #define vifs varinit[0]
  1923. #if ENABLE_ASH_MAIL
  1924. # define vmail varinit[1]
  1925. # define vmpath varinit[2]
  1926. #endif
  1927. #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
  1928. #define vpath varinit[VAR_OFFSET1 + 1]
  1929. #define vps1 varinit[VAR_OFFSET1 + 2]
  1930. #define vps2 varinit[VAR_OFFSET1 + 3]
  1931. #define vps4 varinit[VAR_OFFSET1 + 4]
  1932. #if ENABLE_ASH_GETOPTS
  1933. # define voptind varinit[VAR_OFFSET1 + 5]
  1934. #endif
  1935. #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
  1936. #define vlineno varinit[VAR_OFFSET2 + 5]
  1937. #if ENABLE_ASH_RANDOM_SUPPORT
  1938. # define vrandom varinit[VAR_OFFSET2 + 6]
  1939. #endif
  1940. #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
  1941. #if BASH_EPOCH_VARS
  1942. # define vepochs varinit[VAR_OFFSET3 + 6]
  1943. # define vepochr varinit[VAR_OFFSET3 + 7]
  1944. #endif
  1945. #define INIT_G_var() do { \
  1946. unsigned i; \
  1947. (*(struct globals_var**)not_const_pp(&ash_ptr_to_globals_var)) = xzalloc(sizeof(G_var)); \
  1948. barrier(); \
  1949. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1950. varinit[i].flags = varinit_data[i].flags; \
  1951. varinit[i].var_text = varinit_data[i].var_text; \
  1952. varinit[i].var_func = varinit_data[i].var_func; \
  1953. } \
  1954. strcpy(linenovar, "LINENO="); \
  1955. vlineno.var_text = linenovar; \
  1956. } while (0)
  1957. /*
  1958. * The following macros access the values of the above variables.
  1959. * They have to skip over the name. They return the null string
  1960. * for unset variables.
  1961. */
  1962. #define ifsval() (vifs.var_text + 4)
  1963. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1964. #if ENABLE_ASH_MAIL
  1965. # define mailval() (vmail.var_text + 5)
  1966. # define mpathval() (vmpath.var_text + 9)
  1967. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1968. #endif
  1969. #define pathval() (vpath.var_text + 5)
  1970. #define ps1val() (vps1.var_text + 4)
  1971. #define ps2val() (vps2.var_text + 4)
  1972. #define ps4val() (vps4.var_text + 4)
  1973. #if ENABLE_ASH_GETOPTS
  1974. # define optindval() (voptind.var_text + 7)
  1975. #endif
  1976. #if ENABLE_ASH_GETOPTS
  1977. static void FAST_FUNC
  1978. getoptsreset(const char *value)
  1979. {
  1980. shellparam.optind = 1;
  1981. if (is_number(value))
  1982. shellparam.optind = number(value) ?: 1;
  1983. shellparam.optoff = -1;
  1984. }
  1985. #endif
  1986. /*
  1987. * Compares two strings up to the first = or '\0'. The first
  1988. * string must be terminated by '='; the second may be terminated by
  1989. * either '=' or '\0'.
  1990. */
  1991. static int
  1992. varcmp(const char *p, const char *q)
  1993. {
  1994. int c, d;
  1995. while ((c = *p) == (d = *q)) {
  1996. if (c == '\0' || c == '=')
  1997. goto out;
  1998. p++;
  1999. q++;
  2000. }
  2001. if (c == '=')
  2002. c = '\0';
  2003. if (d == '=')
  2004. d = '\0';
  2005. out:
  2006. return c - d;
  2007. }
  2008. /*
  2009. * Find the appropriate entry in the hash table from the name.
  2010. */
  2011. static struct var **
  2012. hashvar(const char *p)
  2013. {
  2014. unsigned hashval;
  2015. hashval = ((unsigned char) *p) << 4;
  2016. while (*p && *p != '=')
  2017. hashval += (unsigned char) *p++;
  2018. return &vartab[hashval % VTABSIZE];
  2019. }
  2020. static int
  2021. vpcmp(const void *a, const void *b)
  2022. {
  2023. return varcmp(*(const char **)a, *(const char **)b);
  2024. }
  2025. /*
  2026. * This routine initializes the builtin variables.
  2027. */
  2028. static void
  2029. initvar(void)
  2030. {
  2031. struct var *vp;
  2032. struct var *end;
  2033. struct var **vpp;
  2034. /*
  2035. * PS1 depends on uid
  2036. */
  2037. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2038. vps1.var_text = "PS1=\\w \\$ ";
  2039. #else
  2040. if (!geteuid())
  2041. vps1.var_text = "PS1=# ";
  2042. #endif
  2043. vp = varinit;
  2044. end = vp + ARRAY_SIZE(varinit);
  2045. do {
  2046. vpp = hashvar(vp->var_text);
  2047. vp->next = *vpp;
  2048. *vpp = vp;
  2049. } while (++vp < end);
  2050. }
  2051. static struct var **
  2052. findvar(struct var **vpp, const char *name)
  2053. {
  2054. for (; *vpp; vpp = &(*vpp)->next) {
  2055. if (varcmp((*vpp)->var_text, name) == 0) {
  2056. break;
  2057. }
  2058. }
  2059. return vpp;
  2060. }
  2061. /*
  2062. * Find the value of a variable. Returns NULL if not set.
  2063. */
  2064. static const char* FAST_FUNC
  2065. lookupvar(const char *name)
  2066. {
  2067. struct var *v;
  2068. v = *findvar(hashvar(name), name);
  2069. if (v) {
  2070. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2071. /*
  2072. * Dynamic variables are implemented roughly the same way they are
  2073. * in bash. Namely, they're "special" so long as they aren't unset.
  2074. * As soon as they're unset, they're no longer dynamic, and dynamic
  2075. * lookup will no longer happen at that point. -- PFM.
  2076. */
  2077. if (v->flags & VDYNAMIC)
  2078. v->var_func(NULL);
  2079. #endif
  2080. if (!(v->flags & VUNSET)) {
  2081. if (v == &vlineno && v->var_text == linenovar) {
  2082. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2083. }
  2084. return var_end(v->var_text);
  2085. }
  2086. }
  2087. return NULL;
  2088. }
  2089. #if ENABLE_UNICODE_SUPPORT
  2090. static void
  2091. reinit_unicode_for_ash(void)
  2092. {
  2093. /* Unicode support should be activated even if LANG is set
  2094. * _during_ shell execution, not only if it was set when
  2095. * shell was started. Therefore, re-check LANG every time:
  2096. */
  2097. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2098. || ENABLE_UNICODE_USING_LOCALE
  2099. ) {
  2100. const char *s = lookupvar("LC_ALL");
  2101. if (!s) s = lookupvar("LC_CTYPE");
  2102. if (!s) s = lookupvar("LANG");
  2103. reinit_unicode(s);
  2104. }
  2105. }
  2106. #else
  2107. # define reinit_unicode_for_ash() ((void)0)
  2108. #endif
  2109. /*
  2110. * Search the environment of a builtin command.
  2111. */
  2112. static ALWAYS_INLINE const char *
  2113. bltinlookup(const char *name)
  2114. {
  2115. return lookupvar(name);
  2116. }
  2117. /*
  2118. * Same as setvar except that the variable and value are passed in
  2119. * the first argument as name=value. Since the first argument will
  2120. * be actually stored in the table, it should not be a string that
  2121. * will go away.
  2122. * Called with interrupts off.
  2123. */
  2124. static struct var *
  2125. setvareq(char *s, int flags)
  2126. {
  2127. struct var *vp, **vpp;
  2128. vpp = hashvar(s);
  2129. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2130. vpp = findvar(vpp, s);
  2131. vp = *vpp;
  2132. if (vp) {
  2133. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2134. const char *n;
  2135. if (flags & VNOSAVE)
  2136. free(s);
  2137. n = vp->var_text;
  2138. exitstatus = 1;
  2139. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2140. }
  2141. if (flags & VNOSET)
  2142. goto out;
  2143. if (vp->var_func && !(flags & VNOFUNC))
  2144. vp->var_func(var_end(s));
  2145. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2146. free((char*)vp->var_text);
  2147. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2148. *vpp = vp->next;
  2149. free(vp);
  2150. out_free:
  2151. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2152. free(s);
  2153. goto out;
  2154. }
  2155. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2156. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2157. if (flags & VUNSET)
  2158. flags &= ~VDYNAMIC;
  2159. #endif
  2160. } else {
  2161. /* variable s is not found */
  2162. if (flags & VNOSET)
  2163. goto out;
  2164. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2165. goto out_free;
  2166. vp = ckzalloc(sizeof(*vp));
  2167. vp->next = *vpp;
  2168. /*vp->func = NULL; - ckzalloc did it */
  2169. *vpp = vp;
  2170. }
  2171. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2172. s = ckstrdup(s);
  2173. vp->var_text = s;
  2174. vp->flags = flags;
  2175. out:
  2176. return vp;
  2177. }
  2178. /*
  2179. * Set the value of a variable. The flags argument is ored with the
  2180. * flags of the variable. If val is NULL, the variable is unset.
  2181. */
  2182. static struct var *
  2183. setvar(const char *name, const char *val, int flags)
  2184. {
  2185. const char *q;
  2186. char *p;
  2187. char *nameeq;
  2188. size_t namelen;
  2189. size_t vallen;
  2190. struct var *vp;
  2191. q = endofname(name);
  2192. p = strchrnul(q, '=');
  2193. namelen = p - name;
  2194. if (!namelen || p != q)
  2195. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2196. vallen = 0;
  2197. if (val == NULL) {
  2198. flags |= VUNSET;
  2199. } else {
  2200. vallen = strlen(val);
  2201. }
  2202. INT_OFF;
  2203. nameeq = ckzalloc(namelen + vallen + 2);
  2204. p = mempcpy(nameeq, name, namelen);
  2205. if (val) {
  2206. *p++ = '=';
  2207. memcpy(p, val, vallen);
  2208. }
  2209. vp = setvareq(nameeq, flags | VNOSAVE);
  2210. INT_ON;
  2211. return vp;
  2212. }
  2213. static void FAST_FUNC
  2214. setvar0(const char *name, const char *val)
  2215. {
  2216. setvar(name, val, 0);
  2217. }
  2218. /*
  2219. * Unset the specified variable.
  2220. */
  2221. static void
  2222. unsetvar(const char *s)
  2223. {
  2224. setvar(s, NULL, 0);
  2225. }
  2226. /*
  2227. * Generate a list of variables satisfying the given conditions.
  2228. */
  2229. #if !ENABLE_FEATURE_SH_NOFORK
  2230. # define listvars(on, off, lp, end) listvars(on, off, end)
  2231. #endif
  2232. static char **
  2233. listvars(int on, int off, struct strlist *lp, char ***end)
  2234. {
  2235. struct var **vpp;
  2236. struct var *vp;
  2237. char **ep;
  2238. int mask;
  2239. STARTSTACKSTR(ep);
  2240. vpp = vartab;
  2241. mask = on | off;
  2242. do {
  2243. for (vp = *vpp; vp; vp = vp->next) {
  2244. if ((vp->flags & mask) == on) {
  2245. #if ENABLE_FEATURE_SH_NOFORK
  2246. /* If variable with the same name is both
  2247. * exported and temporarily set for a command:
  2248. * export ZVAR=5
  2249. * ZVAR=6 printenv
  2250. * then "ZVAR=6" will be both in vartab and
  2251. * lp lists. Do not pass it twice to printenv.
  2252. */
  2253. struct strlist *lp1 = lp;
  2254. while (lp1) {
  2255. if (strcmp(lp1->text, vp->var_text) == 0)
  2256. goto skip;
  2257. lp1 = lp1->next;
  2258. }
  2259. #endif
  2260. if (ep == stackstrend())
  2261. ep = growstackstr();
  2262. *ep++ = (char*)vp->var_text;
  2263. #if ENABLE_FEATURE_SH_NOFORK
  2264. skip: ;
  2265. #endif
  2266. }
  2267. }
  2268. } while (++vpp < vartab + VTABSIZE);
  2269. #if ENABLE_FEATURE_SH_NOFORK
  2270. while (lp) {
  2271. if (ep == stackstrend())
  2272. ep = growstackstr();
  2273. *ep++ = lp->text;
  2274. lp = lp->next;
  2275. }
  2276. #endif
  2277. if (ep == stackstrend())
  2278. ep = growstackstr();
  2279. if (end)
  2280. *end = ep;
  2281. *ep++ = NULL;
  2282. return grabstackstr(ep);
  2283. }
  2284. /* ============ Path search helper */
  2285. static const char *
  2286. legal_pathopt(const char *opt, const char *term, int magic)
  2287. {
  2288. switch (magic) {
  2289. case 0:
  2290. opt = NULL;
  2291. break;
  2292. case 1:
  2293. opt = prefix(opt, "builtin") ?: prefix(opt, "func");
  2294. break;
  2295. default:
  2296. opt += strcspn(opt, term);
  2297. break;
  2298. }
  2299. if (opt && *opt == '%')
  2300. opt++;
  2301. return opt;
  2302. }
  2303. /*
  2304. * The variable path (passed by reference) should be set to the start
  2305. * of the path before the first call; padvance will update
  2306. * this value as it proceeds. Successive calls to padvance will return
  2307. * the possible path expansions in sequence. If an option (indicated by
  2308. * a percent sign) appears in the path entry then the global variable
  2309. * pathopt will be set to point to it; otherwise pathopt will be set to
  2310. * NULL.
  2311. *
  2312. * If magic is 0 then pathopt recognition will be disabled. If magic is
  2313. * 1 we shall recognise %builtin/%func. Otherwise we shall accept any
  2314. * pathopt.
  2315. */
  2316. static const char *pathopt; /* set by padvance */
  2317. static int
  2318. padvance_magic(const char **path, const char *name, int magic)
  2319. {
  2320. const char *term = "%:";
  2321. const char *lpathopt;
  2322. const char *p;
  2323. char *q;
  2324. const char *start;
  2325. size_t qlen;
  2326. size_t len;
  2327. if (*path == NULL)
  2328. return -1;
  2329. lpathopt = NULL;
  2330. start = *path;
  2331. if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) {
  2332. lpathopt = start + 1;
  2333. start = p;
  2334. term = ":";
  2335. }
  2336. len = strcspn(start, term);
  2337. p = start + len;
  2338. if (*p == '%') {
  2339. size_t extra = strchrnul(p, ':') - p;
  2340. if (legal_pathopt(p + 1, term, magic))
  2341. lpathopt = p + 1;
  2342. else
  2343. len += extra;
  2344. p += extra;
  2345. }
  2346. pathopt = lpathopt;
  2347. *path = *p == ':' ? p + 1 : NULL;
  2348. /* "2" is for '/' and '\0' */
  2349. qlen = len + strlen(name) + 2;
  2350. q = growstackto(qlen);
  2351. if (len) {
  2352. q = mempcpy(q, start, len);
  2353. *q++ = '/';
  2354. }
  2355. strcpy(q, name);
  2356. return qlen;
  2357. }
  2358. static int
  2359. padvance(const char **path, const char *name)
  2360. {
  2361. return padvance_magic(path, name, 1);
  2362. }
  2363. /* ============ Prompt */
  2364. static smallint doprompt; /* if set, prompt the user */
  2365. static smallint needprompt; /* true if interactive and at start of line */
  2366. #if ENABLE_FEATURE_EDITING
  2367. static line_input_t *line_input_state;
  2368. static const char *cmdedit_prompt;
  2369. static void
  2370. putprompt(const char *s)
  2371. {
  2372. if (ENABLE_ASH_EXPAND_PRMT) {
  2373. free((char*)cmdedit_prompt);
  2374. cmdedit_prompt = ckstrdup(s);
  2375. return;
  2376. }
  2377. cmdedit_prompt = s;
  2378. }
  2379. #else
  2380. static void
  2381. putprompt(const char *s)
  2382. {
  2383. out2str(s);
  2384. }
  2385. #endif
  2386. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2387. static const char *expandstr(const char *ps, int syntax_type);
  2388. /* Values for syntax param */
  2389. #define BASESYNTAX 0 /* not in quotes */
  2390. #define DQSYNTAX 1 /* in double quotes */
  2391. #define SQSYNTAX 2 /* in single quotes */
  2392. #define ARISYNTAX 3 /* in arithmetic */
  2393. #if ENABLE_ASH_EXPAND_PRMT
  2394. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2395. #endif
  2396. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2397. /*
  2398. * called by editline -- any expansions to the prompt should be added here.
  2399. */
  2400. static void
  2401. setprompt_if(smallint do_set, int whichprompt)
  2402. {
  2403. const char *prompt;
  2404. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2405. if (!do_set)
  2406. return;
  2407. needprompt = 0;
  2408. switch (whichprompt) {
  2409. case 1:
  2410. prompt = ps1val();
  2411. break;
  2412. case 2:
  2413. prompt = ps2val();
  2414. break;
  2415. default: /* 0 */
  2416. prompt = nullstr;
  2417. }
  2418. #if ENABLE_ASH_EXPAND_PRMT
  2419. pushstackmark(&smark, stackblocksize());
  2420. putprompt(expandstr(prompt, PSSYNTAX));
  2421. popstackmark(&smark);
  2422. #else
  2423. putprompt(prompt);
  2424. #endif
  2425. }
  2426. /* ============ The cd and pwd commands */
  2427. #define CD_PHYSICAL 1
  2428. #define CD_PRINT 2
  2429. static int
  2430. cdopt(void)
  2431. {
  2432. int flags = 0;
  2433. int i, j;
  2434. j = 'L';
  2435. while ((i = nextopt("LP")) != '\0') {
  2436. if (i != j) {
  2437. flags ^= CD_PHYSICAL;
  2438. j = i;
  2439. }
  2440. }
  2441. return flags;
  2442. }
  2443. /*
  2444. * Update curdir (the name of the current directory) in response to a
  2445. * cd command.
  2446. */
  2447. static const char *
  2448. updatepwd(const char *dir)
  2449. {
  2450. char *new;
  2451. char *p;
  2452. char *cdcomppath;
  2453. const char *lim;
  2454. cdcomppath = sstrdup(dir);
  2455. STARTSTACKSTR(new);
  2456. if (*dir != '/') {
  2457. if (curdir == nullstr)
  2458. return 0;
  2459. new = stack_putstr(curdir, new);
  2460. }
  2461. new = makestrspace(strlen(dir) + 2, new);
  2462. lim = (char *)stackblock() + 1;
  2463. if (*dir != '/') {
  2464. if (new[-1] != '/')
  2465. USTPUTC('/', new);
  2466. if (new > lim && *lim == '/')
  2467. lim++;
  2468. } else {
  2469. USTPUTC('/', new);
  2470. cdcomppath++;
  2471. if (dir[1] == '/' && dir[2] != '/') {
  2472. USTPUTC('/', new);
  2473. cdcomppath++;
  2474. lim++;
  2475. }
  2476. }
  2477. p = strtok(cdcomppath, "/");
  2478. while (p) {
  2479. switch (*p) {
  2480. case '.':
  2481. if (p[1] == '.' && p[2] == '\0') {
  2482. while (new > lim) {
  2483. STUNPUTC(new);
  2484. if (new[-1] == '/')
  2485. break;
  2486. }
  2487. break;
  2488. }
  2489. if (p[1] == '\0')
  2490. break;
  2491. /* fall through */
  2492. default:
  2493. new = stack_putstr(p, new);
  2494. USTPUTC('/', new);
  2495. }
  2496. p = strtok(NULL, "/");
  2497. }
  2498. if (new > lim)
  2499. STUNPUTC(new);
  2500. *new = 0;
  2501. return stackblock();
  2502. }
  2503. /*
  2504. * Find out what the current directory is. If we already know the current
  2505. * directory, this routine returns immediately.
  2506. */
  2507. static char *
  2508. getpwd(void)
  2509. {
  2510. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2511. return dir ? dir : nullstr;
  2512. }
  2513. static void
  2514. setpwd(const char *val, int setold)
  2515. {
  2516. char *oldcur, *dir;
  2517. oldcur = dir = curdir;
  2518. if (setold) {
  2519. setvar("OLDPWD", oldcur, VEXPORT);
  2520. }
  2521. INT_OFF;
  2522. if (physdir != nullstr) {
  2523. if (physdir != oldcur)
  2524. free(physdir);
  2525. physdir = nullstr;
  2526. }
  2527. if (oldcur == val || !val) {
  2528. char *s = getpwd();
  2529. physdir = s;
  2530. if (!val)
  2531. dir = s;
  2532. } else
  2533. dir = ckstrdup(val);
  2534. if (oldcur != dir && oldcur != nullstr) {
  2535. free(oldcur);
  2536. }
  2537. curdir = dir;
  2538. INT_ON;
  2539. setvar("PWD", dir, VEXPORT);
  2540. }
  2541. static void hashcd(void);
  2542. /*
  2543. * Actually do the chdir. We also call hashcd to let other routines
  2544. * know that the current directory has changed.
  2545. */
  2546. static int
  2547. docd(const char *dest, int flags)
  2548. {
  2549. const char *dir = NULL;
  2550. int err;
  2551. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2552. INT_OFF;
  2553. if (!(flags & CD_PHYSICAL)) {
  2554. dir = updatepwd(dest);
  2555. if (dir)
  2556. dest = dir;
  2557. }
  2558. err = chdir(dest);
  2559. if (err)
  2560. goto out;
  2561. setpwd(dir, 1);
  2562. hashcd();
  2563. out:
  2564. INT_ON;
  2565. return err;
  2566. }
  2567. static int FAST_FUNC
  2568. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2569. {
  2570. const char *dest;
  2571. const char *path;
  2572. const char *p;
  2573. char c;
  2574. struct stat statb;
  2575. int flags;
  2576. int len;
  2577. flags = cdopt();
  2578. dest = *argptr;
  2579. if (!dest)
  2580. dest = bltinlookup("HOME");
  2581. else if (LONE_DASH(dest)) {
  2582. dest = bltinlookup("OLDPWD");
  2583. flags |= CD_PRINT;
  2584. }
  2585. if (!dest)
  2586. dest = nullstr;
  2587. if (*dest == '/')
  2588. goto step6;
  2589. if (*dest == '.') {
  2590. c = dest[1];
  2591. dotdot:
  2592. switch (c) {
  2593. case '\0':
  2594. case '/':
  2595. goto step6;
  2596. case '.':
  2597. c = dest[2];
  2598. if (c != '.')
  2599. goto dotdot;
  2600. }
  2601. }
  2602. if (!*dest)
  2603. dest = ".";
  2604. path = bltinlookup("CDPATH");
  2605. while (p = path, (len = padvance(&path, dest)) >= 0) {
  2606. c = *p;
  2607. p = stalloc(len);
  2608. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2609. if (c && c != ':')
  2610. flags |= CD_PRINT;
  2611. docd:
  2612. if (!docd(p, flags))
  2613. goto out;
  2614. goto err;
  2615. }
  2616. }
  2617. step6:
  2618. p = dest;
  2619. goto docd;
  2620. err:
  2621. ash_msg_and_raise_perror("can't cd to %s", dest);
  2622. /* NOTREACHED */
  2623. out:
  2624. if (flags & CD_PRINT)
  2625. out1fmt("%s\n", curdir);
  2626. return 0;
  2627. }
  2628. static int FAST_FUNC
  2629. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2630. {
  2631. int flags;
  2632. const char *dir = curdir;
  2633. flags = cdopt();
  2634. if (flags) {
  2635. if (physdir == nullstr)
  2636. setpwd(dir, 0);
  2637. dir = physdir;
  2638. }
  2639. out1fmt("%s\n", dir);
  2640. return 0;
  2641. }
  2642. /* ============ ... */
  2643. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2644. /* Syntax classes */
  2645. #define CWORD 0 /* character is nothing special */
  2646. #define CNL 1 /* newline character */
  2647. #define CBACK 2 /* a backslash character */
  2648. #define CSQUOTE 3 /* single quote */
  2649. #define CDQUOTE 4 /* double quote */
  2650. #define CENDQUOTE 5 /* a terminating quote */
  2651. #define CBQUOTE 6 /* backwards single quote */
  2652. #define CVAR 7 /* a dollar sign */
  2653. #define CENDVAR 8 /* a '}' character */
  2654. #define CLP 9 /* a left paren in arithmetic */
  2655. #define CRP 10 /* a right paren in arithmetic */
  2656. #define CENDFILE 11 /* end of file */
  2657. #define CCTL 12 /* like CWORD, except it must be escaped */
  2658. #define CSPCL 13 /* these terminate a word */
  2659. #define CIGN 14 /* character should be ignored */
  2660. #define PEOF 256
  2661. #if ENABLE_ASH_ALIAS
  2662. # define PEOA 257
  2663. #endif
  2664. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2665. #if ENABLE_FEATURE_SH_MATH
  2666. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2667. #else
  2668. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2669. #endif
  2670. static const uint16_t S_I_T[] ALIGN2 = {
  2671. #if ENABLE_ASH_ALIAS
  2672. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2673. #endif
  2674. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2675. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2676. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2677. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2678. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2679. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2680. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2681. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2682. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2683. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2684. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2685. #if !USE_SIT_FUNCTION
  2686. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2687. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2688. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2689. #endif
  2690. #undef SIT_ITEM
  2691. };
  2692. /* Constants below must match table above */
  2693. enum {
  2694. #if ENABLE_ASH_ALIAS
  2695. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2696. #endif
  2697. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2698. CNL_CNL_CNL_CNL , /* 2 */
  2699. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2700. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2701. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2702. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2703. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2704. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2705. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2706. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2707. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2708. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2709. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2710. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2711. };
  2712. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2713. * caller must ensure proper cast on it if c is *char_ptr!
  2714. */
  2715. #if USE_SIT_FUNCTION
  2716. static int
  2717. SIT(int c, int syntax)
  2718. {
  2719. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2720. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2721. /*
  2722. * This causes '/' to be prepended with CTLESC in dquoted string,
  2723. * making "./file"* treated incorrectly because we feed
  2724. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2725. * The "homegrown" glob implementation is okay with that,
  2726. * but glibc one isn't. With '/' always treated as CWORD,
  2727. * both work fine.
  2728. */
  2729. # if ENABLE_ASH_ALIAS
  2730. static const uint8_t syntax_index_table[] ALIGN1 = {
  2731. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2732. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2733. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2734. 11, 3 /* "}~" */
  2735. };
  2736. # else
  2737. static const uint8_t syntax_index_table[] ALIGN1 = {
  2738. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2739. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2740. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2741. 10, 2 /* "}~" */
  2742. };
  2743. # endif
  2744. const char *s;
  2745. int indx;
  2746. if (c == PEOF)
  2747. return CENDFILE;
  2748. # if ENABLE_ASH_ALIAS
  2749. if (c == PEOA)
  2750. indx = 0;
  2751. else
  2752. # endif
  2753. {
  2754. /* Cast is purely for paranoia here,
  2755. * just in case someone passed signed char to us */
  2756. if ((unsigned char)c >= CTL_FIRST
  2757. && (unsigned char)c <= CTL_LAST
  2758. ) {
  2759. return CCTL;
  2760. }
  2761. s = strchrnul(spec_symbls, c);
  2762. if (*s == '\0')
  2763. return CWORD;
  2764. indx = syntax_index_table[s - spec_symbls];
  2765. }
  2766. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2767. }
  2768. #else /* !USE_SIT_FUNCTION */
  2769. static const uint8_t syntax_index_table[] ALIGN1 = {
  2770. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2771. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2781. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2782. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2804. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2805. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2806. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2808. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2810. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2811. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2812. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2813. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2814. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2817. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2818. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2819. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2831. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2832. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2833. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2834. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2835. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2836. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2837. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2838. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2839. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2840. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2841. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2842. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2843. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2844. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2864. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2865. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2866. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2869. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2897. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2898. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2899. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2902. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2903. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2904. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2905. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2906. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2907. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2908. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2909. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2922. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2923. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2924. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2925. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2926. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2927. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2928. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2929. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2930. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2931. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2932. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2933. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2934. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2935. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2936. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2937. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2967. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2968. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2969. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2970. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2971. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2972. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2973. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2974. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2975. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2976. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2977. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2978. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2979. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2980. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2981. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2982. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2983. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2984. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2985. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2986. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2987. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2988. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2989. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2990. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2991. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2992. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2993. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2994. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2995. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2996. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2997. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2998. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2999. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  3000. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  3001. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  3002. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3003. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  3004. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  3005. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  3006. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  3007. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  3008. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  3009. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  3010. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  3011. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  3012. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3013. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  3014. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  3015. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  3016. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  3017. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  3018. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  3019. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  3020. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  3021. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  3022. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  3023. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  3024. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  3025. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  3026. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  3027. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  3028. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  3029. # if ENABLE_ASH_ALIAS
  3030. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  3031. # endif
  3032. };
  3033. #if 1
  3034. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  3035. #else /* debug version, caught one signed char bug */
  3036. # define SIT(c, syntax) \
  3037. ({ \
  3038. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  3039. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3040. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  3041. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3042. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  3043. })
  3044. #endif
  3045. #endif /* !USE_SIT_FUNCTION */
  3046. /* ============ Alias handling */
  3047. #if ENABLE_ASH_ALIAS
  3048. #define ALIASINUSE 1
  3049. #define ALIASDEAD 2
  3050. struct alias {
  3051. struct alias *next;
  3052. char *name;
  3053. char *val;
  3054. int flag;
  3055. };
  3056. static struct alias **atab; // [ATABSIZE];
  3057. #define INIT_G_alias() do { \
  3058. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  3059. } while (0)
  3060. static struct alias **
  3061. __lookupalias(const char *name)
  3062. {
  3063. unsigned int hashval;
  3064. struct alias **app;
  3065. const char *p;
  3066. unsigned int ch;
  3067. p = name;
  3068. ch = (unsigned char)*p;
  3069. hashval = ch << 4;
  3070. while (ch) {
  3071. hashval += ch;
  3072. ch = (unsigned char)*++p;
  3073. }
  3074. app = &atab[hashval % ATABSIZE];
  3075. for (; *app; app = &(*app)->next) {
  3076. if (strcmp(name, (*app)->name) == 0) {
  3077. break;
  3078. }
  3079. }
  3080. return app;
  3081. }
  3082. static struct alias *
  3083. lookupalias(const char *name, int check)
  3084. {
  3085. struct alias *ap = *__lookupalias(name);
  3086. if (check && ap && (ap->flag & ALIASINUSE))
  3087. return NULL;
  3088. return ap;
  3089. }
  3090. static struct alias *
  3091. freealias(struct alias *ap)
  3092. {
  3093. struct alias *next;
  3094. if (ap->flag & ALIASINUSE) {
  3095. ap->flag |= ALIASDEAD;
  3096. return ap;
  3097. }
  3098. next = ap->next;
  3099. free(ap->name);
  3100. free(ap->val);
  3101. free(ap);
  3102. return next;
  3103. }
  3104. static void
  3105. setalias(const char *name, const char *val)
  3106. {
  3107. struct alias *ap, **app;
  3108. app = __lookupalias(name);
  3109. ap = *app;
  3110. INT_OFF;
  3111. if (ap) {
  3112. if (!(ap->flag & ALIASINUSE)) {
  3113. free(ap->val);
  3114. }
  3115. ap->val = ckstrdup(val);
  3116. ap->flag &= ~ALIASDEAD;
  3117. } else {
  3118. /* not found */
  3119. ap = ckzalloc(sizeof(struct alias));
  3120. ap->name = ckstrdup(name);
  3121. ap->val = ckstrdup(val);
  3122. /*ap->flag = 0; - ckzalloc did it */
  3123. /*ap->next = NULL;*/
  3124. *app = ap;
  3125. }
  3126. INT_ON;
  3127. }
  3128. static int
  3129. unalias(const char *name)
  3130. {
  3131. struct alias **app;
  3132. app = __lookupalias(name);
  3133. if (*app) {
  3134. INT_OFF;
  3135. *app = freealias(*app);
  3136. INT_ON;
  3137. return 0;
  3138. }
  3139. return 1;
  3140. }
  3141. static void
  3142. rmaliases(void)
  3143. {
  3144. struct alias *ap, **app;
  3145. int i;
  3146. INT_OFF;
  3147. for (i = 0; i < ATABSIZE; i++) {
  3148. app = &atab[i];
  3149. for (ap = *app; ap; ap = *app) {
  3150. *app = freealias(*app);
  3151. if (ap == *app) {
  3152. app = &ap->next;
  3153. }
  3154. }
  3155. }
  3156. INT_ON;
  3157. }
  3158. static void
  3159. printalias(const struct alias *ap)
  3160. {
  3161. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3162. }
  3163. /*
  3164. * TODO - sort output
  3165. */
  3166. static int FAST_FUNC
  3167. aliascmd(int argc UNUSED_PARAM, char **argv)
  3168. {
  3169. char *n, *v;
  3170. int ret = 0;
  3171. struct alias *ap;
  3172. if (!argv[1]) {
  3173. int i;
  3174. for (i = 0; i < ATABSIZE; i++) {
  3175. for (ap = atab[i]; ap; ap = ap->next) {
  3176. printalias(ap);
  3177. }
  3178. }
  3179. return 0;
  3180. }
  3181. while ((n = *++argv) != NULL) {
  3182. v = strchr(n+1, '=');
  3183. if (v == NULL) { /* n+1: funny ksh stuff */
  3184. ap = *__lookupalias(n);
  3185. if (ap == NULL) {
  3186. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3187. ret = 1;
  3188. } else
  3189. printalias(ap);
  3190. } else {
  3191. *v++ = '\0';
  3192. setalias(n, v);
  3193. }
  3194. }
  3195. return ret;
  3196. }
  3197. static int FAST_FUNC
  3198. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3199. {
  3200. int i;
  3201. while (nextopt("a") != '\0') {
  3202. rmaliases();
  3203. return 0;
  3204. }
  3205. for (i = 0; *argptr; argptr++) {
  3206. if (unalias(*argptr)) {
  3207. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3208. i = 1;
  3209. }
  3210. }
  3211. return i;
  3212. }
  3213. #endif /* ASH_ALIAS */
  3214. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3215. #define FORK_FG 0
  3216. #define FORK_BG 1
  3217. #define FORK_NOJOB 2
  3218. /* mode flags for showjob(s) */
  3219. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3220. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3221. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3222. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3223. /*
  3224. * A job structure contains information about a job. A job is either a
  3225. * single process or a set of processes contained in a pipeline. In the
  3226. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3227. * array of pids.
  3228. */
  3229. struct procstat {
  3230. pid_t ps_pid; /* process id */
  3231. int ps_status; /* last process status from wait() */
  3232. char *ps_cmd; /* text of command being run */
  3233. };
  3234. struct job {
  3235. struct procstat ps0; /* status of process */
  3236. struct procstat *ps; /* status of processes when more than one */
  3237. #if JOBS
  3238. int stopstatus; /* status of a stopped job */
  3239. #endif
  3240. unsigned nprocs; /* number of processes */
  3241. #define JOBRUNNING 0 /* at least one proc running */
  3242. #define JOBSTOPPED 1 /* all procs are stopped */
  3243. #define JOBDONE 2 /* all procs are completed */
  3244. unsigned
  3245. state: 8,
  3246. #if JOBS
  3247. sigint: 1, /* job was killed by SIGINT */
  3248. jobctl: 1, /* job running under job control */
  3249. #endif
  3250. waited: 1, /* true if this entry has been waited for */
  3251. used: 1, /* true if this entry is in used */
  3252. changed: 1; /* true if status has changed */
  3253. struct job *prev_job; /* previous job */
  3254. };
  3255. static struct job *makejob(/*union node *,*/ int);
  3256. static int forkshell(struct job *, union node *, int);
  3257. static int waitforjob(struct job *);
  3258. #if !JOBS
  3259. enum { doing_jobctl = 0 };
  3260. #define setjobctl(on) do {} while (0)
  3261. #else
  3262. static smallint doing_jobctl; //references:8
  3263. static void setjobctl(int);
  3264. #endif
  3265. /*
  3266. * Ignore a signal.
  3267. */
  3268. static void
  3269. ignoresig(int signo)
  3270. {
  3271. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3272. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3273. /* No, need to do it */
  3274. signal(signo, SIG_IGN);
  3275. }
  3276. sigmode[signo - 1] = S_HARD_IGN;
  3277. }
  3278. /*
  3279. * Only one usage site - in setsignal()
  3280. */
  3281. static void
  3282. signal_handler(int signo)
  3283. {
  3284. if (signo == SIGCHLD) {
  3285. got_sigchld = 1;
  3286. if (!trap[SIGCHLD])
  3287. return;
  3288. }
  3289. gotsig[signo - 1] = 1;
  3290. pending_sig = signo;
  3291. if (signo == SIGINT && !trap[SIGINT]) {
  3292. if (!suppress_int) {
  3293. pending_sig = 0;
  3294. raise_interrupt(); /* does not return */
  3295. }
  3296. pending_int = 1;
  3297. }
  3298. }
  3299. /*
  3300. * Set the signal handler for the specified signal. The routine figures
  3301. * out what it should be set to.
  3302. */
  3303. static void
  3304. setsignal(int signo)
  3305. {
  3306. char *t;
  3307. char cur_act, new_act;
  3308. struct sigaction act;
  3309. t = trap[signo];
  3310. new_act = S_DFL;
  3311. if (t != NULL) { /* trap for this sig is set */
  3312. new_act = S_CATCH;
  3313. if (t[0] == '\0') /* trap is "": ignore this sig */
  3314. new_act = S_IGN;
  3315. }
  3316. if (rootshell && new_act == S_DFL) {
  3317. switch (signo) {
  3318. case SIGINT:
  3319. if (iflag || minusc || sflag == 0)
  3320. new_act = S_CATCH;
  3321. break;
  3322. case SIGQUIT:
  3323. #if DEBUG
  3324. if (debug)
  3325. break;
  3326. #endif
  3327. /* man bash:
  3328. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3329. * commands run by bash have signal handlers
  3330. * set to the values inherited by the shell
  3331. * from its parent". */
  3332. new_act = S_IGN;
  3333. break;
  3334. case SIGTERM:
  3335. if (iflag)
  3336. new_act = S_IGN;
  3337. break;
  3338. #if JOBS
  3339. case SIGTSTP:
  3340. case SIGTTOU:
  3341. if (mflag)
  3342. new_act = S_IGN;
  3343. break;
  3344. #endif
  3345. }
  3346. }
  3347. /* if !rootshell, we reset SIGQUIT to DFL,
  3348. * whereas we have to restore it to what shell got on entry.
  3349. * This is handled by the fact that if signal was IGNored on entry,
  3350. * then cur_act is S_HARD_IGN and we never change its sigaction
  3351. * (see code below).
  3352. */
  3353. if (signo == SIGCHLD)
  3354. new_act = S_CATCH;
  3355. t = &sigmode[signo - 1];
  3356. cur_act = *t;
  3357. if (cur_act == 0) {
  3358. /* current setting is not yet known */
  3359. if (sigaction(signo, NULL, &act)) {
  3360. /* pretend it worked; maybe we should give a warning,
  3361. * but other shells don't. We don't alter sigmode,
  3362. * so we retry every time.
  3363. * btw, in Linux it never fails. --vda */
  3364. return;
  3365. }
  3366. if (act.sa_handler == SIG_IGN) {
  3367. cur_act = S_HARD_IGN;
  3368. if (mflag
  3369. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3370. ) {
  3371. cur_act = S_IGN; /* don't hard ignore these */
  3372. }
  3373. }
  3374. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3375. /* installing SIG_DFL over SIG_DFL is a no-op */
  3376. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3377. *t = S_DFL;
  3378. return;
  3379. }
  3380. }
  3381. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3382. return;
  3383. *t = new_act;
  3384. act.sa_handler = SIG_DFL;
  3385. switch (new_act) {
  3386. case S_CATCH:
  3387. act.sa_handler = signal_handler;
  3388. break;
  3389. case S_IGN:
  3390. act.sa_handler = SIG_IGN;
  3391. break;
  3392. }
  3393. /* flags and mask matter only if !DFL and !IGN, but we do it
  3394. * for all cases for more deterministic behavior:
  3395. */
  3396. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3397. sigfillset(&act.sa_mask);
  3398. sigaction_set(signo, &act);
  3399. }
  3400. /* mode flags for set_curjob */
  3401. #define CUR_DELETE 2
  3402. #define CUR_RUNNING 1
  3403. #define CUR_STOPPED 0
  3404. #if JOBS
  3405. /* pgrp of shell on invocation */
  3406. static int initialpgrp; //references:2
  3407. static int ttyfd = -1; //5
  3408. #endif
  3409. /* array of jobs */
  3410. static struct job *jobtab; //5
  3411. /* size of array */
  3412. static unsigned njobs; //4
  3413. /* current job */
  3414. static struct job *curjob; //lots
  3415. #if 0
  3416. /* Bash has a feature: it restores termios after a successful wait for
  3417. * a foreground job which had at least one stopped or sigkilled member.
  3418. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3419. * properly restoring tty state. Should we do this too?
  3420. * A reproducer: ^Z an interactive python:
  3421. *
  3422. * # python
  3423. * Python 2.7.12 (...)
  3424. * >>> ^Z
  3425. * { python leaves tty in -icanon -echo state. We do survive that... }
  3426. * [1]+ Stopped python
  3427. * { ...however, next program (python #2) does not survive it well: }
  3428. * # python
  3429. * Python 2.7.12 (...)
  3430. * >>> Traceback (most recent call last):
  3431. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3432. * File "<stdin>", line 1, in <module>
  3433. * NameError: name 'qwerty' is not defined
  3434. *
  3435. * The implementation below is modeled on bash code and seems to work.
  3436. * However, I'm not sure we should do this. For one: what if I'd fg
  3437. * the stopped python instead? It'll be confused by "restored" tty state.
  3438. */
  3439. static struct termios shell_tty_info;
  3440. static void
  3441. get_tty_state(void)
  3442. {
  3443. if (rootshell && ttyfd >= 0)
  3444. tcgetattr(ttyfd, &shell_tty_info);
  3445. }
  3446. static void
  3447. set_tty_state(void)
  3448. {
  3449. /* if (rootshell) - caller ensures this */
  3450. if (ttyfd >= 0)
  3451. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3452. }
  3453. static int
  3454. job_signal_status(struct job *jp)
  3455. {
  3456. int status;
  3457. unsigned i;
  3458. struct procstat *ps = jp->ps;
  3459. for (i = 0; i < jp->nprocs; i++) {
  3460. status = ps[i].ps_status;
  3461. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3462. return status;
  3463. }
  3464. return 0;
  3465. }
  3466. static void
  3467. restore_tty_if_stopped_or_signaled(struct job *jp)
  3468. {
  3469. //TODO: check what happens if we come from waitforjob() in expbackq()
  3470. if (rootshell) {
  3471. int s = job_signal_status(jp);
  3472. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3473. set_tty_state();
  3474. }
  3475. }
  3476. #else
  3477. # define get_tty_state() ((void)0)
  3478. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3479. #endif
  3480. static void
  3481. set_curjob(struct job *jp, unsigned mode)
  3482. {
  3483. struct job *jp1;
  3484. struct job **jpp, **curp;
  3485. /* first remove from list */
  3486. jpp = curp = &curjob;
  3487. while (1) {
  3488. jp1 = *jpp;
  3489. if (jp1 == jp)
  3490. break;
  3491. jpp = &jp1->prev_job;
  3492. }
  3493. *jpp = jp1->prev_job;
  3494. /* Then re-insert in correct position */
  3495. jpp = curp;
  3496. switch (mode) {
  3497. default:
  3498. #if DEBUG
  3499. abort();
  3500. #endif
  3501. case CUR_DELETE:
  3502. /* job being deleted */
  3503. break;
  3504. case CUR_RUNNING:
  3505. /* newly created job or backgrounded job,
  3506. * put after all stopped jobs.
  3507. */
  3508. while (1) {
  3509. jp1 = *jpp;
  3510. #if JOBS
  3511. if (!jp1 || jp1->state != JOBSTOPPED)
  3512. #endif
  3513. break;
  3514. jpp = &jp1->prev_job;
  3515. }
  3516. /* FALLTHROUGH */
  3517. #if JOBS
  3518. case CUR_STOPPED:
  3519. #endif
  3520. /* newly stopped job - becomes curjob */
  3521. jp->prev_job = *jpp;
  3522. *jpp = jp;
  3523. break;
  3524. }
  3525. }
  3526. #if JOBS || DEBUG
  3527. static int
  3528. jobno(const struct job *jp)
  3529. {
  3530. return jp - jobtab + 1;
  3531. }
  3532. #endif
  3533. /*
  3534. * Convert a job name to a job structure.
  3535. */
  3536. #if !JOBS
  3537. #define getjob(name, getctl) getjob(name)
  3538. #endif
  3539. static struct job *
  3540. getjob(const char *name, int getctl)
  3541. {
  3542. struct job *jp;
  3543. struct job *found;
  3544. const char *err_msg = "%s: no such job";
  3545. unsigned num;
  3546. int c;
  3547. const char *p;
  3548. char *(*match)(const char *, const char *);
  3549. jp = curjob;
  3550. p = name;
  3551. if (!p)
  3552. goto currentjob;
  3553. if (*p != '%')
  3554. goto err;
  3555. c = *++p;
  3556. if (!c)
  3557. goto currentjob;
  3558. if (!p[1]) {
  3559. if (c == '+' || c == '%') {
  3560. currentjob:
  3561. err_msg = "No current job";
  3562. goto check;
  3563. }
  3564. if (c == '-') {
  3565. if (jp)
  3566. jp = jp->prev_job;
  3567. err_msg = "No previous job";
  3568. check:
  3569. if (!jp)
  3570. goto err;
  3571. goto gotit;
  3572. }
  3573. }
  3574. if (is_number(p)) {
  3575. num = atoi(p);
  3576. if (num > 0 && num <= njobs) {
  3577. jp = jobtab + num - 1;
  3578. if (jp->used)
  3579. goto gotit;
  3580. goto err;
  3581. }
  3582. }
  3583. match = prefix;
  3584. if (*p == '?') {
  3585. match = strstr;
  3586. p++;
  3587. }
  3588. found = NULL;
  3589. while (jp) {
  3590. if (match(jp->ps[0].ps_cmd, p)) {
  3591. if (found)
  3592. goto err;
  3593. found = jp;
  3594. err_msg = "%s: ambiguous";
  3595. }
  3596. jp = jp->prev_job;
  3597. }
  3598. if (!found)
  3599. goto err;
  3600. jp = found;
  3601. gotit:
  3602. #if JOBS
  3603. err_msg = "job %s not created under job control";
  3604. if (getctl && jp->jobctl == 0)
  3605. goto err;
  3606. #endif
  3607. return jp;
  3608. err:
  3609. ash_msg_and_raise_error(err_msg, name);
  3610. }
  3611. /*
  3612. * Mark a job structure as unused.
  3613. */
  3614. static void
  3615. freejob(struct job *jp)
  3616. {
  3617. struct procstat *ps;
  3618. int i;
  3619. INT_OFF;
  3620. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3621. if (ps->ps_cmd != nullstr)
  3622. free(ps->ps_cmd);
  3623. }
  3624. if (jp->ps != &jp->ps0)
  3625. free(jp->ps);
  3626. jp->used = 0;
  3627. set_curjob(jp, CUR_DELETE);
  3628. INT_ON;
  3629. }
  3630. #if JOBS
  3631. static void
  3632. xtcsetpgrp(int fd, pid_t pgrp)
  3633. {
  3634. if (tcsetpgrp(fd, pgrp))
  3635. ash_msg_and_raise_perror("can't set tty process group");
  3636. }
  3637. /*
  3638. * Turn job control on and off.
  3639. *
  3640. * Note: This code assumes that the third arg to ioctl is a character
  3641. * pointer, which is true on Berkeley systems but not System V. Since
  3642. * System V doesn't have job control yet, this isn't a problem now.
  3643. *
  3644. * Called with interrupts off.
  3645. */
  3646. static void
  3647. setjobctl(int on)
  3648. {
  3649. int fd;
  3650. int pgrp;
  3651. if (on == doing_jobctl || rootshell == 0)
  3652. return;
  3653. if (on) {
  3654. int ofd;
  3655. ofd = fd = open(_PATH_TTY, O_RDWR);
  3656. if (fd < 0) {
  3657. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3658. * That sometimes helps to acquire controlling tty.
  3659. * Obviously, a workaround for bugs when someone
  3660. * failed to provide a controlling tty to bash! :) */
  3661. fd = 2;
  3662. while (!isatty(fd))
  3663. if (--fd < 0)
  3664. goto out;
  3665. }
  3666. /* fd is a tty at this point */
  3667. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3668. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3669. close(ofd);
  3670. if (fd < 0)
  3671. goto out; /* F_DUPFD failed */
  3672. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3673. close_on_exec_on(fd);
  3674. while (1) { /* while we are in the background */
  3675. pgrp = tcgetpgrp(fd);
  3676. if (pgrp < 0) {
  3677. out:
  3678. ash_msg("can't access tty; job control turned off");
  3679. mflag = on = 0;
  3680. goto close;
  3681. }
  3682. if (pgrp == getpgrp())
  3683. break;
  3684. killpg(0, SIGTTIN);
  3685. }
  3686. initialpgrp = pgrp;
  3687. setsignal(SIGTSTP);
  3688. setsignal(SIGTTOU);
  3689. setsignal(SIGTTIN);
  3690. pgrp = rootpid;
  3691. setpgid(0, pgrp);
  3692. xtcsetpgrp(fd, pgrp);
  3693. } else {
  3694. /* turning job control off */
  3695. fd = ttyfd;
  3696. pgrp = initialpgrp;
  3697. /* was xtcsetpgrp, but this can make exiting ash
  3698. * loop forever if pty is already deleted */
  3699. tcsetpgrp(fd, pgrp);
  3700. setpgid(0, pgrp);
  3701. setsignal(SIGTSTP);
  3702. setsignal(SIGTTOU);
  3703. setsignal(SIGTTIN);
  3704. close:
  3705. if (fd >= 0)
  3706. close(fd);
  3707. fd = -1;
  3708. }
  3709. ttyfd = fd;
  3710. doing_jobctl = on;
  3711. }
  3712. static int FAST_FUNC
  3713. killcmd(int argc, char **argv)
  3714. {
  3715. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3716. int i = 1;
  3717. do {
  3718. if (argv[i][0] == '%') {
  3719. /*
  3720. * "kill %N" - job kill
  3721. * Converting to pgrp / pid kill
  3722. */
  3723. struct job *jp;
  3724. char *dst;
  3725. int j, n;
  3726. jp = getjob(argv[i], 0);
  3727. /*
  3728. * In jobs started under job control, we signal
  3729. * entire process group by kill -PGRP_ID.
  3730. * This happens, f.e., in interactive shell.
  3731. *
  3732. * Otherwise, we signal each child via
  3733. * kill PID1 PID2 PID3.
  3734. * Testcases:
  3735. * sh -c 'sleep 1|sleep 1 & kill %1'
  3736. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3737. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3738. */
  3739. n = jp->nprocs; /* can't be 0 (I hope) */
  3740. if (jp->jobctl)
  3741. n = 1;
  3742. dst = alloca(n * sizeof(int)*4);
  3743. argv[i] = dst;
  3744. for (j = 0; j < n; j++) {
  3745. struct procstat *ps = &jp->ps[j];
  3746. /* Skip non-running and not-stopped members
  3747. * (i.e. dead members) of the job
  3748. */
  3749. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3750. continue;
  3751. /*
  3752. * kill_main has matching code to expect
  3753. * leading space. Needed to not confuse
  3754. * negative pids with "kill -SIGNAL_NO" syntax
  3755. */
  3756. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3757. }
  3758. *dst = '\0';
  3759. }
  3760. } while (argv[++i]);
  3761. }
  3762. return kill_main(argc, argv);
  3763. }
  3764. static void
  3765. showpipe(struct job *jp /*, FILE *out*/)
  3766. {
  3767. struct procstat *ps;
  3768. struct procstat *psend;
  3769. psend = jp->ps + jp->nprocs;
  3770. for (ps = jp->ps + 1; ps < psend; ps++)
  3771. printf(" | %s", ps->ps_cmd);
  3772. newline_and_flush(stdout);
  3773. flush_stdout_stderr();
  3774. }
  3775. static int
  3776. restartjob(struct job *jp, int mode)
  3777. {
  3778. struct procstat *ps;
  3779. int i;
  3780. int status;
  3781. pid_t pgid;
  3782. INT_OFF;
  3783. if (jp->state == JOBDONE)
  3784. goto out;
  3785. jp->state = JOBRUNNING;
  3786. pgid = jp->ps[0].ps_pid;
  3787. if (mode == FORK_FG) {
  3788. get_tty_state();
  3789. xtcsetpgrp(ttyfd, pgid);
  3790. }
  3791. killpg(pgid, SIGCONT);
  3792. ps = jp->ps;
  3793. i = jp->nprocs;
  3794. do {
  3795. if (WIFSTOPPED(ps->ps_status)) {
  3796. ps->ps_status = -1;
  3797. }
  3798. ps++;
  3799. } while (--i);
  3800. out:
  3801. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3802. INT_ON;
  3803. return status;
  3804. }
  3805. static int FAST_FUNC
  3806. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3807. {
  3808. struct job *jp;
  3809. int mode;
  3810. int retval;
  3811. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3812. nextopt(nullstr);
  3813. argv = argptr;
  3814. do {
  3815. jp = getjob(*argv, 1);
  3816. if (mode == FORK_BG) {
  3817. set_curjob(jp, CUR_RUNNING);
  3818. printf("[%d] ", jobno(jp));
  3819. }
  3820. out1str(jp->ps[0].ps_cmd);
  3821. showpipe(jp /*, stdout*/);
  3822. retval = restartjob(jp, mode);
  3823. } while (*argv && *++argv);
  3824. return retval;
  3825. }
  3826. #endif
  3827. static int
  3828. sprint_status48(char *os, int status, int sigonly)
  3829. {
  3830. char *s = os;
  3831. int st;
  3832. if (!WIFEXITED(status)) {
  3833. #if JOBS
  3834. if (WIFSTOPPED(status))
  3835. st = WSTOPSIG(status);
  3836. else
  3837. #endif
  3838. st = WTERMSIG(status);
  3839. if (sigonly) {
  3840. if (st == SIGINT || st == SIGPIPE)
  3841. goto out;
  3842. #if JOBS
  3843. if (WIFSTOPPED(status))
  3844. goto out;
  3845. #endif
  3846. }
  3847. st &= 0x7f;
  3848. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3849. //s = stpncpy(s, strsignal(st), 32); //not all libc have stpncpy()
  3850. s += fmtstr(s, 32, strsignal(st));
  3851. if (WCOREDUMP(status)) {
  3852. s = stpcpy(s, " (core dumped)");
  3853. }
  3854. } else if (!sigonly) {
  3855. st = WEXITSTATUS(status);
  3856. s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3857. }
  3858. out:
  3859. return s - os;
  3860. }
  3861. #define DOWAIT_NONBLOCK 0
  3862. #define DOWAIT_BLOCK 1
  3863. #define DOWAIT_BLOCK_OR_SIG 2
  3864. #if BASH_WAIT_N
  3865. # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
  3866. #endif
  3867. static int
  3868. waitproc(int block, int *status)
  3869. {
  3870. sigset_t oldmask;
  3871. int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG;
  3872. int err;
  3873. #if JOBS
  3874. if (doing_jobctl)
  3875. flags |= WUNTRACED;
  3876. #endif
  3877. do {
  3878. got_sigchld = 0;
  3879. do
  3880. err = waitpid(-1, status, flags);
  3881. while (err < 0 && errno == EINTR);
  3882. if (err || (err = -!block))
  3883. break;
  3884. sigfillset(&oldmask);
  3885. sigprocmask2(SIG_SETMASK, &oldmask); /* mask is updated */
  3886. while (!got_sigchld && !pending_sig)
  3887. sigsuspend(&oldmask);
  3888. sigprocmask(SIG_SETMASK, &oldmask, NULL);
  3889. //simpler, but unsafe: a signal can set pending_sig after check, but before pause():
  3890. //while (!got_sigchld && !pending_sig)
  3891. // pause();
  3892. } while (got_sigchld);
  3893. return err;
  3894. }
  3895. static int
  3896. waitone(int block, struct job *job)
  3897. {
  3898. int pid;
  3899. int status;
  3900. struct job *jp;
  3901. struct job *thisjob = NULL;
  3902. #if BASH_WAIT_N
  3903. bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
  3904. block = (block & ~DOWAIT_JOBSTATUS);
  3905. #endif
  3906. TRACE(("dowait(0x%x) called\n", block));
  3907. /* It's wrong to call waitpid() outside of INT_OFF region:
  3908. * signal can arrive just after syscall return and handler can
  3909. * longjmp away, losing stop/exit notification processing.
  3910. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3911. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3912. *
  3913. * However, for "wait" builtin it is wrong to simply call waitpid()
  3914. * in INT_OFF region: "wait" needs to wait for any running job
  3915. * to change state, but should exit on any trap too.
  3916. * In INT_OFF region, a signal just before syscall entry can set
  3917. * pending_sig variables, but we can't check them, and we would
  3918. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3919. *
  3920. * Because of this, we run inside INT_OFF, but use a special routine
  3921. * which combines waitpid() and sigsuspend().
  3922. * This is the reason why we need to have a handler for SIGCHLD:
  3923. * SIG_DFL handler does not wake sigsuspend().
  3924. */
  3925. INT_OFF;
  3926. pid = waitproc(block, &status);
  3927. TRACE(("wait returns pid %d, status=%d\n", pid, status));
  3928. if (pid <= 0)
  3929. goto out;
  3930. for (jp = curjob; jp; jp = jp->prev_job) {
  3931. int jobstate;
  3932. struct procstat *ps;
  3933. struct procstat *psend;
  3934. if (jp->state == JOBDONE)
  3935. continue;
  3936. jobstate = JOBDONE;
  3937. ps = jp->ps;
  3938. psend = ps + jp->nprocs;
  3939. do {
  3940. if (ps->ps_pid == pid) {
  3941. TRACE(("Job %d: changing status of proc %d "
  3942. "from 0x%x to 0x%x\n",
  3943. jobno(jp), pid, ps->ps_status, status));
  3944. ps->ps_status = status;
  3945. thisjob = jp;
  3946. }
  3947. if (ps->ps_status == -1)
  3948. jobstate = JOBRUNNING;
  3949. #if JOBS
  3950. if (jobstate == JOBRUNNING)
  3951. continue;
  3952. if (WIFSTOPPED(ps->ps_status)) {
  3953. jp->stopstatus = ps->ps_status;
  3954. jobstate = JOBSTOPPED;
  3955. }
  3956. #endif
  3957. } while (++ps < psend);
  3958. if (!thisjob)
  3959. continue;
  3960. /* Found the job where one of its processes changed its state.
  3961. * Is there at least one live and running process in this job? */
  3962. if (jobstate != JOBRUNNING) {
  3963. /* No. All live processes in the job are stopped
  3964. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3965. */
  3966. thisjob->changed = 1;
  3967. if (thisjob->state != jobstate) {
  3968. TRACE(("Job %d: changing state from %d to %d\n",
  3969. jobno(thisjob), thisjob->state, jobstate));
  3970. thisjob->state = jobstate;
  3971. #if JOBS
  3972. if (jobstate == JOBSTOPPED)
  3973. set_curjob(thisjob, CUR_STOPPED);
  3974. #endif
  3975. }
  3976. }
  3977. goto out;
  3978. }
  3979. /* The process wasn't found in job list */
  3980. out:
  3981. INT_ON;
  3982. #if BASH_WAIT_N
  3983. if (want_jobexitstatus) {
  3984. pid = -1;
  3985. if (thisjob && thisjob->state == JOBDONE)
  3986. pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
  3987. }
  3988. #endif
  3989. if (thisjob && thisjob == job) {
  3990. char s[48 + 1];
  3991. int len;
  3992. len = sprint_status48(s, status, 1);
  3993. if (len) {
  3994. s[len] = '\n';
  3995. s[len + 1] = '\0';
  3996. out2str(s);
  3997. }
  3998. }
  3999. return pid;
  4000. }
  4001. static int
  4002. dowait(int block, struct job *jp)
  4003. {
  4004. smallint gotchld = *(volatile smallint *)&got_sigchld;
  4005. int rpid;
  4006. int pid;
  4007. if (jp && jp->state != JOBRUNNING)
  4008. block = DOWAIT_NONBLOCK;
  4009. if (block == DOWAIT_NONBLOCK && !gotchld)
  4010. return 1;
  4011. rpid = 1;
  4012. do {
  4013. pid = waitone(block, jp);
  4014. rpid &= !!pid;
  4015. if (!pid || (jp && jp->state != JOBRUNNING))
  4016. block = DOWAIT_NONBLOCK;
  4017. } while (pid >= 0);
  4018. return rpid;
  4019. }
  4020. #if JOBS
  4021. static void
  4022. showjob(struct job *jp, int mode)
  4023. {
  4024. struct procstat *ps;
  4025. struct procstat *psend;
  4026. int col;
  4027. int indent_col;
  4028. char s[16 + 16 + 48];
  4029. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  4030. ps = jp->ps;
  4031. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  4032. /* just output process (group) id of pipeline */
  4033. fprintf(out, "%d\n", ps->ps_pid);
  4034. return;
  4035. }
  4036. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  4037. indent_col = col;
  4038. if (jp == curjob)
  4039. s[col - 3] = '+';
  4040. else if (curjob && jp == curjob->prev_job)
  4041. s[col - 3] = '-';
  4042. if (mode & SHOW_PIDS)
  4043. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  4044. psend = ps + jp->nprocs;
  4045. if (jp->state == JOBRUNNING) {
  4046. strcpy(s + col, "Running");
  4047. col += sizeof("Running") - 1;
  4048. } else {
  4049. int status = psend[-1].ps_status;
  4050. if (jp->state == JOBSTOPPED)
  4051. status = jp->stopstatus;
  4052. col += sprint_status48(s + col, status, 0);
  4053. }
  4054. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  4055. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  4056. * or prints several "PID | <cmdN>" lines,
  4057. * depending on SHOW_PIDS bit.
  4058. * We do not print status of individual processes
  4059. * between PID and <cmdN>. bash does it, but not very well:
  4060. * first line shows overall job status, not process status,
  4061. * making it impossible to know 1st process status.
  4062. */
  4063. goto start;
  4064. do {
  4065. /* for each process */
  4066. s[0] = '\0';
  4067. col = 33;
  4068. if (mode & SHOW_PIDS)
  4069. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  4070. start:
  4071. fprintf(out, "%s%*c%s%s",
  4072. s,
  4073. 33 - col >= 0 ? 33 - col : 0, ' ',
  4074. ps == jp->ps ? "" : "| ",
  4075. ps->ps_cmd
  4076. );
  4077. } while (++ps != psend);
  4078. newline_and_flush(out);
  4079. jp->changed = 0;
  4080. if (jp->state == JOBDONE) {
  4081. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4082. freejob(jp);
  4083. }
  4084. }
  4085. /*
  4086. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4087. * statuses have changed since the last call to showjobs.
  4088. */
  4089. static void
  4090. showjobs(int mode)
  4091. {
  4092. struct job *jp;
  4093. TRACE(("showjobs(0x%x) called\n", mode));
  4094. /* Handle all finished jobs */
  4095. dowait(DOWAIT_NONBLOCK, NULL);
  4096. for (jp = curjob; jp; jp = jp->prev_job) {
  4097. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4098. showjob(jp, mode);
  4099. }
  4100. }
  4101. }
  4102. static int FAST_FUNC
  4103. jobscmd(int argc UNUSED_PARAM, char **argv)
  4104. {
  4105. int mode, m;
  4106. mode = 0;
  4107. while ((m = nextopt("lp")) != '\0') {
  4108. if (m == 'l')
  4109. mode |= SHOW_PIDS;
  4110. else
  4111. mode |= SHOW_ONLY_PGID;
  4112. }
  4113. argv = argptr;
  4114. if (*argv) {
  4115. do
  4116. showjob(getjob(*argv, 0), mode);
  4117. while (*++argv);
  4118. } else {
  4119. showjobs(mode);
  4120. }
  4121. return 0;
  4122. }
  4123. #endif /* JOBS */
  4124. /* Called only on finished or stopped jobs (no members are running) */
  4125. static int
  4126. getstatus(struct job *job)
  4127. {
  4128. int status;
  4129. int retval;
  4130. struct procstat *ps;
  4131. /* Fetch last member's status */
  4132. ps = job->ps + job->nprocs - 1;
  4133. status = ps->ps_status;
  4134. if (pipefail) {
  4135. /* "set -o pipefail" mode: use last _nonzero_ status */
  4136. while (status == 0 && --ps >= job->ps)
  4137. status = ps->ps_status;
  4138. }
  4139. retval = WEXITSTATUS(status);
  4140. if (!WIFEXITED(status)) {
  4141. #if JOBS
  4142. retval = WSTOPSIG(status);
  4143. if (!WIFSTOPPED(status))
  4144. #endif
  4145. {
  4146. /* XXX: limits number of signals */
  4147. retval = WTERMSIG(status);
  4148. #if JOBS
  4149. if (retval == SIGINT)
  4150. job->sigint = 1;
  4151. #endif
  4152. }
  4153. retval += 128;
  4154. }
  4155. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4156. jobno(job), job->nprocs, status, retval));
  4157. return retval;
  4158. }
  4159. static int FAST_FUNC
  4160. waitcmd(int argc UNUSED_PARAM, char **argv)
  4161. {
  4162. struct job *job;
  4163. int retval;
  4164. struct job *jp;
  4165. #if BASH_WAIT_N
  4166. int status;
  4167. char one = nextopt("n");
  4168. #else
  4169. nextopt(nullstr);
  4170. #endif
  4171. retval = 0;
  4172. argv = argptr;
  4173. if (!argv[0]) {
  4174. /* wait for all jobs / one job if -n */
  4175. for (;;) {
  4176. jp = curjob;
  4177. #if BASH_WAIT_N
  4178. if (one && !jp)
  4179. /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
  4180. retval = 127;
  4181. #endif
  4182. while (1) {
  4183. if (!jp) /* no running procs */
  4184. goto ret;
  4185. if (jp->state == JOBRUNNING)
  4186. break;
  4187. jp->waited = 1;
  4188. jp = jp->prev_job;
  4189. }
  4190. /* man bash:
  4191. * "When bash is waiting for an asynchronous command via
  4192. * the wait builtin, the reception of a signal for which a trap
  4193. * has been set will cause the wait builtin to return immediately
  4194. * with an exit status greater than 128, immediately after which
  4195. * the trap is executed."
  4196. */
  4197. #if BASH_WAIT_N
  4198. status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
  4199. #else
  4200. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4201. #endif
  4202. /* if child sends us a signal *and immediately exits*,
  4203. * dowait() returns pid > 0. Check this case,
  4204. * not "if (dowait() < 0)"!
  4205. */
  4206. if (pending_sig)
  4207. goto sigout;
  4208. #if BASH_WAIT_N
  4209. if (one) {
  4210. /* wait -n waits for one _job_, not one _process_.
  4211. * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
  4212. * should wait for 2 seconds. Not 1 or 3.
  4213. */
  4214. if (status != -1 && !WIFSTOPPED(status)) {
  4215. retval = WEXITSTATUS(status);
  4216. if (WIFSIGNALED(status))
  4217. retval = WTERMSIG(status) + 128;
  4218. goto ret;
  4219. }
  4220. }
  4221. #endif
  4222. }
  4223. }
  4224. retval = 127;
  4225. do {
  4226. if (**argv != '%') {
  4227. pid_t pid = number(*argv);
  4228. job = curjob;
  4229. while (1) {
  4230. if (!job)
  4231. goto repeat;
  4232. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4233. break;
  4234. job = job->prev_job;
  4235. }
  4236. } else {
  4237. job = getjob(*argv, 0);
  4238. }
  4239. /* loop until process terminated or stopped */
  4240. dowait(DOWAIT_BLOCK_OR_SIG, job);
  4241. if (pending_sig)
  4242. goto sigout;
  4243. job->waited = 1;
  4244. retval = getstatus(job);
  4245. repeat: ;
  4246. } while (*++argv);
  4247. ret:
  4248. return retval;
  4249. sigout:
  4250. retval = 128 + pending_sig;
  4251. return retval;
  4252. }
  4253. static struct job *
  4254. growjobtab(void)
  4255. {
  4256. size_t len;
  4257. ptrdiff_t offset;
  4258. struct job *jp, *jq;
  4259. len = njobs * sizeof(*jp);
  4260. jq = jobtab;
  4261. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4262. offset = (char *)jp - (char *)jq;
  4263. if (offset) {
  4264. /* Relocate pointers */
  4265. size_t l = len;
  4266. jq = (struct job *)((char *)jq + l);
  4267. while (l) {
  4268. l -= sizeof(*jp);
  4269. jq--;
  4270. #define joff(p) ((struct job *)((char *)(p) + l))
  4271. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4272. if (joff(jp)->ps == &jq->ps0)
  4273. jmove(joff(jp)->ps);
  4274. if (joff(jp)->prev_job)
  4275. jmove(joff(jp)->prev_job);
  4276. }
  4277. if (curjob)
  4278. jmove(curjob);
  4279. #undef joff
  4280. #undef jmove
  4281. }
  4282. njobs += 4;
  4283. jobtab = jp;
  4284. jp = (struct job *)((char *)jp + len);
  4285. jq = jp + 3;
  4286. do {
  4287. jq->used = 0;
  4288. } while (--jq >= jp);
  4289. return jp;
  4290. }
  4291. /*
  4292. * Return a new job structure.
  4293. * Called with interrupts off.
  4294. */
  4295. static struct job *
  4296. makejob(/*union node *node,*/ int nprocs)
  4297. {
  4298. int i;
  4299. struct job *jp;
  4300. for (i = njobs, jp = jobtab; ; jp++) {
  4301. if (--i < 0) {
  4302. jp = growjobtab();
  4303. break;
  4304. }
  4305. if (jp->used == 0)
  4306. break;
  4307. if (jp->state != JOBDONE || !jp->waited)
  4308. continue;
  4309. #if JOBS
  4310. if (doing_jobctl)
  4311. continue;
  4312. #endif
  4313. freejob(jp);
  4314. break;
  4315. }
  4316. memset(jp, 0, sizeof(*jp));
  4317. #if JOBS
  4318. /* jp->jobctl is a bitfield.
  4319. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4320. if (doing_jobctl)
  4321. jp->jobctl = 1;
  4322. #endif
  4323. jp->prev_job = curjob;
  4324. curjob = jp;
  4325. jp->used = 1;
  4326. jp->ps = &jp->ps0;
  4327. if (nprocs > 1) {
  4328. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4329. }
  4330. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4331. jobno(jp)));
  4332. return jp;
  4333. }
  4334. #if JOBS
  4335. /*
  4336. * Return a string identifying a command (to be printed by the
  4337. * jobs command).
  4338. */
  4339. static char *cmdnextc;
  4340. static void
  4341. cmdputs(const char *s)
  4342. {
  4343. static const char vstype[VSTYPE + 1][3] = {
  4344. "", "}", "-", "+", "?", "=",
  4345. "%", "%%", "#", "##"
  4346. IF_BASH_SUBSTR(, ":")
  4347. IF_BASH_PATTERN_SUBST(, "/", "//")
  4348. };
  4349. const char *p, *str;
  4350. char cc[2];
  4351. char *nextc;
  4352. unsigned char c;
  4353. unsigned char subtype = 0;
  4354. int quoted = 0;
  4355. cc[1] = '\0';
  4356. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4357. p = s;
  4358. while ((c = *p++) != '\0') {
  4359. str = NULL;
  4360. switch (c) {
  4361. case CTLESC:
  4362. c = *p++;
  4363. break;
  4364. case CTLVAR:
  4365. subtype = *p++;
  4366. if ((subtype & VSTYPE) == VSLENGTH)
  4367. str = "${#";
  4368. else
  4369. str = "${";
  4370. goto dostr;
  4371. case CTLENDVAR:
  4372. str = "\"}";
  4373. str += !(quoted & 1);
  4374. quoted >>= 1;
  4375. subtype = 0;
  4376. goto dostr;
  4377. case CTLBACKQ:
  4378. str = "$(...)";
  4379. goto dostr;
  4380. #if ENABLE_FEATURE_SH_MATH
  4381. case CTLARI:
  4382. str = "$((";
  4383. goto dostr;
  4384. case CTLENDARI:
  4385. str = "))";
  4386. goto dostr;
  4387. #endif
  4388. case CTLQUOTEMARK:
  4389. quoted ^= 1;
  4390. c = '"';
  4391. break;
  4392. case '=':
  4393. if (subtype == 0)
  4394. break;
  4395. if ((subtype & VSTYPE) != VSNORMAL)
  4396. quoted <<= 1;
  4397. str = vstype[subtype & VSTYPE];
  4398. if (subtype & VSNUL)
  4399. c = ':';
  4400. else
  4401. goto checkstr;
  4402. break;
  4403. case '\'':
  4404. case '\\':
  4405. case '"':
  4406. case '$':
  4407. /* These can only happen inside quotes */
  4408. cc[0] = c;
  4409. str = cc;
  4410. //FIXME:
  4411. // $ true $$ &
  4412. // $ <cr>
  4413. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4414. c = '\\';
  4415. break;
  4416. default:
  4417. break;
  4418. }
  4419. USTPUTC(c, nextc);
  4420. checkstr:
  4421. if (!str)
  4422. continue;
  4423. dostr:
  4424. while ((c = *str++) != '\0') {
  4425. USTPUTC(c, nextc);
  4426. }
  4427. } /* while *p++ not NUL */
  4428. if (quoted & 1) {
  4429. USTPUTC('"', nextc);
  4430. }
  4431. *nextc = 0;
  4432. cmdnextc = nextc;
  4433. }
  4434. /* cmdtxt() and cmdlist() call each other */
  4435. static void cmdtxt(union node *n);
  4436. static void
  4437. cmdlist(union node *np, int sep)
  4438. {
  4439. for (; np; np = np->narg.next) {
  4440. if (!sep)
  4441. cmdputs(" ");
  4442. cmdtxt(np);
  4443. if (sep && np->narg.next)
  4444. cmdputs(" ");
  4445. }
  4446. }
  4447. static void
  4448. cmdtxt(union node *n)
  4449. {
  4450. union node *np;
  4451. struct nodelist *lp;
  4452. const char *p;
  4453. if (!n)
  4454. return;
  4455. switch (n->type) {
  4456. default:
  4457. #if DEBUG
  4458. abort();
  4459. #endif
  4460. case NPIPE:
  4461. lp = n->npipe.cmdlist;
  4462. for (;;) {
  4463. cmdtxt(lp->n);
  4464. lp = lp->next;
  4465. if (!lp)
  4466. break;
  4467. cmdputs(" | ");
  4468. }
  4469. break;
  4470. case NSEMI:
  4471. p = "; ";
  4472. goto binop;
  4473. case NAND:
  4474. p = " && ";
  4475. goto binop;
  4476. case NOR:
  4477. p = " || ";
  4478. binop:
  4479. cmdtxt(n->nbinary.ch1);
  4480. cmdputs(p);
  4481. n = n->nbinary.ch2;
  4482. goto donode;
  4483. case NREDIR:
  4484. case NBACKGND:
  4485. n = n->nredir.n;
  4486. goto donode;
  4487. case NNOT:
  4488. cmdputs("!");
  4489. n = n->nnot.com;
  4490. donode:
  4491. cmdtxt(n);
  4492. break;
  4493. case NIF:
  4494. cmdputs("if ");
  4495. cmdtxt(n->nif.test);
  4496. cmdputs("; then ");
  4497. if (n->nif.elsepart) {
  4498. cmdtxt(n->nif.ifpart);
  4499. cmdputs("; else ");
  4500. n = n->nif.elsepart;
  4501. } else {
  4502. n = n->nif.ifpart;
  4503. }
  4504. p = "; fi";
  4505. goto dotail;
  4506. case NSUBSHELL:
  4507. cmdputs("(");
  4508. n = n->nredir.n;
  4509. p = ")";
  4510. goto dotail;
  4511. case NWHILE:
  4512. p = "while ";
  4513. goto until;
  4514. case NUNTIL:
  4515. p = "until ";
  4516. until:
  4517. cmdputs(p);
  4518. cmdtxt(n->nbinary.ch1);
  4519. n = n->nbinary.ch2;
  4520. p = "; done";
  4521. dodo:
  4522. cmdputs("; do ");
  4523. dotail:
  4524. cmdtxt(n);
  4525. goto dotail2;
  4526. case NFOR:
  4527. cmdputs("for ");
  4528. cmdputs(n->nfor.var);
  4529. cmdputs(" in ");
  4530. cmdlist(n->nfor.args, 1);
  4531. n = n->nfor.body;
  4532. p = "; done";
  4533. goto dodo;
  4534. case NDEFUN:
  4535. cmdputs(n->ndefun.text);
  4536. p = "() { ... }";
  4537. goto dotail2;
  4538. case NCMD:
  4539. cmdlist(n->ncmd.args, 1);
  4540. cmdlist(n->ncmd.redirect, 0);
  4541. break;
  4542. case NARG:
  4543. p = n->narg.text;
  4544. dotail2:
  4545. cmdputs(p);
  4546. break;
  4547. case NHERE:
  4548. case NXHERE:
  4549. p = "<<...";
  4550. goto dotail2;
  4551. case NCASE:
  4552. cmdputs("case ");
  4553. cmdputs(n->ncase.expr->narg.text);
  4554. cmdputs(" in ");
  4555. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4556. cmdtxt(np->nclist.pattern);
  4557. cmdputs(") ");
  4558. cmdtxt(np->nclist.body);
  4559. cmdputs(";; ");
  4560. }
  4561. p = "esac";
  4562. goto dotail2;
  4563. case NTO:
  4564. p = ">";
  4565. goto redir;
  4566. case NCLOBBER:
  4567. p = ">|";
  4568. goto redir;
  4569. case NAPPEND:
  4570. p = ">>";
  4571. goto redir;
  4572. #if BASH_REDIR_OUTPUT
  4573. case NTO2:
  4574. #endif
  4575. case NTOFD:
  4576. p = ">&";
  4577. goto redir;
  4578. case NFROM:
  4579. p = "<";
  4580. goto redir;
  4581. case NFROMFD:
  4582. p = "<&";
  4583. goto redir;
  4584. case NFROMTO:
  4585. p = "<>";
  4586. redir:
  4587. cmdputs(utoa(n->nfile.fd));
  4588. cmdputs(p);
  4589. if (n->type == NTOFD || n->type == NFROMFD) {
  4590. if (n->ndup.dupfd >= 0)
  4591. cmdputs(utoa(n->ndup.dupfd));
  4592. else
  4593. cmdputs("-");
  4594. break;
  4595. }
  4596. n = n->nfile.fname;
  4597. goto donode;
  4598. }
  4599. }
  4600. static char *
  4601. commandtext(union node *n)
  4602. {
  4603. char *name;
  4604. STARTSTACKSTR(cmdnextc);
  4605. cmdtxt(n);
  4606. name = stackblock();
  4607. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4608. return ckstrdup(name);
  4609. }
  4610. #endif /* JOBS */
  4611. /*
  4612. * Fork off a subshell. If we are doing job control, give the subshell its
  4613. * own process group. Jp is a job structure that the job is to be added to.
  4614. * N is the command that will be evaluated by the child. Both jp and n may
  4615. * be NULL. The mode parameter can be one of the following:
  4616. * FORK_FG - Fork off a foreground process.
  4617. * FORK_BG - Fork off a background process.
  4618. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4619. * process group even if job control is on.
  4620. *
  4621. * When job control is turned off, background processes have their standard
  4622. * input redirected to /dev/null (except for the second and later processes
  4623. * in a pipeline).
  4624. *
  4625. * Called with interrupts off.
  4626. */
  4627. /*
  4628. * Clear traps on a fork.
  4629. */
  4630. static void
  4631. clear_traps(void)
  4632. {
  4633. char **tp;
  4634. INT_OFF;
  4635. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4636. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4637. if (trap_ptr == trap)
  4638. free(*tp);
  4639. /* else: it "belongs" to trap_ptr vector, don't free */
  4640. *tp = NULL;
  4641. if ((tp - trap) != 0)
  4642. setsignal(tp - trap);
  4643. }
  4644. }
  4645. may_have_traps = 0;
  4646. INT_ON;
  4647. }
  4648. /* Lives far away from here, needed for forkchild */
  4649. static void closescript(void);
  4650. /* Called after fork(), in child */
  4651. /* jp and n are NULL when called by openhere() for heredoc support */
  4652. static NOINLINE void
  4653. forkchild(struct job *jp, union node *n, int mode)
  4654. {
  4655. int oldlvl;
  4656. TRACE(("Child shell %d\n", getpid()));
  4657. oldlvl = shlvl;
  4658. shlvl++;
  4659. /* man bash: "Non-builtin commands run by bash have signal handlers
  4660. * set to the values inherited by the shell from its parent".
  4661. * Do we do it correctly? */
  4662. closescript();
  4663. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4664. && n && n->type == NCMD /* is it single cmd? */
  4665. /* && n->ncmd.args->type == NARG - always true? */
  4666. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4667. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4668. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4669. ) {
  4670. TRACE(("Trap hack\n"));
  4671. /* Awful hack for `trap` or $(trap).
  4672. *
  4673. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4674. * contains an example where "trap" is executed in a subshell:
  4675. *
  4676. * save_traps=$(trap)
  4677. * ...
  4678. * eval "$save_traps"
  4679. *
  4680. * Standard does not say that "trap" in subshell shall print
  4681. * parent shell's traps. It only says that its output
  4682. * must have suitable form, but then, in the above example
  4683. * (which is not supposed to be normative), it implies that.
  4684. *
  4685. * bash (and probably other shell) does implement it
  4686. * (traps are reset to defaults, but "trap" still shows them),
  4687. * but as a result, "trap" logic is hopelessly messed up:
  4688. *
  4689. * # trap
  4690. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4691. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4692. * # true | trap <--- trap is in subshell - no output (ditto)
  4693. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4694. * trap -- 'echo Ho' SIGWINCH
  4695. * # echo `(trap)` <--- in subshell in subshell - output
  4696. * trap -- 'echo Ho' SIGWINCH
  4697. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4698. * trap -- 'echo Ho' SIGWINCH
  4699. *
  4700. * The rules when to forget and when to not forget traps
  4701. * get really complex and nonsensical.
  4702. *
  4703. * Our solution: ONLY bare $(trap) or `trap` is special.
  4704. */
  4705. /* Save trap handler strings for trap builtin to print */
  4706. trap_ptr = xmemdup(trap, sizeof(trap));
  4707. /* Fall through into clearing traps */
  4708. }
  4709. clear_traps();
  4710. #if JOBS
  4711. /* do job control only in root shell */
  4712. doing_jobctl = 0;
  4713. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4714. pid_t pgrp;
  4715. if (jp->nprocs == 0)
  4716. pgrp = getpid();
  4717. else
  4718. pgrp = jp->ps[0].ps_pid;
  4719. /* this can fail because we are doing it in the parent also */
  4720. setpgid(0, pgrp);
  4721. if (mode == FORK_FG)
  4722. xtcsetpgrp(ttyfd, pgrp);
  4723. setsignal(SIGTSTP);
  4724. setsignal(SIGTTOU);
  4725. } else
  4726. #endif
  4727. if (mode == FORK_BG) {
  4728. /* man bash: "When job control is not in effect,
  4729. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4730. ignoresig(SIGINT);
  4731. ignoresig(SIGQUIT);
  4732. if (jp->nprocs == 0) {
  4733. close(0);
  4734. if (open(bb_dev_null, O_RDONLY) != 0)
  4735. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4736. }
  4737. }
  4738. if (oldlvl == 0) {
  4739. if (iflag) { /* why if iflag only? */
  4740. setsignal(SIGINT);
  4741. setsignal(SIGTERM);
  4742. }
  4743. /* man bash:
  4744. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4745. * commands run by bash have signal handlers
  4746. * set to the values inherited by the shell
  4747. * from its parent".
  4748. * Take care of the second rule: */
  4749. setsignal(SIGQUIT);
  4750. }
  4751. #if JOBS
  4752. if (n && n->type == NCMD
  4753. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4754. ) {
  4755. TRACE(("Job hack\n"));
  4756. /* "jobs": we do not want to clear job list for it,
  4757. * instead we remove only _its_ own_ job from job list.
  4758. * This makes "jobs .... | cat" more useful.
  4759. */
  4760. freejob(curjob);
  4761. return;
  4762. }
  4763. #endif
  4764. for (jp = curjob; jp; jp = jp->prev_job)
  4765. freejob(jp);
  4766. }
  4767. /* Called after fork(), in parent */
  4768. #if !JOBS
  4769. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4770. #endif
  4771. static void
  4772. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4773. {
  4774. TRACE(("In parent shell: child = %d\n", pid));
  4775. if (!jp) /* jp is NULL when called by openhere() for heredoc support */
  4776. return;
  4777. #if JOBS
  4778. if (mode != FORK_NOJOB && jp->jobctl) {
  4779. int pgrp;
  4780. if (jp->nprocs == 0)
  4781. pgrp = pid;
  4782. else
  4783. pgrp = jp->ps[0].ps_pid;
  4784. /* This can fail because we are doing it in the child also */
  4785. setpgid(pid, pgrp);
  4786. }
  4787. #endif
  4788. if (mode == FORK_BG) {
  4789. backgndpid = pid; /* set $! */
  4790. set_curjob(jp, CUR_RUNNING);
  4791. }
  4792. if (jp) {
  4793. struct procstat *ps = &jp->ps[jp->nprocs++];
  4794. ps->ps_pid = pid;
  4795. ps->ps_status = -1;
  4796. ps->ps_cmd = nullstr;
  4797. #if JOBS
  4798. if (doing_jobctl && n)
  4799. ps->ps_cmd = commandtext(n);
  4800. #endif
  4801. }
  4802. }
  4803. /* jp and n are NULL when called by openhere() for heredoc support */
  4804. static int
  4805. forkshell(struct job *jp, union node *n, int mode)
  4806. {
  4807. int pid;
  4808. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4809. pid = fork();
  4810. if (pid < 0) {
  4811. TRACE(("Fork failed, errno=%d", errno));
  4812. if (jp)
  4813. freejob(jp);
  4814. ash_msg_and_raise_perror("can't fork");
  4815. }
  4816. if (pid == 0) {
  4817. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4818. forkchild(jp, n, mode);
  4819. } else {
  4820. forkparent(jp, n, mode, pid);
  4821. }
  4822. return pid;
  4823. }
  4824. /*
  4825. * Wait for job to finish.
  4826. *
  4827. * Under job control we have the problem that while a child process
  4828. * is running interrupts generated by the user are sent to the child
  4829. * but not to the shell. This means that an infinite loop started by
  4830. * an interactive user may be hard to kill. With job control turned off,
  4831. * an interactive user may place an interactive program inside a loop.
  4832. * If the interactive program catches interrupts, the user doesn't want
  4833. * these interrupts to also abort the loop. The approach we take here
  4834. * is to have the shell ignore interrupt signals while waiting for a
  4835. * foreground process to terminate, and then send itself an interrupt
  4836. * signal if the child process was terminated by an interrupt signal.
  4837. * Unfortunately, some programs want to do a bit of cleanup and then
  4838. * exit on interrupt; unless these processes terminate themselves by
  4839. * sending a signal to themselves (instead of calling exit) they will
  4840. * confuse this approach.
  4841. *
  4842. * Called with interrupts off.
  4843. */
  4844. static int
  4845. waitforjob(struct job *jp)
  4846. {
  4847. int st;
  4848. TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0));
  4849. /* In non-interactive shells, we _can_ get
  4850. * a keyboard signal here and be EINTRed, but we just loop
  4851. * inside dowait(), waiting for command to complete.
  4852. *
  4853. * man bash:
  4854. * "If bash is waiting for a command to complete and receives
  4855. * a signal for which a trap has been set, the trap
  4856. * will not be executed until the command completes."
  4857. *
  4858. * Reality is that even if trap is not set, bash
  4859. * will not act on the signal until command completes.
  4860. * Try this. sleep5intoff.c:
  4861. * #include <signal.h>
  4862. * #include <unistd.h>
  4863. * int main() {
  4864. * sigset_t set;
  4865. * sigemptyset(&set);
  4866. * sigaddset(&set, SIGINT);
  4867. * sigaddset(&set, SIGQUIT);
  4868. * sigprocmask(SIG_BLOCK, &set, NULL);
  4869. * sleep(5);
  4870. * return 0;
  4871. * }
  4872. * $ bash -c './sleep5intoff; echo hi'
  4873. * ^C^C^C^C <--- pressing ^C once a second
  4874. * $ _
  4875. * $ bash -c './sleep5intoff; echo hi'
  4876. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4877. * $ _
  4878. */
  4879. dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp);
  4880. if (!jp)
  4881. return exitstatus;
  4882. st = getstatus(jp);
  4883. #if JOBS
  4884. if (jp->jobctl) {
  4885. xtcsetpgrp(ttyfd, rootpid);
  4886. restore_tty_if_stopped_or_signaled(jp);
  4887. /*
  4888. * This is truly gross.
  4889. * If we're doing job control, then we did a TIOCSPGRP which
  4890. * caused us (the shell) to no longer be in the controlling
  4891. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4892. * intuit from the subprocess exit status whether a SIGINT
  4893. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4894. */
  4895. if (jp->sigint) /* TODO: do the same with all signals */
  4896. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4897. }
  4898. if (jp->state == JOBDONE)
  4899. #endif
  4900. freejob(jp);
  4901. return st;
  4902. }
  4903. /*
  4904. * return 1 if there are stopped jobs, otherwise 0
  4905. */
  4906. static int
  4907. stoppedjobs(void)
  4908. {
  4909. struct job *jp;
  4910. int retval;
  4911. retval = 0;
  4912. if (job_warning)
  4913. goto out;
  4914. jp = curjob;
  4915. if (jp && jp->state == JOBSTOPPED) {
  4916. out2str("You have stopped jobs.\n");
  4917. job_warning = 2;
  4918. retval++;
  4919. }
  4920. out:
  4921. return retval;
  4922. }
  4923. /*
  4924. * Code for dealing with input/output redirection.
  4925. */
  4926. #undef EMPTY
  4927. #undef CLOSED
  4928. #define EMPTY -2 /* marks an unused slot in redirtab */
  4929. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4930. /*
  4931. * Handle here documents. Normally we fork off a process to write the
  4932. * data to a pipe. If the document is short, we can stuff the data in
  4933. * the pipe without forking.
  4934. */
  4935. /* openhere needs this forward reference */
  4936. static void expandhere(union node *arg);
  4937. static int
  4938. openhere(union node *redir)
  4939. {
  4940. char *p;
  4941. int pip[2];
  4942. size_t len = 0;
  4943. if (pipe(pip) < 0)
  4944. ash_msg_and_raise_perror("can't create pipe");
  4945. p = redir->nhere.doc->narg.text;
  4946. if (redir->type == NXHERE) {
  4947. expandhere(redir->nhere.doc);
  4948. p = stackblock();
  4949. }
  4950. len = strlen(p);
  4951. if (len <= PIPE_BUF) {
  4952. xwrite(pip[1], p, len);
  4953. goto out;
  4954. }
  4955. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4956. /* child */
  4957. close(pip[0]);
  4958. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4959. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4960. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4961. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4962. signal(SIGPIPE, SIG_DFL);
  4963. xwrite(pip[1], p, len);
  4964. _exit(EXIT_SUCCESS);
  4965. }
  4966. out:
  4967. close(pip[1]);
  4968. return pip[0];
  4969. }
  4970. static int
  4971. openredirect(union node *redir)
  4972. {
  4973. struct stat sb;
  4974. char *fname;
  4975. int f;
  4976. switch (redir->nfile.type) {
  4977. /* Can't happen, our single caller does this itself */
  4978. // case NTOFD:
  4979. // case NFROMFD:
  4980. // return -1;
  4981. case NHERE:
  4982. case NXHERE:
  4983. return openhere(redir);
  4984. }
  4985. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4986. * allocated space. Do it only when we know it is safe.
  4987. */
  4988. fname = redir->nfile.expfname;
  4989. switch (redir->nfile.type) {
  4990. default:
  4991. #if DEBUG
  4992. abort();
  4993. #endif
  4994. case NFROM:
  4995. f = open(fname, O_RDONLY);
  4996. if (f < 0)
  4997. goto eopen;
  4998. break;
  4999. case NFROMTO:
  5000. f = open(fname, O_RDWR|O_CREAT, 0666);
  5001. if (f < 0)
  5002. goto ecreate;
  5003. break;
  5004. case NTO:
  5005. #if BASH_REDIR_OUTPUT
  5006. case NTO2:
  5007. #endif
  5008. /* Take care of noclobber mode. */
  5009. if (Cflag) {
  5010. if (stat(fname, &sb) < 0) {
  5011. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  5012. if (f < 0)
  5013. goto ecreate;
  5014. } else if (!S_ISREG(sb.st_mode)) {
  5015. f = open(fname, O_WRONLY, 0666);
  5016. if (f < 0)
  5017. goto ecreate;
  5018. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  5019. close(f);
  5020. errno = EEXIST;
  5021. goto ecreate;
  5022. }
  5023. } else {
  5024. errno = EEXIST;
  5025. goto ecreate;
  5026. }
  5027. break;
  5028. }
  5029. /* FALLTHROUGH */
  5030. case NCLOBBER:
  5031. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  5032. if (f < 0)
  5033. goto ecreate;
  5034. break;
  5035. case NAPPEND:
  5036. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  5037. if (f < 0)
  5038. goto ecreate;
  5039. break;
  5040. }
  5041. return f;
  5042. ecreate:
  5043. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  5044. eopen:
  5045. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  5046. }
  5047. /*
  5048. * Copy a file descriptor to be >= 10. Throws exception on error.
  5049. */
  5050. static int
  5051. savefd(int from)
  5052. {
  5053. int newfd;
  5054. int err;
  5055. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  5056. err = newfd < 0 ? errno : 0;
  5057. if (err != EBADF) {
  5058. if (err)
  5059. ash_msg_and_raise_perror("%d", from);
  5060. close(from);
  5061. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5062. close_on_exec_on(newfd);
  5063. }
  5064. return newfd;
  5065. }
  5066. static int
  5067. dup2_or_raise(int from, int to)
  5068. {
  5069. int newfd;
  5070. newfd = (from != to) ? dup2(from, to) : to;
  5071. if (newfd < 0) {
  5072. /* Happens when source fd is not open: try "echo >&99" */
  5073. ash_msg_and_raise_perror("%d", from);
  5074. }
  5075. return newfd;
  5076. }
  5077. static int
  5078. dup_CLOEXEC(int fd, int avoid_fd)
  5079. {
  5080. int newfd;
  5081. repeat:
  5082. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5083. if (newfd >= 0) {
  5084. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  5085. close_on_exec_on(newfd);
  5086. } else { /* newfd < 0 */
  5087. if (errno == EBUSY)
  5088. goto repeat;
  5089. if (errno == EINTR)
  5090. goto repeat;
  5091. }
  5092. return newfd;
  5093. }
  5094. static int
  5095. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5096. {
  5097. int newfd;
  5098. repeat:
  5099. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5100. if (newfd < 0) {
  5101. if (errno == EBUSY)
  5102. goto repeat;
  5103. if (errno == EINTR)
  5104. goto repeat;
  5105. /* fd was not open? */
  5106. if (errno == EBADF)
  5107. return fd;
  5108. ash_msg_and_raise_perror("%d", newfd);
  5109. }
  5110. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5111. close_on_exec_on(newfd);
  5112. close(fd);
  5113. return newfd;
  5114. }
  5115. /* Struct def and variable are moved down to the first usage site */
  5116. struct squirrel {
  5117. int orig_fd;
  5118. int moved_to;
  5119. };
  5120. struct redirtab {
  5121. struct redirtab *next;
  5122. int pair_count;
  5123. struct squirrel two_fd[];
  5124. };
  5125. #define redirlist (G_var.redirlist)
  5126. static void
  5127. add_squirrel_closed(struct redirtab *sq, int fd)
  5128. {
  5129. int i;
  5130. if (!sq)
  5131. return;
  5132. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5133. /* If we collide with an already moved fd... */
  5134. if (fd == sq->two_fd[i].orig_fd) {
  5135. /* Examples:
  5136. * "echo 3>FILE 3>&- 3>FILE"
  5137. * "echo 3>&- 3>FILE"
  5138. * No need for last redirect to insert
  5139. * another "need to close 3" indicator.
  5140. */
  5141. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5142. return;
  5143. }
  5144. }
  5145. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5146. sq->two_fd[i].orig_fd = fd;
  5147. sq->two_fd[i].moved_to = CLOSED;
  5148. }
  5149. static int
  5150. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5151. {
  5152. int i, new_fd;
  5153. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5154. avoid_fd = 9;
  5155. #if JOBS
  5156. if (fd == ttyfd) {
  5157. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5158. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5159. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5160. return 1; /* "we closed fd" */
  5161. }
  5162. #endif
  5163. /* Are we called from redirect(0)? E.g. redirect
  5164. * in a forked child. No need to save fds,
  5165. * we aren't going to use them anymore, ok to trash.
  5166. */
  5167. if (!sq)
  5168. return 0;
  5169. /* If this one of script's fds? */
  5170. if (fd != 0) {
  5171. struct parsefile *pf = g_parsefile;
  5172. while (pf) {
  5173. /* We skip fd == 0 case because of the following:
  5174. * $ ash # running ash interactively
  5175. * $ . ./script.sh
  5176. * and in script.sh: "exec 9>&0".
  5177. * Even though top-level pf_fd _is_ 0,
  5178. * it's still ok to use it: "read" builtin uses it,
  5179. * why should we cripple "exec" builtin?
  5180. */
  5181. if (fd == pf->pf_fd) {
  5182. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5183. return 1; /* "we closed fd" */
  5184. }
  5185. pf = pf->prev;
  5186. }
  5187. }
  5188. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5189. /* First: do we collide with some already moved fds? */
  5190. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5191. /* If we collide with an already moved fd... */
  5192. if (fd == sq->two_fd[i].moved_to) {
  5193. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5194. sq->two_fd[i].moved_to = new_fd;
  5195. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5196. if (new_fd < 0) /* what? */
  5197. xfunc_die();
  5198. return 0; /* "we did not close fd" */
  5199. }
  5200. if (fd == sq->two_fd[i].orig_fd) {
  5201. /* Example: echo Hello >/dev/null 1>&2 */
  5202. TRACE(("redirect_fd %d: already moved\n", fd));
  5203. return 0; /* "we did not close fd" */
  5204. }
  5205. }
  5206. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5207. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5208. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5209. if (new_fd < 0) {
  5210. if (errno != EBADF)
  5211. xfunc_die();
  5212. /* new_fd = CLOSED; - already is -1 */
  5213. }
  5214. sq->two_fd[i].moved_to = new_fd;
  5215. sq->two_fd[i].orig_fd = fd;
  5216. /* if we move stderr, let "set -x" code know */
  5217. if (fd == preverrout_fd)
  5218. preverrout_fd = new_fd;
  5219. return 0; /* "we did not close fd" */
  5220. }
  5221. static int
  5222. internally_opened_fd(int fd, struct redirtab *sq)
  5223. {
  5224. int i;
  5225. #if JOBS
  5226. if (fd == ttyfd)
  5227. return 1;
  5228. #endif
  5229. /* If this one of script's fds? */
  5230. if (fd != 0) {
  5231. struct parsefile *pf = g_parsefile;
  5232. while (pf) {
  5233. if (fd == pf->pf_fd)
  5234. return 1;
  5235. pf = pf->prev;
  5236. }
  5237. }
  5238. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5239. if (fd == sq->two_fd[i].moved_to)
  5240. return 1;
  5241. }
  5242. return 0;
  5243. }
  5244. /*
  5245. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5246. * old file descriptors are stashed away so that the redirection can be
  5247. * undone by calling popredir.
  5248. */
  5249. /* flags passed to redirect */
  5250. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5251. static void
  5252. redirect(union node *redir, int flags)
  5253. {
  5254. struct redirtab *sv;
  5255. if (!redir)
  5256. return;
  5257. sv = NULL;
  5258. INT_OFF;
  5259. if (flags & REDIR_PUSH)
  5260. sv = redirlist;
  5261. do {
  5262. int fd;
  5263. int newfd;
  5264. int close_fd;
  5265. int closed;
  5266. fd = redir->nfile.fd;
  5267. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5268. //bb_error_msg("doing %d > %d", fd, newfd);
  5269. newfd = redir->ndup.dupfd;
  5270. close_fd = -1;
  5271. } else {
  5272. newfd = openredirect(redir); /* always >= 0 */
  5273. if (fd == newfd) {
  5274. /* open() gave us precisely the fd we wanted.
  5275. * This means that this fd was not busy
  5276. * (not opened to anywhere).
  5277. * Remember to close it on restore:
  5278. */
  5279. add_squirrel_closed(sv, fd);
  5280. continue;
  5281. }
  5282. close_fd = newfd;
  5283. }
  5284. if (fd == newfd)
  5285. continue;
  5286. /* if "N>FILE": move newfd to fd */
  5287. /* if "N>&M": dup newfd to fd */
  5288. /* if "N>&-": close fd (newfd is -1) */
  5289. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5290. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5291. if (newfd == -1) {
  5292. /* "N>&-" means "close me" */
  5293. if (!closed) {
  5294. /* ^^^ optimization: saving may already
  5295. * have closed it. If not... */
  5296. close(fd);
  5297. }
  5298. } else {
  5299. /* if newfd is a script fd or saved fd, simulate EBADF */
  5300. if (internally_opened_fd(newfd, sv)) {
  5301. errno = EBADF;
  5302. ash_msg_and_raise_perror("%d", newfd);
  5303. }
  5304. dup2_or_raise(newfd, fd);
  5305. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5306. close(close_fd);
  5307. #if BASH_REDIR_OUTPUT
  5308. if (redir->nfile.type == NTO2 && fd == 1) {
  5309. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5310. fd = 2;
  5311. newfd = 1;
  5312. close_fd = -1;
  5313. goto redirect_more;
  5314. }
  5315. #endif
  5316. }
  5317. } while ((redir = redir->nfile.next) != NULL);
  5318. INT_ON;
  5319. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5320. #define REDIR_SAVEFD2 0
  5321. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5322. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5323. // not only for calls with flags containing REDIR_SAVEFD2.
  5324. // We do this unconditionally (see save_fd_on_redirect()).
  5325. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5326. // preverrout_fd = copied_fd2;
  5327. }
  5328. static int
  5329. redirectsafe(union node *redir, int flags)
  5330. {
  5331. int err;
  5332. volatile int saveint;
  5333. struct jmploc *volatile savehandler = exception_handler;
  5334. struct jmploc jmploc;
  5335. SAVE_INT(saveint);
  5336. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5337. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5338. if (!err) {
  5339. exception_handler = &jmploc;
  5340. redirect(redir, flags);
  5341. }
  5342. exception_handler = savehandler;
  5343. if (err && exception_type != EXERROR)
  5344. longjmp(exception_handler->loc, 1);
  5345. RESTORE_INT(saveint);
  5346. return err;
  5347. }
  5348. static struct redirtab*
  5349. pushredir(union node *redir)
  5350. {
  5351. struct redirtab *sv;
  5352. int i;
  5353. if (!redir)
  5354. return redirlist;
  5355. i = 0;
  5356. do {
  5357. i++;
  5358. #if BASH_REDIR_OUTPUT
  5359. if (redir->nfile.type == NTO2)
  5360. i++;
  5361. #endif
  5362. redir = redir->nfile.next;
  5363. } while (redir);
  5364. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5365. sv->pair_count = i;
  5366. while (--i >= 0)
  5367. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5368. sv->next = redirlist;
  5369. redirlist = sv;
  5370. return sv->next;
  5371. }
  5372. /*
  5373. * Undo the effects of the last redirection.
  5374. */
  5375. static void
  5376. popredir(int drop)
  5377. {
  5378. struct redirtab *rp;
  5379. int i;
  5380. if (redirlist == NULL)
  5381. return;
  5382. INT_OFF;
  5383. rp = redirlist;
  5384. for (i = 0; i < rp->pair_count; i++) {
  5385. int fd = rp->two_fd[i].orig_fd;
  5386. int copy = rp->two_fd[i].moved_to;
  5387. if (copy == CLOSED) {
  5388. if (!drop)
  5389. close(fd);
  5390. continue;
  5391. }
  5392. if (copy != EMPTY) {
  5393. if (!drop) {
  5394. /*close(fd);*/
  5395. dup2_or_raise(copy, fd);
  5396. }
  5397. close(copy);
  5398. }
  5399. }
  5400. redirlist = rp->next;
  5401. free(rp);
  5402. INT_ON;
  5403. }
  5404. static void
  5405. unwindredir(struct redirtab *stop)
  5406. {
  5407. while (redirlist != stop)
  5408. popredir(/*drop:*/ 0);
  5409. }
  5410. /* ============ Routines to expand arguments to commands
  5411. *
  5412. * We have to deal with backquotes, shell variables, and file metacharacters.
  5413. */
  5414. #if ENABLE_FEATURE_SH_MATH
  5415. static arith_t
  5416. ash_arith(const char *s)
  5417. {
  5418. arith_state_t math_state;
  5419. arith_t result;
  5420. math_state.lookupvar = lookupvar;
  5421. math_state.setvar = setvar0;
  5422. //math_state.endofname = endofname;
  5423. INT_OFF;
  5424. result = arith(&math_state, s);
  5425. if (math_state.errmsg)
  5426. ash_msg_and_raise_error(math_state.errmsg);
  5427. INT_ON;
  5428. return result;
  5429. }
  5430. #endif
  5431. #if BASH_SUBSTR
  5432. # if ENABLE_FEATURE_SH_MATH
  5433. static int substr_atoi(const char *s)
  5434. {
  5435. arith_t t = ash_arith(s);
  5436. if (sizeof(t) > sizeof(int)) {
  5437. /* clamp very large or very large negative nums for ${v:N:M}:
  5438. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5439. */
  5440. if (t > INT_MAX)
  5441. t = INT_MAX;
  5442. if (t < INT_MIN)
  5443. t = INT_MIN;
  5444. }
  5445. return t;
  5446. }
  5447. # else
  5448. # define substr_atoi(s) number(s)
  5449. # endif
  5450. #endif
  5451. /*
  5452. * expandarg flags
  5453. */
  5454. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5455. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5456. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5457. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5458. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5459. * POSIX says for this case:
  5460. * Pathname expansion shall not be performed on the word by a
  5461. * non-interactive shell; an interactive shell may perform it, but shall
  5462. * do so only when the expansion would result in one word.
  5463. * Currently, our code complies to the above rule by never globbing
  5464. * redirection filenames.
  5465. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5466. * (this means that on a typical Linux distro, bash almost always
  5467. * performs globbing, and thus diverges from what we do).
  5468. */
  5469. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5470. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5471. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5472. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5473. #define EXP_KEEPNUL 0x200 /* do not skip NUL characters */
  5474. #define EXP_DISCARD 0x400 /* discard result of expansion */
  5475. /*
  5476. * rmescape() flags
  5477. */
  5478. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5479. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5480. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5481. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5482. /* Add CTLESC when necessary. */
  5483. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5484. /*
  5485. * Structure specifying which parts of the string should be searched
  5486. * for IFS characters.
  5487. */
  5488. struct ifsregion {
  5489. struct ifsregion *next; /* next region in list */
  5490. int begoff; /* offset of start of region */
  5491. int endoff; /* offset of end of region */
  5492. int nulonly; /* search for nul bytes only */
  5493. };
  5494. struct arglist {
  5495. struct strlist *list;
  5496. struct strlist **lastp;
  5497. };
  5498. /* output of current string */
  5499. static char *expdest;
  5500. /* list of back quote expressions */
  5501. static struct nodelist *argbackq;
  5502. /* first struct in list of ifs regions */
  5503. static struct ifsregion ifsfirst;
  5504. /* last struct in list */
  5505. static struct ifsregion *ifslastp;
  5506. /* holds expanded arg list */
  5507. static struct arglist exparg;
  5508. /*
  5509. * Break the argument string into pieces based upon IFS and add the
  5510. * strings to the argument list. The regions of the string to be
  5511. * searched for IFS characters have been stored by recordregion.
  5512. */
  5513. static void
  5514. ifsbreakup(char *string, struct arglist *arglist)
  5515. {
  5516. struct ifsregion *ifsp;
  5517. struct strlist *sp;
  5518. char *start;
  5519. char *p;
  5520. char *q;
  5521. const char *ifs, *realifs;
  5522. int ifsspc;
  5523. int nulonly;
  5524. start = string;
  5525. if (ifslastp != NULL) {
  5526. ifsspc = 0;
  5527. nulonly = 0;
  5528. realifs = ifsset() ? ifsval() : defifs;
  5529. ifsp = &ifsfirst;
  5530. do {
  5531. int afternul;
  5532. p = string + ifsp->begoff;
  5533. afternul = nulonly;
  5534. nulonly = ifsp->nulonly;
  5535. ifs = nulonly ? nullstr : realifs;
  5536. ifsspc = 0;
  5537. while (p < string + ifsp->endoff) {
  5538. q = p;
  5539. if ((unsigned char)*p == CTLESC)
  5540. p++;
  5541. if (!strchr(ifs, *p)) {
  5542. p++;
  5543. continue;
  5544. }
  5545. if (!(afternul || nulonly))
  5546. ifsspc = (strchr(defifs, *p) != NULL);
  5547. /* Ignore IFS whitespace at start */
  5548. if (q == start && ifsspc) {
  5549. p++;
  5550. start = p;
  5551. continue;
  5552. }
  5553. *q = '\0';
  5554. sp = stzalloc(sizeof(*sp));
  5555. sp->text = start;
  5556. *arglist->lastp = sp;
  5557. arglist->lastp = &sp->next;
  5558. p++;
  5559. if (!nulonly) {
  5560. for (;;) {
  5561. if (p >= string + ifsp->endoff) {
  5562. break;
  5563. }
  5564. q = p;
  5565. if ((unsigned char)*p == CTLESC)
  5566. p++;
  5567. if (strchr(ifs, *p) == NULL) {
  5568. p = q;
  5569. break;
  5570. }
  5571. if (strchr(defifs, *p) == NULL) {
  5572. if (ifsspc) {
  5573. p++;
  5574. ifsspc = 0;
  5575. } else {
  5576. p = q;
  5577. break;
  5578. }
  5579. } else
  5580. p++;
  5581. }
  5582. }
  5583. start = p;
  5584. } /* while */
  5585. ifsp = ifsp->next;
  5586. } while (ifsp != NULL);
  5587. if (nulonly)
  5588. goto add;
  5589. }
  5590. if (!*start)
  5591. return;
  5592. add:
  5593. sp = stzalloc(sizeof(*sp));
  5594. sp->text = start;
  5595. *arglist->lastp = sp;
  5596. arglist->lastp = &sp->next;
  5597. }
  5598. static void
  5599. ifsfree(void)
  5600. {
  5601. struct ifsregion *p = ifsfirst.next;
  5602. if (!p)
  5603. goto out;
  5604. INT_OFF;
  5605. do {
  5606. struct ifsregion *ifsp;
  5607. ifsp = p->next;
  5608. free(p);
  5609. p = ifsp;
  5610. } while (p);
  5611. ifsfirst.next = NULL;
  5612. INT_ON;
  5613. out:
  5614. ifslastp = NULL;
  5615. }
  5616. static size_t
  5617. esclen(const char *start, const char *p)
  5618. {
  5619. size_t esc = 0;
  5620. while (p > start && (unsigned char)*--p == CTLESC) {
  5621. esc++;
  5622. }
  5623. return esc;
  5624. }
  5625. /*
  5626. * Remove any CTLESC characters from a string.
  5627. */
  5628. #if !BASH_PATTERN_SUBST
  5629. #define rmescapes(str, flag, slash_position) \
  5630. rmescapes(str, flag)
  5631. #endif
  5632. static char *
  5633. rmescapes(char *str, int flag, int *slash_position)
  5634. {
  5635. static const char qchars[] ALIGN1 = {
  5636. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5637. char *p, *q, *r;
  5638. unsigned protect_against_glob;
  5639. unsigned globbing;
  5640. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5641. if (!p)
  5642. return str;
  5643. q = p;
  5644. r = str;
  5645. if (flag & RMESCAPE_ALLOC) {
  5646. size_t len = p - str;
  5647. size_t fulllen = len + strlen(p) + 1;
  5648. if (flag & RMESCAPE_GROW) {
  5649. int strloc = str - (char *)stackblock();
  5650. r = makestrspace(fulllen, expdest);
  5651. /* p and str may be invalidated by makestrspace */
  5652. str = (char *)stackblock() + strloc;
  5653. p = str + len;
  5654. } else if (flag & RMESCAPE_HEAP) {
  5655. r = ckmalloc(fulllen);
  5656. } else {
  5657. r = stalloc(fulllen);
  5658. }
  5659. q = r;
  5660. if (len > 0) {
  5661. q = (char *)mempcpy(q, str, len);
  5662. }
  5663. }
  5664. globbing = flag & RMESCAPE_GLOB;
  5665. protect_against_glob = globbing;
  5666. while (*p) {
  5667. if ((unsigned char)*p == CTLQUOTEMARK) {
  5668. // Note: protect_against_glob only affect whether
  5669. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5670. p++;
  5671. protect_against_glob = globbing;
  5672. continue;
  5673. }
  5674. if (*p == '\\') {
  5675. /* naked back slash */
  5676. protect_against_glob = 0;
  5677. goto copy;
  5678. }
  5679. if ((unsigned char)*p == CTLESC) {
  5680. p++;
  5681. #if DEBUG
  5682. if (*p == '\0')
  5683. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5684. #endif
  5685. if (protect_against_glob) {
  5686. /*
  5687. * We used to trust glob() and fnmatch() to eat
  5688. * superfluous escapes (\z where z has no
  5689. * special meaning anyway). But this causes
  5690. * bugs such as string of one greek letter rho
  5691. * (unicode-encoded as two bytes "cf,81")
  5692. * getting encoded as "cf,CTLESC,81"
  5693. * and here, converted to "cf,\,81" -
  5694. * which does not go well with some flavors
  5695. * of fnmatch() in unicode locales
  5696. * (for example, glibc <= 2.22).
  5697. *
  5698. * Lets add "\" only on the chars which need it.
  5699. * Testcases for less obvious chars are shown.
  5700. */
  5701. if (*p == '*'
  5702. || *p == '?'
  5703. || *p == '['
  5704. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5705. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5706. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5707. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5708. /* Some libc support [^negate], that's why "^" also needs love */
  5709. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5710. ) {
  5711. *q++ = '\\';
  5712. }
  5713. }
  5714. }
  5715. #if BASH_PATTERN_SUBST
  5716. else if (slash_position && p == str + *slash_position) {
  5717. /* stop handling globbing */
  5718. globbing = 0;
  5719. *slash_position = q - r;
  5720. slash_position = NULL;
  5721. }
  5722. #endif
  5723. protect_against_glob = globbing;
  5724. copy:
  5725. *q++ = *p++;
  5726. }
  5727. *q = '\0';
  5728. if (flag & RMESCAPE_GROW) {
  5729. expdest = r;
  5730. STADJUST(q - r + 1, expdest);
  5731. }
  5732. return r;
  5733. }
  5734. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5735. /*
  5736. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5737. *
  5738. * Returns an stalloced string.
  5739. */
  5740. static char *
  5741. preglob(const char *pattern, int flag)
  5742. {
  5743. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5744. }
  5745. /*
  5746. * Put a string on the stack.
  5747. */
  5748. static size_t
  5749. memtodest(const char *p, size_t len, int flags)
  5750. {
  5751. int syntax = flags & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5752. char *q;
  5753. char *s;
  5754. if (!len)
  5755. return 0;
  5756. q = makestrspace(len * 2, expdest);
  5757. s = q;
  5758. do {
  5759. unsigned char c = *p++;
  5760. if (c) {
  5761. if (flags & QUOTES_ESC) {
  5762. int n = SIT(c, syntax);
  5763. if (n == CCTL
  5764. || ((flags & EXP_QUOTED) && n == CBACK)
  5765. ) {
  5766. USTPUTC(CTLESC, q);
  5767. }
  5768. }
  5769. } else if (!(flags & EXP_KEEPNUL))
  5770. continue;
  5771. USTPUTC(c, q);
  5772. } while (--len);
  5773. expdest = q;
  5774. return q - s;
  5775. }
  5776. static size_t
  5777. strtodest(const char *p, int flags)
  5778. {
  5779. size_t len = strlen(p);
  5780. memtodest(p, len, flags);
  5781. return len;
  5782. }
  5783. /*
  5784. * Our own itoa().
  5785. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5786. */
  5787. static int
  5788. cvtnum(arith_t num, int flags)
  5789. {
  5790. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5791. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5792. int len = (sizeof(arith_t) >= 4) ? sizeof(arith_t) * 3 : sizeof(arith_t) * 3 + 2;
  5793. char buf[len];
  5794. len = fmtstr(buf, len, ARITH_FMT, num);
  5795. return memtodest(buf, len, flags);
  5796. }
  5797. /*
  5798. * Record the fact that we have to scan this region of the
  5799. * string for IFS characters.
  5800. */
  5801. static void
  5802. recordregion(int start, int end, int nulonly)
  5803. {
  5804. struct ifsregion *ifsp;
  5805. if (ifslastp == NULL) {
  5806. ifsp = &ifsfirst;
  5807. } else {
  5808. INT_OFF;
  5809. ifsp = ckzalloc(sizeof(*ifsp));
  5810. /*ifsp->next = NULL; - ckzalloc did it */
  5811. ifslastp->next = ifsp;
  5812. INT_ON;
  5813. }
  5814. ifslastp = ifsp;
  5815. ifslastp->begoff = start;
  5816. ifslastp->endoff = end;
  5817. ifslastp->nulonly = nulonly;
  5818. }
  5819. static void
  5820. removerecordregions(int endoff)
  5821. {
  5822. if (ifslastp == NULL)
  5823. return;
  5824. if (ifsfirst.endoff > endoff) {
  5825. while (ifsfirst.next) {
  5826. struct ifsregion *ifsp;
  5827. INT_OFF;
  5828. ifsp = ifsfirst.next->next;
  5829. free(ifsfirst.next);
  5830. ifsfirst.next = ifsp;
  5831. INT_ON;
  5832. }
  5833. if (ifsfirst.begoff > endoff) {
  5834. ifslastp = NULL;
  5835. } else {
  5836. ifslastp = &ifsfirst;
  5837. ifsfirst.endoff = endoff;
  5838. }
  5839. return;
  5840. }
  5841. ifslastp = &ifsfirst;
  5842. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5843. ifslastp = ifslastp->next;
  5844. while (ifslastp->next) {
  5845. struct ifsregion *ifsp;
  5846. INT_OFF;
  5847. ifsp = ifslastp->next->next;
  5848. free(ifslastp->next);
  5849. ifslastp->next = ifsp;
  5850. INT_ON;
  5851. }
  5852. if (ifslastp->endoff > endoff)
  5853. ifslastp->endoff = endoff;
  5854. }
  5855. static char *
  5856. exptilde(char *startp, int flag)
  5857. {
  5858. unsigned char c;
  5859. char *name;
  5860. struct passwd *pw;
  5861. const char *home;
  5862. char *p;
  5863. p = startp;
  5864. name = p + 1;
  5865. while ((c = *++p) != '\0') {
  5866. switch (c) {
  5867. case CTLESC:
  5868. return startp;
  5869. case CTLQUOTEMARK:
  5870. return startp;
  5871. case ':':
  5872. if (flag & EXP_VARTILDE)
  5873. goto done;
  5874. break;
  5875. case '/':
  5876. case CTLENDVAR:
  5877. goto done;
  5878. }
  5879. }
  5880. done:
  5881. if (flag & EXP_DISCARD)
  5882. goto out;
  5883. *p = '\0';
  5884. if (*name == '\0') {
  5885. home = lookupvar("HOME");
  5886. } else {
  5887. pw = getpwnam(name);
  5888. if (pw == NULL)
  5889. goto lose;
  5890. home = pw->pw_dir;
  5891. }
  5892. *p = c;
  5893. if (!home)
  5894. goto lose;
  5895. strtodest(home, flag | EXP_QUOTED);
  5896. out:
  5897. return p;
  5898. lose:
  5899. return startp;
  5900. }
  5901. /*
  5902. * Execute a command inside back quotes. If it's a builtin command, we
  5903. * want to save its output in a block obtained from malloc. Otherwise
  5904. * we fork off a subprocess and get the output of the command via a pipe.
  5905. * Should be called with interrupts off.
  5906. */
  5907. struct backcmd { /* result of evalbackcmd */
  5908. int fd; /* file descriptor to read from */
  5909. int nleft; /* number of chars in buffer */
  5910. char *buf; /* buffer */
  5911. struct job *jp; /* job structure for command */
  5912. };
  5913. /* These forward decls are needed to use "eval" code for backticks handling: */
  5914. /* flags in argument to evaltree */
  5915. #define EV_EXIT 01 /* exit after evaluating tree */
  5916. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5917. static int evaltree(union node *, int);
  5918. /* An evaltree() which is known to never return.
  5919. * Used to use an alias:
  5920. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5921. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5922. */
  5923. static ALWAYS_INLINE NORETURN void
  5924. evaltreenr(union node *n, int flags)
  5925. {
  5926. evaltree(n, flags);
  5927. bb_unreachable(abort());
  5928. /* NOTREACHED */
  5929. }
  5930. static void FAST_FUNC
  5931. evalbackcmd(union node *n, struct backcmd *result)
  5932. {
  5933. int pip[2];
  5934. struct job *jp;
  5935. result->fd = -1;
  5936. result->buf = NULL;
  5937. result->nleft = 0;
  5938. result->jp = NULL;
  5939. if (n == NULL) {
  5940. goto out;
  5941. }
  5942. if (pipe(pip) < 0)
  5943. ash_msg_and_raise_perror("can't create pipe");
  5944. jp = makejob(/*n,*/ 1);
  5945. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5946. /* child */
  5947. FORCE_INT_ON;
  5948. close(pip[0]);
  5949. if (pip[1] != 1) {
  5950. /*close(1);*/
  5951. dup2_or_raise(pip[1], 1);
  5952. close(pip[1]);
  5953. }
  5954. /* TODO: eflag clearing makes the following not abort:
  5955. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5956. * which is what bash does (unless it is in POSIX mode).
  5957. * dash deleted "eflag = 0" line in the commit
  5958. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5959. * [EVAL] Don't clear eflag in evalbackcmd
  5960. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5961. */
  5962. eflag = 0;
  5963. ifsfree();
  5964. evaltreenr(n, EV_EXIT);
  5965. /* NOTREACHED */
  5966. }
  5967. /* parent */
  5968. close(pip[1]);
  5969. result->fd = pip[0];
  5970. result->jp = jp;
  5971. out:
  5972. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5973. result->fd, result->buf, result->nleft, result->jp));
  5974. }
  5975. /*
  5976. * Expand stuff in backwards quotes.
  5977. */
  5978. static void
  5979. expbackq(union node *cmd, int flag)
  5980. {
  5981. struct backcmd in;
  5982. int i;
  5983. char buf[128];
  5984. char *p;
  5985. char *dest;
  5986. int startloc;
  5987. struct stackmark smark;
  5988. if (flag & EXP_DISCARD)
  5989. goto out;
  5990. INT_OFF;
  5991. startloc = expdest - (char *)stackblock();
  5992. pushstackmark(&smark, startloc);
  5993. evalbackcmd(cmd, &in);
  5994. popstackmark(&smark);
  5995. p = in.buf;
  5996. i = in.nleft;
  5997. if (i == 0)
  5998. goto read;
  5999. for (;;) {
  6000. memtodest(p, i, flag);
  6001. read:
  6002. if (in.fd < 0)
  6003. break;
  6004. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  6005. TRACE(("expbackq: read returns %d\n", i));
  6006. if (i <= 0)
  6007. break;
  6008. p = buf;
  6009. }
  6010. free(in.buf);
  6011. if (in.fd >= 0) {
  6012. close(in.fd);
  6013. back_exitstatus = waitforjob(in.jp);
  6014. }
  6015. INT_ON;
  6016. /* Eat all trailing newlines */
  6017. dest = expdest;
  6018. for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';)
  6019. STUNPUTC(dest);
  6020. expdest = dest;
  6021. if (!(flag & EXP_QUOTED))
  6022. recordregion(startloc, dest - (char *)stackblock(), 0);
  6023. TRACE(("evalbackq: size:%d:'%.*s'\n",
  6024. (int)((dest - (char *)stackblock()) - startloc),
  6025. (int)((dest - (char *)stackblock()) - startloc),
  6026. stackblock() + startloc));
  6027. out:
  6028. argbackq = argbackq->next;
  6029. }
  6030. /* expari needs it */
  6031. static char *argstr(char *p, int flag);
  6032. #if ENABLE_FEATURE_SH_MATH
  6033. /*
  6034. * Expand arithmetic expression. Backup to start of expression,
  6035. * evaluate, place result in (backed up) result, adjust string position.
  6036. */
  6037. static char *
  6038. expari(char *start, int flag)
  6039. {
  6040. struct stackmark sm;
  6041. int begoff;
  6042. int endoff;
  6043. int len;
  6044. arith_t result;
  6045. char *p;
  6046. p = stackblock();
  6047. begoff = expdest - p;
  6048. p = argstr(start, flag & EXP_DISCARD);
  6049. if (flag & EXP_DISCARD)
  6050. goto out;
  6051. start = stackblock();
  6052. endoff = expdest - start;
  6053. start += begoff;
  6054. STADJUST(start - expdest, expdest);
  6055. removerecordregions(begoff);
  6056. if (flag & QUOTES_ESC)
  6057. rmescapes(start, 0, NULL);
  6058. pushstackmark(&sm, endoff);
  6059. result = ash_arith(start);
  6060. popstackmark(&sm);
  6061. len = cvtnum(result, flag);
  6062. if (!(flag & EXP_QUOTED))
  6063. recordregion(begoff, begoff + len, 0);
  6064. out:
  6065. return p;
  6066. }
  6067. #endif
  6068. /* argstr needs it */
  6069. static char *evalvar(char *p, int flags);
  6070. /*
  6071. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  6072. * characters to allow for further processing. Otherwise treat
  6073. * $@ like $* since no splitting will be performed.
  6074. */
  6075. static char *
  6076. argstr(char *p, int flag)
  6077. {
  6078. static const char spclchars[] ALIGN1 = {
  6079. '=',
  6080. ':',
  6081. CTLQUOTEMARK,
  6082. CTLENDVAR,
  6083. CTLESC,
  6084. CTLVAR,
  6085. CTLBACKQ,
  6086. #if ENABLE_FEATURE_SH_MATH
  6087. CTLARI,
  6088. CTLENDARI,
  6089. #endif
  6090. '\0'
  6091. };
  6092. const char *reject = spclchars;
  6093. int breakall = (flag & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6094. int inquotes;
  6095. size_t length;
  6096. int startloc;
  6097. reject += !!(flag & EXP_VARTILDE2);
  6098. reject += flag & EXP_VARTILDE ? 0 : 2;
  6099. inquotes = 0;
  6100. length = 0;
  6101. if (flag & EXP_TILDE) {
  6102. flag &= ~EXP_TILDE;
  6103. tilde:
  6104. if (*p == '~')
  6105. p = exptilde(p, flag);
  6106. }
  6107. start:
  6108. startloc = expdest - (char *)stackblock();
  6109. for (;;) {
  6110. int end;
  6111. unsigned char c;
  6112. length += strcspn(p + length, reject);
  6113. end = 0;
  6114. c = p[length];
  6115. if (!(c & 0x80)
  6116. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6117. || c == CTLENDVAR
  6118. ) {
  6119. /*
  6120. * c == '=' || c == ':' || c == '\0' ||
  6121. * c == CTLENDARI || c == CTLENDVAR
  6122. */
  6123. length++;
  6124. /* c == '\0' || c == CTLENDARI || c == CTLENDVAR */
  6125. end = !!((c - 1) & 0x80);
  6126. }
  6127. if (length > 0 && !(flag & EXP_DISCARD)) {
  6128. int newloc;
  6129. char *q;
  6130. q = stnputs(p, length, expdest);
  6131. q[-1] &= end - 1;
  6132. expdest = q - (flag & EXP_WORD ? end : 0);
  6133. newloc = q - (char *)stackblock() - end;
  6134. if (breakall && !inquotes && newloc > startloc) {
  6135. recordregion(startloc, newloc, 0);
  6136. }
  6137. startloc = newloc;
  6138. }
  6139. p += length + 1;
  6140. length = 0;
  6141. if (end)
  6142. break;
  6143. switch (c) {
  6144. case '=':
  6145. flag |= EXP_VARTILDE2;
  6146. reject++;
  6147. /* fall through */
  6148. case ':':
  6149. /*
  6150. * sort of a hack - expand tildes in variable
  6151. * assignments (after the first '=' and after ':'s).
  6152. */
  6153. if (*--p == '~') {
  6154. goto tilde;
  6155. }
  6156. continue;
  6157. case CTLQUOTEMARK:
  6158. /* "$@" syntax adherence hack */
  6159. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6160. p = evalvar(p + 1, flag | EXP_QUOTED) + 1;
  6161. goto start;
  6162. }
  6163. inquotes ^= EXP_QUOTED;
  6164. addquote:
  6165. if (flag & QUOTES_ESC) {
  6166. p--;
  6167. length++;
  6168. startloc++;
  6169. }
  6170. break;
  6171. case CTLESC:
  6172. startloc++;
  6173. length++;
  6174. goto addquote;
  6175. case CTLVAR:
  6176. TRACE(("argstr: evalvar('%s')\n", p));
  6177. p = evalvar(p, flag | inquotes);
  6178. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6179. goto start;
  6180. case CTLBACKQ:
  6181. expbackq(argbackq->n, flag | inquotes);
  6182. goto start;
  6183. #if ENABLE_FEATURE_SH_MATH
  6184. case CTLARI:
  6185. p = expari(p, flag | inquotes);
  6186. goto start;
  6187. #endif
  6188. }
  6189. }
  6190. return p - 1;
  6191. }
  6192. static char *
  6193. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6194. char *pattern, int quotes, int zero)
  6195. {
  6196. char *loc, *loc2;
  6197. char c;
  6198. loc = startp;
  6199. loc2 = rmesc;
  6200. do {
  6201. int match;
  6202. const char *s = loc2;
  6203. c = *loc2;
  6204. if (zero) {
  6205. *loc2 = '\0';
  6206. s = rmesc;
  6207. }
  6208. match = pmatch(pattern, s);
  6209. *loc2 = c;
  6210. if (match)
  6211. return loc;
  6212. if (quotes && (unsigned char)*loc == CTLESC)
  6213. loc++;
  6214. loc++;
  6215. loc2++;
  6216. } while (c);
  6217. return NULL;
  6218. }
  6219. static char *
  6220. scanright(char *startp, char *rmesc, char *rmescend,
  6221. char *pattern, int quotes, int match_at_start)
  6222. {
  6223. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6224. int try2optimize = match_at_start;
  6225. #endif
  6226. int esc = 0;
  6227. char *loc;
  6228. char *loc2;
  6229. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6230. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6231. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6232. * Logic:
  6233. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6234. * and on each iteration they go back two/one char until they reach the beginning.
  6235. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6236. */
  6237. /* TODO: document in what other circumstances we are called. */
  6238. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6239. int match;
  6240. char c = *loc2;
  6241. const char *s = loc2;
  6242. if (match_at_start) {
  6243. *loc2 = '\0';
  6244. s = rmesc;
  6245. }
  6246. match = pmatch(pattern, s);
  6247. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6248. *loc2 = c;
  6249. if (match)
  6250. return loc;
  6251. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6252. if (try2optimize) {
  6253. /* Maybe we can optimize this:
  6254. * if pattern ends with unescaped *, we can avoid checking
  6255. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6256. * it won't match truncated "raw_value_of_" strings too.
  6257. */
  6258. unsigned plen = strlen(pattern);
  6259. /* Does it end with "*"? */
  6260. if (plen != 0 && pattern[--plen] == '*') {
  6261. /* "xxxx*" is not escaped */
  6262. /* "xxx\*" is escaped */
  6263. /* "xx\\*" is not escaped */
  6264. /* "x\\\*" is escaped */
  6265. int slashes = 0;
  6266. while (plen != 0 && pattern[--plen] == '\\')
  6267. slashes++;
  6268. if (!(slashes & 1))
  6269. break; /* ends with unescaped "*" */
  6270. }
  6271. try2optimize = 0;
  6272. }
  6273. #endif
  6274. loc--;
  6275. if (quotes) {
  6276. if (--esc < 0) {
  6277. esc = esclen(startp, loc);
  6278. }
  6279. if (esc % 2) {
  6280. esc--;
  6281. loc--;
  6282. }
  6283. }
  6284. }
  6285. return NULL;
  6286. }
  6287. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6288. static void
  6289. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6290. {
  6291. const char *msg;
  6292. const char *tail;
  6293. tail = nullstr;
  6294. msg = "parameter not set";
  6295. if (umsg) {
  6296. if ((unsigned char)*end == CTLENDVAR) {
  6297. if (varflags & VSNUL)
  6298. tail = " or null";
  6299. } else {
  6300. msg = umsg;
  6301. }
  6302. }
  6303. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6304. }
  6305. static char *
  6306. subevalvar(char *start, char *str, int strloc,
  6307. int startloc, int varflags, int flag)
  6308. {
  6309. int subtype = varflags & VSTYPE;
  6310. int quotes = flag & QUOTES_ESC;
  6311. char *startp;
  6312. char *loc;
  6313. char *rmesc, *rmescend;
  6314. long amount;
  6315. int resetloc;
  6316. int argstr_flags;
  6317. IF_BASH_PATTERN_SUBST(int workloc;)
  6318. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6319. IF_BASH_PATTERN_SUBST(char *repl;)
  6320. int zero;
  6321. char *(*scan)(char*, char*, char*, char*, int, int);
  6322. char *p;
  6323. //bb_error_msg("subevalvar(start:'%s',str:'%s',strloc:%d,startloc:%d,varflags:%x,quotes:%d)",
  6324. // start, str, strloc, startloc, varflags, quotes);
  6325. #if BASH_PATTERN_SUBST
  6326. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6327. * argstr() call expands possible variable references in pattern:
  6328. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6329. */
  6330. repl = NULL;
  6331. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6332. /* Find '/' and replace with NUL */
  6333. repl = start;
  6334. /* The pattern can't be empty.
  6335. * IOW: if the first char after "${v//" is a slash,
  6336. * it does not terminate the pattern - it's the first char of the pattern:
  6337. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6338. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6339. */
  6340. if (*repl == '/')
  6341. repl++;
  6342. for (;;) {
  6343. if (*repl == '\0') {
  6344. repl = NULL;
  6345. break;
  6346. }
  6347. if (*repl == '/') {
  6348. *repl = '\0';
  6349. break;
  6350. }
  6351. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6352. if ((unsigned char)*repl == CTLESC && repl[1])
  6353. repl++;
  6354. repl++;
  6355. }
  6356. }
  6357. #endif
  6358. argstr_flags = (flag & EXP_DISCARD) | EXP_TILDE;
  6359. if (!str
  6360. #if BASH_SUBSTR
  6361. && subtype != VSSUBSTR
  6362. #endif
  6363. ) {
  6364. /* EXP_CASE keeps CTLESC's */
  6365. argstr_flags |= EXP_CASE;
  6366. }
  6367. p = argstr(start, argstr_flags);
  6368. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6369. #if BASH_PATTERN_SUBST
  6370. slash_pos = -1;
  6371. if (repl) {
  6372. slash_pos = expdest - ((char *)stackblock() + strloc);
  6373. if (!(flag & EXP_DISCARD))
  6374. STPUTC('/', expdest);
  6375. //bb_error_msg("repl+1:'%s'", repl + 1);
  6376. p = argstr(repl + 1, (flag & EXP_DISCARD) | EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6377. *repl = '/';
  6378. }
  6379. #endif
  6380. if (flag & EXP_DISCARD)
  6381. return p;
  6382. startp = (char *)stackblock() + startloc;
  6383. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6384. switch (subtype) {
  6385. case VSASSIGN:
  6386. setvar0(str, startp);
  6387. loc = startp;
  6388. goto out;
  6389. case VSQUESTION:
  6390. varunset(start, str, startp, varflags);
  6391. /* NOTREACHED */
  6392. #if BASH_SUBSTR
  6393. case VSSUBSTR: {
  6394. int pos, len, orig_len;
  6395. char *colon;
  6396. char *vstr;
  6397. loc = vstr = stackblock() + strloc;
  6398. /* Read POS in ${var:POS:LEN} */
  6399. colon = strchr(loc, ':');
  6400. if (colon) *colon = '\0';
  6401. pos = substr_atoi(loc);
  6402. if (colon) *colon = ':';
  6403. /* Read LEN in ${var:POS:LEN} */
  6404. len = vstr - startp - 1;
  6405. /* *loc != '\0', guaranteed by parser */
  6406. if (quotes) {
  6407. char *ptr;
  6408. /* Adjust the length by the number of escapes */
  6409. for (ptr = startp; ptr < (vstr - 1); ptr++) {
  6410. if ((unsigned char)*ptr == CTLESC) {
  6411. len--;
  6412. ptr++;
  6413. }
  6414. }
  6415. }
  6416. orig_len = len;
  6417. if (*loc++ == ':') {
  6418. /* ${var::LEN} */
  6419. len = substr_atoi(loc);
  6420. } else {
  6421. /* Skip POS in ${var:POS:LEN} */
  6422. len = orig_len;
  6423. while (*loc && *loc != ':')
  6424. loc++;
  6425. if (*loc++ == ':')
  6426. len = substr_atoi(loc);
  6427. }
  6428. if (pos < 0) {
  6429. /* ${VAR:$((-n)):l} starts n chars from the end */
  6430. pos = orig_len + pos;
  6431. }
  6432. if ((unsigned)pos >= orig_len) {
  6433. /* apart from obvious ${VAR:999999:l},
  6434. * covers ${VAR:$((-9999999)):l} - result is ""
  6435. * (bash compat)
  6436. */
  6437. pos = 0;
  6438. len = 0;
  6439. }
  6440. if (len < 0) {
  6441. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6442. len = (orig_len - pos) + len;
  6443. }
  6444. if ((unsigned)len > (orig_len - pos))
  6445. len = orig_len - pos;
  6446. for (vstr = startp; pos; vstr++, pos--) {
  6447. if (quotes && (unsigned char)*vstr == CTLESC)
  6448. vstr++;
  6449. }
  6450. for (loc = startp; len; len--) {
  6451. if (quotes && (unsigned char)*vstr == CTLESC)
  6452. *loc++ = *vstr++;
  6453. *loc++ = *vstr++;
  6454. }
  6455. *loc = '\0';
  6456. goto out;
  6457. }
  6458. #endif /* BASH_SUBSTR */
  6459. }
  6460. resetloc = expdest - (char *)stackblock();
  6461. #if BASH_PATTERN_SUBST
  6462. repl = NULL;
  6463. /* We'll comeback here if we grow the stack while handling
  6464. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6465. * stack will need rebasing, and we'll need to remove our work
  6466. * areas each time
  6467. */
  6468. restart:
  6469. #endif
  6470. amount = expdest - ((char *)stackblock() + resetloc);
  6471. STADJUST(-amount, expdest);
  6472. startp = (char *)stackblock() + startloc;
  6473. rmesc = startp;
  6474. rmescend = (char *)stackblock() + strloc;
  6475. //bb_error_msg("str7:'%s'", rmescend);
  6476. if (quotes) {
  6477. //TODO: how to handle slash_pos here if string changes (shortens?)
  6478. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6479. if (rmesc != startp) {
  6480. rmescend = expdest;
  6481. startp = (char *)stackblock() + startloc;
  6482. }
  6483. }
  6484. rmescend--;
  6485. str = (char *)stackblock() + strloc;
  6486. /*
  6487. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6488. * The result is a_\_z_c (not a\_\_z_c)!
  6489. *
  6490. * The search pattern and replace string treat backslashes differently!
  6491. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6492. * and string. It's only used on the first call.
  6493. */
  6494. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6495. rmescapes(str, RMESCAPE_GLOB,
  6496. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6497. );
  6498. #if BASH_PATTERN_SUBST
  6499. workloc = expdest - (char *)stackblock();
  6500. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6501. int len;
  6502. char *idx, *end;
  6503. if (!repl) {
  6504. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6505. repl = nullstr;
  6506. if (slash_pos >= 0) {
  6507. repl = str + slash_pos;
  6508. *repl++ = '\0';
  6509. }
  6510. }
  6511. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6512. /* If there's no pattern to match, return the expansion unmolested */
  6513. if (str[0] == '\0')
  6514. goto out1;
  6515. len = 0;
  6516. idx = startp;
  6517. end = str - 1;
  6518. while (idx < end) {
  6519. try_to_match:
  6520. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6521. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6522. if (!loc) {
  6523. /* No match, advance */
  6524. char *restart_detect = stackblock();
  6525. skip_matching:
  6526. STPUTC(*idx, expdest);
  6527. if (quotes && (unsigned char)*idx == CTLESC) {
  6528. idx++;
  6529. len++;
  6530. STPUTC(*idx, expdest);
  6531. }
  6532. if (stackblock() != restart_detect)
  6533. goto restart;
  6534. idx++;
  6535. len++;
  6536. rmesc++;
  6537. /* continue; - prone to quadratic behavior, smarter code: */
  6538. if (idx >= end)
  6539. break;
  6540. if (str[0] == '*') {
  6541. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6542. * it would never match "ong_string" etc, no point in trying.
  6543. */
  6544. goto skip_matching;
  6545. }
  6546. goto try_to_match;
  6547. }
  6548. if (subtype == VSREPLACEALL) {
  6549. while (idx < loc) {
  6550. if (quotes && (unsigned char)*idx == CTLESC)
  6551. idx++;
  6552. idx++;
  6553. rmesc++;
  6554. }
  6555. } else {
  6556. idx = loc;
  6557. }
  6558. //bb_error_msg("repl:'%s'", repl);
  6559. for (loc = (char*)repl; *loc; loc++) {
  6560. char *restart_detect = stackblock();
  6561. if (quotes && *loc == '\\') {
  6562. STPUTC(CTLESC, expdest);
  6563. len++;
  6564. }
  6565. STPUTC(*loc, expdest);
  6566. if (stackblock() != restart_detect)
  6567. goto restart;
  6568. len++;
  6569. }
  6570. if (subtype == VSREPLACE) {
  6571. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6572. while (*idx) {
  6573. char *restart_detect = stackblock();
  6574. STPUTC(*idx, expdest);
  6575. if (stackblock() != restart_detect)
  6576. goto restart;
  6577. len++;
  6578. idx++;
  6579. }
  6580. break;
  6581. }
  6582. }
  6583. /* We've put the replaced text into a buffer at workloc, now
  6584. * move it to the right place and adjust the stack.
  6585. */
  6586. STPUTC('\0', expdest);
  6587. startp = (char *)stackblock() + startloc;
  6588. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6589. //bb_error_msg("startp:'%s'", startp);
  6590. loc = startp + len;
  6591. goto out;
  6592. }
  6593. #endif /* BASH_PATTERN_SUBST */
  6594. subtype -= VSTRIMRIGHT;
  6595. #if DEBUG
  6596. if (subtype < 0 || subtype > 7)
  6597. abort();
  6598. #endif
  6599. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6600. zero = subtype >> 1;
  6601. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6602. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6603. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6604. if (loc) {
  6605. if (zero) {
  6606. memmove(startp, loc, str - loc);
  6607. loc = startp + (str - loc) - 1;
  6608. }
  6609. *loc = '\0';
  6610. } else
  6611. loc = str - 1;
  6612. out:
  6613. amount = loc - expdest;
  6614. STADJUST(amount, expdest);
  6615. out1:
  6616. /* Remove any recorded regions beyond start of variable */
  6617. removerecordregions(startloc);
  6618. return p;
  6619. }
  6620. /*
  6621. * Add the value of a specialized variable to the stack string.
  6622. * name parameter (examples):
  6623. * ash -c 'echo $1' name:'1='
  6624. * ash -c 'echo $qwe' name:'qwe='
  6625. * ash -c 'echo $$' name:'$='
  6626. * ash -c 'echo ${$}' name:'$='
  6627. * ash -c 'echo ${$##q}' name:'$=q'
  6628. * ash -c 'echo ${#$}' name:'$='
  6629. * note: examples with bad shell syntax:
  6630. * ash -c 'echo ${#$1}' name:'$=1'
  6631. * ash -c 'echo ${#1#}' name:'1=#'
  6632. */
  6633. static NOINLINE ssize_t
  6634. varvalue(char *name, int varflags, int flags, int quoted)
  6635. {
  6636. const char *p;
  6637. int num;
  6638. int i;
  6639. ssize_t len = 0;
  6640. int sep;
  6641. int subtype = varflags & VSTYPE;
  6642. int discard = (subtype == VSPLUS || subtype == VSLENGTH) | (flags & EXP_DISCARD);
  6643. if (!subtype) {
  6644. if (discard)
  6645. return -1;
  6646. raise_error_syntax("bad substitution");
  6647. }
  6648. flags |= EXP_KEEPNUL;
  6649. flags &= discard ? ~QUOTES_ESC : ~0;
  6650. sep = (flags & EXP_FULL) << CHAR_BIT;
  6651. switch (*name) {
  6652. case '$':
  6653. num = rootpid;
  6654. goto numvar;
  6655. case '?':
  6656. num = exitstatus;
  6657. goto numvar;
  6658. case '#':
  6659. num = shellparam.nparam;
  6660. goto numvar;
  6661. case '!':
  6662. num = backgndpid;
  6663. if (num == 0)
  6664. return -1;
  6665. numvar:
  6666. len = cvtnum(num, flags);
  6667. goto check_1char_name;
  6668. case '-':
  6669. expdest = makestrspace(NOPTS, expdest);
  6670. for (i = NOPTS - 1; i >= 0; i--) {
  6671. if (optlist[i] && optletters(i)) {
  6672. USTPUTC(optletters(i), expdest);
  6673. len++;
  6674. }
  6675. }
  6676. check_1char_name:
  6677. #if 0
  6678. /* handles cases similar to ${#$1} */
  6679. if (name[2] != '\0')
  6680. raise_error_syntax("bad substitution");
  6681. #endif
  6682. break;
  6683. case '@':
  6684. if (quoted && sep)
  6685. goto param;
  6686. /* fall through */
  6687. case '*': {
  6688. char **ap;
  6689. char sepc;
  6690. char c;
  6691. /* We will set c to 0 or ~0 depending on whether
  6692. * we're doing field splitting. We won't do field
  6693. * splitting if either we're quoted or sep is zero.
  6694. *
  6695. * Instead of testing (quoted || !sep) the following
  6696. * trick optimises away any branches by using the
  6697. * fact that EXP_QUOTED (which is the only bit that
  6698. * can be set in quoted) is the same as EXP_FULL <<
  6699. * CHAR_BIT (which is the only bit that can be set
  6700. * in sep).
  6701. */
  6702. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6703. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6704. #endif
  6705. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6706. sep &= ~quoted;
  6707. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6708. param:
  6709. sepc = sep;
  6710. ap = shellparam.p;
  6711. if (!ap)
  6712. return -1;
  6713. while ((p = *ap++) != NULL) {
  6714. len += strtodest(p, flags);
  6715. if (*ap && sep) {
  6716. len++;
  6717. memtodest(&sepc, 1, flags);
  6718. }
  6719. }
  6720. break;
  6721. } /* case '*' */
  6722. case '0':
  6723. case '1':
  6724. case '2':
  6725. case '3':
  6726. case '4':
  6727. case '5':
  6728. case '6':
  6729. case '7':
  6730. case '8':
  6731. case '9':
  6732. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6733. if (num < 0 || num > shellparam.nparam)
  6734. return -1;
  6735. p = num ? shellparam.p[num - 1] : arg0;
  6736. goto value;
  6737. default:
  6738. /* NB: name has form "VAR=..." */
  6739. p = lookupvar(name);
  6740. value:
  6741. if (!p)
  6742. return -1;
  6743. len = strtodest(p, flags);
  6744. #if ENABLE_UNICODE_SUPPORT
  6745. if (subtype == VSLENGTH && len > 0) {
  6746. reinit_unicode_for_ash();
  6747. if (unicode_status == UNICODE_ON) {
  6748. STADJUST(-len, expdest);
  6749. discard = 0;
  6750. len = unicode_strlen(p);
  6751. }
  6752. }
  6753. #endif
  6754. break;
  6755. }
  6756. if (discard)
  6757. STADJUST(-len, expdest);
  6758. return len;
  6759. }
  6760. /*
  6761. * Expand a variable, and return a pointer to the next character in the
  6762. * input string.
  6763. */
  6764. static char *
  6765. evalvar(char *p, int flag)
  6766. {
  6767. char varflags;
  6768. char subtype;
  6769. char *var;
  6770. int patloc;
  6771. int startloc;
  6772. ssize_t varlen;
  6773. int discard;
  6774. int quoted;
  6775. varflags = (unsigned char) *p++;
  6776. subtype = varflags & VSTYPE;
  6777. quoted = flag & EXP_QUOTED;
  6778. var = p;
  6779. startloc = expdest - (char *)stackblock();
  6780. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6781. again:
  6782. varlen = varvalue(var, varflags, flag, quoted);
  6783. if (varflags & VSNUL)
  6784. varlen--;
  6785. discard = varlen < 0 ? EXP_DISCARD : 0;
  6786. switch (subtype) {
  6787. case VSPLUS:
  6788. discard ^= EXP_DISCARD;
  6789. /* fall through */
  6790. case 0:
  6791. case VSMINUS:
  6792. p = argstr(p, flag | EXP_TILDE | EXP_WORD | (discard ^ EXP_DISCARD));
  6793. goto record;
  6794. case VSASSIGN:
  6795. case VSQUESTION:
  6796. p = subevalvar(p, var, 0, startloc, varflags,
  6797. (flag & ~QUOTES_ESC) | (discard ^ EXP_DISCARD));
  6798. if ((flag | ~discard) & EXP_DISCARD)
  6799. goto record;
  6800. varflags &= ~VSNUL;
  6801. subtype = VSNORMAL;
  6802. goto again;
  6803. }
  6804. if ((discard & ~flag) && uflag)
  6805. varunset(p, var, 0, 0);
  6806. if (subtype == VSLENGTH) {
  6807. p++;
  6808. if (flag & EXP_DISCARD)
  6809. return p;
  6810. cvtnum(varlen > 0 ? varlen : 0, flag);
  6811. goto really_record;
  6812. }
  6813. if (subtype == VSNORMAL)
  6814. goto record;
  6815. #if DEBUG
  6816. switch (subtype) {
  6817. case VSTRIMLEFT:
  6818. case VSTRIMLEFTMAX:
  6819. case VSTRIMRIGHT:
  6820. case VSTRIMRIGHTMAX:
  6821. #if BASH_SUBSTR
  6822. case VSSUBSTR:
  6823. #endif
  6824. #if BASH_PATTERN_SUBST
  6825. case VSREPLACE:
  6826. case VSREPLACEALL:
  6827. #endif
  6828. break;
  6829. default:
  6830. abort();
  6831. }
  6832. #endif
  6833. flag |= discard;
  6834. if (!(flag & EXP_DISCARD)) {
  6835. /*
  6836. * Terminate the string and start recording the pattern
  6837. * right after it
  6838. */
  6839. STPUTC('\0', expdest);
  6840. }
  6841. patloc = expdest - (char *)stackblock();
  6842. p = subevalvar(p, NULL, patloc, startloc, varflags, flag);
  6843. record:
  6844. if ((flag | discard) & EXP_DISCARD)
  6845. return p;
  6846. really_record:
  6847. if (quoted) {
  6848. quoted = *var == '@' && shellparam.nparam;
  6849. if (!quoted)
  6850. return p;
  6851. }
  6852. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6853. return p;
  6854. }
  6855. /*
  6856. * Add a file name to the list.
  6857. */
  6858. static void
  6859. addfname(const char *name)
  6860. {
  6861. struct strlist *sp;
  6862. sp = stzalloc(sizeof(*sp));
  6863. sp->text = sstrdup(name);
  6864. *exparg.lastp = sp;
  6865. exparg.lastp = &sp->next;
  6866. }
  6867. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6868. static int
  6869. hasmeta(const char *p)
  6870. {
  6871. static const char chars[] ALIGN1 = {
  6872. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6873. };
  6874. for (;;) {
  6875. p = strpbrk(p, chars);
  6876. if (!p)
  6877. break;
  6878. switch ((unsigned char)*p) {
  6879. case CTLQUOTEMARK:
  6880. for (;;) {
  6881. p++;
  6882. if ((unsigned char)*p == CTLQUOTEMARK)
  6883. break;
  6884. if ((unsigned char)*p == CTLESC)
  6885. p++;
  6886. if (*p == '\0') /* huh? */
  6887. return 0;
  6888. }
  6889. break;
  6890. case '\\':
  6891. case CTLESC:
  6892. p++;
  6893. if (*p == '\0')
  6894. return 0;
  6895. break;
  6896. case '[':
  6897. if (!strchr(p + 1, ']')) {
  6898. /* It's not a properly closed [] pattern,
  6899. * but other metas may follow. Continue checking.
  6900. * my[file* _is_ globbed by bash
  6901. * and matches filenames like "my[file1".
  6902. */
  6903. break;
  6904. }
  6905. /* fallthrough */
  6906. default:
  6907. /* case '*': */
  6908. /* case '?': */
  6909. return 1;
  6910. }
  6911. p++;
  6912. }
  6913. return 0;
  6914. }
  6915. /* If we want to use glob() from libc... */
  6916. #if !ENABLE_ASH_INTERNAL_GLOB
  6917. /* Add the result of glob() to the list */
  6918. static void
  6919. addglob(const glob_t *pglob)
  6920. {
  6921. char **p = pglob->gl_pathv;
  6922. do {
  6923. addfname(*p);
  6924. } while (*++p);
  6925. }
  6926. static void
  6927. expandmeta(struct strlist *str /*, int flag*/)
  6928. {
  6929. /* TODO - EXP_REDIR */
  6930. while (str) {
  6931. char *p;
  6932. glob_t pglob;
  6933. int i;
  6934. if (fflag)
  6935. goto nometa;
  6936. if (!hasmeta(str->text))
  6937. goto nometa;
  6938. INT_OFF;
  6939. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6940. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6941. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6942. //
  6943. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6944. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6945. // Which means you need to unescape the string, right? Not so fast:
  6946. // if there _is_ a file named "file\?" (with backslash), it is returned
  6947. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6948. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6949. //
  6950. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6951. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6952. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6953. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6954. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6955. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6956. i = glob(p, 0, NULL, &pglob);
  6957. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6958. if (p != str->text)
  6959. free(p);
  6960. switch (i) {
  6961. case 0:
  6962. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6963. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6964. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6965. goto nometa2;
  6966. #endif
  6967. addglob(&pglob);
  6968. globfree(&pglob);
  6969. INT_ON;
  6970. break;
  6971. case GLOB_NOMATCH:
  6972. //nometa2:
  6973. globfree(&pglob);
  6974. INT_ON;
  6975. nometa:
  6976. *exparg.lastp = str;
  6977. rmescapes(str->text, 0, NULL);
  6978. exparg.lastp = &str->next;
  6979. break;
  6980. default: /* GLOB_NOSPACE */
  6981. globfree(&pglob);
  6982. INT_ON;
  6983. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  6984. }
  6985. str = str->next;
  6986. }
  6987. }
  6988. #else
  6989. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  6990. /*
  6991. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6992. */
  6993. typedef struct exp_t {
  6994. char *dir;
  6995. unsigned dir_max;
  6996. } exp_t;
  6997. static void
  6998. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  6999. {
  7000. #define expdir exp->dir
  7001. #define expdir_max exp->dir_max
  7002. char *enddir = expdir + expdir_len;
  7003. char *p;
  7004. const char *cp;
  7005. char *start;
  7006. char *endname;
  7007. int metaflag;
  7008. struct stat statb;
  7009. DIR *dirp;
  7010. struct dirent *dp;
  7011. int atend;
  7012. int matchdot;
  7013. int esc;
  7014. metaflag = 0;
  7015. start = name;
  7016. for (p = name; esc = 0, *p; p += esc + 1) {
  7017. if (*p == '*' || *p == '?')
  7018. metaflag = 1;
  7019. else if (*p == '[') {
  7020. char *q = p + 1;
  7021. if (*q == '!')
  7022. q++;
  7023. for (;;) {
  7024. if (*q == '\\')
  7025. q++;
  7026. if (*q == '/' || *q == '\0')
  7027. break;
  7028. if (*++q == ']') {
  7029. metaflag = 1;
  7030. break;
  7031. }
  7032. }
  7033. } else {
  7034. if (*p == '\\' && p[1])
  7035. esc++;
  7036. if (p[esc] == '/') {
  7037. if (metaflag)
  7038. break;
  7039. start = p + esc + 1;
  7040. }
  7041. }
  7042. }
  7043. if (metaflag == 0) { /* we've reached the end of the file name */
  7044. if (!expdir_len)
  7045. return;
  7046. p = name;
  7047. do {
  7048. if (*p == '\\' && p[1])
  7049. p++;
  7050. *enddir++ = *p;
  7051. } while (*p++);
  7052. if (lstat(expdir, &statb) == 0)
  7053. addfname(expdir);
  7054. return;
  7055. }
  7056. endname = p;
  7057. if (name < start) {
  7058. p = name;
  7059. do {
  7060. if (*p == '\\' && p[1])
  7061. p++;
  7062. *enddir++ = *p++;
  7063. } while (p < start);
  7064. }
  7065. *enddir = '\0';
  7066. cp = expdir;
  7067. expdir_len = enddir - cp;
  7068. if (!expdir_len)
  7069. cp = ".";
  7070. dirp = opendir(cp);
  7071. if (dirp == NULL)
  7072. return;
  7073. if (*endname == 0) {
  7074. atend = 1;
  7075. } else {
  7076. atend = 0;
  7077. *endname = '\0';
  7078. endname += esc + 1;
  7079. }
  7080. name_len -= endname - name;
  7081. matchdot = 0;
  7082. p = start;
  7083. if (*p == '\\')
  7084. p++;
  7085. if (*p == '.')
  7086. matchdot++;
  7087. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7088. if (dp->d_name[0] == '.' && !matchdot)
  7089. continue;
  7090. if (pmatch(start, dp->d_name)) {
  7091. if (atend) {
  7092. strcpy(enddir, dp->d_name);
  7093. addfname(expdir);
  7094. } else {
  7095. unsigned offset;
  7096. unsigned len;
  7097. p = stpcpy(enddir, dp->d_name);
  7098. *p = '/';
  7099. offset = p - expdir + 1;
  7100. len = offset + name_len + NAME_MAX;
  7101. if (len > expdir_max) {
  7102. len += PATH_MAX;
  7103. expdir = ckrealloc(expdir, len);
  7104. expdir_max = len;
  7105. }
  7106. expmeta(exp, endname, name_len, offset);
  7107. enddir = expdir + expdir_len;
  7108. }
  7109. }
  7110. }
  7111. closedir(dirp);
  7112. if (!atend)
  7113. endname[-esc - 1] = esc ? '\\' : '/';
  7114. #undef expdir
  7115. #undef expdir_max
  7116. }
  7117. static struct strlist *
  7118. msort(struct strlist *list, int len)
  7119. {
  7120. struct strlist *p, *q = NULL;
  7121. struct strlist **lpp;
  7122. int half;
  7123. int n;
  7124. if (len <= 1)
  7125. return list;
  7126. half = len >> 1;
  7127. p = list;
  7128. for (n = half; --n >= 0;) {
  7129. q = p;
  7130. p = p->next;
  7131. }
  7132. q->next = NULL; /* terminate first half of list */
  7133. q = msort(list, half); /* sort first half of list */
  7134. p = msort(p, len - half); /* sort second half */
  7135. lpp = &list;
  7136. for (;;) {
  7137. #if ENABLE_LOCALE_SUPPORT
  7138. if (strcoll(p->text, q->text) < 0)
  7139. #else
  7140. if (strcmp(p->text, q->text) < 0)
  7141. #endif
  7142. {
  7143. *lpp = p;
  7144. lpp = &p->next;
  7145. p = *lpp;
  7146. if (p == NULL) {
  7147. *lpp = q;
  7148. break;
  7149. }
  7150. } else {
  7151. *lpp = q;
  7152. lpp = &q->next;
  7153. q = *lpp;
  7154. if (q == NULL) {
  7155. *lpp = p;
  7156. break;
  7157. }
  7158. }
  7159. }
  7160. return list;
  7161. }
  7162. /*
  7163. * Sort the results of file name expansion. It calculates the number of
  7164. * strings to sort and then calls msort (short for merge sort) to do the
  7165. * work.
  7166. */
  7167. static struct strlist *
  7168. expsort(struct strlist *str)
  7169. {
  7170. int len;
  7171. struct strlist *sp;
  7172. len = 0;
  7173. for (sp = str; sp; sp = sp->next)
  7174. len++;
  7175. return msort(str, len);
  7176. }
  7177. static void
  7178. expandmeta(struct strlist *str /*, int flag*/)
  7179. {
  7180. /* TODO - EXP_REDIR */
  7181. while (str) {
  7182. exp_t exp;
  7183. struct strlist **savelastp;
  7184. struct strlist *sp;
  7185. char *p;
  7186. unsigned len;
  7187. if (fflag)
  7188. goto nometa;
  7189. if (!hasmeta(str->text))
  7190. goto nometa;
  7191. savelastp = exparg.lastp;
  7192. INT_OFF;
  7193. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7194. len = strlen(p);
  7195. exp.dir_max = len + PATH_MAX;
  7196. exp.dir = ckmalloc(exp.dir_max);
  7197. expmeta(&exp, p, len, 0);
  7198. free(exp.dir);
  7199. if (p != str->text)
  7200. free(p);
  7201. INT_ON;
  7202. if (exparg.lastp == savelastp) {
  7203. /*
  7204. * no matches
  7205. */
  7206. nometa:
  7207. *exparg.lastp = str;
  7208. rmescapes(str->text, 0, NULL);
  7209. exparg.lastp = &str->next;
  7210. } else {
  7211. *exparg.lastp = NULL;
  7212. *savelastp = sp = expsort(*savelastp);
  7213. while (sp->next != NULL)
  7214. sp = sp->next;
  7215. exparg.lastp = &sp->next;
  7216. }
  7217. str = str->next;
  7218. }
  7219. }
  7220. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7221. /*
  7222. * Perform variable substitution and command substitution on an argument,
  7223. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7224. * perform splitting and file name expansion. When arglist is NULL, perform
  7225. * here document expansion.
  7226. */
  7227. static void
  7228. expandarg(union node *arg, struct arglist *arglist, int flag)
  7229. {
  7230. struct strlist *sp;
  7231. char *p;
  7232. argbackq = arg->narg.backquote;
  7233. STARTSTACKSTR(expdest);
  7234. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7235. argstr(arg->narg.text, flag);
  7236. if (arglist == NULL) {
  7237. /* here document expanded */
  7238. goto out;
  7239. }
  7240. p = grabstackstr(expdest);
  7241. TRACE(("expandarg: p:'%s'\n", p));
  7242. exparg.lastp = &exparg.list;
  7243. /*
  7244. * TODO - EXP_REDIR
  7245. */
  7246. if (flag & EXP_FULL) {
  7247. ifsbreakup(p, &exparg);
  7248. *exparg.lastp = NULL;
  7249. exparg.lastp = &exparg.list;
  7250. expandmeta(exparg.list /*, flag*/);
  7251. } else {
  7252. sp = stzalloc(sizeof(*sp));
  7253. sp->text = p;
  7254. *exparg.lastp = sp;
  7255. exparg.lastp = &sp->next;
  7256. }
  7257. *exparg.lastp = NULL;
  7258. if (exparg.list) {
  7259. *arglist->lastp = exparg.list;
  7260. arglist->lastp = exparg.lastp;
  7261. }
  7262. out:
  7263. ifsfree();
  7264. }
  7265. /*
  7266. * Expand shell variables and backquotes inside a here document.
  7267. */
  7268. static void
  7269. expandhere(union node *arg)
  7270. {
  7271. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7272. }
  7273. /*
  7274. * Returns true if the pattern matches the string.
  7275. */
  7276. static int
  7277. patmatch(char *pattern, const char *string)
  7278. {
  7279. char *p = preglob(pattern, 0);
  7280. int r = pmatch(p, string);
  7281. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7282. return r;
  7283. }
  7284. /*
  7285. * See if a pattern matches in a case statement.
  7286. */
  7287. static int
  7288. casematch(union node *pattern, char *val)
  7289. {
  7290. struct stackmark smark;
  7291. int result;
  7292. setstackmark(&smark);
  7293. argbackq = pattern->narg.backquote;
  7294. STARTSTACKSTR(expdest);
  7295. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7296. ifsfree();
  7297. result = patmatch(stackblock(), val);
  7298. popstackmark(&smark);
  7299. return result;
  7300. }
  7301. /* ============ find_command */
  7302. struct builtincmd {
  7303. const char *name;
  7304. int (*builtin)(int, char **) FAST_FUNC;
  7305. /* unsigned flags; */
  7306. };
  7307. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7308. /* "regular" builtins always take precedence over commands,
  7309. * regardless of PATH=....%builtin... position */
  7310. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7311. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7312. struct cmdentry {
  7313. smallint cmdtype; /* CMDxxx */
  7314. union param {
  7315. int index;
  7316. /* index >= 0 for commands without path (slashes) */
  7317. /* (TODO: what exactly does the value mean? PATH position?) */
  7318. /* index == -1 for commands with slashes */
  7319. /* index == (-2 - applet_no) for NOFORK applets */
  7320. const struct builtincmd *cmd;
  7321. struct funcnode *func;
  7322. } u;
  7323. };
  7324. /* values of cmdtype */
  7325. #define CMDUNKNOWN -1 /* no entry in table for command */
  7326. #define CMDNORMAL 0 /* command is an executable program */
  7327. #define CMDFUNCTION 1 /* command is a shell function */
  7328. #define CMDBUILTIN 2 /* command is a shell builtin */
  7329. /* action to find_command() */
  7330. #define DO_ERR 0x01 /* prints errors */
  7331. #define DO_ABS 0x02 /* checks absolute paths */
  7332. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7333. #define DO_ALTPATH 0x08 /* using alternate path */
  7334. #define DO_REGBLTIN 0x10 /* regular built-ins and functions only */
  7335. static void find_command(char *, struct cmdentry *, int, const char *);
  7336. /* ============ Hashing commands */
  7337. /*
  7338. * When commands are first encountered, they are entered in a hash table.
  7339. * This ensures that a full path search will not have to be done for them
  7340. * on each invocation.
  7341. *
  7342. * We should investigate converting to a linear search, even though that
  7343. * would make the command name "hash" a misnomer.
  7344. */
  7345. struct tblentry {
  7346. struct tblentry *next; /* next entry in hash chain */
  7347. union param param; /* definition of builtin function */
  7348. smallint cmdtype; /* CMDxxx */
  7349. char rehash; /* if set, cd done since entry created */
  7350. char cmdname[1]; /* name of command */
  7351. };
  7352. static struct tblentry **cmdtable;
  7353. #define INIT_G_cmdtable() do { \
  7354. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7355. } while (0)
  7356. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7357. static void
  7358. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7359. {
  7360. #if ENABLE_FEATURE_SH_STANDALONE
  7361. if (applet_no >= 0) {
  7362. if (APPLET_IS_NOEXEC(applet_no)) {
  7363. clearenv();
  7364. while (*envp)
  7365. putenv(*envp++);
  7366. popredir(/*drop:*/ 1);
  7367. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7368. }
  7369. /* re-exec ourselves with the new arguments */
  7370. execve(bb_busybox_exec_path, argv, envp);
  7371. /* If they called chroot or otherwise made the binary no longer
  7372. * executable, fall through */
  7373. }
  7374. #endif
  7375. repeat:
  7376. #ifdef SYSV
  7377. do {
  7378. execve(cmd, argv, envp);
  7379. } while (errno == EINTR);
  7380. #else
  7381. execve(cmd, argv, envp);
  7382. #endif
  7383. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7384. /* Run "cmd" as a shell script:
  7385. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7386. * "If the execve() function fails with ENOEXEC, the shell
  7387. * shall execute a command equivalent to having a shell invoked
  7388. * with the command name as its first operand,
  7389. * with any remaining arguments passed to the new shell"
  7390. *
  7391. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7392. * just call ourselves.
  7393. *
  7394. * Note that bash reads ~80 chars of the file, and if it sees
  7395. * a zero byte before it sees newline, it doesn't try to
  7396. * interpret it, but fails with "cannot execute binary file"
  7397. * message and exit code 126. For one, this prevents attempts
  7398. * to interpret foreign ELF binaries as shell scripts.
  7399. */
  7400. argv[0] = (char*) cmd;
  7401. cmd = bb_busybox_exec_path;
  7402. /* NB: this is only possible because all callers of shellexec()
  7403. * ensure that the argv[-1] slot exists!
  7404. */
  7405. argv--;
  7406. argv[0] = (char*) "ash";
  7407. goto repeat;
  7408. }
  7409. }
  7410. /*
  7411. * Exec a program. Never returns. If you change this routine, you may
  7412. * have to change the find_command routine as well.
  7413. * argv[-1] must exist and be writable! See tryexec() for why.
  7414. */
  7415. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7416. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7417. {
  7418. char *cmdname;
  7419. int e;
  7420. char **envp;
  7421. int exerrno;
  7422. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7423. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7424. if (strchr(prog, '/') != NULL
  7425. #if ENABLE_FEATURE_SH_STANDALONE
  7426. || (applet_no = find_applet_by_name(prog)) >= 0
  7427. #endif
  7428. ) {
  7429. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7430. if (applet_no >= 0) {
  7431. /* We tried execing ourself, but it didn't work.
  7432. * Maybe /proc/self/exe doesn't exist?
  7433. * Try $PATH search.
  7434. */
  7435. goto try_PATH;
  7436. }
  7437. e = errno;
  7438. } else {
  7439. try_PATH:
  7440. e = ENOENT;
  7441. while (padvance(&path, argv[0]) >= 0) {
  7442. cmdname = stackblock();
  7443. if (--idx < 0 && pathopt == NULL) {
  7444. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7445. if (errno != ENOENT && errno != ENOTDIR)
  7446. e = errno;
  7447. }
  7448. }
  7449. }
  7450. /* Map to POSIX errors */
  7451. switch (e) {
  7452. default:
  7453. exerrno = 126;
  7454. break;
  7455. case ELOOP:
  7456. case ENAMETOOLONG:
  7457. case ENOENT:
  7458. case ENOTDIR:
  7459. exerrno = 127;
  7460. break;
  7461. }
  7462. exitstatus = exerrno;
  7463. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7464. prog, e, suppress_int));
  7465. ash_msg_and_raise(EXEND, "%s: %s", prog, errmsg(e, "not found"));
  7466. /* NOTREACHED */
  7467. }
  7468. static void
  7469. printentry(struct tblentry *cmdp)
  7470. {
  7471. int idx;
  7472. const char *path;
  7473. char *name;
  7474. idx = cmdp->param.index;
  7475. path = pathval();
  7476. do {
  7477. padvance(&path, cmdp->cmdname);
  7478. } while (--idx >= 0);
  7479. name = stackblock();
  7480. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7481. }
  7482. /*
  7483. * Clear out command entries.
  7484. */
  7485. static void
  7486. clearcmdentry(void)
  7487. {
  7488. struct tblentry **tblp;
  7489. struct tblentry **pp;
  7490. struct tblentry *cmdp;
  7491. INT_OFF;
  7492. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7493. pp = tblp;
  7494. while ((cmdp = *pp) != NULL) {
  7495. if (cmdp->cmdtype == CMDNORMAL
  7496. || (cmdp->cmdtype == CMDBUILTIN
  7497. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7498. && builtinloc > 0
  7499. )
  7500. ) {
  7501. *pp = cmdp->next;
  7502. free(cmdp);
  7503. } else {
  7504. pp = &cmdp->next;
  7505. }
  7506. }
  7507. }
  7508. INT_ON;
  7509. }
  7510. /*
  7511. * Locate a command in the command hash table. If "add" is nonzero,
  7512. * add the command to the table if it is not already present. The
  7513. * variable "lastcmdentry" is set to point to the address of the link
  7514. * pointing to the entry, so that delete_cmd_entry can delete the
  7515. * entry.
  7516. *
  7517. * Interrupts must be off if called with add != 0.
  7518. */
  7519. static struct tblentry **lastcmdentry;
  7520. static struct tblentry *
  7521. cmdlookup(const char *name, int add)
  7522. {
  7523. unsigned int hashval;
  7524. const char *p;
  7525. struct tblentry *cmdp;
  7526. struct tblentry **pp;
  7527. p = name;
  7528. hashval = (unsigned char)*p << 4;
  7529. while (*p)
  7530. hashval += (unsigned char)*p++;
  7531. hashval &= 0x7FFF;
  7532. pp = &cmdtable[hashval % CMDTABLESIZE];
  7533. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7534. if (strcmp(cmdp->cmdname, name) == 0)
  7535. break;
  7536. pp = &cmdp->next;
  7537. }
  7538. if (add && cmdp == NULL) {
  7539. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7540. + strlen(name)
  7541. /* + 1 - already done because
  7542. * tblentry::cmdname is char[1] */);
  7543. /*cmdp->next = NULL; - ckzalloc did it */
  7544. cmdp->cmdtype = CMDUNKNOWN;
  7545. strcpy(cmdp->cmdname, name);
  7546. }
  7547. lastcmdentry = pp;
  7548. return cmdp;
  7549. }
  7550. /*
  7551. * Delete the command entry returned on the last lookup.
  7552. */
  7553. static void
  7554. delete_cmd_entry(void)
  7555. {
  7556. struct tblentry *cmdp;
  7557. INT_OFF;
  7558. cmdp = *lastcmdentry;
  7559. *lastcmdentry = cmdp->next;
  7560. if (cmdp->cmdtype == CMDFUNCTION)
  7561. freefunc(cmdp->param.func);
  7562. free(cmdp);
  7563. INT_ON;
  7564. }
  7565. /*
  7566. * Add a new command entry, replacing any existing command entry for
  7567. * the same name - except special builtins.
  7568. */
  7569. static void
  7570. addcmdentry(char *name, struct cmdentry *entry)
  7571. {
  7572. struct tblentry *cmdp;
  7573. cmdp = cmdlookup(name, 1);
  7574. if (cmdp->cmdtype == CMDFUNCTION) {
  7575. freefunc(cmdp->param.func);
  7576. }
  7577. cmdp->cmdtype = entry->cmdtype;
  7578. cmdp->param = entry->u;
  7579. cmdp->rehash = 0;
  7580. }
  7581. static int FAST_FUNC
  7582. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7583. {
  7584. struct tblentry **pp;
  7585. struct tblentry *cmdp;
  7586. int c;
  7587. struct cmdentry entry;
  7588. char *name;
  7589. if (nextopt("r") != '\0') {
  7590. clearcmdentry();
  7591. return 0;
  7592. }
  7593. if (*argptr == NULL) {
  7594. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7595. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7596. if (cmdp->cmdtype == CMDNORMAL)
  7597. printentry(cmdp);
  7598. }
  7599. }
  7600. return 0;
  7601. }
  7602. c = 0;
  7603. while ((name = *argptr) != NULL) {
  7604. cmdp = cmdlookup(name, 0);
  7605. if (cmdp != NULL
  7606. && (cmdp->cmdtype == CMDNORMAL
  7607. || (cmdp->cmdtype == CMDBUILTIN
  7608. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7609. && builtinloc > 0
  7610. )
  7611. )
  7612. ) {
  7613. delete_cmd_entry();
  7614. }
  7615. find_command(name, &entry, DO_ERR, pathval());
  7616. if (entry.cmdtype == CMDUNKNOWN)
  7617. c = 1;
  7618. argptr++;
  7619. }
  7620. return c;
  7621. }
  7622. /*
  7623. * Called when a cd is done. Marks all commands so the next time they
  7624. * are executed they will be rehashed.
  7625. */
  7626. static void
  7627. hashcd(void)
  7628. {
  7629. struct tblentry **pp;
  7630. struct tblentry *cmdp;
  7631. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7632. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7633. if (cmdp->cmdtype == CMDNORMAL
  7634. || (cmdp->cmdtype == CMDBUILTIN
  7635. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7636. && builtinloc > 0)
  7637. ) {
  7638. cmdp->rehash = 1;
  7639. }
  7640. }
  7641. }
  7642. }
  7643. /*
  7644. * Fix command hash table when PATH changed.
  7645. * Called before PATH is changed. The argument is the new value of PATH;
  7646. * pathval() still returns the old value at this point.
  7647. * Called with interrupts off.
  7648. */
  7649. static void FAST_FUNC
  7650. changepath(const char *newval)
  7651. {
  7652. const char *new;
  7653. int idx;
  7654. int bltin;
  7655. new = newval;
  7656. idx = 0;
  7657. bltin = -1;
  7658. for (;;) {
  7659. if (*new == '%' && prefix(new + 1, "builtin")) {
  7660. bltin = idx;
  7661. break;
  7662. }
  7663. new = strchr(new, ':');
  7664. if (!new)
  7665. break;
  7666. idx++;
  7667. new++;
  7668. }
  7669. builtinloc = bltin;
  7670. clearcmdentry();
  7671. }
  7672. enum {
  7673. TEOF,
  7674. TNL,
  7675. TREDIR,
  7676. TWORD,
  7677. TSEMI,
  7678. TBACKGND,
  7679. TAND,
  7680. TOR,
  7681. TPIPE,
  7682. TLP,
  7683. TRP,
  7684. TENDCASE,
  7685. TENDBQUOTE,
  7686. TNOT,
  7687. TCASE,
  7688. TDO,
  7689. TDONE,
  7690. TELIF,
  7691. TELSE,
  7692. TESAC,
  7693. TFI,
  7694. TFOR,
  7695. #if BASH_FUNCTION
  7696. TFUNCTION,
  7697. #endif
  7698. TIF,
  7699. TIN,
  7700. TTHEN,
  7701. TUNTIL,
  7702. TWHILE,
  7703. TBEGIN,
  7704. TEND
  7705. };
  7706. typedef smallint token_id_t;
  7707. /* Nth bit indicates if token marks the end of a list */
  7708. enum {
  7709. tokendlist = 0
  7710. /* 0 */ | (1u << TEOF)
  7711. /* 1 */ | (0u << TNL)
  7712. /* 2 */ | (0u << TREDIR)
  7713. /* 3 */ | (0u << TWORD)
  7714. /* 4 */ | (0u << TSEMI)
  7715. /* 5 */ | (0u << TBACKGND)
  7716. /* 6 */ | (0u << TAND)
  7717. /* 7 */ | (0u << TOR)
  7718. /* 8 */ | (0u << TPIPE)
  7719. /* 9 */ | (0u << TLP)
  7720. /* 10 */ | (1u << TRP)
  7721. /* 11 */ | (1u << TENDCASE)
  7722. /* 12 */ | (1u << TENDBQUOTE)
  7723. /* 13 */ | (0u << TNOT)
  7724. /* 14 */ | (0u << TCASE)
  7725. /* 15 */ | (1u << TDO)
  7726. /* 16 */ | (1u << TDONE)
  7727. /* 17 */ | (1u << TELIF)
  7728. /* 18 */ | (1u << TELSE)
  7729. /* 19 */ | (1u << TESAC)
  7730. /* 20 */ | (1u << TFI)
  7731. /* 21 */ | (0u << TFOR)
  7732. #if BASH_FUNCTION
  7733. /* 22 */ | (0u << TFUNCTION)
  7734. #endif
  7735. /* 23 */ | (0u << TIF)
  7736. /* 24 */ | (0u << TIN)
  7737. /* 25 */ | (1u << TTHEN)
  7738. /* 26 */ | (0u << TUNTIL)
  7739. /* 27 */ | (0u << TWHILE)
  7740. /* 28 */ | (0u << TBEGIN)
  7741. /* 29 */ | (1u << TEND)
  7742. , /* thus far 29 bits used */
  7743. };
  7744. static const char *const tokname_array[] = {
  7745. "end of file",
  7746. "newline",
  7747. "redirection",
  7748. "word",
  7749. ";",
  7750. "&",
  7751. "&&",
  7752. "||",
  7753. "|",
  7754. "(",
  7755. ")",
  7756. ";;",
  7757. "`",
  7758. #define KWDOFFSET 13
  7759. /* the following are keywords */
  7760. "!",
  7761. "case",
  7762. "do",
  7763. "done",
  7764. "elif",
  7765. "else",
  7766. "esac",
  7767. "fi",
  7768. "for",
  7769. #if BASH_FUNCTION
  7770. "function",
  7771. #endif
  7772. "if",
  7773. "in",
  7774. "then",
  7775. "until",
  7776. "while",
  7777. "{",
  7778. "}",
  7779. };
  7780. /* Wrapper around strcmp for qsort/bsearch/... */
  7781. static int
  7782. pstrcmp(const void *a, const void *b)
  7783. {
  7784. return strcmp((char*)a, *(char**)b);
  7785. }
  7786. static const char *const *
  7787. findkwd(const char *s)
  7788. {
  7789. return bsearch(s, tokname_array + KWDOFFSET,
  7790. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7791. sizeof(tokname_array[0]), pstrcmp);
  7792. }
  7793. /*
  7794. * Locate and print what a word is...
  7795. */
  7796. static int
  7797. describe_command(char *command, const char *path, int describe_command_verbose)
  7798. {
  7799. struct cmdentry entry;
  7800. #if ENABLE_ASH_ALIAS
  7801. const struct alias *ap;
  7802. #endif
  7803. path = path ? path : pathval();
  7804. if (describe_command_verbose) {
  7805. out1str(command);
  7806. }
  7807. /* First look at the keywords */
  7808. if (findkwd(command)) {
  7809. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7810. goto out;
  7811. }
  7812. #if ENABLE_ASH_ALIAS
  7813. /* Then look at the aliases */
  7814. ap = lookupalias(command, 0);
  7815. if (ap != NULL) {
  7816. if (!describe_command_verbose) {
  7817. out1str("alias ");
  7818. printalias(ap);
  7819. return 0;
  7820. }
  7821. out1fmt(" is an alias for %s", ap->val);
  7822. goto out;
  7823. }
  7824. #endif
  7825. /* Brute force */
  7826. find_command(command, &entry, DO_ABS, path);
  7827. switch (entry.cmdtype) {
  7828. case CMDNORMAL: {
  7829. int j = entry.u.index;
  7830. char *p;
  7831. if (j < 0) {
  7832. p = command;
  7833. } else {
  7834. do {
  7835. padvance(&path, command);
  7836. } while (--j >= 0);
  7837. p = stackblock();
  7838. }
  7839. if (describe_command_verbose) {
  7840. out1fmt(" is %s", p);
  7841. } else {
  7842. out1str(p);
  7843. }
  7844. break;
  7845. }
  7846. case CMDFUNCTION:
  7847. if (describe_command_verbose) {
  7848. /*out1str(" is a shell function");*/
  7849. out1str(" is a function"); /* bash says this */
  7850. } else {
  7851. out1str(command);
  7852. }
  7853. break;
  7854. case CMDBUILTIN:
  7855. if (describe_command_verbose) {
  7856. out1fmt(" is a %sshell builtin",
  7857. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7858. "special " : nullstr
  7859. );
  7860. } else {
  7861. out1str(command);
  7862. }
  7863. break;
  7864. default:
  7865. if (describe_command_verbose) {
  7866. out1str(": not found\n");
  7867. }
  7868. return 127;
  7869. }
  7870. out:
  7871. out1str("\n");
  7872. return 0;
  7873. }
  7874. static int FAST_FUNC
  7875. typecmd(int argc UNUSED_PARAM, char **argv)
  7876. {
  7877. int i = 1;
  7878. int err = 0;
  7879. int verbose = 1;
  7880. /* type -p ... ? (we don't bother checking for 'p') */
  7881. if (argv[1] && argv[1][0] == '-') {
  7882. i++;
  7883. verbose = 0;
  7884. }
  7885. while (argv[i]) {
  7886. err |= describe_command(argv[i++], NULL, verbose);
  7887. }
  7888. return err;
  7889. }
  7890. static struct strlist *
  7891. fill_arglist(struct arglist *arglist, union node **argpp)
  7892. {
  7893. struct strlist **lastp = arglist->lastp;
  7894. union node *argp;
  7895. while ((argp = *argpp) != NULL) {
  7896. expandarg(argp, arglist, EXP_FULL | EXP_TILDE);
  7897. *argpp = argp->narg.next;
  7898. if (*lastp)
  7899. break;
  7900. }
  7901. return *lastp;
  7902. }
  7903. #if ENABLE_ASH_CMDCMD
  7904. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7905. static int
  7906. parse_command_args(struct arglist *arglist, union node **argpp, const char **path)
  7907. {
  7908. struct strlist *sp = arglist->list;
  7909. char *cp, c;
  7910. for (;;) {
  7911. sp = sp->next ? sp->next : fill_arglist(arglist, argpp);
  7912. if (!sp)
  7913. return 0;
  7914. cp = sp->text;
  7915. if (*cp++ != '-')
  7916. break;
  7917. c = *cp++;
  7918. if (!c)
  7919. break;
  7920. if (c == '-' && !*cp) {
  7921. if (!sp->next && !fill_arglist(arglist, argpp))
  7922. return 0;
  7923. sp = sp->next;
  7924. break;
  7925. }
  7926. do {
  7927. switch (c) {
  7928. case 'p':
  7929. *path = bb_default_path;
  7930. break;
  7931. default:
  7932. /* run 'typecmd' for other options */
  7933. return 0;
  7934. }
  7935. c = *cp++;
  7936. } while (c);
  7937. }
  7938. arglist->list = sp;
  7939. return DO_NOFUNC;
  7940. }
  7941. static int FAST_FUNC
  7942. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7943. {
  7944. char *cmd;
  7945. int c;
  7946. enum {
  7947. VERIFY_BRIEF = 1,
  7948. VERIFY_VERBOSE = 2,
  7949. } verify = 0;
  7950. const char *path = NULL;
  7951. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7952. * never reaches this function.
  7953. */
  7954. while ((c = nextopt("pvV")) != '\0')
  7955. if (c == 'V')
  7956. verify |= VERIFY_VERBOSE;
  7957. else if (c == 'v')
  7958. /*verify |= VERIFY_BRIEF*/;
  7959. #if DEBUG
  7960. else if (c != 'p')
  7961. abort();
  7962. #endif
  7963. else
  7964. path = bb_default_path;
  7965. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7966. cmd = *argptr;
  7967. if (/*verify && */ cmd)
  7968. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7969. return 0;
  7970. }
  7971. #endif
  7972. /*static int funcblocksize; // size of structures in function */
  7973. /*static int funcstringsize; // size of strings in node */
  7974. static void *funcblock; /* block to allocate function from */
  7975. static char *funcstring_end; /* end of block to allocate strings from */
  7976. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7977. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7978. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7979. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7980. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7981. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7982. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7983. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7984. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7985. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7986. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7987. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7988. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7989. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7990. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7991. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7992. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7993. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7994. #if BASH_REDIR_OUTPUT
  7995. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7996. #endif
  7997. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7998. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7999. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8000. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  8001. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8002. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8003. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8004. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8005. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  8006. };
  8007. static int calcsize(int funcblocksize, union node *n);
  8008. static int
  8009. sizenodelist(int funcblocksize, struct nodelist *lp)
  8010. {
  8011. while (lp) {
  8012. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  8013. funcblocksize = calcsize(funcblocksize, lp->n);
  8014. lp = lp->next;
  8015. }
  8016. return funcblocksize;
  8017. }
  8018. static int
  8019. calcsize(int funcblocksize, union node *n)
  8020. {
  8021. if (n == NULL)
  8022. return funcblocksize;
  8023. funcblocksize += nodesize[n->type];
  8024. switch (n->type) {
  8025. case NCMD:
  8026. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  8027. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  8028. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  8029. break;
  8030. case NPIPE:
  8031. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  8032. break;
  8033. case NREDIR:
  8034. case NBACKGND:
  8035. case NSUBSHELL:
  8036. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  8037. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  8038. break;
  8039. case NAND:
  8040. case NOR:
  8041. case NSEMI:
  8042. case NWHILE:
  8043. case NUNTIL:
  8044. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  8045. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  8046. break;
  8047. case NIF:
  8048. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  8049. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  8050. funcblocksize = calcsize(funcblocksize, n->nif.test);
  8051. break;
  8052. case NFOR:
  8053. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  8054. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  8055. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  8056. break;
  8057. case NCASE:
  8058. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  8059. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  8060. break;
  8061. case NCLIST:
  8062. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  8063. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  8064. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  8065. break;
  8066. case NDEFUN:
  8067. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8068. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8069. break;
  8070. case NARG:
  8071. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8072. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8073. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8074. break;
  8075. case NTO:
  8076. #if BASH_REDIR_OUTPUT
  8077. case NTO2:
  8078. #endif
  8079. case NCLOBBER:
  8080. case NFROM:
  8081. case NFROMTO:
  8082. case NAPPEND:
  8083. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8084. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8085. break;
  8086. case NTOFD:
  8087. case NFROMFD:
  8088. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8089. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8090. break;
  8091. case NHERE:
  8092. case NXHERE:
  8093. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8094. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8095. break;
  8096. case NNOT:
  8097. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8098. break;
  8099. };
  8100. return funcblocksize;
  8101. }
  8102. static char *
  8103. nodeckstrdup(char *s)
  8104. {
  8105. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8106. return strcpy(funcstring_end, s);
  8107. }
  8108. static union node *copynode(union node *);
  8109. static struct nodelist *
  8110. copynodelist(struct nodelist *lp)
  8111. {
  8112. struct nodelist *start;
  8113. struct nodelist **lpp;
  8114. lpp = &start;
  8115. while (lp) {
  8116. *lpp = funcblock;
  8117. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8118. (*lpp)->n = copynode(lp->n);
  8119. lp = lp->next;
  8120. lpp = &(*lpp)->next;
  8121. }
  8122. *lpp = NULL;
  8123. return start;
  8124. }
  8125. static union node *
  8126. copynode(union node *n)
  8127. {
  8128. union node *new;
  8129. if (n == NULL)
  8130. return NULL;
  8131. new = funcblock;
  8132. funcblock = (char *) funcblock + nodesize[n->type];
  8133. switch (n->type) {
  8134. case NCMD:
  8135. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8136. new->ncmd.args = copynode(n->ncmd.args);
  8137. new->ncmd.assign = copynode(n->ncmd.assign);
  8138. new->ncmd.linno = n->ncmd.linno;
  8139. break;
  8140. case NPIPE:
  8141. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8142. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8143. break;
  8144. case NREDIR:
  8145. case NBACKGND:
  8146. case NSUBSHELL:
  8147. new->nredir.redirect = copynode(n->nredir.redirect);
  8148. new->nredir.n = copynode(n->nredir.n);
  8149. new->nredir.linno = n->nredir.linno;
  8150. break;
  8151. case NAND:
  8152. case NOR:
  8153. case NSEMI:
  8154. case NWHILE:
  8155. case NUNTIL:
  8156. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8157. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8158. break;
  8159. case NIF:
  8160. new->nif.elsepart = copynode(n->nif.elsepart);
  8161. new->nif.ifpart = copynode(n->nif.ifpart);
  8162. new->nif.test = copynode(n->nif.test);
  8163. break;
  8164. case NFOR:
  8165. new->nfor.var = nodeckstrdup(n->nfor.var);
  8166. new->nfor.body = copynode(n->nfor.body);
  8167. new->nfor.args = copynode(n->nfor.args);
  8168. new->nfor.linno = n->nfor.linno;
  8169. break;
  8170. case NCASE:
  8171. new->ncase.cases = copynode(n->ncase.cases);
  8172. new->ncase.expr = copynode(n->ncase.expr);
  8173. new->ncase.linno = n->ncase.linno;
  8174. break;
  8175. case NCLIST:
  8176. new->nclist.body = copynode(n->nclist.body);
  8177. new->nclist.pattern = copynode(n->nclist.pattern);
  8178. new->nclist.next = copynode(n->nclist.next);
  8179. break;
  8180. case NDEFUN:
  8181. new->ndefun.body = copynode(n->ndefun.body);
  8182. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8183. new->ndefun.linno = n->ndefun.linno;
  8184. break;
  8185. case NARG:
  8186. new->narg.backquote = copynodelist(n->narg.backquote);
  8187. new->narg.text = nodeckstrdup(n->narg.text);
  8188. new->narg.next = copynode(n->narg.next);
  8189. break;
  8190. case NTO:
  8191. #if BASH_REDIR_OUTPUT
  8192. case NTO2:
  8193. #endif
  8194. case NCLOBBER:
  8195. case NFROM:
  8196. case NFROMTO:
  8197. case NAPPEND:
  8198. new->nfile.fname = copynode(n->nfile.fname);
  8199. new->nfile.fd = n->nfile.fd;
  8200. new->nfile.next = copynode(n->nfile.next);
  8201. break;
  8202. case NTOFD:
  8203. case NFROMFD:
  8204. new->ndup.vname = copynode(n->ndup.vname);
  8205. new->ndup.dupfd = n->ndup.dupfd;
  8206. new->ndup.fd = n->ndup.fd;
  8207. new->ndup.next = copynode(n->ndup.next);
  8208. break;
  8209. case NHERE:
  8210. case NXHERE:
  8211. new->nhere.doc = copynode(n->nhere.doc);
  8212. new->nhere.fd = n->nhere.fd;
  8213. new->nhere.next = copynode(n->nhere.next);
  8214. break;
  8215. case NNOT:
  8216. new->nnot.com = copynode(n->nnot.com);
  8217. break;
  8218. };
  8219. new->type = n->type;
  8220. return new;
  8221. }
  8222. /*
  8223. * Make a copy of a parse tree.
  8224. */
  8225. static struct funcnode *
  8226. copyfunc(union node *n)
  8227. {
  8228. struct funcnode *f;
  8229. size_t blocksize;
  8230. /*funcstringsize = 0;*/
  8231. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8232. f = ckzalloc(blocksize /* + funcstringsize */);
  8233. funcblock = (char *) f + offsetof(struct funcnode, n);
  8234. funcstring_end = (char *) f + blocksize;
  8235. copynode(n);
  8236. /* f->count = 0; - ckzalloc did it */
  8237. return f;
  8238. }
  8239. /*
  8240. * Define a shell function.
  8241. */
  8242. static void
  8243. defun(union node *func)
  8244. {
  8245. struct cmdentry entry;
  8246. INT_OFF;
  8247. entry.cmdtype = CMDFUNCTION;
  8248. entry.u.func = copyfunc(func);
  8249. addcmdentry(func->ndefun.text, &entry);
  8250. INT_ON;
  8251. }
  8252. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8253. #define SKIPBREAK (1 << 0)
  8254. #define SKIPCONT (1 << 1)
  8255. #define SKIPFUNC (1 << 2)
  8256. #define SKIPFUNCDEF (1 << 3)
  8257. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8258. static int skipcount; /* number of levels to skip */
  8259. static int loopnest; /* current loop nesting level */
  8260. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8261. /* Forward decl way out to parsing code - dotrap needs it */
  8262. static int evalstring(char *s, int flags);
  8263. /* Called to execute a trap.
  8264. * Single callsite - at the end of evaltree().
  8265. * If we return non-zero, evaltree raises EXEXIT exception.
  8266. *
  8267. * Perhaps we should avoid entering new trap handlers
  8268. * while we are executing a trap handler. [is it a TODO?]
  8269. */
  8270. static void
  8271. dotrap(void)
  8272. {
  8273. uint8_t *g;
  8274. int sig;
  8275. int status, last_status;
  8276. if (!pending_sig)
  8277. return;
  8278. status = savestatus;
  8279. last_status = status;
  8280. if (status < 0) {
  8281. status = exitstatus;
  8282. savestatus = status;
  8283. }
  8284. pending_sig = 0;
  8285. barrier();
  8286. TRACE(("dotrap entered\n"));
  8287. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8288. char *p;
  8289. if (!*g)
  8290. continue;
  8291. if (evalskip) {
  8292. pending_sig = sig;
  8293. break;
  8294. }
  8295. p = trap[sig];
  8296. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8297. * don't upset it by resetting gotsig[SIGINT-1] */
  8298. if (sig == SIGINT && !p)
  8299. continue;
  8300. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8301. *g = 0;
  8302. if (!p)
  8303. continue;
  8304. evalstring(p, 0);
  8305. if (evalskip != SKIPFUNC)
  8306. exitstatus = status;
  8307. }
  8308. savestatus = last_status;
  8309. TRACE(("dotrap returns\n"));
  8310. }
  8311. /* forward declarations - evaluation is fairly recursive business... */
  8312. static int evalloop(union node *, int);
  8313. static int evalfor(union node *, int);
  8314. static int evalcase(union node *, int);
  8315. static int evalsubshell(union node *, int);
  8316. static void expredir(union node *);
  8317. static int evalpipe(union node *, int);
  8318. static int evalcommand(union node *, int);
  8319. static int evalbltin(const struct builtincmd *, int, char **, int);
  8320. static void prehash(union node *);
  8321. /*
  8322. * Evaluate a parse tree. The value is left in the global variable
  8323. * exitstatus.
  8324. */
  8325. static int
  8326. evaltree(union node *n, int flags)
  8327. {
  8328. int checkexit = 0;
  8329. int (*evalfn)(union node *, int);
  8330. struct stackmark smark;
  8331. int status = 0;
  8332. setstackmark(&smark);
  8333. if (n == NULL) {
  8334. TRACE(("evaltree(NULL) called\n"));
  8335. goto out;
  8336. }
  8337. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8338. dotrap();
  8339. switch (n->type) {
  8340. default:
  8341. #if DEBUG
  8342. out1fmt("Node type = %d\n", n->type);
  8343. fflush_all();
  8344. break;
  8345. #endif
  8346. case NNOT:
  8347. status = !evaltree(n->nnot.com, EV_TESTED);
  8348. goto setstatus;
  8349. case NREDIR:
  8350. errlinno = lineno = n->nredir.linno;
  8351. if (funcline)
  8352. lineno -= funcline - 1;
  8353. expredir(n->nredir.redirect);
  8354. pushredir(n->nredir.redirect);
  8355. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8356. if (!status) {
  8357. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8358. }
  8359. if (n->nredir.redirect)
  8360. popredir(/*drop:*/ 0);
  8361. goto setstatus;
  8362. case NCMD:
  8363. evalfn = evalcommand;
  8364. checkexit:
  8365. if (eflag && !(flags & EV_TESTED))
  8366. checkexit = ~0;
  8367. goto calleval;
  8368. case NFOR:
  8369. evalfn = evalfor;
  8370. goto calleval;
  8371. case NWHILE:
  8372. case NUNTIL:
  8373. evalfn = evalloop;
  8374. goto calleval;
  8375. case NSUBSHELL:
  8376. case NBACKGND:
  8377. evalfn = evalsubshell;
  8378. goto checkexit;
  8379. case NPIPE:
  8380. evalfn = evalpipe;
  8381. goto checkexit;
  8382. case NCASE:
  8383. evalfn = evalcase;
  8384. goto calleval;
  8385. case NAND:
  8386. case NOR:
  8387. case NSEMI: {
  8388. #if NAND + 1 != NOR
  8389. #error NAND + 1 != NOR
  8390. #endif
  8391. #if NOR + 1 != NSEMI
  8392. #error NOR + 1 != NSEMI
  8393. #endif
  8394. unsigned is_or = n->type - NAND;
  8395. status = evaltree(
  8396. n->nbinary.ch1,
  8397. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8398. );
  8399. if ((!status) == is_or || evalskip)
  8400. break;
  8401. n = n->nbinary.ch2;
  8402. evaln:
  8403. evalfn = evaltree;
  8404. calleval:
  8405. status = evalfn(n, flags);
  8406. goto setstatus;
  8407. }
  8408. case NIF:
  8409. status = evaltree(n->nif.test, EV_TESTED);
  8410. if (evalskip)
  8411. break;
  8412. if (!status) {
  8413. n = n->nif.ifpart;
  8414. goto evaln;
  8415. }
  8416. if (n->nif.elsepart) {
  8417. n = n->nif.elsepart;
  8418. goto evaln;
  8419. }
  8420. status = 0;
  8421. goto setstatus;
  8422. case NDEFUN:
  8423. defun(n);
  8424. /* Not necessary. To test it:
  8425. * "false; f() { qwerty; }; echo $?" should print 0.
  8426. */
  8427. /* status = 0; */
  8428. setstatus:
  8429. exitstatus = status;
  8430. break;
  8431. }
  8432. out:
  8433. /* Order of checks below is important:
  8434. * signal handlers trigger before exit caused by "set -e".
  8435. */
  8436. dotrap();
  8437. if (checkexit & status)
  8438. raise_exception(EXEND);
  8439. if (flags & EV_EXIT)
  8440. raise_exception(EXEND);
  8441. popstackmark(&smark);
  8442. TRACE(("leaving evaltree (no interrupts)\n"));
  8443. return exitstatus;
  8444. }
  8445. static int
  8446. skiploop(void)
  8447. {
  8448. int skip = evalskip;
  8449. switch (skip) {
  8450. case 0:
  8451. break;
  8452. case SKIPBREAK:
  8453. case SKIPCONT:
  8454. if (--skipcount <= 0) {
  8455. evalskip = 0;
  8456. break;
  8457. }
  8458. skip = SKIPBREAK;
  8459. break;
  8460. }
  8461. return skip;
  8462. }
  8463. static int
  8464. evalloop(union node *n, int flags)
  8465. {
  8466. int skip;
  8467. int status;
  8468. loopnest++;
  8469. status = 0;
  8470. flags &= EV_TESTED;
  8471. do {
  8472. int i;
  8473. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8474. skip = skiploop();
  8475. if (skip == SKIPFUNC)
  8476. status = i;
  8477. if (skip)
  8478. continue;
  8479. if (n->type != NWHILE)
  8480. i = !i;
  8481. if (i != 0)
  8482. break;
  8483. status = evaltree(n->nbinary.ch2, flags);
  8484. skip = skiploop();
  8485. } while (!(skip & ~SKIPCONT));
  8486. loopnest--;
  8487. return status;
  8488. }
  8489. static int
  8490. evalfor(union node *n, int flags)
  8491. {
  8492. struct arglist arglist;
  8493. union node *argp;
  8494. struct strlist *sp;
  8495. int status = 0;
  8496. errlinno = lineno = n->ncase.linno;
  8497. if (funcline)
  8498. lineno -= funcline - 1;
  8499. arglist.list = NULL;
  8500. arglist.lastp = &arglist.list;
  8501. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8502. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8503. }
  8504. *arglist.lastp = NULL;
  8505. loopnest++;
  8506. flags &= EV_TESTED;
  8507. for (sp = arglist.list; sp; sp = sp->next) {
  8508. setvar0(n->nfor.var, sp->text);
  8509. status = evaltree(n->nfor.body, flags);
  8510. if (skiploop() & ~SKIPCONT)
  8511. break;
  8512. }
  8513. loopnest--;
  8514. return status;
  8515. }
  8516. static int
  8517. evalcase(union node *n, int flags)
  8518. {
  8519. union node *cp;
  8520. union node *patp;
  8521. struct arglist arglist;
  8522. int status = 0;
  8523. errlinno = lineno = n->ncase.linno;
  8524. if (funcline)
  8525. lineno -= funcline - 1;
  8526. arglist.list = NULL;
  8527. arglist.lastp = &arglist.list;
  8528. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8529. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8530. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8531. if (casematch(patp, arglist.list->text)) {
  8532. /* Ensure body is non-empty as otherwise
  8533. * EV_EXIT may prevent us from setting the
  8534. * exit status.
  8535. */
  8536. if (evalskip == 0 && cp->nclist.body) {
  8537. status = evaltree(cp->nclist.body, flags);
  8538. }
  8539. goto out;
  8540. }
  8541. }
  8542. }
  8543. out:
  8544. return status;
  8545. }
  8546. /*
  8547. * Kick off a subshell to evaluate a tree.
  8548. */
  8549. static int
  8550. evalsubshell(union node *n, int flags)
  8551. {
  8552. struct job *jp;
  8553. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8554. int status;
  8555. errlinno = lineno = n->nredir.linno;
  8556. if (funcline)
  8557. lineno -= funcline - 1;
  8558. expredir(n->nredir.redirect);
  8559. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8560. goto nofork;
  8561. INT_OFF;
  8562. if (backgnd == FORK_FG)
  8563. get_tty_state();
  8564. jp = makejob(/*n,*/ 1);
  8565. if (forkshell(jp, n, backgnd) == 0) {
  8566. /* child */
  8567. INT_ON;
  8568. flags |= EV_EXIT;
  8569. if (backgnd)
  8570. flags &= ~EV_TESTED;
  8571. nofork:
  8572. redirect(n->nredir.redirect, 0);
  8573. evaltreenr(n->nredir.n, flags);
  8574. /* never returns */
  8575. }
  8576. /* parent */
  8577. status = 0;
  8578. if (backgnd == FORK_FG)
  8579. status = waitforjob(jp);
  8580. INT_ON;
  8581. return status;
  8582. }
  8583. /*
  8584. * Compute the names of the files in a redirection list.
  8585. */
  8586. static void fixredir(union node *, const char *, int);
  8587. static void
  8588. expredir(union node *n)
  8589. {
  8590. union node *redir;
  8591. for (redir = n; redir; redir = redir->nfile.next) {
  8592. struct arglist fn;
  8593. fn.list = NULL;
  8594. fn.lastp = &fn.list;
  8595. switch (redir->type) {
  8596. case NFROMTO:
  8597. case NFROM:
  8598. case NTO:
  8599. #if BASH_REDIR_OUTPUT
  8600. case NTO2:
  8601. #endif
  8602. case NCLOBBER:
  8603. case NAPPEND:
  8604. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8605. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8606. #if BASH_REDIR_OUTPUT
  8607. store_expfname:
  8608. #endif
  8609. #if 0
  8610. // By the design of stack allocator, the loop of this kind:
  8611. // while true; do while true; do break; done </dev/null; done
  8612. // will look like a memory leak: ash plans to free expfname's
  8613. // of "/dev/null" as soon as it finishes running the loop
  8614. // (in this case, never).
  8615. // This "fix" is wrong:
  8616. if (redir->nfile.expfname)
  8617. stunalloc(redir->nfile.expfname);
  8618. // It results in corrupted state of stacked allocations.
  8619. #endif
  8620. redir->nfile.expfname = fn.list->text;
  8621. break;
  8622. case NFROMFD:
  8623. case NTOFD: /* >& */
  8624. if (redir->ndup.vname) {
  8625. expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
  8626. if (fn.list == NULL)
  8627. ash_msg_and_raise_error("redir error");
  8628. #if BASH_REDIR_OUTPUT
  8629. if (!isdigit_str9(fn.list->text)) {
  8630. /* >&file, not >&fd */
  8631. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8632. ash_msg_and_raise_error("redir error");
  8633. redir->type = NTO2;
  8634. goto store_expfname;
  8635. }
  8636. #endif
  8637. fixredir(redir, fn.list->text, 1);
  8638. }
  8639. break;
  8640. }
  8641. }
  8642. }
  8643. /*
  8644. * Evaluate a pipeline. All the processes in the pipeline are children
  8645. * of the process creating the pipeline. (This differs from some versions
  8646. * of the shell, which make the last process in a pipeline the parent
  8647. * of all the rest.)
  8648. */
  8649. static int
  8650. evalpipe(union node *n, int flags)
  8651. {
  8652. struct job *jp;
  8653. struct nodelist *lp;
  8654. int pipelen;
  8655. int prevfd;
  8656. int pip[2];
  8657. int status = 0;
  8658. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8659. pipelen = 0;
  8660. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8661. pipelen++;
  8662. flags |= EV_EXIT;
  8663. INT_OFF;
  8664. if (n->npipe.pipe_backgnd == 0)
  8665. get_tty_state();
  8666. jp = makejob(/*n,*/ pipelen);
  8667. prevfd = -1;
  8668. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8669. prehash(lp->n);
  8670. pip[1] = -1;
  8671. if (lp->next) {
  8672. if (pipe(pip) < 0) {
  8673. close(prevfd);
  8674. ash_msg_and_raise_perror("can't create pipe");
  8675. }
  8676. }
  8677. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8678. /* child */
  8679. INT_ON;
  8680. if (pip[1] >= 0) {
  8681. close(pip[0]);
  8682. }
  8683. if (prevfd > 0) {
  8684. dup2(prevfd, 0);
  8685. close(prevfd);
  8686. }
  8687. if (pip[1] > 1) {
  8688. dup2(pip[1], 1);
  8689. close(pip[1]);
  8690. }
  8691. evaltreenr(lp->n, flags);
  8692. /* never returns */
  8693. }
  8694. /* parent */
  8695. if (prevfd >= 0)
  8696. close(prevfd);
  8697. prevfd = pip[0];
  8698. /* Don't want to trigger debugging */
  8699. if (pip[1] != -1)
  8700. close(pip[1]);
  8701. }
  8702. if (n->npipe.pipe_backgnd == 0) {
  8703. status = waitforjob(jp);
  8704. TRACE(("evalpipe: job done exit status %d\n", status));
  8705. }
  8706. INT_ON;
  8707. return status;
  8708. }
  8709. /* setinteractive needs this forward reference */
  8710. #if EDITING_HAS_get_exe_name
  8711. static const char *get_builtin_name(int i) FAST_FUNC;
  8712. #endif
  8713. /*
  8714. * Controls whether the shell is interactive or not.
  8715. */
  8716. static void
  8717. setinteractive(int on)
  8718. {
  8719. static smallint is_interactive;
  8720. if (++on == is_interactive)
  8721. return;
  8722. is_interactive = on;
  8723. setsignal(SIGINT);
  8724. setsignal(SIGQUIT);
  8725. setsignal(SIGTERM);
  8726. if (is_interactive > 1) {
  8727. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8728. /* Looks like they want an interactive shell */
  8729. static smallint did_banner;
  8730. if (!did_banner) {
  8731. /* note: ash and hush share this string */
  8732. out1fmt("\n\n%s %s\n"
  8733. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8734. "\n",
  8735. bb_banner,
  8736. "built-in shell (ash)"
  8737. );
  8738. did_banner = 1;
  8739. }
  8740. #endif
  8741. #if ENABLE_FEATURE_EDITING
  8742. if (!line_input_state) {
  8743. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  8744. # if EDITING_HAS_get_exe_name
  8745. line_input_state->get_exe_name = get_builtin_name;
  8746. # endif
  8747. }
  8748. #endif
  8749. }
  8750. }
  8751. static void
  8752. optschanged(void)
  8753. {
  8754. #if DEBUG
  8755. opentrace();
  8756. #endif
  8757. setinteractive(iflag);
  8758. setjobctl(mflag);
  8759. #if ENABLE_FEATURE_EDITING_VI
  8760. if (line_input_state) {
  8761. if (viflag)
  8762. line_input_state->flags |= VI_MODE;
  8763. else
  8764. line_input_state->flags &= ~VI_MODE;
  8765. }
  8766. #else
  8767. viflag = 0; /* forcibly keep the option off */
  8768. #endif
  8769. }
  8770. struct localvar_list {
  8771. struct localvar_list *next;
  8772. struct localvar *lv;
  8773. };
  8774. static struct localvar_list *localvar_stack;
  8775. /*
  8776. * Called after a function returns.
  8777. * Interrupts must be off.
  8778. */
  8779. static void
  8780. poplocalvars(int keep)
  8781. {
  8782. struct localvar_list *ll;
  8783. struct localvar *lvp, *next;
  8784. struct var *vp;
  8785. INT_OFF;
  8786. ll = localvar_stack;
  8787. localvar_stack = ll->next;
  8788. next = ll->lv;
  8789. free(ll);
  8790. while ((lvp = next) != NULL) {
  8791. next = lvp->next;
  8792. vp = lvp->vp;
  8793. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8794. if (keep) {
  8795. int bits = VSTRFIXED;
  8796. if (lvp->flags != VUNSET) {
  8797. if (vp->var_text == lvp->text)
  8798. bits |= VTEXTFIXED;
  8799. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8800. free((char*)lvp->text);
  8801. }
  8802. vp->flags &= ~bits;
  8803. vp->flags |= (lvp->flags & bits);
  8804. if ((vp->flags &
  8805. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8806. unsetvar(vp->var_text);
  8807. } else if (vp == NULL) { /* $- saved */
  8808. memcpy(optlist, lvp->text, sizeof(optlist));
  8809. free((char*)lvp->text);
  8810. optschanged();
  8811. } else if (lvp->flags == VUNSET) {
  8812. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8813. unsetvar(vp->var_text);
  8814. } else {
  8815. if (vp->var_func)
  8816. vp->var_func(var_end(lvp->text));
  8817. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8818. free((char*)vp->var_text);
  8819. vp->flags = lvp->flags;
  8820. vp->var_text = lvp->text;
  8821. }
  8822. free(lvp);
  8823. }
  8824. INT_ON;
  8825. }
  8826. /*
  8827. * Create a new localvar environment.
  8828. */
  8829. static struct localvar_list *
  8830. pushlocalvars(int push)
  8831. {
  8832. struct localvar_list *ll;
  8833. struct localvar_list *top;
  8834. top = localvar_stack;
  8835. if (!push)
  8836. goto out;
  8837. INT_OFF;
  8838. ll = ckzalloc(sizeof(*ll));
  8839. /*ll->lv = NULL; - zalloc did it */
  8840. ll->next = top;
  8841. localvar_stack = ll;
  8842. INT_ON;
  8843. out:
  8844. return top;
  8845. }
  8846. static void
  8847. unwindlocalvars(struct localvar_list *stop)
  8848. {
  8849. while (localvar_stack != stop)
  8850. poplocalvars(0);
  8851. }
  8852. static int
  8853. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8854. {
  8855. volatile struct shparam saveparam;
  8856. struct jmploc *volatile savehandler;
  8857. struct jmploc jmploc;
  8858. int e;
  8859. int savefuncline;
  8860. saveparam = shellparam;
  8861. savefuncline = funcline;
  8862. savehandler = exception_handler;
  8863. e = setjmp(jmploc.loc);
  8864. if (e) {
  8865. goto funcdone;
  8866. }
  8867. INT_OFF;
  8868. exception_handler = &jmploc;
  8869. shellparam.malloced = 0;
  8870. func->count++;
  8871. funcline = func->n.ndefun.linno;
  8872. INT_ON;
  8873. shellparam.nparam = argc - 1;
  8874. shellparam.p = argv + 1;
  8875. #if ENABLE_ASH_GETOPTS
  8876. shellparam.optind = 1;
  8877. shellparam.optoff = -1;
  8878. #endif
  8879. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  8880. funcdone:
  8881. INT_OFF;
  8882. funcline = savefuncline;
  8883. freefunc(func);
  8884. freeparam(&shellparam);
  8885. shellparam = saveparam;
  8886. exception_handler = savehandler;
  8887. INT_ON;
  8888. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  8889. return e;
  8890. }
  8891. /*
  8892. * Make a variable a local variable. When a variable is made local, it's
  8893. * value and flags are saved in a localvar structure. The saved values
  8894. * will be restored when the shell function returns. We handle the name
  8895. * "-" as a special case: it makes changes to "set +-options" local
  8896. * (options will be restored on return from the function).
  8897. */
  8898. static void
  8899. mklocal(char *name, int flags)
  8900. {
  8901. struct localvar *lvp;
  8902. struct var **vpp;
  8903. struct var *vp;
  8904. char *eq = strchr(name, '=');
  8905. INT_OFF;
  8906. /* Cater for duplicate "local". Examples:
  8907. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8908. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8909. */
  8910. lvp = localvar_stack->lv;
  8911. while (lvp) {
  8912. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8913. if (eq)
  8914. setvareq(name, 0);
  8915. /* else:
  8916. * it's a duplicate "local VAR" declaration, do nothing
  8917. */
  8918. goto ret;
  8919. }
  8920. lvp = lvp->next;
  8921. }
  8922. lvp = ckzalloc(sizeof(*lvp));
  8923. if (LONE_DASH(name)) {
  8924. char *p;
  8925. p = ckmalloc(sizeof(optlist));
  8926. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8927. vp = NULL;
  8928. } else {
  8929. vpp = hashvar(name);
  8930. vp = *findvar(vpp, name);
  8931. if (vp == NULL) {
  8932. /* variable did not exist yet */
  8933. if (eq)
  8934. vp = setvareq(name, VSTRFIXED | flags);
  8935. else
  8936. vp = setvar(name, NULL, VSTRFIXED | flags);
  8937. lvp->flags = VUNSET;
  8938. } else {
  8939. lvp->text = vp->var_text;
  8940. lvp->flags = vp->flags;
  8941. /* make sure neither "struct var" nor string gets freed
  8942. * during (un)setting:
  8943. */
  8944. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8945. if (eq)
  8946. setvareq(name, flags);
  8947. else
  8948. /* "local VAR" unsets VAR: */
  8949. setvar0(name, NULL);
  8950. }
  8951. }
  8952. lvp->vp = vp;
  8953. lvp->next = localvar_stack->lv;
  8954. localvar_stack->lv = lvp;
  8955. ret:
  8956. INT_ON;
  8957. }
  8958. /*
  8959. * The "local" command.
  8960. */
  8961. static int FAST_FUNC
  8962. localcmd(int argc UNUSED_PARAM, char **argv)
  8963. {
  8964. char *name;
  8965. if (!localvar_stack)
  8966. ash_msg_and_raise_error("not in a function");
  8967. argv = argptr;
  8968. while ((name = *argv++) != NULL) {
  8969. mklocal(name, 0);
  8970. }
  8971. return 0;
  8972. }
  8973. static int FAST_FUNC
  8974. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8975. {
  8976. return 1;
  8977. }
  8978. static int FAST_FUNC
  8979. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8980. {
  8981. return 0;
  8982. }
  8983. static int FAST_FUNC
  8984. execcmd(int argc UNUSED_PARAM, char **argv)
  8985. {
  8986. optionarg = NULL;
  8987. while (nextopt("a:") != '\0')
  8988. /* nextopt() sets optionarg to "-a ARGV0" */;
  8989. argv = argptr;
  8990. if (argv[0]) {
  8991. char *prog;
  8992. iflag = 0; /* exit on error */
  8993. mflag = 0;
  8994. optschanged();
  8995. /* We should set up signals for "exec CMD"
  8996. * the same way as for "CMD" without "exec".
  8997. * But optschanged->setinteractive->setsignal
  8998. * still thought we are a root shell. Therefore, for example,
  8999. * SIGQUIT is still set to IGN. Fix it:
  9000. */
  9001. shlvl++;
  9002. setsignal(SIGQUIT);
  9003. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  9004. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  9005. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  9006. prog = argv[0];
  9007. if (optionarg)
  9008. argv[0] = optionarg;
  9009. shellexec(prog, argv, pathval(), 0);
  9010. /* NOTREACHED */
  9011. }
  9012. return 0;
  9013. }
  9014. /*
  9015. * The return command.
  9016. */
  9017. static int FAST_FUNC
  9018. returncmd(int argc UNUSED_PARAM, char **argv)
  9019. {
  9020. int skip;
  9021. int status;
  9022. /*
  9023. * If called outside a function, do what ksh does;
  9024. * skip the rest of the file.
  9025. */
  9026. if (argv[1]) {
  9027. skip = SKIPFUNC;
  9028. status = number(argv[1]);
  9029. } else {
  9030. skip = SKIPFUNCDEF;
  9031. status = exitstatus;
  9032. }
  9033. evalskip = skip;
  9034. return status;
  9035. }
  9036. /* Forward declarations for builtintab[] */
  9037. static int breakcmd(int, char **) FAST_FUNC;
  9038. static int dotcmd(int, char **) FAST_FUNC;
  9039. static int evalcmd(int, char **, int) FAST_FUNC;
  9040. static int exitcmd(int, char **) FAST_FUNC;
  9041. static int exportcmd(int, char **) FAST_FUNC;
  9042. #if ENABLE_ASH_GETOPTS
  9043. static int getoptscmd(int, char **) FAST_FUNC;
  9044. #endif
  9045. #if ENABLE_ASH_HELP
  9046. static int helpcmd(int, char **) FAST_FUNC;
  9047. #endif
  9048. #if MAX_HISTORY
  9049. static int historycmd(int, char **) FAST_FUNC;
  9050. #endif
  9051. #if ENABLE_FEATURE_SH_MATH
  9052. static int letcmd(int, char **) FAST_FUNC;
  9053. #endif
  9054. static int readcmd(int, char **) FAST_FUNC;
  9055. static int setcmd(int, char **) FAST_FUNC;
  9056. static int shiftcmd(int, char **) FAST_FUNC;
  9057. static int timescmd(int, char **) FAST_FUNC;
  9058. static int trapcmd(int, char **) FAST_FUNC;
  9059. static int umaskcmd(int, char **) FAST_FUNC;
  9060. static int unsetcmd(int, char **) FAST_FUNC;
  9061. static int ulimitcmd(int, char **) FAST_FUNC;
  9062. #define BUILTIN_NOSPEC "0"
  9063. #define BUILTIN_SPECIAL "1"
  9064. #define BUILTIN_REGULAR "2"
  9065. #define BUILTIN_SPEC_REG "3"
  9066. #define BUILTIN_ASSIGN "4"
  9067. #define BUILTIN_SPEC_ASSG "5"
  9068. #define BUILTIN_REG_ASSG "6"
  9069. #define BUILTIN_SPEC_REG_ASSG "7"
  9070. /* Stubs for calling non-FAST_FUNC's */
  9071. #if ENABLE_ASH_ECHO
  9072. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  9073. #endif
  9074. #if ENABLE_ASH_PRINTF
  9075. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  9076. #endif
  9077. #if ENABLE_ASH_TEST || BASH_TEST2
  9078. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  9079. #endif
  9080. /* Keep these in proper order since it is searched via bsearch() */
  9081. static const struct builtincmd builtintab[] = {
  9082. { BUILTIN_SPEC_REG "." , dotcmd },
  9083. { BUILTIN_SPEC_REG ":" , truecmd },
  9084. #if ENABLE_ASH_TEST
  9085. { BUILTIN_REGULAR "[" , testcmd },
  9086. #endif
  9087. #if BASH_TEST2
  9088. { BUILTIN_REGULAR "[[" , testcmd },
  9089. #endif
  9090. #if ENABLE_ASH_ALIAS
  9091. { BUILTIN_REG_ASSG "alias" , aliascmd },
  9092. #endif
  9093. #if JOBS
  9094. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  9095. #endif
  9096. { BUILTIN_SPEC_REG "break" , breakcmd },
  9097. { BUILTIN_REGULAR "cd" , cdcmd },
  9098. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9099. #if ENABLE_ASH_CMDCMD
  9100. { BUILTIN_REGULAR "command" , commandcmd },
  9101. #endif
  9102. { BUILTIN_SPEC_REG "continue", breakcmd },
  9103. #if ENABLE_ASH_ECHO
  9104. { BUILTIN_REGULAR "echo" , echocmd },
  9105. #endif
  9106. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9107. { BUILTIN_SPEC_REG "exec" , execcmd },
  9108. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9109. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9110. { BUILTIN_REGULAR "false" , falsecmd },
  9111. #if JOBS
  9112. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9113. #endif
  9114. #if ENABLE_ASH_GETOPTS
  9115. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9116. #endif
  9117. { BUILTIN_REGULAR "hash" , hashcmd },
  9118. #if ENABLE_ASH_HELP
  9119. { BUILTIN_NOSPEC "help" , helpcmd },
  9120. #endif
  9121. #if MAX_HISTORY
  9122. { BUILTIN_NOSPEC "history" , historycmd },
  9123. #endif
  9124. #if JOBS
  9125. { BUILTIN_REGULAR "jobs" , jobscmd },
  9126. { BUILTIN_REGULAR "kill" , killcmd },
  9127. #endif
  9128. #if ENABLE_FEATURE_SH_MATH
  9129. { BUILTIN_NOSPEC "let" , letcmd },
  9130. #endif
  9131. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9132. #if ENABLE_ASH_PRINTF
  9133. { BUILTIN_REGULAR "printf" , printfcmd },
  9134. #endif
  9135. { BUILTIN_REGULAR "pwd" , pwdcmd },
  9136. { BUILTIN_REGULAR "read" , readcmd },
  9137. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9138. { BUILTIN_SPEC_REG "return" , returncmd },
  9139. { BUILTIN_SPEC_REG "set" , setcmd },
  9140. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9141. #if BASH_SOURCE
  9142. { BUILTIN_SPEC_REG "source" , dotcmd },
  9143. #endif
  9144. #if ENABLE_ASH_TEST
  9145. { BUILTIN_REGULAR "test" , testcmd },
  9146. #endif
  9147. { BUILTIN_SPEC_REG "times" , timescmd },
  9148. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9149. { BUILTIN_REGULAR "true" , truecmd },
  9150. { BUILTIN_REGULAR "type" , typecmd },
  9151. { BUILTIN_REGULAR "ulimit" , ulimitcmd },
  9152. { BUILTIN_REGULAR "umask" , umaskcmd },
  9153. #if ENABLE_ASH_ALIAS
  9154. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9155. #endif
  9156. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9157. { BUILTIN_REGULAR "wait" , waitcmd },
  9158. };
  9159. /* Should match the above table! */
  9160. #define COMMANDCMD (builtintab + \
  9161. /* . : */ 2 + \
  9162. /* [ */ 1 * ENABLE_ASH_TEST + \
  9163. /* [[ */ 1 * BASH_TEST2 + \
  9164. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9165. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9166. /* break cd cddir */ 3)
  9167. #define EVALCMD (COMMANDCMD + \
  9168. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9169. /* continue */ 1 + \
  9170. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9171. 0)
  9172. #define EXECCMD (EVALCMD + \
  9173. /* eval */ 1)
  9174. /*
  9175. * Search the table of builtin commands.
  9176. */
  9177. static int
  9178. pstrcmp1(const void *a, const void *b)
  9179. {
  9180. return strcmp((char*)a, *(char**)b + 1);
  9181. }
  9182. static struct builtincmd *
  9183. find_builtin(const char *name)
  9184. {
  9185. struct builtincmd *bp;
  9186. bp = bsearch(
  9187. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9188. pstrcmp1
  9189. );
  9190. return bp;
  9191. }
  9192. #if EDITING_HAS_get_exe_name
  9193. static const char * FAST_FUNC
  9194. get_builtin_name(int i)
  9195. {
  9196. return /*i >= 0 &&*/ i < ARRAY_SIZE(builtintab) ? builtintab[i].name + 1 : NULL;
  9197. }
  9198. #endif
  9199. /*
  9200. * Execute a simple command.
  9201. */
  9202. static void unwindfiles(struct parsefile *stop);
  9203. static int
  9204. isassignment(const char *p)
  9205. {
  9206. const char *q = endofname(p);
  9207. if (p == q)
  9208. return 0;
  9209. return *q == '=';
  9210. }
  9211. static int FAST_FUNC
  9212. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9213. {
  9214. /* Preserve exitstatus of a previous possible redirection
  9215. * as POSIX mandates */
  9216. return back_exitstatus;
  9217. }
  9218. static int
  9219. evalcommand(union node *cmd, int flags)
  9220. {
  9221. static const struct builtincmd null_bltin = {
  9222. BUILTIN_REGULAR "", bltincmd
  9223. };
  9224. struct localvar_list *localvar_stop;
  9225. struct parsefile *file_stop;
  9226. struct redirtab *redir_stop;
  9227. union node *argp;
  9228. struct arglist arglist;
  9229. struct arglist varlist;
  9230. char **argv;
  9231. int argc;
  9232. struct strlist *osp;
  9233. const struct strlist *sp;
  9234. struct cmdentry cmdentry;
  9235. struct job *jp;
  9236. char *lastarg;
  9237. const char *path;
  9238. int spclbltin;
  9239. int cmd_flag;
  9240. int status;
  9241. char **nargv;
  9242. smallint cmd_is_exec;
  9243. int vflags;
  9244. int vlocal;
  9245. errlinno = lineno = cmd->ncmd.linno;
  9246. if (funcline)
  9247. lineno -= funcline - 1;
  9248. /* First expand the arguments. */
  9249. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9250. file_stop = g_parsefile;
  9251. back_exitstatus = 0;
  9252. cmdentry.cmdtype = CMDBUILTIN;
  9253. cmdentry.u.cmd = &null_bltin;
  9254. varlist.lastp = &varlist.list;
  9255. *varlist.lastp = NULL;
  9256. arglist.lastp = &arglist.list;
  9257. *arglist.lastp = NULL;
  9258. cmd_flag = 0;
  9259. cmd_is_exec = 0;
  9260. spclbltin = -1;
  9261. vflags = 0;
  9262. vlocal = 0;
  9263. path = NULL;
  9264. argc = 0;
  9265. argp = cmd->ncmd.args;
  9266. osp = fill_arglist(&arglist, &argp);
  9267. if (osp) {
  9268. int pseudovarflag = 0;
  9269. for (;;) {
  9270. find_command(arglist.list->text, &cmdentry,
  9271. cmd_flag | DO_REGBLTIN, pathval());
  9272. vlocal++;
  9273. /* implement bltin and command here */
  9274. if (cmdentry.cmdtype != CMDBUILTIN)
  9275. break;
  9276. pseudovarflag = IS_BUILTIN_ASSIGN(cmdentry.u.cmd);
  9277. if (spclbltin < 0) {
  9278. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9279. vlocal = !spclbltin;
  9280. }
  9281. cmd_is_exec = cmdentry.u.cmd == EXECCMD;
  9282. #if ENABLE_ASH_CMDCMD
  9283. if (cmdentry.u.cmd != COMMANDCMD)
  9284. break;
  9285. cmd_flag = parse_command_args(&arglist, &argp, &path);
  9286. if (!cmd_flag)
  9287. #endif
  9288. break;
  9289. }
  9290. for (; argp; argp = argp->narg.next)
  9291. expandarg(argp, &arglist,
  9292. pseudovarflag &&
  9293. isassignment(argp->narg.text) ?
  9294. EXP_VARTILDE : EXP_FULL | EXP_TILDE);
  9295. for (sp = arglist.list; sp; sp = sp->next)
  9296. argc++;
  9297. if (cmd_is_exec && argc > 1)
  9298. vflags = VEXPORT;
  9299. }
  9300. localvar_stop = pushlocalvars(vlocal);
  9301. /* Reserve one extra spot at the front for shellexec. */
  9302. nargv = stalloc(sizeof(char *) * (argc + 2));
  9303. argv = ++nargv;
  9304. for (sp = arglist.list; sp; sp = sp->next) {
  9305. TRACE(("evalcommand arg: %s\n", sp->text));
  9306. *nargv++ = sp->text;
  9307. }
  9308. *nargv = NULL;
  9309. lastarg = NULL;
  9310. if (iflag && funcline == 0 && argc > 0)
  9311. lastarg = nargv[-1];
  9312. expredir(cmd->ncmd.redirect);
  9313. redir_stop = pushredir(cmd->ncmd.redirect);
  9314. preverrout_fd = 2;
  9315. if (BASH_XTRACEFD && xflag) {
  9316. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9317. * we do not emulate this. We only use its value.
  9318. */
  9319. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9320. if (xtracefd && is_number(xtracefd))
  9321. preverrout_fd = atoi(xtracefd);
  9322. }
  9323. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9324. if (status) {
  9325. bail:
  9326. exitstatus = status;
  9327. /* We have a redirection error. */
  9328. if (spclbltin > 0)
  9329. raise_exception(EXERROR);
  9330. goto out;
  9331. }
  9332. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9333. struct strlist **spp;
  9334. spp = varlist.lastp;
  9335. expandarg(argp, &varlist, EXP_VARTILDE);
  9336. if (vlocal)
  9337. mklocal((*spp)->text, VEXPORT);
  9338. else
  9339. setvareq((*spp)->text, vflags);
  9340. }
  9341. /* Print the command if xflag is set. */
  9342. if (xflag) {
  9343. const char *pfx = "";
  9344. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9345. sp = varlist.list;
  9346. while (sp) {
  9347. char *varval = sp->text;
  9348. char *eq = strchrnul(varval, '=');
  9349. if (*eq)
  9350. eq++;
  9351. fdprintf(preverrout_fd, "%s%.*s%s",
  9352. pfx,
  9353. (int)(eq - varval), varval,
  9354. maybe_single_quote(eq)
  9355. );
  9356. sp = sp->next;
  9357. pfx = " ";
  9358. }
  9359. sp = arglist.list;
  9360. while (sp) {
  9361. fdprintf(preverrout_fd, "%s%s",
  9362. pfx,
  9363. /* always quote if matches reserved word: */
  9364. findkwd(sp->text)
  9365. ? single_quote(sp->text)
  9366. : maybe_single_quote(sp->text)
  9367. );
  9368. sp = sp->next;
  9369. pfx = " ";
  9370. }
  9371. safe_write(preverrout_fd, "\n", 1);
  9372. }
  9373. /* Now locate the command. */
  9374. if (cmdentry.cmdtype != CMDBUILTIN
  9375. || !(IS_BUILTIN_REGULAR(cmdentry.u.cmd))
  9376. ) {
  9377. path = path ? path : pathval();
  9378. find_command(argv[0], &cmdentry, cmd_flag | DO_ERR, path);
  9379. }
  9380. jp = NULL;
  9381. /* Execute the command. */
  9382. switch (cmdentry.cmdtype) {
  9383. case CMDUNKNOWN:
  9384. status = 127;
  9385. flush_stdout_stderr();
  9386. goto bail;
  9387. default: {
  9388. #if ENABLE_FEATURE_SH_STANDALONE \
  9389. && ENABLE_FEATURE_SH_NOFORK \
  9390. && NUM_APPLETS > 1
  9391. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9392. * around run_nofork_applet() call.
  9393. * (2) Should this check also be done in forkshell()?
  9394. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9395. */
  9396. /* find_command() encodes applet_no as (-2 - applet_no) */
  9397. int applet_no = (- cmdentry.u.index - 2);
  9398. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9399. char **sv_environ;
  9400. INT_OFF;
  9401. sv_environ = environ;
  9402. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9403. /*
  9404. * Run <applet>_main().
  9405. * Signals (^C) can't interrupt here.
  9406. * Otherwise we can mangle stdio or malloc internal state.
  9407. * This makes applets which can run for a long time
  9408. * and/or wait for user input ineligible for NOFORK:
  9409. * for example, "yes" or "rm" (rm -i waits for input).
  9410. */
  9411. exitstatus = run_nofork_applet(applet_no, argv);
  9412. environ = sv_environ;
  9413. /*
  9414. * Try enabling NOFORK for "yes" applet.
  9415. * ^C _will_ stop it (write returns EINTR),
  9416. * but this causes stdout FILE to be stuck
  9417. * and needing clearerr(). What if other applets
  9418. * also can get EINTRs? Do we need to switch
  9419. * our signals to SA_RESTART?
  9420. */
  9421. /*clearerr(stdout);*/
  9422. INT_ON;
  9423. break;
  9424. }
  9425. #endif
  9426. /* Can we avoid forking? For example, very last command
  9427. * in a script or a subshell does not need forking,
  9428. * we can just exec it.
  9429. */
  9430. if (!(flags & EV_EXIT) || may_have_traps) {
  9431. /* No, forking off a child is necessary */
  9432. INT_OFF;
  9433. get_tty_state();
  9434. jp = makejob(/*cmd,*/ 1);
  9435. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9436. /* parent */
  9437. break;
  9438. }
  9439. /* child */
  9440. FORCE_INT_ON;
  9441. /* fall through to exec'ing external program */
  9442. }
  9443. shellexec(argv[0], argv, path, cmdentry.u.index);
  9444. /* NOTREACHED */
  9445. } /* default */
  9446. case CMDBUILTIN:
  9447. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)
  9448. && !(exception_type == EXERROR && spclbltin <= 0)
  9449. ) {
  9450. raise:
  9451. longjmp(exception_handler->loc, 1);
  9452. }
  9453. break;
  9454. case CMDFUNCTION:
  9455. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9456. goto raise;
  9457. break;
  9458. } /* switch */
  9459. status = waitforjob(jp);
  9460. if (jp)
  9461. TRACE(("forked child exited with %d\n", status));
  9462. FORCE_INT_ON;
  9463. out:
  9464. if (cmd->ncmd.redirect)
  9465. popredir(/*drop:*/ cmd_is_exec);
  9466. unwindredir(redir_stop);
  9467. unwindfiles(file_stop);
  9468. unwindlocalvars(localvar_stop);
  9469. if (lastarg) {
  9470. /* dsl: I think this is intended to be used to support
  9471. * '_' in 'vi' command mode during line editing...
  9472. * However I implemented that within libedit itself.
  9473. */
  9474. setvar0("_", lastarg);
  9475. }
  9476. return status;
  9477. }
  9478. static int
  9479. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9480. {
  9481. char *volatile savecmdname;
  9482. struct jmploc *volatile savehandler;
  9483. struct jmploc jmploc;
  9484. int status;
  9485. int i;
  9486. savecmdname = commandname;
  9487. savehandler = exception_handler;
  9488. i = setjmp(jmploc.loc);
  9489. if (i)
  9490. goto cmddone;
  9491. exception_handler = &jmploc;
  9492. commandname = argv[0];
  9493. argptr = argv + 1;
  9494. optptr = NULL; /* initialize nextopt */
  9495. if (cmd == EVALCMD)
  9496. status = evalcmd(argc, argv, flags);
  9497. else
  9498. status = (*cmd->builtin)(argc, argv);
  9499. flush_stdout_stderr();
  9500. status |= ferror(stdout);
  9501. exitstatus = status;
  9502. cmddone:
  9503. clearerr(stdout);
  9504. commandname = savecmdname;
  9505. exception_handler = savehandler;
  9506. return i;
  9507. }
  9508. static int
  9509. goodname(const char *p)
  9510. {
  9511. return endofname(p)[0] == '\0';
  9512. }
  9513. /*
  9514. * Search for a command. This is called before we fork so that the
  9515. * location of the command will be available in the parent as well as
  9516. * the child. The check for "goodname" is an overly conservative
  9517. * check that the name will not be subject to expansion.
  9518. */
  9519. static void
  9520. prehash(union node *n)
  9521. {
  9522. struct cmdentry entry;
  9523. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9524. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9525. }
  9526. /* ============ Builtin commands
  9527. *
  9528. * Builtin commands whose functions are closely tied to evaluation
  9529. * are implemented here.
  9530. */
  9531. /*
  9532. * Handle break and continue commands. Break, continue, and return are
  9533. * all handled by setting the evalskip flag. The evaluation routines
  9534. * above all check this flag, and if it is set they start skipping
  9535. * commands rather than executing them. The variable skipcount is
  9536. * the number of loops to break/continue, or the number of function
  9537. * levels to return. (The latter is always 1.) It should probably
  9538. * be an error to break out of more loops than exist, but it isn't
  9539. * in the standard shell so we don't make it one here.
  9540. */
  9541. static int FAST_FUNC
  9542. breakcmd(int argc UNUSED_PARAM, char **argv)
  9543. {
  9544. int n = argv[1] ? number(argv[1]) : 1;
  9545. if (n <= 0)
  9546. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9547. if (n > loopnest)
  9548. n = loopnest;
  9549. if (n > 0) {
  9550. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9551. skipcount = n;
  9552. }
  9553. return 0;
  9554. }
  9555. /*
  9556. * This implements the input routines used by the parser.
  9557. */
  9558. enum {
  9559. INPUT_PUSH_FILE = 1,
  9560. INPUT_NOFILE_OK = 2,
  9561. };
  9562. static smallint checkkwd;
  9563. /* values of checkkwd variable */
  9564. #define CHKALIAS 0x1
  9565. #define CHKKWD 0x2
  9566. #define CHKNL 0x4
  9567. #define CHKEOFMARK 0x8
  9568. /*
  9569. * Push a string back onto the input at this current parsefile level.
  9570. * We handle aliases this way.
  9571. */
  9572. #if !ENABLE_ASH_ALIAS
  9573. #define pushstring(s, ap) pushstring(s)
  9574. #endif
  9575. static void
  9576. pushstring(char *s, struct alias *ap)
  9577. {
  9578. struct strpush *sp;
  9579. int len;
  9580. len = strlen(s);
  9581. INT_OFF;
  9582. if (g_parsefile->strpush) {
  9583. sp = ckzalloc(sizeof(*sp));
  9584. sp->prev = g_parsefile->strpush;
  9585. } else {
  9586. sp = &(g_parsefile->basestrpush);
  9587. }
  9588. g_parsefile->strpush = sp;
  9589. sp->prev_string = g_parsefile->next_to_pgetc;
  9590. sp->prev_left_in_line = g_parsefile->left_in_line;
  9591. sp->unget = g_parsefile->unget;
  9592. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9593. #if ENABLE_ASH_ALIAS
  9594. sp->ap = ap;
  9595. if (ap) {
  9596. ap->flag |= ALIASINUSE;
  9597. sp->string = s;
  9598. }
  9599. #endif
  9600. g_parsefile->next_to_pgetc = s;
  9601. g_parsefile->left_in_line = len;
  9602. g_parsefile->unget = 0;
  9603. INT_ON;
  9604. }
  9605. static void
  9606. popstring(void)
  9607. {
  9608. struct strpush *sp = g_parsefile->strpush;
  9609. INT_OFF;
  9610. #if ENABLE_ASH_ALIAS
  9611. if (sp->ap) {
  9612. if (g_parsefile->next_to_pgetc[-1] == ' '
  9613. || g_parsefile->next_to_pgetc[-1] == '\t'
  9614. ) {
  9615. checkkwd |= CHKALIAS;
  9616. }
  9617. if (sp->string != sp->ap->val) {
  9618. free(sp->string);
  9619. }
  9620. sp->ap->flag &= ~ALIASINUSE;
  9621. if (sp->ap->flag & ALIASDEAD) {
  9622. unalias(sp->ap->name);
  9623. }
  9624. }
  9625. #endif
  9626. g_parsefile->next_to_pgetc = sp->prev_string;
  9627. g_parsefile->left_in_line = sp->prev_left_in_line;
  9628. g_parsefile->unget = sp->unget;
  9629. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9630. g_parsefile->strpush = sp->prev;
  9631. if (sp != &(g_parsefile->basestrpush))
  9632. free(sp);
  9633. INT_ON;
  9634. }
  9635. static int
  9636. preadfd(void)
  9637. {
  9638. int nr;
  9639. char *buf = g_parsefile->buf;
  9640. g_parsefile->next_to_pgetc = buf;
  9641. #if ENABLE_FEATURE_EDITING
  9642. retry:
  9643. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9644. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9645. else {
  9646. # if ENABLE_ASH_IDLE_TIMEOUT
  9647. int timeout = -1;
  9648. const char *tmout_var = lookupvar("TMOUT");
  9649. if (tmout_var) {
  9650. timeout = atoi(tmout_var) * 1000;
  9651. if (timeout <= 0)
  9652. timeout = -1;
  9653. }
  9654. line_input_state->timeout = timeout;
  9655. # endif
  9656. # if ENABLE_FEATURE_TAB_COMPLETION
  9657. line_input_state->path_lookup = pathval();
  9658. # endif
  9659. reinit_unicode_for_ash();
  9660. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9661. if (nr == 0) {
  9662. /* ^C pressed, "convert" to SIGINT */
  9663. write(STDOUT_FILENO, "^C", 2);
  9664. if (trap[SIGINT]) {
  9665. buf[0] = '\n';
  9666. buf[1] = '\0';
  9667. raise(SIGINT);
  9668. return 1;
  9669. }
  9670. exitstatus = 128 + SIGINT;
  9671. bb_putchar('\n');
  9672. goto retry;
  9673. }
  9674. if (nr < 0) {
  9675. if (errno == 0) {
  9676. /* Ctrl+D pressed */
  9677. nr = 0;
  9678. }
  9679. # if ENABLE_ASH_IDLE_TIMEOUT
  9680. else if (errno == EAGAIN && timeout > 0) {
  9681. puts("\007timed out waiting for input: auto-logout");
  9682. exitshell();
  9683. }
  9684. # endif
  9685. }
  9686. }
  9687. #else
  9688. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9689. #endif
  9690. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9691. if (nr < 0) {
  9692. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9693. int flags = fcntl(0, F_GETFL);
  9694. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9695. flags &= ~O_NONBLOCK;
  9696. if (fcntl(0, F_SETFL, flags) >= 0) {
  9697. out2str("sh: turning off NDELAY mode\n");
  9698. goto retry;
  9699. }
  9700. }
  9701. }
  9702. }
  9703. #endif
  9704. return nr;
  9705. }
  9706. /*
  9707. * Refill the input buffer and return the next input character:
  9708. *
  9709. * 1) If a string was pushed back on the input, pop it;
  9710. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9711. * or we are reading from a string so we can't refill the buffer,
  9712. * return EOF.
  9713. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9714. * 4) Process input up to the next newline, deleting nul characters.
  9715. */
  9716. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9717. #define pgetc_debug(...) ((void)0)
  9718. static int pgetc(void);
  9719. static int
  9720. preadbuffer(void)
  9721. {
  9722. char *q;
  9723. int more;
  9724. if (g_parsefile->strpush) {
  9725. #if ENABLE_ASH_ALIAS
  9726. if (g_parsefile->left_in_line == -1
  9727. && g_parsefile->strpush->ap
  9728. && g_parsefile->next_to_pgetc[-1] != ' '
  9729. && g_parsefile->next_to_pgetc[-1] != '\t'
  9730. ) {
  9731. pgetc_debug("preadbuffer PEOA");
  9732. return PEOA;
  9733. }
  9734. #endif
  9735. popstring();
  9736. return pgetc();
  9737. }
  9738. /* on both branches above g_parsefile->left_in_line < 0.
  9739. * "pgetc" needs refilling.
  9740. */
  9741. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9742. * pungetc() may increment it a few times.
  9743. * Assuming it won't increment it to less than -90.
  9744. */
  9745. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9746. pgetc_debug("preadbuffer PEOF1");
  9747. /* even in failure keep left_in_line and next_to_pgetc
  9748. * in lock step, for correct multi-layer pungetc.
  9749. * left_in_line was decremented before preadbuffer(),
  9750. * must inc next_to_pgetc: */
  9751. g_parsefile->next_to_pgetc++;
  9752. return PEOF;
  9753. }
  9754. more = g_parsefile->left_in_buffer;
  9755. if (more <= 0) {
  9756. flush_stdout_stderr();
  9757. again:
  9758. more = preadfd();
  9759. if (more <= 0) {
  9760. /* don't try reading again */
  9761. g_parsefile->left_in_line = -99;
  9762. pgetc_debug("preadbuffer PEOF2");
  9763. g_parsefile->next_to_pgetc++;
  9764. return PEOF;
  9765. }
  9766. }
  9767. /* Find out where's the end of line.
  9768. * Set g_parsefile->left_in_line
  9769. * and g_parsefile->left_in_buffer acordingly.
  9770. * NUL chars are deleted.
  9771. */
  9772. q = g_parsefile->next_to_pgetc;
  9773. for (;;) {
  9774. char c;
  9775. more--;
  9776. c = *q;
  9777. if (c == '\0') {
  9778. memmove(q, q + 1, more);
  9779. } else {
  9780. q++;
  9781. if (c == '\n') {
  9782. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9783. break;
  9784. }
  9785. }
  9786. if (more <= 0) {
  9787. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9788. if (g_parsefile->left_in_line < 0)
  9789. goto again;
  9790. break;
  9791. }
  9792. }
  9793. g_parsefile->left_in_buffer = more;
  9794. if (vflag) {
  9795. char save = *q;
  9796. *q = '\0';
  9797. out2str(g_parsefile->next_to_pgetc);
  9798. *q = save;
  9799. }
  9800. pgetc_debug("preadbuffer at %d:%p'%s'",
  9801. g_parsefile->left_in_line,
  9802. g_parsefile->next_to_pgetc,
  9803. g_parsefile->next_to_pgetc);
  9804. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9805. }
  9806. static void
  9807. nlprompt(void)
  9808. {
  9809. g_parsefile->linno++;
  9810. setprompt_if(doprompt, 2);
  9811. }
  9812. static void
  9813. nlnoprompt(void)
  9814. {
  9815. g_parsefile->linno++;
  9816. needprompt = doprompt;
  9817. }
  9818. static int
  9819. pgetc(void)
  9820. {
  9821. int c;
  9822. pgetc_debug("pgetc at %d:%p'%s'",
  9823. g_parsefile->left_in_line,
  9824. g_parsefile->next_to_pgetc,
  9825. g_parsefile->next_to_pgetc);
  9826. if (g_parsefile->unget)
  9827. return g_parsefile->lastc[--g_parsefile->unget];
  9828. if (--g_parsefile->left_in_line >= 0)
  9829. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9830. else
  9831. c = preadbuffer();
  9832. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9833. g_parsefile->lastc[0] = c;
  9834. return c;
  9835. }
  9836. #if ENABLE_ASH_ALIAS
  9837. static int
  9838. pgetc_without_PEOA(void)
  9839. {
  9840. int c;
  9841. do {
  9842. pgetc_debug("pgetc at %d:%p'%s'",
  9843. g_parsefile->left_in_line,
  9844. g_parsefile->next_to_pgetc,
  9845. g_parsefile->next_to_pgetc);
  9846. c = pgetc();
  9847. } while (c == PEOA);
  9848. return c;
  9849. }
  9850. #else
  9851. # define pgetc_without_PEOA() pgetc()
  9852. #endif
  9853. /*
  9854. * Undo a call to pgetc. Only two characters may be pushed back.
  9855. * PEOF may be pushed back.
  9856. */
  9857. static void
  9858. pungetc(void)
  9859. {
  9860. g_parsefile->unget++;
  9861. }
  9862. /* This one eats backslash+newline */
  9863. static int
  9864. pgetc_eatbnl(void)
  9865. {
  9866. int c;
  9867. while ((c = pgetc()) == '\\') {
  9868. if (pgetc() != '\n') {
  9869. pungetc();
  9870. break;
  9871. }
  9872. nlprompt();
  9873. }
  9874. return c;
  9875. }
  9876. struct synstack {
  9877. smalluint syntax;
  9878. uint8_t innerdq :1;
  9879. uint8_t varpushed :1;
  9880. uint8_t dblquote :1;
  9881. int varnest; /* levels of variables expansion */
  9882. int dqvarnest; /* levels of variables expansion within double quotes */
  9883. int parenlevel; /* levels of parens in arithmetic */
  9884. struct synstack *prev;
  9885. struct synstack *next;
  9886. };
  9887. static int
  9888. pgetc_top(struct synstack *stack)
  9889. {
  9890. return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
  9891. }
  9892. static void
  9893. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  9894. {
  9895. memset(next, 0, sizeof(*next));
  9896. next->syntax = syntax;
  9897. next->next = *stack;
  9898. (*stack)->prev = next;
  9899. *stack = next;
  9900. }
  9901. static ALWAYS_INLINE void
  9902. synstack_pop(struct synstack **stack)
  9903. {
  9904. *stack = (*stack)->next;
  9905. }
  9906. /*
  9907. * To handle the "." command, a stack of input files is used. Pushfile
  9908. * adds a new entry to the stack and popfile restores the previous level.
  9909. */
  9910. static void
  9911. pushfile(void)
  9912. {
  9913. struct parsefile *pf;
  9914. pf = ckzalloc(sizeof(*pf));
  9915. pf->prev = g_parsefile;
  9916. pf->pf_fd = -1;
  9917. /*pf->strpush = NULL; - ckzalloc did it */
  9918. /*pf->basestrpush.prev = NULL;*/
  9919. /*pf->unget = 0;*/
  9920. g_parsefile = pf;
  9921. }
  9922. static void
  9923. popfile(void)
  9924. {
  9925. struct parsefile *pf = g_parsefile;
  9926. if (pf == &basepf)
  9927. return;
  9928. INT_OFF;
  9929. if (pf->pf_fd >= 0)
  9930. close(pf->pf_fd);
  9931. free(pf->buf);
  9932. while (pf->strpush)
  9933. popstring();
  9934. g_parsefile = pf->prev;
  9935. free(pf);
  9936. INT_ON;
  9937. }
  9938. static void
  9939. unwindfiles(struct parsefile *stop)
  9940. {
  9941. while (g_parsefile != stop)
  9942. popfile();
  9943. }
  9944. /*
  9945. * Return to top level.
  9946. */
  9947. static void
  9948. popallfiles(void)
  9949. {
  9950. unwindfiles(&basepf);
  9951. }
  9952. /*
  9953. * Close the file(s) that the shell is reading commands from. Called
  9954. * after a fork is done.
  9955. */
  9956. static void
  9957. closescript(void)
  9958. {
  9959. popallfiles();
  9960. if (g_parsefile->pf_fd > 0) {
  9961. close(g_parsefile->pf_fd);
  9962. g_parsefile->pf_fd = 0;
  9963. }
  9964. }
  9965. /*
  9966. * Like setinputfile, but takes an open file descriptor. Call this with
  9967. * interrupts off.
  9968. */
  9969. static void
  9970. setinputfd(int fd, int push)
  9971. {
  9972. if (push) {
  9973. pushfile();
  9974. g_parsefile->buf = NULL;
  9975. }
  9976. g_parsefile->pf_fd = fd;
  9977. if (g_parsefile->buf == NULL)
  9978. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9979. g_parsefile->left_in_buffer = 0;
  9980. g_parsefile->left_in_line = 0;
  9981. g_parsefile->linno = 1;
  9982. }
  9983. /*
  9984. * Set the input to take input from a file. If push is set, push the
  9985. * old input onto the stack first.
  9986. */
  9987. static int
  9988. setinputfile(const char *fname, int flags)
  9989. {
  9990. int fd;
  9991. INT_OFF;
  9992. fd = open(fname, O_RDONLY | O_CLOEXEC);
  9993. if (fd < 0) {
  9994. if (flags & INPUT_NOFILE_OK)
  9995. goto out;
  9996. exitstatus = 127;
  9997. ash_msg_and_raise_perror("can't open '%s'", fname);
  9998. }
  9999. if (fd < 10)
  10000. fd = savefd(fd);
  10001. else if (O_CLOEXEC == 0) /* old libc */
  10002. close_on_exec_on(fd);
  10003. setinputfd(fd, flags & INPUT_PUSH_FILE);
  10004. out:
  10005. INT_ON;
  10006. return fd;
  10007. }
  10008. /*
  10009. * Like setinputfile, but takes input from a string.
  10010. */
  10011. static void
  10012. setinputstring(char *string)
  10013. {
  10014. INT_OFF;
  10015. pushfile();
  10016. g_parsefile->next_to_pgetc = string;
  10017. g_parsefile->left_in_line = strlen(string);
  10018. g_parsefile->buf = NULL;
  10019. g_parsefile->linno = 1;
  10020. INT_ON;
  10021. }
  10022. /*
  10023. * Routines to check for mail.
  10024. */
  10025. #if ENABLE_ASH_MAIL
  10026. /* Hash of mtimes of mailboxes */
  10027. static unsigned mailtime_hash;
  10028. /* Set if MAIL or MAILPATH is changed. */
  10029. static smallint mail_var_path_changed;
  10030. /*
  10031. * Print appropriate message(s) if mail has arrived.
  10032. * If mail_var_path_changed is set,
  10033. * then the value of MAIL has mail_var_path_changed,
  10034. * so we just update the values.
  10035. */
  10036. static void
  10037. chkmail(void)
  10038. {
  10039. const char *mpath;
  10040. char *p;
  10041. char *q;
  10042. unsigned new_hash;
  10043. struct stackmark smark;
  10044. struct stat statb;
  10045. setstackmark(&smark);
  10046. mpath = mpathset() ? mpathval() : mailval();
  10047. new_hash = 0;
  10048. for (;;) {
  10049. int len;
  10050. len = padvance_magic(&mpath, nullstr, 2);
  10051. if (!len)
  10052. break;
  10053. p = stackblock();
  10054. break;
  10055. if (*p == '\0')
  10056. continue;
  10057. for (q = p; *q; q++)
  10058. continue;
  10059. #if DEBUG
  10060. if (q[-1] != '/')
  10061. abort();
  10062. #endif
  10063. q[-1] = '\0'; /* delete trailing '/' */
  10064. if (stat(p, &statb) < 0) {
  10065. continue;
  10066. }
  10067. /* Very simplistic "hash": just a sum of all mtimes */
  10068. new_hash += (unsigned)statb.st_mtime;
  10069. }
  10070. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  10071. if (mailtime_hash != 0)
  10072. out2str("you have mail\n");
  10073. mailtime_hash = new_hash;
  10074. }
  10075. mail_var_path_changed = 0;
  10076. popstackmark(&smark);
  10077. }
  10078. static void FAST_FUNC
  10079. changemail(const char *val UNUSED_PARAM)
  10080. {
  10081. mail_var_path_changed = 1;
  10082. }
  10083. #endif /* ASH_MAIL */
  10084. /* ============ ??? */
  10085. /*
  10086. * Set the shell parameters.
  10087. */
  10088. static void
  10089. setparam(char **argv)
  10090. {
  10091. char **newparam;
  10092. char **ap;
  10093. int nparam;
  10094. for (nparam = 0; argv[nparam]; nparam++)
  10095. continue;
  10096. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10097. while (*argv) {
  10098. *ap++ = ckstrdup(*argv++);
  10099. }
  10100. *ap = NULL;
  10101. freeparam(&shellparam);
  10102. shellparam.malloced = 1;
  10103. shellparam.nparam = nparam;
  10104. shellparam.p = newparam;
  10105. #if ENABLE_ASH_GETOPTS
  10106. shellparam.optind = 1;
  10107. shellparam.optoff = -1;
  10108. #endif
  10109. }
  10110. /*
  10111. * Process shell options. The global variable argptr contains a pointer
  10112. * to the argument list; we advance it past the options.
  10113. *
  10114. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10115. * For a non-interactive shell, an error condition encountered
  10116. * by a special built-in ... shall cause the shell to write a diagnostic message
  10117. * to standard error and exit as shown in the following table:
  10118. * Error Special Built-In
  10119. * ...
  10120. * Utility syntax error (option or operand error) Shall exit
  10121. * ...
  10122. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10123. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10124. * and shell continues), and people rely on this behavior!
  10125. * Testcase:
  10126. * set -o barfoo 2>/dev/null
  10127. * echo $?
  10128. *
  10129. * Oh well. Let's mimic that.
  10130. */
  10131. static int
  10132. plus_minus_o(char *name, int val)
  10133. {
  10134. int i;
  10135. if (name) {
  10136. for (i = 0; i < NOPTS; i++) {
  10137. if (strcmp(name, optnames(i)) == 0) {
  10138. optlist[i] = val;
  10139. return 0;
  10140. }
  10141. }
  10142. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10143. return 1;
  10144. }
  10145. for (i = 0; i < NOPTS; i++) {
  10146. if (optnames(i)[0] == '\0')
  10147. continue;
  10148. if (val) {
  10149. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10150. } else {
  10151. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10152. }
  10153. }
  10154. return 0;
  10155. }
  10156. static void
  10157. setoption(int flag, int val)
  10158. {
  10159. int i;
  10160. for (i = 0; i < NOPTS; i++) {
  10161. if (optletters(i) == flag && optnames(i)[0] != '\0') {
  10162. optlist[i] = val;
  10163. return;
  10164. }
  10165. }
  10166. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10167. /* NOTREACHED */
  10168. }
  10169. /* If login_sh is not NULL, we are called to parse command line opts,
  10170. * not "set -opts"
  10171. */
  10172. static int
  10173. options(int *login_sh)
  10174. {
  10175. char *p;
  10176. int val;
  10177. int c;
  10178. if (login_sh)
  10179. minusc = NULL;
  10180. while ((p = *argptr) != NULL) {
  10181. c = *p++;
  10182. if (c != '-' && c != '+')
  10183. break;
  10184. argptr++;
  10185. val = 0; /* val = 0 if c == '+' */
  10186. if (c == '-') {
  10187. val = 1;
  10188. if (p[0] == '\0' || LONE_DASH(p)) {
  10189. if (!login_sh) {
  10190. /* "-" means turn off -x and -v */
  10191. if (p[0] == '\0')
  10192. xflag = vflag = 0;
  10193. /* "--" means reset params */
  10194. else if (*argptr == NULL)
  10195. setparam(argptr);
  10196. }
  10197. break; /* "-" or "--" terminates options */
  10198. }
  10199. }
  10200. /* first char was + or - */
  10201. while ((c = *p++) != '\0') {
  10202. if (login_sh) {
  10203. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10204. if (c == 'c') {
  10205. minusc = p; /* command is after shell args */
  10206. cflag = 1;
  10207. continue;
  10208. }
  10209. if (c == 's') { /* -s, +s */
  10210. sflag = 1;
  10211. continue;
  10212. }
  10213. if (c == 'i') { /* -i, +i */
  10214. iflag = 1;
  10215. continue;
  10216. }
  10217. if (c == 'l') {
  10218. *login_sh = 1; /* -l or +l == --login */
  10219. continue;
  10220. }
  10221. /* bash does not accept +-login, we also won't */
  10222. if (val && (c == '-')) { /* long options */
  10223. if (strcmp(p, "login") == 0) {
  10224. *login_sh = 1;
  10225. }
  10226. break;
  10227. }
  10228. }
  10229. if (c == 'o') {
  10230. if (plus_minus_o(*argptr, val)) {
  10231. /* it already printed err message */
  10232. return 1; /* error */
  10233. }
  10234. if (*argptr)
  10235. argptr++;
  10236. } else {
  10237. setoption(c, val);
  10238. }
  10239. }
  10240. }
  10241. return 0;
  10242. }
  10243. /*
  10244. * The shift builtin command.
  10245. */
  10246. static int FAST_FUNC
  10247. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10248. {
  10249. int n;
  10250. char **ap1, **ap2;
  10251. n = 1;
  10252. if (argv[1])
  10253. n = number(argv[1]);
  10254. if (n > shellparam.nparam)
  10255. return 1;
  10256. INT_OFF;
  10257. shellparam.nparam -= n;
  10258. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10259. if (shellparam.malloced)
  10260. free(*ap1);
  10261. }
  10262. ap2 = shellparam.p;
  10263. while ((*ap2++ = *ap1++) != NULL)
  10264. continue;
  10265. #if ENABLE_ASH_GETOPTS
  10266. shellparam.optind = 1;
  10267. shellparam.optoff = -1;
  10268. #endif
  10269. INT_ON;
  10270. return 0;
  10271. }
  10272. /*
  10273. * POSIX requires that 'set' (but not export or readonly) output the
  10274. * variables in lexicographic order - by the locale's collating order (sigh).
  10275. * Maybe we could keep them in an ordered balanced binary tree
  10276. * instead of hashed lists.
  10277. * For now just roll 'em through qsort for printing...
  10278. */
  10279. static int
  10280. showvars(const char *sep_prefix, int on, int off)
  10281. {
  10282. const char *sep;
  10283. char **ep, **epend;
  10284. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10285. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10286. sep = *sep_prefix ? " " : sep_prefix;
  10287. for (; ep < epend; ep++) {
  10288. const char *p;
  10289. const char *q;
  10290. p = endofname(*ep);
  10291. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10292. * makes "export -p" to have output not suitable for "eval":
  10293. * import os
  10294. * os.environ["test-test"]="test"
  10295. * if os.fork() == 0:
  10296. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10297. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10298. */
  10299. q = nullstr;
  10300. if (*p == '=')
  10301. q = single_quote(++p);
  10302. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10303. }
  10304. return 0;
  10305. }
  10306. /*
  10307. * The set command builtin.
  10308. */
  10309. static int FAST_FUNC
  10310. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10311. {
  10312. int retval;
  10313. if (!argv[1])
  10314. return showvars(nullstr, 0, VUNSET);
  10315. INT_OFF;
  10316. retval = options(/*login_sh:*/ NULL);
  10317. if (retval == 0) { /* if no parse error... */
  10318. optschanged();
  10319. if (*argptr != NULL) {
  10320. setparam(argptr);
  10321. }
  10322. }
  10323. INT_ON;
  10324. return retval;
  10325. }
  10326. #if ENABLE_ASH_RANDOM_SUPPORT
  10327. static void FAST_FUNC
  10328. change_random(const char *value)
  10329. {
  10330. uint32_t t;
  10331. if (value == NULL) {
  10332. /* "get", generate */
  10333. t = next_random(&random_gen);
  10334. /* set without recursion */
  10335. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10336. vrandom.flags &= ~VNOFUNC;
  10337. } else {
  10338. /* set/reset */
  10339. t = strtoul(value, NULL, 10);
  10340. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10341. }
  10342. }
  10343. #endif
  10344. #if BASH_EPOCH_VARS
  10345. static void FAST_FUNC
  10346. change_epoch(struct var *vepoch, const char *fmt)
  10347. {
  10348. struct timeval tv;
  10349. char buffer[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  10350. gettimeofday(&tv, NULL);
  10351. sprintf(buffer, fmt, (unsigned long)tv.tv_sec, (unsigned)tv.tv_usec);
  10352. setvar(vepoch->var_text, buffer, VNOFUNC);
  10353. vepoch->flags &= ~VNOFUNC;
  10354. }
  10355. static void FAST_FUNC
  10356. change_seconds(const char *value UNUSED_PARAM)
  10357. {
  10358. change_epoch(&vepochs, "%lu");
  10359. }
  10360. static void FAST_FUNC
  10361. change_realtime(const char *value UNUSED_PARAM)
  10362. {
  10363. change_epoch(&vepochr, "%lu.%06u");
  10364. }
  10365. #endif
  10366. #if ENABLE_ASH_GETOPTS
  10367. static int
  10368. getopts(char *optstr, char *optvar, char **optfirst)
  10369. {
  10370. char *p, *q;
  10371. char c = '?';
  10372. int done = 0;
  10373. char sbuf[2];
  10374. char **optnext;
  10375. int ind = shellparam.optind;
  10376. int off = shellparam.optoff;
  10377. sbuf[1] = '\0';
  10378. shellparam.optind = -1;
  10379. optnext = optfirst + ind - 1;
  10380. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10381. p = NULL;
  10382. else
  10383. p = optnext[-1] + off;
  10384. if (p == NULL || *p == '\0') {
  10385. /* Current word is done, advance */
  10386. p = *optnext;
  10387. if (p == NULL || *p != '-' || *++p == '\0') {
  10388. atend:
  10389. unsetvar("OPTARG");
  10390. p = NULL;
  10391. done = 1;
  10392. goto out;
  10393. }
  10394. optnext++;
  10395. if (LONE_DASH(p)) /* check for "--" */
  10396. goto atend;
  10397. }
  10398. c = *p++;
  10399. for (q = optstr; *q != c;) {
  10400. if (*q == '\0') {
  10401. /* OPTERR is a bashism */
  10402. const char *cp = lookupvar("OPTERR");
  10403. if ((cp && LONE_CHAR(cp, '0'))
  10404. || (optstr[0] == ':')
  10405. ) {
  10406. sbuf[0] = c;
  10407. /*sbuf[1] = '\0'; - already is */
  10408. setvar0("OPTARG", sbuf);
  10409. } else {
  10410. fprintf(stderr, "Illegal option -%c\n", c);
  10411. unsetvar("OPTARG");
  10412. }
  10413. c = '?';
  10414. goto out;
  10415. }
  10416. if (*++q == ':')
  10417. q++;
  10418. }
  10419. if (*++q == ':') {
  10420. if (*p == '\0' && (p = *optnext) == NULL) {
  10421. /* OPTERR is a bashism */
  10422. const char *cp = lookupvar("OPTERR");
  10423. if ((cp && LONE_CHAR(cp, '0'))
  10424. || (optstr[0] == ':')
  10425. ) {
  10426. sbuf[0] = c;
  10427. /*sbuf[1] = '\0'; - already is */
  10428. setvar0("OPTARG", sbuf);
  10429. c = ':';
  10430. } else {
  10431. fprintf(stderr, "No arg for -%c option\n", c);
  10432. unsetvar("OPTARG");
  10433. c = '?';
  10434. }
  10435. goto out;
  10436. }
  10437. if (p == *optnext)
  10438. optnext++;
  10439. setvar0("OPTARG", p);
  10440. p = NULL;
  10441. } else
  10442. setvar0("OPTARG", nullstr);
  10443. out:
  10444. ind = optnext - optfirst + 1;
  10445. setvar("OPTIND", itoa(ind), VNOFUNC);
  10446. sbuf[0] = c;
  10447. /*sbuf[1] = '\0'; - already is */
  10448. setvar0(optvar, sbuf);
  10449. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10450. shellparam.optind = ind;
  10451. return done;
  10452. }
  10453. /*
  10454. * The getopts builtin. Shellparam.optnext points to the next argument
  10455. * to be processed. Shellparam.optptr points to the next character to
  10456. * be processed in the current argument. If shellparam.optnext is NULL,
  10457. * then it's the first time getopts has been called.
  10458. */
  10459. static int FAST_FUNC
  10460. getoptscmd(int argc, char **argv)
  10461. {
  10462. char **optbase;
  10463. if (argc < 3)
  10464. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10465. if (argc == 3) {
  10466. optbase = shellparam.p;
  10467. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10468. shellparam.optind = 1;
  10469. shellparam.optoff = -1;
  10470. }
  10471. } else {
  10472. optbase = &argv[3];
  10473. if ((unsigned)shellparam.optind > argc - 2) {
  10474. shellparam.optind = 1;
  10475. shellparam.optoff = -1;
  10476. }
  10477. }
  10478. return getopts(argv[1], argv[2], optbase);
  10479. }
  10480. #endif /* ASH_GETOPTS */
  10481. /* ============ Shell parser */
  10482. struct heredoc {
  10483. struct heredoc *next; /* next here document in list */
  10484. union node *here; /* redirection node */
  10485. char *eofmark; /* string indicating end of input */
  10486. smallint striptabs; /* if set, strip leading tabs */
  10487. };
  10488. static smallint tokpushback; /* last token pushed back */
  10489. static smallint quoteflag; /* set if (part of) last token was quoted */
  10490. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10491. static struct heredoc *heredoclist; /* list of here documents to read */
  10492. static char *wordtext; /* text of last word returned by readtoken */
  10493. static struct nodelist *backquotelist;
  10494. static union node *redirnode;
  10495. static struct heredoc *heredoc;
  10496. static const char *
  10497. tokname(char *buf, int tok)
  10498. {
  10499. if (tok < TSEMI)
  10500. return tokname_array[tok];
  10501. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10502. return buf;
  10503. }
  10504. /* raise_error_unexpected_syntax:
  10505. * Called when an unexpected token is read during the parse. The argument
  10506. * is the token that is expected, or -1 if more than one type of token can
  10507. * occur at this point.
  10508. */
  10509. static void raise_error_unexpected_syntax(int) NORETURN;
  10510. static void
  10511. raise_error_unexpected_syntax(int token)
  10512. {
  10513. char msg[64];
  10514. char buf[16];
  10515. int l;
  10516. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10517. if (token >= 0)
  10518. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10519. raise_error_syntax(msg);
  10520. /* NOTREACHED */
  10521. }
  10522. /* parsing is heavily cross-recursive, need these forward decls */
  10523. static union node *andor(void);
  10524. static union node *pipeline(void);
  10525. static union node *parse_command(void);
  10526. static void parseheredoc(void);
  10527. static int peektoken(void);
  10528. static int readtoken(void);
  10529. static union node *
  10530. list(int nlflag)
  10531. {
  10532. union node *n1, *n2, *n3;
  10533. int tok;
  10534. n1 = NULL;
  10535. for (;;) {
  10536. switch (readtoken()) {
  10537. case TNL:
  10538. if (!(nlflag & 1))
  10539. break;
  10540. parseheredoc();
  10541. return n1;
  10542. case TEOF:
  10543. if (!n1 && (nlflag & 1))
  10544. n1 = NODE_EOF;
  10545. parseheredoc();
  10546. tokpushback++;
  10547. lasttoken = TEOF;
  10548. return n1;
  10549. }
  10550. tokpushback++;
  10551. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10552. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10553. return n1;
  10554. nlflag |= 2;
  10555. n2 = andor();
  10556. tok = readtoken();
  10557. if (tok == TBACKGND) {
  10558. if (n2->type == NPIPE) {
  10559. n2->npipe.pipe_backgnd = 1;
  10560. } else {
  10561. if (n2->type != NREDIR) {
  10562. n3 = stzalloc(sizeof(struct nredir));
  10563. n3->nredir.n = n2;
  10564. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10565. n2 = n3;
  10566. }
  10567. n2->type = NBACKGND;
  10568. }
  10569. }
  10570. if (n1 == NULL) {
  10571. n1 = n2;
  10572. } else {
  10573. n3 = stzalloc(sizeof(struct nbinary));
  10574. n3->type = NSEMI;
  10575. n3->nbinary.ch1 = n1;
  10576. n3->nbinary.ch2 = n2;
  10577. n1 = n3;
  10578. }
  10579. switch (tok) {
  10580. case TNL:
  10581. case TEOF:
  10582. tokpushback = 1;
  10583. /* fall through */
  10584. case TBACKGND:
  10585. case TSEMI:
  10586. break;
  10587. default:
  10588. if ((nlflag & 1))
  10589. raise_error_unexpected_syntax(-1);
  10590. tokpushback = 1;
  10591. return n1;
  10592. }
  10593. }
  10594. }
  10595. static union node *
  10596. andor(void)
  10597. {
  10598. union node *n1, *n2, *n3;
  10599. int t;
  10600. n1 = pipeline();
  10601. for (;;) {
  10602. t = readtoken();
  10603. if (t == TAND) {
  10604. t = NAND;
  10605. } else if (t == TOR) {
  10606. t = NOR;
  10607. } else {
  10608. tokpushback = 1;
  10609. return n1;
  10610. }
  10611. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10612. n2 = pipeline();
  10613. n3 = stzalloc(sizeof(struct nbinary));
  10614. n3->type = t;
  10615. n3->nbinary.ch1 = n1;
  10616. n3->nbinary.ch2 = n2;
  10617. n1 = n3;
  10618. }
  10619. }
  10620. static union node *
  10621. pipeline(void)
  10622. {
  10623. union node *n1, *n2, *pipenode;
  10624. struct nodelist *lp, *prev;
  10625. int negate;
  10626. negate = 0;
  10627. TRACE(("pipeline: entered\n"));
  10628. if (readtoken() == TNOT) {
  10629. negate = !negate;
  10630. checkkwd = CHKKWD | CHKALIAS;
  10631. } else
  10632. tokpushback = 1;
  10633. n1 = parse_command();
  10634. if (readtoken() == TPIPE) {
  10635. pipenode = stzalloc(sizeof(struct npipe));
  10636. pipenode->type = NPIPE;
  10637. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10638. lp = stzalloc(sizeof(struct nodelist));
  10639. pipenode->npipe.cmdlist = lp;
  10640. lp->n = n1;
  10641. do {
  10642. prev = lp;
  10643. lp = stzalloc(sizeof(struct nodelist));
  10644. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10645. lp->n = parse_command();
  10646. prev->next = lp;
  10647. } while (readtoken() == TPIPE);
  10648. lp->next = NULL;
  10649. n1 = pipenode;
  10650. }
  10651. tokpushback = 1;
  10652. if (negate) {
  10653. n2 = stzalloc(sizeof(struct nnot));
  10654. n2->type = NNOT;
  10655. n2->nnot.com = n1;
  10656. return n2;
  10657. }
  10658. return n1;
  10659. }
  10660. static union node *
  10661. makename(void)
  10662. {
  10663. union node *n;
  10664. n = stzalloc(sizeof(struct narg));
  10665. n->type = NARG;
  10666. /*n->narg.next = NULL; - stzalloc did it */
  10667. n->narg.text = wordtext;
  10668. n->narg.backquote = backquotelist;
  10669. return n;
  10670. }
  10671. static void
  10672. fixredir(union node *n, const char *text, int err)
  10673. {
  10674. int fd;
  10675. TRACE(("Fix redir %s %d\n", text, err));
  10676. if (!err)
  10677. n->ndup.vname = NULL;
  10678. fd = bb_strtou(text, NULL, 10);
  10679. if (!errno && fd >= 0)
  10680. n->ndup.dupfd = fd;
  10681. else if (LONE_DASH(text))
  10682. n->ndup.dupfd = -1;
  10683. else {
  10684. if (err)
  10685. raise_error_syntax("bad fd number");
  10686. n->ndup.vname = makename();
  10687. }
  10688. }
  10689. static void
  10690. parsefname(void)
  10691. {
  10692. union node *n = redirnode;
  10693. if (n->type == NHERE)
  10694. checkkwd = CHKEOFMARK;
  10695. if (readtoken() != TWORD)
  10696. raise_error_unexpected_syntax(-1);
  10697. if (n->type == NHERE) {
  10698. struct heredoc *here = heredoc;
  10699. struct heredoc *p;
  10700. if (quoteflag == 0)
  10701. n->type = NXHERE;
  10702. TRACE(("Here document %d\n", n->type));
  10703. rmescapes(wordtext, 0, NULL);
  10704. here->eofmark = wordtext;
  10705. here->next = NULL;
  10706. if (heredoclist == NULL)
  10707. heredoclist = here;
  10708. else {
  10709. for (p = heredoclist; p->next; p = p->next)
  10710. continue;
  10711. p->next = here;
  10712. }
  10713. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10714. fixredir(n, wordtext, 0);
  10715. } else {
  10716. n->nfile.fname = makename();
  10717. }
  10718. }
  10719. static union node *
  10720. simplecmd(void)
  10721. {
  10722. union node *args, **app;
  10723. union node *n = NULL;
  10724. union node *vars, **vpp;
  10725. union node **rpp, *redir;
  10726. int savecheckkwd;
  10727. int savelinno;
  10728. #if BASH_TEST2
  10729. smallint double_brackets_flag = 0;
  10730. #endif
  10731. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10732. args = NULL;
  10733. app = &args;
  10734. vars = NULL;
  10735. vpp = &vars;
  10736. redir = NULL;
  10737. rpp = &redir;
  10738. savecheckkwd = CHKALIAS;
  10739. savelinno = g_parsefile->linno;
  10740. for (;;) {
  10741. int t;
  10742. checkkwd = savecheckkwd;
  10743. t = readtoken();
  10744. switch (t) {
  10745. #if BASH_FUNCTION
  10746. case TFUNCTION:
  10747. if (peektoken() != TWORD)
  10748. raise_error_unexpected_syntax(TWORD);
  10749. function_flag = 1;
  10750. break;
  10751. #endif
  10752. #if BASH_TEST2
  10753. case TAND: /* "&&" */
  10754. case TOR: /* "||" */
  10755. if (!double_brackets_flag) {
  10756. tokpushback = 1;
  10757. goto out;
  10758. }
  10759. wordtext = (char *) (t == TAND ? "-a" : "-o");
  10760. #endif
  10761. case TWORD:
  10762. n = stzalloc(sizeof(struct narg));
  10763. n->type = NARG;
  10764. /*n->narg.next = NULL; - stzalloc did it */
  10765. n->narg.text = wordtext;
  10766. #if BASH_TEST2
  10767. if (strcmp("[[", wordtext) == 0)
  10768. double_brackets_flag = 1;
  10769. else if (strcmp("]]", wordtext) == 0)
  10770. double_brackets_flag = 0;
  10771. #endif
  10772. n->narg.backquote = backquotelist;
  10773. if (savecheckkwd && isassignment(wordtext)) {
  10774. *vpp = n;
  10775. vpp = &n->narg.next;
  10776. } else {
  10777. *app = n;
  10778. app = &n->narg.next;
  10779. savecheckkwd = 0;
  10780. }
  10781. #if BASH_FUNCTION
  10782. if (function_flag) {
  10783. checkkwd = CHKNL | CHKKWD;
  10784. switch (peektoken()) {
  10785. case TBEGIN:
  10786. case TIF:
  10787. case TCASE:
  10788. case TUNTIL:
  10789. case TWHILE:
  10790. case TFOR:
  10791. goto do_func;
  10792. case TLP:
  10793. function_flag = 0;
  10794. break;
  10795. # if BASH_TEST2
  10796. case TWORD:
  10797. if (strcmp("[[", wordtext) == 0)
  10798. goto do_func;
  10799. /* fall through */
  10800. # endif
  10801. default:
  10802. raise_error_unexpected_syntax(-1);
  10803. }
  10804. }
  10805. #endif
  10806. break;
  10807. case TREDIR:
  10808. *rpp = n = redirnode;
  10809. rpp = &n->nfile.next;
  10810. parsefname(); /* read name of redirection file */
  10811. break;
  10812. case TLP:
  10813. IF_BASH_FUNCTION(do_func:)
  10814. if (args && app == &args->narg.next
  10815. && !vars && !redir
  10816. ) {
  10817. struct builtincmd *bcmd;
  10818. const char *name;
  10819. /* We have a function */
  10820. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10821. raise_error_unexpected_syntax(TRP);
  10822. name = n->narg.text;
  10823. if (!goodname(name)
  10824. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10825. ) {
  10826. raise_error_syntax("bad function name");
  10827. }
  10828. n->type = NDEFUN;
  10829. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10830. n->ndefun.text = n->narg.text;
  10831. n->ndefun.linno = g_parsefile->linno;
  10832. n->ndefun.body = parse_command();
  10833. return n;
  10834. }
  10835. IF_BASH_FUNCTION(function_flag = 0;)
  10836. /* fall through */
  10837. default:
  10838. tokpushback = 1;
  10839. goto out;
  10840. }
  10841. }
  10842. out:
  10843. *app = NULL;
  10844. *vpp = NULL;
  10845. *rpp = NULL;
  10846. n = stzalloc(sizeof(struct ncmd));
  10847. if (NCMD != 0)
  10848. n->type = NCMD;
  10849. n->ncmd.linno = savelinno;
  10850. n->ncmd.args = args;
  10851. n->ncmd.assign = vars;
  10852. n->ncmd.redirect = redir;
  10853. return n;
  10854. }
  10855. static union node *
  10856. parse_command(void)
  10857. {
  10858. union node *n1, *n2;
  10859. union node *ap, **app;
  10860. union node *cp, **cpp;
  10861. union node *redir, **rpp;
  10862. union node **rpp2;
  10863. int t;
  10864. int savelinno;
  10865. redir = NULL;
  10866. rpp2 = &redir;
  10867. savelinno = g_parsefile->linno;
  10868. switch (readtoken()) {
  10869. default:
  10870. raise_error_unexpected_syntax(-1);
  10871. /* NOTREACHED */
  10872. case TIF:
  10873. n1 = stzalloc(sizeof(struct nif));
  10874. n1->type = NIF;
  10875. n1->nif.test = list(0);
  10876. if (readtoken() != TTHEN)
  10877. raise_error_unexpected_syntax(TTHEN);
  10878. n1->nif.ifpart = list(0);
  10879. n2 = n1;
  10880. while (readtoken() == TELIF) {
  10881. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10882. n2 = n2->nif.elsepart;
  10883. n2->type = NIF;
  10884. n2->nif.test = list(0);
  10885. if (readtoken() != TTHEN)
  10886. raise_error_unexpected_syntax(TTHEN);
  10887. n2->nif.ifpart = list(0);
  10888. }
  10889. if (lasttoken == TELSE)
  10890. n2->nif.elsepart = list(0);
  10891. else {
  10892. n2->nif.elsepart = NULL;
  10893. tokpushback = 1;
  10894. }
  10895. t = TFI;
  10896. break;
  10897. case TWHILE:
  10898. case TUNTIL: {
  10899. int got;
  10900. n1 = stzalloc(sizeof(struct nbinary));
  10901. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10902. n1->nbinary.ch1 = list(0);
  10903. got = readtoken();
  10904. if (got != TDO) {
  10905. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10906. got == TWORD ? wordtext : ""));
  10907. raise_error_unexpected_syntax(TDO);
  10908. }
  10909. n1->nbinary.ch2 = list(0);
  10910. t = TDONE;
  10911. break;
  10912. }
  10913. case TFOR:
  10914. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10915. raise_error_syntax("bad for loop variable");
  10916. n1 = stzalloc(sizeof(struct nfor));
  10917. n1->type = NFOR;
  10918. n1->nfor.linno = savelinno;
  10919. n1->nfor.var = wordtext;
  10920. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10921. if (readtoken() == TIN) {
  10922. app = &ap;
  10923. while (readtoken() == TWORD) {
  10924. n2 = stzalloc(sizeof(struct narg));
  10925. n2->type = NARG;
  10926. /*n2->narg.next = NULL; - stzalloc did it */
  10927. n2->narg.text = wordtext;
  10928. n2->narg.backquote = backquotelist;
  10929. *app = n2;
  10930. app = &n2->narg.next;
  10931. }
  10932. *app = NULL;
  10933. n1->nfor.args = ap;
  10934. if (lasttoken != TNL && lasttoken != TSEMI)
  10935. raise_error_unexpected_syntax(-1);
  10936. } else {
  10937. n2 = stzalloc(sizeof(struct narg));
  10938. n2->type = NARG;
  10939. /*n2->narg.next = NULL; - stzalloc did it */
  10940. n2->narg.text = (char *)dolatstr;
  10941. /*n2->narg.backquote = NULL;*/
  10942. n1->nfor.args = n2;
  10943. /*
  10944. * Newline or semicolon here is optional (but note
  10945. * that the original Bourne shell only allowed NL).
  10946. */
  10947. if (lasttoken != TSEMI)
  10948. tokpushback = 1;
  10949. }
  10950. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10951. if (readtoken() != TDO)
  10952. raise_error_unexpected_syntax(TDO);
  10953. n1->nfor.body = list(0);
  10954. t = TDONE;
  10955. break;
  10956. case TCASE:
  10957. n1 = stzalloc(sizeof(struct ncase));
  10958. n1->type = NCASE;
  10959. n1->ncase.linno = savelinno;
  10960. if (readtoken() != TWORD)
  10961. raise_error_unexpected_syntax(TWORD);
  10962. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10963. n2->type = NARG;
  10964. /*n2->narg.next = NULL; - stzalloc did it */
  10965. n2->narg.text = wordtext;
  10966. n2->narg.backquote = backquotelist;
  10967. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10968. if (readtoken() != TIN)
  10969. raise_error_unexpected_syntax(TIN);
  10970. cpp = &n1->ncase.cases;
  10971. next_case:
  10972. checkkwd = CHKNL | CHKKWD;
  10973. t = readtoken();
  10974. while (t != TESAC) {
  10975. if (lasttoken == TLP)
  10976. readtoken();
  10977. *cpp = cp = stzalloc(sizeof(struct nclist));
  10978. cp->type = NCLIST;
  10979. app = &cp->nclist.pattern;
  10980. for (;;) {
  10981. *app = ap = stzalloc(sizeof(struct narg));
  10982. ap->type = NARG;
  10983. /*ap->narg.next = NULL; - stzalloc did it */
  10984. ap->narg.text = wordtext;
  10985. ap->narg.backquote = backquotelist;
  10986. if (readtoken() != TPIPE)
  10987. break;
  10988. app = &ap->narg.next;
  10989. readtoken();
  10990. }
  10991. //ap->narg.next = NULL;
  10992. if (lasttoken != TRP)
  10993. raise_error_unexpected_syntax(TRP);
  10994. cp->nclist.body = list(2);
  10995. cpp = &cp->nclist.next;
  10996. checkkwd = CHKNL | CHKKWD;
  10997. t = readtoken();
  10998. if (t != TESAC) {
  10999. if (t != TENDCASE)
  11000. raise_error_unexpected_syntax(TENDCASE);
  11001. goto next_case;
  11002. }
  11003. }
  11004. *cpp = NULL;
  11005. goto redir;
  11006. case TLP:
  11007. n1 = stzalloc(sizeof(struct nredir));
  11008. n1->type = NSUBSHELL;
  11009. n1->nredir.linno = savelinno;
  11010. n1->nredir.n = list(0);
  11011. /*n1->nredir.redirect = NULL; - stzalloc did it */
  11012. t = TRP;
  11013. break;
  11014. case TBEGIN:
  11015. n1 = list(0);
  11016. t = TEND;
  11017. break;
  11018. IF_BASH_FUNCTION(case TFUNCTION:)
  11019. case TWORD:
  11020. case TREDIR:
  11021. tokpushback = 1;
  11022. return simplecmd();
  11023. }
  11024. if (readtoken() != t)
  11025. raise_error_unexpected_syntax(t);
  11026. redir:
  11027. /* Now check for redirection which may follow command */
  11028. checkkwd = CHKKWD | CHKALIAS;
  11029. rpp = rpp2;
  11030. while (readtoken() == TREDIR) {
  11031. *rpp = n2 = redirnode;
  11032. rpp = &n2->nfile.next;
  11033. parsefname();
  11034. }
  11035. tokpushback = 1;
  11036. *rpp = NULL;
  11037. if (redir) {
  11038. if (n1->type != NSUBSHELL) {
  11039. n2 = stzalloc(sizeof(struct nredir));
  11040. n2->type = NREDIR;
  11041. n2->nredir.linno = savelinno;
  11042. n2->nredir.n = n1;
  11043. n1 = n2;
  11044. }
  11045. n1->nredir.redirect = redir;
  11046. }
  11047. return n1;
  11048. }
  11049. #if BASH_DOLLAR_SQUOTE
  11050. static int
  11051. decode_dollar_squote(void)
  11052. {
  11053. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  11054. int c, cnt;
  11055. char *p;
  11056. char buf[4];
  11057. c = pgetc();
  11058. p = strchr(C_escapes, c);
  11059. if (p) {
  11060. buf[0] = c;
  11061. p = buf;
  11062. cnt = 3;
  11063. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  11064. do {
  11065. c = pgetc();
  11066. *++p = c;
  11067. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  11068. pungetc();
  11069. } else if (c == 'x') { /* \xHH */
  11070. do {
  11071. c = pgetc();
  11072. *++p = c;
  11073. } while (isxdigit(c) && --cnt);
  11074. pungetc();
  11075. if (cnt == 3) { /* \x but next char is "bad" */
  11076. c = 'x';
  11077. goto unrecognized;
  11078. }
  11079. } else { /* simple seq like \\ or \t */
  11080. p++;
  11081. }
  11082. *p = '\0';
  11083. p = buf;
  11084. c = bb_process_escape_sequence((void*)&p);
  11085. } else { /* unrecognized "\z": print both chars unless ' or " */
  11086. if (c != '\'' && c != '"') {
  11087. unrecognized:
  11088. c |= 0x100; /* "please encode \, then me" */
  11089. }
  11090. }
  11091. return c;
  11092. }
  11093. #endif
  11094. /* Used by expandstr to get here-doc like behaviour. */
  11095. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  11096. static ALWAYS_INLINE int
  11097. realeofmark(const char *eofmark)
  11098. {
  11099. return eofmark && eofmark != FAKEEOFMARK;
  11100. }
  11101. /*
  11102. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  11103. * is not NULL, read a here document. In the latter case, eofmark is the
  11104. * word which marks the end of the document and striptabs is true if
  11105. * leading tabs should be stripped from the document. The argument c
  11106. * is the first character of the input token or document.
  11107. *
  11108. * Because C does not have internal subroutines, I have simulated them
  11109. * using goto's to implement the subroutine linkage. The following macros
  11110. * will run code that appears at the end of readtoken1.
  11111. */
  11112. #define CHECKEND() {goto checkend; checkend_return:;}
  11113. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  11114. #define PARSESUB() {goto parsesub; parsesub_return:;}
  11115. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  11116. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  11117. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  11118. static int
  11119. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  11120. {
  11121. /* NB: syntax parameter fits into smallint */
  11122. /* c parameter is an unsigned char or PEOF or PEOA */
  11123. char *out;
  11124. size_t len;
  11125. struct nodelist *bqlist;
  11126. smallint quotef;
  11127. smallint oldstyle;
  11128. smallint pssyntax; /* we are expanding a prompt string */
  11129. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  11130. /* syntax stack */
  11131. struct synstack synbase = { };
  11132. struct synstack *synstack = &synbase;
  11133. #if ENABLE_ASH_EXPAND_PRMT
  11134. pssyntax = (syntax == PSSYNTAX);
  11135. if (pssyntax)
  11136. syntax = DQSYNTAX;
  11137. #else
  11138. pssyntax = 0; /* constant */
  11139. #endif
  11140. synstack->syntax = syntax;
  11141. if (syntax == DQSYNTAX)
  11142. synstack->dblquote = 1;
  11143. quotef = 0;
  11144. bqlist = NULL;
  11145. STARTSTACKSTR(out);
  11146. loop:
  11147. /* For each line, until end of word */
  11148. CHECKEND(); /* set c to PEOF if at end of here document */
  11149. for (;;) { /* until end of line or end of word */
  11150. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11151. switch (SIT(c, synstack->syntax)) {
  11152. case CNL: /* '\n' */
  11153. if (synstack->syntax == BASESYNTAX
  11154. && !synstack->varnest
  11155. ) {
  11156. goto endword; /* exit outer loop */
  11157. }
  11158. USTPUTC(c, out);
  11159. nlprompt();
  11160. c = pgetc_top(synstack);
  11161. goto loop; /* continue outer loop */
  11162. case CWORD:
  11163. USTPUTC(c, out);
  11164. break;
  11165. case CCTL:
  11166. #if BASH_DOLLAR_SQUOTE
  11167. if (c == '\\' && bash_dollar_squote) {
  11168. c = decode_dollar_squote();
  11169. if (c == '\0') {
  11170. /* skip $'\000', $'\x00' (like bash) */
  11171. break;
  11172. }
  11173. if (c & 0x100) {
  11174. /* Unknown escape. Encode as '\z' */
  11175. c = (unsigned char)c;
  11176. if (eofmark == NULL || synstack->dblquote)
  11177. USTPUTC(CTLESC, out);
  11178. USTPUTC('\\', out);
  11179. }
  11180. }
  11181. #endif
  11182. if (!eofmark || synstack->dblquote || synstack->varnest)
  11183. USTPUTC(CTLESC, out);
  11184. USTPUTC(c, out);
  11185. break;
  11186. case CBACK: /* backslash */
  11187. c = pgetc_without_PEOA();
  11188. if (c == PEOF) {
  11189. USTPUTC(CTLESC, out);
  11190. USTPUTC('\\', out);
  11191. pungetc();
  11192. } else {
  11193. if (pssyntax && c == '$') {
  11194. USTPUTC(CTLESC, out);
  11195. USTPUTC('\\', out);
  11196. }
  11197. /* Backslash is retained if we are in "str"
  11198. * and next char isn't dquote-special.
  11199. */
  11200. if (synstack->dblquote
  11201. && c != '\\'
  11202. && c != '`'
  11203. && c != '$'
  11204. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11205. && (c != '}' || !synstack->varnest)
  11206. ) {
  11207. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11208. USTPUTC('\\', out);
  11209. }
  11210. USTPUTC(CTLESC, out);
  11211. USTPUTC(c, out);
  11212. quotef = 1;
  11213. }
  11214. break;
  11215. case CSQUOTE:
  11216. synstack->syntax = SQSYNTAX;
  11217. quotemark:
  11218. if (eofmark == NULL) {
  11219. USTPUTC(CTLQUOTEMARK, out);
  11220. }
  11221. break;
  11222. case CDQUOTE:
  11223. synstack->syntax = DQSYNTAX;
  11224. synstack->dblquote = 1;
  11225. toggledq:
  11226. if (synstack->varnest)
  11227. synstack->innerdq ^= 1;
  11228. goto quotemark;
  11229. case CENDQUOTE:
  11230. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11231. if (eofmark != NULL && synstack->varnest == 0) {
  11232. USTPUTC(c, out);
  11233. break;
  11234. }
  11235. if (synstack->dqvarnest == 0) {
  11236. synstack->syntax = BASESYNTAX;
  11237. synstack->dblquote = 0;
  11238. }
  11239. quotef = 1;
  11240. if (c == '"')
  11241. goto toggledq;
  11242. goto quotemark;
  11243. case CVAR: /* '$' */
  11244. PARSESUB(); /* parse substitution */
  11245. break;
  11246. case CENDVAR: /* '}' */
  11247. if (!synstack->innerdq && synstack->varnest > 0) {
  11248. if (!--synstack->varnest && synstack->varpushed)
  11249. synstack_pop(&synstack);
  11250. else if (synstack->dqvarnest > 0)
  11251. synstack->dqvarnest--;
  11252. c = CTLENDVAR;
  11253. }
  11254. USTPUTC(c, out);
  11255. break;
  11256. #if ENABLE_FEATURE_SH_MATH
  11257. case CLP: /* '(' in arithmetic */
  11258. synstack->parenlevel++;
  11259. USTPUTC(c, out);
  11260. break;
  11261. case CRP: /* ')' in arithmetic */
  11262. if (synstack->parenlevel > 0) {
  11263. synstack->parenlevel--;
  11264. } else {
  11265. if (pgetc_eatbnl() == ')') {
  11266. c = CTLENDARI;
  11267. synstack_pop(&synstack);
  11268. } else {
  11269. /*
  11270. * unbalanced parens
  11271. * (don't 2nd guess - no error)
  11272. */
  11273. pungetc();
  11274. }
  11275. }
  11276. USTPUTC(c, out);
  11277. break;
  11278. #endif
  11279. case CBQUOTE: /* '`' */
  11280. if (checkkwd & CHKEOFMARK) {
  11281. quotef = 1;
  11282. USTPUTC('`', out);
  11283. break;
  11284. }
  11285. PARSEBACKQOLD();
  11286. break;
  11287. case CENDFILE:
  11288. goto endword; /* exit outer loop */
  11289. case CIGN:
  11290. break;
  11291. default:
  11292. if (synstack->varnest == 0) {
  11293. #if BASH_REDIR_OUTPUT
  11294. if (c == '&') {
  11295. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11296. if (pgetc() == '>')
  11297. c = 0x100 + '>'; /* flag &> */
  11298. pungetc();
  11299. }
  11300. #endif
  11301. goto endword; /* exit outer loop */
  11302. }
  11303. IF_ASH_ALIAS(if (c != PEOA))
  11304. USTPUTC(c, out);
  11305. }
  11306. c = pgetc_top(synstack);
  11307. } /* for (;;) */
  11308. endword:
  11309. #if ENABLE_FEATURE_SH_MATH
  11310. if (synstack->syntax == ARISYNTAX)
  11311. raise_error_syntax("missing '))'");
  11312. #endif
  11313. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11314. raise_error_syntax("unterminated quoted string");
  11315. if (synstack->varnest != 0) {
  11316. /* { */
  11317. raise_error_syntax("missing '}'");
  11318. }
  11319. USTPUTC('\0', out);
  11320. len = out - (char *)stackblock();
  11321. out = stackblock();
  11322. if (eofmark == NULL) {
  11323. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11324. && quotef == 0
  11325. ) {
  11326. if (isdigit_str9(out)) {
  11327. PARSEREDIR(); /* passed as params: out, c */
  11328. lasttoken = TREDIR;
  11329. return lasttoken;
  11330. }
  11331. /* else: non-number X seen, interpret it
  11332. * as "NNNX>file" = "NNNX >file" */
  11333. }
  11334. pungetc();
  11335. }
  11336. quoteflag = quotef;
  11337. backquotelist = bqlist;
  11338. grabstackblock(len);
  11339. wordtext = out;
  11340. lasttoken = TWORD;
  11341. return lasttoken;
  11342. /* end of readtoken routine */
  11343. /*
  11344. * Check to see whether we are at the end of the here document. When this
  11345. * is called, c is set to the first character of the next input line. If
  11346. * we are at the end of the here document, this routine sets the c to PEOF.
  11347. */
  11348. checkend: {
  11349. if (realeofmark(eofmark)) {
  11350. int markloc;
  11351. char *p;
  11352. #if ENABLE_ASH_ALIAS
  11353. if (c == PEOA)
  11354. c = pgetc_without_PEOA();
  11355. #endif
  11356. if (striptabs) {
  11357. while (c == '\t') {
  11358. c = pgetc_without_PEOA();
  11359. }
  11360. }
  11361. markloc = out - (char *)stackblock();
  11362. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11363. if (c != *p)
  11364. goto more_heredoc;
  11365. /* FIXME: fails for backslash-newlined terminator:
  11366. * cat <<EOF
  11367. * ...
  11368. * EO\
  11369. * F
  11370. * (see heredoc_bkslash_newline2.tests)
  11371. */
  11372. c = pgetc_without_PEOA();
  11373. }
  11374. if (c == '\n' || c == PEOF) {
  11375. c = PEOF;
  11376. g_parsefile->linno++;
  11377. needprompt = doprompt;
  11378. } else {
  11379. int len_here;
  11380. more_heredoc:
  11381. p = (char *)stackblock() + markloc + 1;
  11382. len_here = out - p;
  11383. if (len_here) {
  11384. len_here -= (c >= PEOF);
  11385. c = p[-1];
  11386. if (len_here) {
  11387. char *str;
  11388. str = alloca(len_here + 1);
  11389. *(char *)mempcpy(str, p, len_here) = '\0';
  11390. pushstring(str, NULL);
  11391. }
  11392. }
  11393. }
  11394. STADJUST((char *)stackblock() + markloc - out, out);
  11395. }
  11396. goto checkend_return;
  11397. }
  11398. /*
  11399. * Parse a redirection operator. The variable "out" points to a string
  11400. * specifying the fd to be redirected. The variable "c" contains the
  11401. * first character of the redirection operator.
  11402. */
  11403. parseredir: {
  11404. /* out is already checked to be a valid number or "" */
  11405. int fd = (*out == '\0' ? -1 : atoi(out));
  11406. union node *np;
  11407. np = stzalloc(sizeof(struct nfile));
  11408. if (c == '>') {
  11409. np->nfile.fd = 1;
  11410. c = pgetc_eatbnl();
  11411. if (c == '>')
  11412. np->type = NAPPEND;
  11413. else if (c == '|')
  11414. np->type = NCLOBBER;
  11415. else if (c == '&')
  11416. np->type = NTOFD;
  11417. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11418. else {
  11419. np->type = NTO;
  11420. pungetc();
  11421. }
  11422. }
  11423. #if BASH_REDIR_OUTPUT
  11424. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11425. np->nfile.fd = 1;
  11426. pgetc(); /* this is '>', no need to check */
  11427. np->type = NTO2;
  11428. }
  11429. #endif
  11430. else { /* c == '<' */
  11431. /*np->nfile.fd = 0; - stzalloc did it */
  11432. c = pgetc_eatbnl();
  11433. switch (c) {
  11434. case '<':
  11435. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11436. np = stzalloc(sizeof(struct nhere));
  11437. /*np->nfile.fd = 0; - stzalloc did it */
  11438. }
  11439. np->type = NHERE;
  11440. heredoc = stzalloc(sizeof(struct heredoc));
  11441. heredoc->here = np;
  11442. c = pgetc_eatbnl();
  11443. if (c == '-') {
  11444. heredoc->striptabs = 1;
  11445. } else {
  11446. /*heredoc->striptabs = 0; - stzalloc did it */
  11447. pungetc();
  11448. }
  11449. break;
  11450. case '&':
  11451. np->type = NFROMFD;
  11452. break;
  11453. case '>':
  11454. np->type = NFROMTO;
  11455. break;
  11456. default:
  11457. np->type = NFROM;
  11458. pungetc();
  11459. break;
  11460. }
  11461. }
  11462. if (fd >= 0)
  11463. np->nfile.fd = fd;
  11464. redirnode = np;
  11465. goto parseredir_return;
  11466. }
  11467. /*
  11468. * Parse a substitution. At this point, we have read the dollar sign
  11469. * and nothing else.
  11470. */
  11471. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11472. * (assuming ascii char codes, as the original implementation did) */
  11473. #define is_special(c) \
  11474. (((unsigned)(c) - 33 < 32) \
  11475. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11476. parsesub: {
  11477. unsigned char subtype;
  11478. int typeloc;
  11479. c = pgetc_eatbnl();
  11480. if ((checkkwd & CHKEOFMARK)
  11481. || c > 255 /* PEOA or PEOF */
  11482. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11483. ) {
  11484. #if BASH_DOLLAR_SQUOTE
  11485. if (synstack->syntax != DQSYNTAX && c == '\'')
  11486. bash_dollar_squote = 1;
  11487. else
  11488. #endif
  11489. USTPUTC('$', out);
  11490. pungetc();
  11491. } else if (c == '(') {
  11492. /* $(command) or $((arith)) */
  11493. if (pgetc_eatbnl() == '(') {
  11494. #if ENABLE_FEATURE_SH_MATH
  11495. PARSEARITH();
  11496. #else
  11497. raise_error_syntax("support for $((arith)) is disabled");
  11498. #endif
  11499. } else {
  11500. pungetc();
  11501. PARSEBACKQNEW();
  11502. }
  11503. } else {
  11504. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11505. smalluint newsyn = synstack->syntax;
  11506. USTPUTC(CTLVAR, out);
  11507. typeloc = out - (char *)stackblock();
  11508. STADJUST(1, out);
  11509. subtype = VSNORMAL;
  11510. if (c == '{') {
  11511. c = pgetc_eatbnl();
  11512. subtype = 0;
  11513. }
  11514. varname:
  11515. if (is_name(c)) {
  11516. /* $[{[#]]NAME[}] */
  11517. do {
  11518. STPUTC(c, out);
  11519. c = pgetc_eatbnl();
  11520. } while (is_in_name(c));
  11521. } else if (isdigit(c)) {
  11522. /* $[{[#]]NUM[}] */
  11523. do {
  11524. STPUTC(c, out);
  11525. c = pgetc_eatbnl();
  11526. } while (!subtype && isdigit(c));
  11527. } else if (c != '}') {
  11528. /* $[{[#]]<specialchar>[}] */
  11529. int cc = c;
  11530. c = pgetc_eatbnl();
  11531. if (!subtype && cc == '#') {
  11532. subtype = VSLENGTH;
  11533. if (c == '_' || isalnum(c))
  11534. goto varname;
  11535. cc = c;
  11536. c = pgetc_eatbnl();
  11537. if (cc == '}' || c != '}') {
  11538. pungetc();
  11539. subtype = 0;
  11540. c = cc;
  11541. cc = '#';
  11542. }
  11543. }
  11544. if (!is_special(cc)) {
  11545. if (subtype == VSLENGTH)
  11546. subtype = 0;
  11547. goto badsub;
  11548. }
  11549. USTPUTC(cc, out);
  11550. } else
  11551. goto badsub;
  11552. if (c != '}' && subtype == VSLENGTH) {
  11553. /* ${#VAR didn't end with } */
  11554. goto badsub;
  11555. }
  11556. if (subtype == 0) {
  11557. static const char types[] ALIGN1 = "}-+?=";
  11558. /* ${VAR...} but not $VAR or ${#VAR} */
  11559. /* c == first char after VAR */
  11560. int cc = c;
  11561. switch (c) {
  11562. case ':':
  11563. c = pgetc_eatbnl();
  11564. #if BASH_SUBSTR
  11565. /* This check is only needed to not misinterpret
  11566. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11567. * constructs.
  11568. */
  11569. if (!strchr(types, c)) {
  11570. subtype = VSSUBSTR;
  11571. pungetc();
  11572. break; /* "goto badsub" is bigger (!) */
  11573. }
  11574. #endif
  11575. subtype = VSNUL;
  11576. /*FALLTHROUGH*/
  11577. default: {
  11578. const char *p = strchr(types, c);
  11579. if (p == NULL)
  11580. break;
  11581. subtype |= p - types + VSNORMAL;
  11582. break;
  11583. }
  11584. case '%':
  11585. case '#':
  11586. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11587. c = pgetc_eatbnl();
  11588. if (c == cc)
  11589. subtype++;
  11590. else
  11591. pungetc();
  11592. newsyn = BASESYNTAX;
  11593. break;
  11594. #if BASH_PATTERN_SUBST
  11595. case '/':
  11596. /* ${v/[/]pattern/repl} */
  11597. //TODO: encode pattern and repl separately.
  11598. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11599. // are broken (should print "ONE")
  11600. subtype = VSREPLACE;
  11601. newsyn = BASESYNTAX;
  11602. c = pgetc_eatbnl();
  11603. if (c != '/')
  11604. goto badsub;
  11605. subtype++; /* VSREPLACEALL */
  11606. break;
  11607. #endif
  11608. }
  11609. } else {
  11610. badsub:
  11611. pungetc();
  11612. }
  11613. if (newsyn == ARISYNTAX)
  11614. newsyn = DQSYNTAX;
  11615. if ((newsyn != synstack->syntax || synstack->innerdq)
  11616. && subtype != VSNORMAL
  11617. ) {
  11618. synstack_push(&synstack,
  11619. synstack->prev ?: alloca(sizeof(*synstack)),
  11620. newsyn);
  11621. synstack->varpushed = 1;
  11622. synstack->dblquote = newsyn != BASESYNTAX;
  11623. }
  11624. ((unsigned char *)stackblock())[typeloc] = subtype;
  11625. if (subtype != VSNORMAL) {
  11626. synstack->varnest++;
  11627. if (synstack->dblquote)
  11628. synstack->dqvarnest++;
  11629. }
  11630. STPUTC('=', out);
  11631. }
  11632. goto parsesub_return;
  11633. }
  11634. /*
  11635. * Called to parse command substitutions. Newstyle is set if the command
  11636. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11637. * list of commands (passed by reference), and savelen is the number of
  11638. * characters on the top of the stack which must be preserved.
  11639. */
  11640. parsebackq: {
  11641. struct nodelist **nlpp;
  11642. union node *n;
  11643. char *str;
  11644. size_t savelen;
  11645. struct heredoc *saveheredoclist;
  11646. smallint saveprompt = 0;
  11647. str = NULL;
  11648. savelen = out - (char *)stackblock();
  11649. if (savelen > 0) {
  11650. /*
  11651. * FIXME: this can allocate very large block on stack and SEGV.
  11652. * Example:
  11653. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11654. * allocates 100kb for every command subst. With about
  11655. * a hundred command substitutions stack overflows.
  11656. * With larger prepended string, SEGV happens sooner.
  11657. */
  11658. str = alloca(savelen);
  11659. memcpy(str, stackblock(), savelen);
  11660. }
  11661. if (oldstyle) {
  11662. /* We must read until the closing backquote, giving special
  11663. * treatment to some slashes, and then push the string and
  11664. * reread it as input, interpreting it normally.
  11665. */
  11666. char *pout;
  11667. size_t psavelen;
  11668. char *pstr;
  11669. STARTSTACKSTR(pout);
  11670. for (;;) {
  11671. int pc;
  11672. setprompt_if(needprompt, 2);
  11673. pc = pgetc_eatbnl();
  11674. switch (pc) {
  11675. case '`':
  11676. goto done;
  11677. case '\\':
  11678. pc = pgetc(); /* not pgetc_eatbnl! */
  11679. if (pc != '\\' && pc != '`' && pc != '$'
  11680. && (!synstack->dblquote || pc != '"')
  11681. ) {
  11682. STPUTC('\\', pout);
  11683. }
  11684. if (pc <= 255 /* not PEOA or PEOF */) {
  11685. break;
  11686. }
  11687. /* fall through */
  11688. case PEOF:
  11689. IF_ASH_ALIAS(case PEOA:)
  11690. raise_error_syntax("EOF in backquote substitution");
  11691. case '\n':
  11692. nlnoprompt();
  11693. break;
  11694. default:
  11695. break;
  11696. }
  11697. STPUTC(pc, pout);
  11698. }
  11699. done:
  11700. STPUTC('\0', pout);
  11701. psavelen = pout - (char *)stackblock();
  11702. if (psavelen > 0) {
  11703. pstr = grabstackstr(pout);
  11704. setinputstring(pstr);
  11705. }
  11706. }
  11707. nlpp = &bqlist;
  11708. while (*nlpp)
  11709. nlpp = &(*nlpp)->next;
  11710. *nlpp = stzalloc(sizeof(**nlpp));
  11711. /* (*nlpp)->next = NULL; - stzalloc did it */
  11712. saveheredoclist = heredoclist;
  11713. heredoclist = NULL;
  11714. if (oldstyle) {
  11715. saveprompt = doprompt;
  11716. doprompt = 0;
  11717. }
  11718. n = list(2);
  11719. if (oldstyle)
  11720. doprompt = saveprompt;
  11721. else {
  11722. if (readtoken() != TRP)
  11723. raise_error_unexpected_syntax(TRP);
  11724. setinputstring(nullstr);
  11725. }
  11726. parseheredoc();
  11727. heredoclist = saveheredoclist;
  11728. (*nlpp)->n = n;
  11729. /* Start reading from old file again. */
  11730. popfile();
  11731. /* Ignore any pushed back tokens left from the backquote parsing. */
  11732. if (oldstyle)
  11733. tokpushback = 0;
  11734. out = growstackto(savelen + 1);
  11735. if (str) {
  11736. memcpy(out, str, savelen);
  11737. STADJUST(savelen, out);
  11738. }
  11739. USTPUTC(CTLBACKQ, out);
  11740. if (oldstyle)
  11741. goto parsebackq_oldreturn;
  11742. goto parsebackq_newreturn;
  11743. }
  11744. #if ENABLE_FEATURE_SH_MATH
  11745. /*
  11746. * Parse an arithmetic expansion (indicate start of one and set state)
  11747. */
  11748. parsearith: {
  11749. synstack_push(&synstack,
  11750. synstack->prev ?: alloca(sizeof(*synstack)),
  11751. ARISYNTAX);
  11752. synstack->dblquote = 1;
  11753. USTPUTC(CTLARI, out);
  11754. goto parsearith_return;
  11755. }
  11756. #endif
  11757. } /* end of readtoken */
  11758. /*
  11759. * Read the next input token.
  11760. * If the token is a word, we set backquotelist to the list of cmds in
  11761. * backquotes. We set quoteflag to true if any part of the word was
  11762. * quoted.
  11763. * If the token is TREDIR, then we set redirnode to a structure containing
  11764. * the redirection.
  11765. *
  11766. * [Change comment: here documents and internal procedures]
  11767. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11768. * word parsing code into a separate routine. In this case, readtoken
  11769. * doesn't need to have any internal procedures, but parseword does.
  11770. * We could also make parseoperator in essence the main routine, and
  11771. * have parseword (readtoken1?) handle both words and redirection.]
  11772. */
  11773. #define NEW_xxreadtoken
  11774. #ifdef NEW_xxreadtoken
  11775. /* singles must be first! */
  11776. static const char xxreadtoken_chars[7] ALIGN1 = {
  11777. '\n', '(', ')', /* singles */
  11778. '&', '|', ';', /* doubles */
  11779. 0
  11780. };
  11781. #define xxreadtoken_singles 3
  11782. #define xxreadtoken_doubles 3
  11783. static const char xxreadtoken_tokens[] ALIGN1 = {
  11784. TNL, TLP, TRP, /* only single occurrence allowed */
  11785. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11786. TEOF, /* corresponds to trailing nul */
  11787. TAND, TOR, TENDCASE /* if double occurrence */
  11788. };
  11789. static int
  11790. xxreadtoken(void)
  11791. {
  11792. int c;
  11793. if (tokpushback) {
  11794. tokpushback = 0;
  11795. return lasttoken;
  11796. }
  11797. setprompt_if(needprompt, 2);
  11798. for (;;) { /* until token or start of word found */
  11799. c = pgetc_eatbnl();
  11800. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11801. continue;
  11802. if (c == '#') {
  11803. while ((c = pgetc()) != '\n' && c != PEOF)
  11804. continue;
  11805. pungetc();
  11806. } else if (c == '\\') {
  11807. break; /* return readtoken1(...) */
  11808. } else {
  11809. const char *p;
  11810. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11811. if (c != PEOF) {
  11812. if (c == '\n') {
  11813. nlnoprompt();
  11814. }
  11815. p = strchr(xxreadtoken_chars, c);
  11816. if (p == NULL)
  11817. break; /* return readtoken1(...) */
  11818. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11819. int cc = pgetc_eatbnl();
  11820. if (cc == c) { /* double occurrence? */
  11821. p += xxreadtoken_doubles + 1;
  11822. } else {
  11823. pungetc();
  11824. #if BASH_REDIR_OUTPUT
  11825. if (c == '&' && cc == '>') /* &> */
  11826. break; /* return readtoken1(...) */
  11827. #endif
  11828. }
  11829. }
  11830. }
  11831. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11832. return lasttoken;
  11833. }
  11834. } /* for (;;) */
  11835. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11836. }
  11837. #else /* old xxreadtoken */
  11838. #define RETURN(token) return lasttoken = token
  11839. static int
  11840. xxreadtoken(void)
  11841. {
  11842. int c;
  11843. if (tokpushback) {
  11844. tokpushback = 0;
  11845. return lasttoken;
  11846. }
  11847. setprompt_if(needprompt, 2);
  11848. for (;;) { /* until token or start of word found */
  11849. c = pgetc_eatbnl();
  11850. switch (c) {
  11851. case ' ': case '\t':
  11852. IF_ASH_ALIAS(case PEOA:)
  11853. continue;
  11854. case '#':
  11855. while ((c = pgetc()) != '\n' && c != PEOF)
  11856. continue;
  11857. pungetc();
  11858. continue;
  11859. case '\n':
  11860. nlnoprompt();
  11861. RETURN(TNL);
  11862. case PEOF:
  11863. RETURN(TEOF);
  11864. case '&':
  11865. if (pgetc_eatbnl() == '&')
  11866. RETURN(TAND);
  11867. pungetc();
  11868. RETURN(TBACKGND);
  11869. case '|':
  11870. if (pgetc_eatbnl() == '|')
  11871. RETURN(TOR);
  11872. pungetc();
  11873. RETURN(TPIPE);
  11874. case ';':
  11875. if (pgetc_eatbnl() == ';')
  11876. RETURN(TENDCASE);
  11877. pungetc();
  11878. RETURN(TSEMI);
  11879. case '(':
  11880. RETURN(TLP);
  11881. case ')':
  11882. RETURN(TRP);
  11883. }
  11884. break;
  11885. }
  11886. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11887. #undef RETURN
  11888. }
  11889. #endif /* old xxreadtoken */
  11890. static int
  11891. readtoken(void)
  11892. {
  11893. int t;
  11894. int kwd = checkkwd;
  11895. #if DEBUG
  11896. smallint alreadyseen = tokpushback;
  11897. #endif
  11898. #if ENABLE_ASH_ALIAS
  11899. top:
  11900. #endif
  11901. t = xxreadtoken();
  11902. /*
  11903. * eat newlines
  11904. */
  11905. if (kwd & CHKNL) {
  11906. while (t == TNL) {
  11907. parseheredoc();
  11908. t = xxreadtoken();
  11909. }
  11910. }
  11911. if (t != TWORD || quoteflag) {
  11912. goto out;
  11913. }
  11914. /*
  11915. * check for keywords
  11916. */
  11917. if (kwd & CHKKWD) {
  11918. const char *const *pp;
  11919. pp = findkwd(wordtext);
  11920. if (pp) {
  11921. lasttoken = t = pp - tokname_array;
  11922. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11923. goto out;
  11924. }
  11925. }
  11926. if (checkkwd & CHKALIAS) {
  11927. #if ENABLE_ASH_ALIAS
  11928. struct alias *ap;
  11929. ap = lookupalias(wordtext, 1);
  11930. if (ap != NULL) {
  11931. if (*ap->val) {
  11932. pushstring(ap->val, ap);
  11933. }
  11934. goto top;
  11935. }
  11936. #endif
  11937. }
  11938. out:
  11939. checkkwd = 0;
  11940. #if DEBUG
  11941. if (!alreadyseen)
  11942. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11943. else
  11944. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11945. #endif
  11946. return t;
  11947. }
  11948. static int
  11949. peektoken(void)
  11950. {
  11951. int t;
  11952. t = readtoken();
  11953. tokpushback = 1;
  11954. return t;
  11955. }
  11956. /*
  11957. * Read and parse a command. Returns NODE_EOF on end of file.
  11958. * (NULL is a valid parse tree indicating a blank line.)
  11959. */
  11960. static union node *
  11961. parsecmd(int interact)
  11962. {
  11963. tokpushback = 0;
  11964. checkkwd = 0;
  11965. heredoclist = 0;
  11966. doprompt = interact;
  11967. setprompt_if(doprompt, doprompt);
  11968. needprompt = 0;
  11969. return list(1);
  11970. }
  11971. /*
  11972. * Input any here documents.
  11973. */
  11974. static void
  11975. parseheredoc(void)
  11976. {
  11977. struct heredoc *here;
  11978. union node *n;
  11979. here = heredoclist;
  11980. heredoclist = NULL;
  11981. while (here) {
  11982. tokpushback = 0;
  11983. setprompt_if(needprompt, 2);
  11984. if (here->here->type == NHERE)
  11985. readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
  11986. else
  11987. readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
  11988. n = stzalloc(sizeof(struct narg));
  11989. n->narg.type = NARG;
  11990. /*n->narg.next = NULL; - stzalloc did it */
  11991. n->narg.text = wordtext;
  11992. n->narg.backquote = backquotelist;
  11993. here->here->nhere.doc = n;
  11994. here = here->next;
  11995. }
  11996. }
  11997. static const char *
  11998. expandstr(const char *ps, int syntax_type)
  11999. {
  12000. union node n;
  12001. int saveprompt;
  12002. struct parsefile *file_stop = g_parsefile;
  12003. volatile int saveint;
  12004. struct jmploc *volatile savehandler = exception_handler;
  12005. struct jmploc jmploc;
  12006. const char *volatile result;
  12007. int err;
  12008. /* XXX Fix (char *) cast. */
  12009. setinputstring((char *)ps);
  12010. saveprompt = doprompt;
  12011. doprompt = 0;
  12012. result = ps;
  12013. SAVE_INT(saveint);
  12014. err = setjmp(jmploc.loc);
  12015. if (err)
  12016. goto out;
  12017. /* readtoken1() might die horribly.
  12018. * Try a prompt with syntactically wrong command:
  12019. * PS1='$(date "+%H:%M:%S) > '
  12020. */
  12021. exception_handler = &jmploc;
  12022. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  12023. n.narg.type = NARG;
  12024. n.narg.next = NULL;
  12025. n.narg.text = wordtext;
  12026. n.narg.backquote = backquotelist;
  12027. /* expandarg() might fail too:
  12028. * PS1='$((123+))'
  12029. */
  12030. expandarg(&n, NULL, EXP_QUOTED);
  12031. result = stackblock();
  12032. out:
  12033. exception_handler = savehandler;
  12034. if (err && exception_type != EXERROR)
  12035. longjmp(exception_handler->loc, 1);
  12036. RESTORE_INT(saveint);
  12037. doprompt = saveprompt;
  12038. /* Try: PS1='`xxx(`' */
  12039. unwindfiles(file_stop);
  12040. return result;
  12041. }
  12042. static inline int
  12043. parser_eof(void)
  12044. {
  12045. return tokpushback && lasttoken == TEOF;
  12046. }
  12047. /*
  12048. * Execute a command or commands contained in a string.
  12049. */
  12050. static int
  12051. evalstring(char *s, int flags)
  12052. {
  12053. struct jmploc *volatile savehandler;
  12054. struct jmploc jmploc;
  12055. int ex;
  12056. union node *n;
  12057. struct stackmark smark;
  12058. int status;
  12059. s = sstrdup(s);
  12060. setinputstring(s);
  12061. setstackmark(&smark);
  12062. status = 0;
  12063. /* On exception inside execution loop, we must popfile().
  12064. * Try interactively:
  12065. * readonly a=a
  12066. * command eval "a=b" # throws "is read only" error
  12067. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  12068. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  12069. */
  12070. savehandler = exception_handler;
  12071. ex = setjmp(jmploc.loc);
  12072. if (ex)
  12073. goto out;
  12074. exception_handler = &jmploc;
  12075. while ((n = parsecmd(0)) != NODE_EOF) {
  12076. int i;
  12077. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  12078. if (n)
  12079. status = i;
  12080. popstackmark(&smark);
  12081. if (evalskip)
  12082. break;
  12083. }
  12084. out:
  12085. popstackmark(&smark);
  12086. popfile();
  12087. stunalloc(s);
  12088. exception_handler = savehandler;
  12089. if (ex)
  12090. longjmp(exception_handler->loc, ex);
  12091. return status;
  12092. }
  12093. /*
  12094. * The eval command.
  12095. */
  12096. static int FAST_FUNC
  12097. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  12098. {
  12099. char *p;
  12100. char *concat;
  12101. if (argv[1]) {
  12102. p = argv[1];
  12103. argv += 2;
  12104. if (argv[0]) {
  12105. STARTSTACKSTR(concat);
  12106. for (;;) {
  12107. concat = stack_putstr(p, concat);
  12108. p = *argv++;
  12109. if (p == NULL)
  12110. break;
  12111. STPUTC(' ', concat);
  12112. }
  12113. STPUTC('\0', concat);
  12114. p = grabstackstr(concat);
  12115. }
  12116. return evalstring(p, flags & EV_TESTED);
  12117. }
  12118. return 0;
  12119. }
  12120. /*
  12121. * Read and execute commands.
  12122. * "Top" is nonzero for the top level command loop;
  12123. * it turns on prompting if the shell is interactive.
  12124. */
  12125. static int
  12126. cmdloop(int top)
  12127. {
  12128. union node *n;
  12129. struct stackmark smark;
  12130. int inter;
  12131. int status = 0;
  12132. int numeof = 0;
  12133. TRACE(("cmdloop(%d) called\n", top));
  12134. for (;;) {
  12135. int skip;
  12136. setstackmark(&smark);
  12137. #if JOBS
  12138. if (doing_jobctl)
  12139. showjobs(SHOW_CHANGED|SHOW_STDERR);
  12140. #endif
  12141. inter = 0;
  12142. if (iflag && top) {
  12143. inter++;
  12144. chkmail();
  12145. }
  12146. n = parsecmd(inter);
  12147. #if DEBUG
  12148. if (DEBUG > 2 && debug && (n != NODE_EOF))
  12149. showtree(n);
  12150. #endif
  12151. if (n == NODE_EOF) {
  12152. if (!top || numeof >= 50)
  12153. break;
  12154. if (!stoppedjobs()) {
  12155. if (!Iflag) {
  12156. if (iflag) {
  12157. newline_and_flush(stderr);
  12158. }
  12159. break;
  12160. }
  12161. out2str("\nUse \"exit\" to leave shell.\n");
  12162. }
  12163. numeof++;
  12164. } else if (nflag == 0) {
  12165. int i;
  12166. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12167. job_warning >>= 1;
  12168. numeof = 0;
  12169. i = evaltree(n, 0);
  12170. if (n)
  12171. status = i;
  12172. }
  12173. popstackmark(&smark);
  12174. skip = evalskip;
  12175. if (skip) {
  12176. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  12177. break;
  12178. }
  12179. }
  12180. return status;
  12181. }
  12182. /*
  12183. * Take commands from a file. To be compatible we should do a path
  12184. * search for the file, which is necessary to find sub-commands.
  12185. */
  12186. static char *
  12187. find_dot_file(char *basename)
  12188. {
  12189. char *fullname;
  12190. const char *path = pathval();
  12191. struct stat statb;
  12192. int len;
  12193. /* don't try this for absolute or relative paths */
  12194. if (strchr(basename, '/'))
  12195. return basename;
  12196. while ((len = padvance(&path, basename)) >= 0) {
  12197. fullname = stackblock();
  12198. if ((!pathopt || *pathopt == 'f')
  12199. && !stat(fullname, &statb) && S_ISREG(statb.st_mode)
  12200. ) {
  12201. /* This will be freed by the caller. */
  12202. return stalloc(len);
  12203. }
  12204. }
  12205. /* not found in PATH */
  12206. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12207. return basename;
  12208. #else
  12209. ash_msg_and_raise_error("%s: not found", basename);
  12210. /* NOTREACHED */
  12211. #endif
  12212. }
  12213. static int FAST_FUNC
  12214. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12215. {
  12216. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12217. int status = 0;
  12218. char *fullname;
  12219. char **argv;
  12220. char *args_need_save;
  12221. volatile struct shparam saveparam;
  12222. //???
  12223. // struct strlist *sp;
  12224. // for (sp = cmdenviron; sp; sp = sp->next)
  12225. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12226. nextopt(nullstr); /* handle possible "--" */
  12227. argv = argptr;
  12228. if (!argv[0]) {
  12229. /* bash says: "bash: .: filename argument required" */
  12230. return 2; /* bash compat */
  12231. }
  12232. /* This aborts if file isn't found, which is POSIXly correct.
  12233. * bash returns exitcode 1 instead.
  12234. */
  12235. fullname = find_dot_file(argv[0]);
  12236. argv++;
  12237. args_need_save = argv[0];
  12238. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12239. int argc;
  12240. saveparam = shellparam;
  12241. shellparam.malloced = 0;
  12242. argc = 1;
  12243. while (argv[argc])
  12244. argc++;
  12245. shellparam.nparam = argc;
  12246. shellparam.p = argv;
  12247. };
  12248. /* This aborts if file can't be opened, which is POSIXly correct.
  12249. * bash returns exitcode 1 instead.
  12250. */
  12251. setinputfile(fullname, INPUT_PUSH_FILE);
  12252. commandname = fullname;
  12253. status = cmdloop(0);
  12254. popfile();
  12255. if (args_need_save) {
  12256. freeparam(&shellparam);
  12257. shellparam = saveparam;
  12258. };
  12259. return status;
  12260. }
  12261. static int FAST_FUNC
  12262. exitcmd(int argc UNUSED_PARAM, char **argv)
  12263. {
  12264. if (stoppedjobs())
  12265. return 0;
  12266. if (argv[1])
  12267. savestatus = number(argv[1]);
  12268. raise_exception(EXEXIT);
  12269. /* NOTREACHED */
  12270. }
  12271. /*
  12272. * Read a file containing shell functions.
  12273. */
  12274. static void
  12275. readcmdfile(char *name)
  12276. {
  12277. setinputfile(name, INPUT_PUSH_FILE);
  12278. cmdloop(0);
  12279. popfile();
  12280. }
  12281. /* ============ find_command inplementation */
  12282. /*
  12283. * Resolve a command name. If you change this routine, you may have to
  12284. * change the shellexec routine as well.
  12285. */
  12286. static void
  12287. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12288. {
  12289. struct tblentry *cmdp;
  12290. int idx;
  12291. int prev;
  12292. char *fullname;
  12293. struct stat statb;
  12294. int e;
  12295. int updatetbl;
  12296. struct builtincmd *bcmd;
  12297. int len;
  12298. /* If name contains a slash, don't use PATH or hash table */
  12299. if (strchr(name, '/') != NULL) {
  12300. entry->u.index = -1;
  12301. if (act & DO_ABS) {
  12302. while (stat(name, &statb) < 0) {
  12303. #ifdef SYSV
  12304. if (errno == EINTR)
  12305. continue;
  12306. #endif
  12307. entry->cmdtype = CMDUNKNOWN;
  12308. return;
  12309. }
  12310. }
  12311. entry->cmdtype = CMDNORMAL;
  12312. return;
  12313. }
  12314. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12315. updatetbl = (path == pathval());
  12316. if (!updatetbl)
  12317. act |= DO_ALTPATH;
  12318. /* If name is in the table, check answer will be ok */
  12319. cmdp = cmdlookup(name, 0);
  12320. if (cmdp != NULL) {
  12321. int bit;
  12322. switch (cmdp->cmdtype) {
  12323. default:
  12324. #if DEBUG
  12325. abort();
  12326. #endif
  12327. case CMDNORMAL:
  12328. bit = DO_ALTPATH | DO_REGBLTIN;
  12329. break;
  12330. case CMDFUNCTION:
  12331. bit = DO_NOFUNC;
  12332. break;
  12333. case CMDBUILTIN:
  12334. bit = IS_BUILTIN_REGULAR(cmdp->param.cmd) ? 0 : DO_REGBLTIN;
  12335. break;
  12336. }
  12337. if (act & bit) {
  12338. if (act & bit & DO_REGBLTIN)
  12339. goto fail;
  12340. updatetbl = 0;
  12341. cmdp = NULL;
  12342. } else if (cmdp->rehash == 0)
  12343. /* if not invalidated by cd, we're done */
  12344. goto success;
  12345. }
  12346. /* If %builtin not in path, check for builtin next */
  12347. bcmd = find_builtin(name);
  12348. if (bcmd) {
  12349. if (IS_BUILTIN_REGULAR(bcmd))
  12350. goto builtin_success;
  12351. if (act & DO_ALTPATH)
  12352. goto builtin_success;
  12353. if (builtinloc <= 0)
  12354. goto builtin_success;
  12355. }
  12356. if (act & DO_REGBLTIN)
  12357. goto fail;
  12358. #if ENABLE_FEATURE_SH_STANDALONE
  12359. {
  12360. int applet_no = find_applet_by_name(name);
  12361. if (applet_no >= 0) {
  12362. entry->cmdtype = CMDNORMAL;
  12363. entry->u.index = -2 - applet_no;
  12364. return;
  12365. }
  12366. }
  12367. #endif
  12368. /* We have to search path. */
  12369. prev = -1; /* where to start */
  12370. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12371. if (cmdp->cmdtype == CMDBUILTIN)
  12372. prev = builtinloc;
  12373. else
  12374. prev = cmdp->param.index;
  12375. }
  12376. e = ENOENT;
  12377. idx = -1;
  12378. loop:
  12379. while ((len = padvance(&path, name)) >= 0) {
  12380. const char *lpathopt = pathopt;
  12381. fullname = stackblock();
  12382. idx++;
  12383. if (lpathopt) {
  12384. if (*lpathopt == 'b') {
  12385. if (bcmd)
  12386. goto builtin_success;
  12387. continue;
  12388. } else if (!(act & DO_NOFUNC)) {
  12389. /* handled below */
  12390. } else {
  12391. /* ignore unimplemented options */
  12392. continue;
  12393. }
  12394. }
  12395. /* if rehash, don't redo absolute path names */
  12396. if (fullname[0] == '/' && idx <= prev) {
  12397. if (idx < prev)
  12398. continue;
  12399. TRACE(("searchexec \"%s\": no change\n", name));
  12400. goto success;
  12401. }
  12402. while (stat(fullname, &statb) < 0) {
  12403. #ifdef SYSV
  12404. if (errno == EINTR)
  12405. continue;
  12406. #endif
  12407. if (errno != ENOENT && errno != ENOTDIR)
  12408. e = errno;
  12409. goto loop;
  12410. }
  12411. e = EACCES; /* if we fail, this will be the error */
  12412. if (!S_ISREG(statb.st_mode))
  12413. continue;
  12414. if (lpathopt) { /* this is a %func directory */
  12415. stalloc(len);
  12416. /* NB: stalloc will return space pointed by fullname
  12417. * (because we don't have any intervening allocations
  12418. * between stunalloc above and this stalloc) */
  12419. readcmdfile(fullname);
  12420. cmdp = cmdlookup(name, 0);
  12421. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12422. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12423. stunalloc(fullname);
  12424. goto success;
  12425. }
  12426. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12427. if (!updatetbl) {
  12428. entry->cmdtype = CMDNORMAL;
  12429. entry->u.index = idx;
  12430. return;
  12431. }
  12432. INT_OFF;
  12433. cmdp = cmdlookup(name, 1);
  12434. cmdp->cmdtype = CMDNORMAL;
  12435. cmdp->param.index = idx;
  12436. INT_ON;
  12437. goto success;
  12438. }
  12439. /* We failed. If there was an entry for this command, delete it */
  12440. if (cmdp && updatetbl)
  12441. delete_cmd_entry();
  12442. if (act & DO_ERR) {
  12443. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12444. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12445. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12446. char *argv[3];
  12447. argv[0] = (char*) "command_not_found_handle";
  12448. argv[1] = name;
  12449. argv[2] = NULL;
  12450. evalfun(hookp->param.func, 2, argv, 0);
  12451. entry->cmdtype = CMDUNKNOWN;
  12452. return;
  12453. }
  12454. #endif
  12455. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12456. }
  12457. fail:
  12458. entry->cmdtype = CMDUNKNOWN;
  12459. return;
  12460. builtin_success:
  12461. if (!updatetbl) {
  12462. entry->cmdtype = CMDBUILTIN;
  12463. entry->u.cmd = bcmd;
  12464. return;
  12465. }
  12466. INT_OFF;
  12467. cmdp = cmdlookup(name, 1);
  12468. cmdp->cmdtype = CMDBUILTIN;
  12469. cmdp->param.cmd = bcmd;
  12470. INT_ON;
  12471. success:
  12472. cmdp->rehash = 0;
  12473. entry->cmdtype = cmdp->cmdtype;
  12474. entry->u = cmdp->param;
  12475. }
  12476. /*
  12477. * The trap builtin.
  12478. */
  12479. static int FAST_FUNC
  12480. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12481. {
  12482. char *action;
  12483. char **ap;
  12484. int signo, exitcode;
  12485. nextopt(nullstr);
  12486. ap = argptr;
  12487. if (!*ap) {
  12488. for (signo = 0; signo < NSIG; signo++) {
  12489. char *tr = trap_ptr[signo];
  12490. if (tr) {
  12491. /* note: bash adds "SIG", but only if invoked
  12492. * as "bash". If called as "sh", or if set -o posix,
  12493. * then it prints short signal names.
  12494. * We are printing short names: */
  12495. out1fmt("trap -- %s %s\n",
  12496. single_quote(tr),
  12497. get_signame(signo));
  12498. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12499. * In this case, we will exit very soon, no need to free(). */
  12500. /* if (trap_ptr != trap && tp[0]) */
  12501. /* free(tr); */
  12502. }
  12503. }
  12504. /*
  12505. if (trap_ptr != trap) {
  12506. free(trap_ptr);
  12507. trap_ptr = trap;
  12508. }
  12509. */
  12510. return 0;
  12511. }
  12512. /* Why the second check?
  12513. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12514. * In this case, NUM is signal no, not an action.
  12515. */
  12516. action = NULL;
  12517. if (ap[1] && !is_number(ap[0]))
  12518. action = *ap++;
  12519. exitcode = 0;
  12520. while (*ap) {
  12521. signo = get_signum(*ap);
  12522. if (signo < 0) {
  12523. /* Mimic bash message exactly */
  12524. ash_msg("%s: invalid signal specification", *ap);
  12525. exitcode = 1;
  12526. goto next;
  12527. }
  12528. INT_OFF;
  12529. if (action) {
  12530. if (LONE_DASH(action))
  12531. action = NULL;
  12532. else {
  12533. if (action[0]) /* not NULL and not "" and not "-" */
  12534. may_have_traps = 1;
  12535. action = ckstrdup(action);
  12536. }
  12537. }
  12538. free(trap[signo]);
  12539. trap[signo] = action;
  12540. if (signo != 0)
  12541. setsignal(signo);
  12542. INT_ON;
  12543. next:
  12544. ap++;
  12545. }
  12546. return exitcode;
  12547. }
  12548. /* ============ Builtins */
  12549. #if ENABLE_ASH_HELP
  12550. static int FAST_FUNC
  12551. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12552. {
  12553. unsigned col;
  12554. unsigned i;
  12555. out1fmt(
  12556. "Built-in commands:\n"
  12557. "------------------\n");
  12558. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12559. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12560. builtintab[i].name + 1);
  12561. if (col > 60) {
  12562. out1fmt("\n");
  12563. col = 0;
  12564. }
  12565. }
  12566. # if ENABLE_FEATURE_SH_STANDALONE
  12567. {
  12568. const char *a = applet_names;
  12569. while (*a) {
  12570. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12571. if (col > 60) {
  12572. out1fmt("\n");
  12573. col = 0;
  12574. }
  12575. while (*a++ != '\0')
  12576. continue;
  12577. }
  12578. }
  12579. # endif
  12580. newline_and_flush(stdout);
  12581. return EXIT_SUCCESS;
  12582. }
  12583. #endif
  12584. #if MAX_HISTORY
  12585. static int FAST_FUNC
  12586. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12587. {
  12588. show_history(line_input_state);
  12589. return EXIT_SUCCESS;
  12590. }
  12591. #endif
  12592. /*
  12593. * The export and readonly commands.
  12594. */
  12595. static int FAST_FUNC
  12596. exportcmd(int argc UNUSED_PARAM, char **argv)
  12597. {
  12598. struct var *vp;
  12599. char *name;
  12600. const char *p;
  12601. char **aptr;
  12602. char opt;
  12603. int flag;
  12604. int flag_off;
  12605. /* "readonly" in bash accepts, but ignores -n.
  12606. * We do the same: it saves a conditional in nextopt's param.
  12607. */
  12608. flag_off = 0;
  12609. while ((opt = nextopt("np")) != '\0') {
  12610. if (opt == 'n')
  12611. flag_off = VEXPORT;
  12612. }
  12613. flag = VEXPORT;
  12614. if (argv[0][0] == 'r') {
  12615. flag = VREADONLY;
  12616. flag_off = 0; /* readonly ignores -n */
  12617. }
  12618. flag_off = ~flag_off;
  12619. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12620. {
  12621. aptr = argptr;
  12622. name = *aptr;
  12623. if (name) {
  12624. do {
  12625. p = strchr(name, '=');
  12626. if (p != NULL) {
  12627. p++;
  12628. } else {
  12629. vp = *findvar(hashvar(name), name);
  12630. if (vp) {
  12631. vp->flags = ((vp->flags | flag) & flag_off);
  12632. continue;
  12633. }
  12634. }
  12635. setvar(name, p, (flag & flag_off));
  12636. } while ((name = *++aptr) != NULL);
  12637. return 0;
  12638. }
  12639. }
  12640. /* No arguments. Show the list of exported or readonly vars.
  12641. * -n is ignored.
  12642. */
  12643. showvars(argv[0], flag, 0);
  12644. return 0;
  12645. }
  12646. /*
  12647. * Delete a function if it exists.
  12648. */
  12649. static void
  12650. unsetfunc(const char *name)
  12651. {
  12652. struct tblentry *cmdp;
  12653. cmdp = cmdlookup(name, 0);
  12654. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12655. delete_cmd_entry();
  12656. }
  12657. /*
  12658. * The unset builtin command. We unset the function before we unset the
  12659. * variable to allow a function to be unset when there is a readonly variable
  12660. * with the same name.
  12661. */
  12662. static int FAST_FUNC
  12663. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12664. {
  12665. char **ap;
  12666. int i;
  12667. int flag = 0;
  12668. while ((i = nextopt("vf")) != 0) {
  12669. flag = i;
  12670. }
  12671. for (ap = argptr; *ap; ap++) {
  12672. if (flag != 'f') {
  12673. unsetvar(*ap);
  12674. continue;
  12675. }
  12676. if (flag != 'v')
  12677. unsetfunc(*ap);
  12678. }
  12679. return 0;
  12680. }
  12681. static const unsigned char timescmd_str[] ALIGN1 = {
  12682. ' ', offsetof(struct tms, tms_utime),
  12683. '\n', offsetof(struct tms, tms_stime),
  12684. ' ', offsetof(struct tms, tms_cutime),
  12685. '\n', offsetof(struct tms, tms_cstime),
  12686. 0
  12687. };
  12688. static int FAST_FUNC
  12689. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12690. {
  12691. unsigned clk_tck;
  12692. const unsigned char *p;
  12693. struct tms buf;
  12694. clk_tck = bb_clk_tck();
  12695. times(&buf);
  12696. p = timescmd_str;
  12697. do {
  12698. unsigned sec, frac;
  12699. unsigned long t;
  12700. t = *(clock_t *)(((char *) &buf) + p[1]);
  12701. sec = t / clk_tck;
  12702. frac = t % clk_tck;
  12703. out1fmt("%um%u.%03us%c",
  12704. sec / 60, sec % 60,
  12705. (frac * 1000) / clk_tck,
  12706. p[0]);
  12707. p += 2;
  12708. } while (*p);
  12709. return 0;
  12710. }
  12711. #if ENABLE_FEATURE_SH_MATH
  12712. /*
  12713. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12714. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12715. *
  12716. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12717. */
  12718. static int FAST_FUNC
  12719. letcmd(int argc UNUSED_PARAM, char **argv)
  12720. {
  12721. arith_t i;
  12722. argv++;
  12723. if (!*argv)
  12724. ash_msg_and_raise_error("expression expected");
  12725. do {
  12726. i = ash_arith(*argv);
  12727. } while (*++argv);
  12728. return !i;
  12729. }
  12730. #endif
  12731. /*
  12732. * The read builtin. Options:
  12733. * -r Do not interpret '\' specially
  12734. * -s Turn off echo (tty only)
  12735. * -n NCHARS Read NCHARS max
  12736. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12737. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12738. * -u FD Read from given FD instead of fd 0
  12739. * -d DELIM End on DELIM char, not newline
  12740. * This uses unbuffered input, which may be avoidable in some cases.
  12741. * TODO: bash also has:
  12742. * -a ARRAY Read into array[0],[1],etc
  12743. * -e Use line editing (tty only)
  12744. */
  12745. static int FAST_FUNC
  12746. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12747. {
  12748. struct builtin_read_params params;
  12749. const char *r;
  12750. int i;
  12751. memset(&params, 0, sizeof(params));
  12752. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12753. switch (i) {
  12754. case 'p':
  12755. params.opt_p = optionarg;
  12756. break;
  12757. case 'n':
  12758. params.opt_n = optionarg;
  12759. break;
  12760. case 's':
  12761. params.read_flags |= BUILTIN_READ_SILENT;
  12762. break;
  12763. case 't':
  12764. params.opt_t = optionarg;
  12765. break;
  12766. case 'r':
  12767. params.read_flags |= BUILTIN_READ_RAW;
  12768. break;
  12769. case 'u':
  12770. params.opt_u = optionarg;
  12771. break;
  12772. #if BASH_READ_D
  12773. case 'd':
  12774. params.opt_d = optionarg;
  12775. break;
  12776. #endif
  12777. default:
  12778. break;
  12779. }
  12780. }
  12781. params.argv = argptr;
  12782. params.setvar = setvar0;
  12783. params.ifs = bltinlookup("IFS"); /* can be NULL */
  12784. /* "read -s" needs to save/restore termios, can't allow ^C
  12785. * to jump out of it.
  12786. */
  12787. again:
  12788. INT_OFF;
  12789. r = shell_builtin_read(&params);
  12790. INT_ON;
  12791. if ((uintptr_t)r == 1 && errno == EINTR) {
  12792. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12793. * Correct behavior is to not exit "read"
  12794. */
  12795. if (pending_sig == 0)
  12796. goto again;
  12797. }
  12798. if ((uintptr_t)r > 1)
  12799. ash_msg_and_raise_error(r);
  12800. return (uintptr_t)r;
  12801. }
  12802. static int FAST_FUNC
  12803. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12804. {
  12805. static const char permuser[3] ALIGN1 = "ogu";
  12806. mode_t mask;
  12807. int symbolic_mode = 0;
  12808. while (nextopt("S") != '\0') {
  12809. symbolic_mode = 1;
  12810. }
  12811. INT_OFF;
  12812. mask = umask(0);
  12813. umask(mask);
  12814. INT_ON;
  12815. if (*argptr == NULL) {
  12816. if (symbolic_mode) {
  12817. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12818. char *p = buf;
  12819. int i;
  12820. i = 2;
  12821. for (;;) {
  12822. *p++ = ',';
  12823. *p++ = permuser[i];
  12824. *p++ = '=';
  12825. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12826. if (!(mask & 0400)) *p++ = 'r';
  12827. if (!(mask & 0200)) *p++ = 'w';
  12828. if (!(mask & 0100)) *p++ = 'x';
  12829. mask <<= 3;
  12830. if (--i < 0)
  12831. break;
  12832. }
  12833. *p = '\0';
  12834. puts(buf + 1);
  12835. } else {
  12836. out1fmt("%04o\n", mask);
  12837. }
  12838. } else {
  12839. char *modestr = *argptr;
  12840. /* numeric umasks are taken as-is */
  12841. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12842. if (!isdigit(modestr[0]))
  12843. mask ^= 0777;
  12844. mask = bb_parse_mode(modestr, mask);
  12845. if ((unsigned)mask > 0777) {
  12846. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12847. }
  12848. if (!isdigit(modestr[0]))
  12849. mask ^= 0777;
  12850. umask(mask);
  12851. }
  12852. return 0;
  12853. }
  12854. static int FAST_FUNC
  12855. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12856. {
  12857. return shell_builtin_ulimit(argv);
  12858. }
  12859. /* ============ main() and helpers */
  12860. /*
  12861. * This routine is called when an error or an interrupt occurs in an
  12862. * interactive shell and control is returned to the main command loop
  12863. * but prior to exitshell.
  12864. */
  12865. static void
  12866. exitreset(void)
  12867. {
  12868. /* from eval.c: */
  12869. if (savestatus >= 0) {
  12870. if (exception_type == EXEXIT || evalskip == SKIPFUNCDEF)
  12871. exitstatus = savestatus;
  12872. savestatus = -1;
  12873. }
  12874. evalskip = 0;
  12875. loopnest = 0;
  12876. /* from expand.c: */
  12877. ifsfree();
  12878. /* from redir.c: */
  12879. unwindredir(NULL);
  12880. }
  12881. /*
  12882. * This routine is called when an error or an interrupt occurs in an
  12883. * interactive shell and control is returned to the main command loop.
  12884. * (In dash, this function is auto-generated by build machinery).
  12885. */
  12886. static void
  12887. reset(void)
  12888. {
  12889. /* from input.c: */
  12890. g_parsefile->left_in_buffer = 0;
  12891. g_parsefile->left_in_line = 0; /* clear input buffer */
  12892. popallfiles();
  12893. /* from var.c: */
  12894. unwindlocalvars(NULL);
  12895. }
  12896. /*
  12897. * Called to exit the shell.
  12898. */
  12899. static void
  12900. exitshell(void)
  12901. {
  12902. struct jmploc loc;
  12903. char *p;
  12904. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12905. if (line_input_state)
  12906. save_history(line_input_state);
  12907. #endif
  12908. savestatus = exitstatus;
  12909. TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
  12910. if (setjmp(loc.loc))
  12911. goto out;
  12912. exception_handler = &loc;
  12913. p = trap[0];
  12914. if (p) {
  12915. trap[0] = NULL;
  12916. evalskip = 0;
  12917. evalstring(p, 0);
  12918. evalskip = SKIPFUNCDEF;
  12919. /*free(p); - we'll exit soon */
  12920. }
  12921. out:
  12922. exitreset();
  12923. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12924. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12925. */
  12926. setjobctl(0);
  12927. flush_stdout_stderr();
  12928. _exit(exitstatus);
  12929. /* NOTREACHED */
  12930. }
  12931. /* Don't inline: conserve stack of caller from having our locals too */
  12932. static NOINLINE void
  12933. init(void)
  12934. {
  12935. /* we will never free this */
  12936. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12937. basepf.linno = 1;
  12938. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  12939. setsignal(SIGCHLD);
  12940. {
  12941. char **envp;
  12942. const char *p;
  12943. initvar();
  12944. for (envp = environ; envp && *envp; envp++) {
  12945. /* Used to have
  12946. * p = endofname(*envp);
  12947. * if (p != *envp && *p == '=') {
  12948. * here to weed out badly-named variables, but this breaks
  12949. * scenarios where people do want them passed to children:
  12950. * import os
  12951. * os.environ["test-test"]="test"
  12952. * if os.fork() == 0:
  12953. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  12954. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  12955. */
  12956. if (strchr(*envp, '=')) {
  12957. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12958. }
  12959. }
  12960. setvareq((char*)defifsvar, VTEXTFIXED);
  12961. setvareq((char*)defoptindvar, VTEXTFIXED);
  12962. setvar0("PPID", utoa(getppid()));
  12963. #if BASH_SHLVL_VAR
  12964. p = lookupvar("SHLVL");
  12965. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12966. #endif
  12967. #if BASH_HOSTNAME_VAR
  12968. if (!lookupvar("HOSTNAME")) {
  12969. struct utsname uts;
  12970. uname(&uts);
  12971. setvar0("HOSTNAME", uts.nodename);
  12972. }
  12973. #endif
  12974. p = lookupvar("PWD");
  12975. if (p) {
  12976. struct stat st1, st2;
  12977. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12978. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12979. ) {
  12980. p = NULL;
  12981. }
  12982. }
  12983. setpwd(p, 0);
  12984. }
  12985. }
  12986. //usage:#define ash_trivial_usage
  12987. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  12988. //usage:#define ash_full_usage "\n\n"
  12989. //usage: "Unix shell interpreter"
  12990. /*
  12991. * Process the shell command line arguments.
  12992. */
  12993. static int
  12994. procargs(char **argv)
  12995. {
  12996. int i;
  12997. const char *xminusc;
  12998. char **xargv;
  12999. int login_sh;
  13000. xargv = argv;
  13001. login_sh = xargv[0] && xargv[0][0] == '-';
  13002. #if NUM_SCRIPTS > 0
  13003. if (minusc)
  13004. goto setarg0;
  13005. #endif
  13006. arg0 = xargv[0];
  13007. /* if (xargv[0]) - mmm, this is always true! */
  13008. xargv++;
  13009. argptr = xargv;
  13010. for (i = 0; i < NOPTS; i++)
  13011. optlist[i] = 2;
  13012. if (options(&login_sh)) {
  13013. /* it already printed err message */
  13014. raise_exception(EXERROR);
  13015. }
  13016. xargv = argptr;
  13017. xminusc = minusc;
  13018. if (*xargv == NULL) {
  13019. if (xminusc)
  13020. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  13021. sflag = 1;
  13022. }
  13023. if (iflag == 2 /* no explicit -i given */
  13024. && sflag == 1 /* -s given (or implied) */
  13025. && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
  13026. && isatty(0) && isatty(1) /* we are on tty */
  13027. ) {
  13028. iflag = 1;
  13029. }
  13030. if (mflag == 2)
  13031. mflag = iflag;
  13032. for (i = 0; i < NOPTS; i++)
  13033. if (optlist[i] == 2)
  13034. optlist[i] = 0;
  13035. #if DEBUG == 2
  13036. debug = 1;
  13037. #endif
  13038. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  13039. if (xminusc) {
  13040. minusc = *xargv++;
  13041. if (*xargv)
  13042. goto setarg0;
  13043. } else if (!sflag) {
  13044. setinputfile(*xargv, 0);
  13045. setarg0:
  13046. arg0 = *xargv++;
  13047. commandname = arg0;
  13048. }
  13049. shellparam.p = xargv;
  13050. #if ENABLE_ASH_GETOPTS
  13051. shellparam.optind = 1;
  13052. shellparam.optoff = -1;
  13053. #endif
  13054. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  13055. while (*xargv) {
  13056. shellparam.nparam++;
  13057. xargv++;
  13058. }
  13059. optschanged();
  13060. return login_sh;
  13061. }
  13062. /*
  13063. * Read /etc/profile, ~/.profile, $ENV.
  13064. */
  13065. static void
  13066. read_profile(const char *name)
  13067. {
  13068. name = expandstr(name, DQSYNTAX);
  13069. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  13070. return;
  13071. cmdloop(0);
  13072. popfile();
  13073. }
  13074. #if PROFILE
  13075. static short profile_buf[16384];
  13076. extern int etext();
  13077. #endif
  13078. /*
  13079. * Main routine. We initialize things, parse the arguments, execute
  13080. * profiles if we're a login shell, and then call cmdloop to execute
  13081. * commands. The setjmp call sets up the location to jump to when an
  13082. * exception occurs. When an exception occurs the variable "state"
  13083. * is used to figure out how far we had gotten.
  13084. */
  13085. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13086. #if NUM_SCRIPTS > 0
  13087. int ash_main(int argc, char **argv)
  13088. #else
  13089. int ash_main(int argc UNUSED_PARAM, char **argv)
  13090. #endif
  13091. /* note: 'argc' is used only if embedded scripts are enabled */
  13092. {
  13093. volatile smallint state;
  13094. struct jmploc jmploc;
  13095. struct stackmark smark;
  13096. int login_sh;
  13097. /* Initialize global data */
  13098. INIT_G_misc();
  13099. INIT_G_memstack();
  13100. INIT_G_var();
  13101. #if ENABLE_ASH_ALIAS
  13102. INIT_G_alias();
  13103. #endif
  13104. INIT_G_cmdtable();
  13105. #if PROFILE
  13106. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  13107. #endif
  13108. state = 0;
  13109. if (setjmp(jmploc.loc)) {
  13110. smallint e;
  13111. smallint s;
  13112. exitreset();
  13113. e = exception_type;
  13114. s = state;
  13115. if (e == EXEND || e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  13116. exitshell();
  13117. }
  13118. reset();
  13119. if (e == EXINT) {
  13120. newline_and_flush(stderr);
  13121. }
  13122. popstackmark(&smark);
  13123. FORCE_INT_ON; /* enable interrupts */
  13124. if (s == 1)
  13125. goto state1;
  13126. if (s == 2)
  13127. goto state2;
  13128. if (s == 3)
  13129. goto state3;
  13130. goto state4;
  13131. }
  13132. exception_handler = &jmploc;
  13133. rootpid = getpid();
  13134. init();
  13135. setstackmark(&smark);
  13136. #if NUM_SCRIPTS > 0
  13137. if (argc < 0)
  13138. /* Non-NULL minusc tells procargs that an embedded script is being run */
  13139. minusc = get_script_content(-argc - 1);
  13140. #endif
  13141. login_sh = procargs(argv);
  13142. #if DEBUG
  13143. TRACE(("Shell args: "));
  13144. trace_puts_args(argv);
  13145. #endif
  13146. if (login_sh) {
  13147. const char *hp;
  13148. state = 1;
  13149. read_profile("/etc/profile");
  13150. state1:
  13151. state = 2;
  13152. hp = lookupvar("HOME");
  13153. if (hp)
  13154. read_profile("$HOME/.profile");
  13155. }
  13156. state2:
  13157. state = 3;
  13158. if (
  13159. #ifndef linux
  13160. getuid() == geteuid() && getgid() == getegid() &&
  13161. #endif
  13162. iflag
  13163. ) {
  13164. const char *shinit = lookupvar("ENV");
  13165. if (shinit != NULL && *shinit != '\0')
  13166. read_profile(shinit);
  13167. }
  13168. popstackmark(&smark);
  13169. state3:
  13170. state = 4;
  13171. if (minusc) {
  13172. /* evalstring pushes parsefile stack.
  13173. * Ensure we don't falsely claim that 0 (stdin)
  13174. * is one of stacked source fds.
  13175. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13176. // if (!sflag) g_parsefile->pf_fd = -1;
  13177. // ^^ not necessary since now we special-case fd 0
  13178. // in save_fd_on_redirect()
  13179. // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
  13180. // The above makes
  13181. // ash -sc 'echo $-'
  13182. // continue reading input from stdin after running 'echo'.
  13183. // bash does not do this: it prints "hBcs" and exits.
  13184. evalstring(minusc, EV_EXIT);
  13185. }
  13186. if (sflag || minusc == NULL) {
  13187. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13188. if (iflag) {
  13189. const char *hp = lookupvar("HISTFILE");
  13190. if (!hp) {
  13191. hp = lookupvar("HOME");
  13192. if (hp) {
  13193. INT_OFF;
  13194. hp = concat_path_file(hp, ".ash_history");
  13195. setvar0("HISTFILE", hp);
  13196. free((char*)hp);
  13197. INT_ON;
  13198. hp = lookupvar("HISTFILE");
  13199. }
  13200. }
  13201. if (hp)
  13202. line_input_state->hist_file = hp;
  13203. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13204. hp = lookupvar("HISTFILESIZE");
  13205. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13206. # endif
  13207. }
  13208. #endif
  13209. state4: /* XXX ??? - why isn't this before the "if" statement */
  13210. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  13211. * Try:
  13212. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  13213. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  13214. */
  13215. signal(SIGHUP, SIG_DFL);
  13216. cmdloop(1);
  13217. }
  13218. #if PROFILE
  13219. monitor(0);
  13220. #endif
  13221. #ifdef GPROF
  13222. {
  13223. extern void _mcleanup(void);
  13224. _mcleanup();
  13225. }
  13226. #endif
  13227. TRACE(("End of main reached\n"));
  13228. exitshell();
  13229. /* NOTREACHED */
  13230. }
  13231. /*-
  13232. * Copyright (c) 1989, 1991, 1993, 1994
  13233. * The Regents of the University of California. All rights reserved.
  13234. *
  13235. * This code is derived from software contributed to Berkeley by
  13236. * Kenneth Almquist.
  13237. *
  13238. * Redistribution and use in source and binary forms, with or without
  13239. * modification, are permitted provided that the following conditions
  13240. * are met:
  13241. * 1. Redistributions of source code must retain the above copyright
  13242. * notice, this list of conditions and the following disclaimer.
  13243. * 2. Redistributions in binary form must reproduce the above copyright
  13244. * notice, this list of conditions and the following disclaimer in the
  13245. * documentation and/or other materials provided with the distribution.
  13246. * 3. Neither the name of the University nor the names of its contributors
  13247. * may be used to endorse or promote products derived from this software
  13248. * without specific prior written permission.
  13249. *
  13250. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13251. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13252. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13253. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13254. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13255. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13256. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13257. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13258. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13259. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13260. * SUCH DAMAGE.
  13261. */