libbpf.c 327 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446
  1. // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
  2. /*
  3. * Common eBPF ELF object loading operations.
  4. *
  5. * Copyright (C) 2013-2015 Alexei Starovoitov <[email protected]>
  6. * Copyright (C) 2015 Wang Nan <[email protected]>
  7. * Copyright (C) 2015 Huawei Inc.
  8. * Copyright (C) 2017 Nicira, Inc.
  9. * Copyright (C) 2019 Isovalent, Inc.
  10. */
  11. #ifndef _GNU_SOURCE
  12. #define _GNU_SOURCE
  13. #endif
  14. #include <stdlib.h>
  15. #include <stdio.h>
  16. #include <stdarg.h>
  17. #include <libgen.h>
  18. #include <inttypes.h>
  19. #include <limits.h>
  20. #include <string.h>
  21. #include <unistd.h>
  22. #include <endian.h>
  23. #include <fcntl.h>
  24. #include <errno.h>
  25. #include <ctype.h>
  26. #include <asm/unistd.h>
  27. #include <linux/err.h>
  28. #include <linux/kernel.h>
  29. #include <linux/bpf.h>
  30. #include <linux/btf.h>
  31. #include <linux/filter.h>
  32. #include <linux/limits.h>
  33. #include <linux/perf_event.h>
  34. #include <linux/ring_buffer.h>
  35. #include <linux/version.h>
  36. #include <sys/epoll.h>
  37. #include <sys/ioctl.h>
  38. #include <sys/mman.h>
  39. #include <sys/stat.h>
  40. #include <sys/types.h>
  41. #include <sys/vfs.h>
  42. #include <sys/utsname.h>
  43. #include <sys/resource.h>
  44. #include <libelf.h>
  45. #include <gelf.h>
  46. #include <zlib.h>
  47. #include "libbpf.h"
  48. #include "bpf.h"
  49. #include "btf.h"
  50. #include "str_error.h"
  51. #include "libbpf_internal.h"
  52. #include "hashmap.h"
  53. #include "bpf_gen_internal.h"
  54. #ifndef BPF_FS_MAGIC
  55. #define BPF_FS_MAGIC 0xcafe4a11
  56. #endif
  57. #define BPF_INSN_SZ (sizeof(struct bpf_insn))
  58. /* vsprintf() in __base_pr() uses nonliteral format string. It may break
  59. * compilation if user enables corresponding warning. Disable it explicitly.
  60. */
  61. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  62. #define __printf(a, b) __attribute__((format(printf, a, b)))
  63. static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
  64. static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
  65. static const char * const attach_type_name[] = {
  66. [BPF_CGROUP_INET_INGRESS] = "cgroup_inet_ingress",
  67. [BPF_CGROUP_INET_EGRESS] = "cgroup_inet_egress",
  68. [BPF_CGROUP_INET_SOCK_CREATE] = "cgroup_inet_sock_create",
  69. [BPF_CGROUP_INET_SOCK_RELEASE] = "cgroup_inet_sock_release",
  70. [BPF_CGROUP_SOCK_OPS] = "cgroup_sock_ops",
  71. [BPF_CGROUP_DEVICE] = "cgroup_device",
  72. [BPF_CGROUP_INET4_BIND] = "cgroup_inet4_bind",
  73. [BPF_CGROUP_INET6_BIND] = "cgroup_inet6_bind",
  74. [BPF_CGROUP_INET4_CONNECT] = "cgroup_inet4_connect",
  75. [BPF_CGROUP_INET6_CONNECT] = "cgroup_inet6_connect",
  76. [BPF_CGROUP_INET4_POST_BIND] = "cgroup_inet4_post_bind",
  77. [BPF_CGROUP_INET6_POST_BIND] = "cgroup_inet6_post_bind",
  78. [BPF_CGROUP_INET4_GETPEERNAME] = "cgroup_inet4_getpeername",
  79. [BPF_CGROUP_INET6_GETPEERNAME] = "cgroup_inet6_getpeername",
  80. [BPF_CGROUP_INET4_GETSOCKNAME] = "cgroup_inet4_getsockname",
  81. [BPF_CGROUP_INET6_GETSOCKNAME] = "cgroup_inet6_getsockname",
  82. [BPF_CGROUP_UDP4_SENDMSG] = "cgroup_udp4_sendmsg",
  83. [BPF_CGROUP_UDP6_SENDMSG] = "cgroup_udp6_sendmsg",
  84. [BPF_CGROUP_SYSCTL] = "cgroup_sysctl",
  85. [BPF_CGROUP_UDP4_RECVMSG] = "cgroup_udp4_recvmsg",
  86. [BPF_CGROUP_UDP6_RECVMSG] = "cgroup_udp6_recvmsg",
  87. [BPF_CGROUP_GETSOCKOPT] = "cgroup_getsockopt",
  88. [BPF_CGROUP_SETSOCKOPT] = "cgroup_setsockopt",
  89. [BPF_SK_SKB_STREAM_PARSER] = "sk_skb_stream_parser",
  90. [BPF_SK_SKB_STREAM_VERDICT] = "sk_skb_stream_verdict",
  91. [BPF_SK_SKB_VERDICT] = "sk_skb_verdict",
  92. [BPF_SK_MSG_VERDICT] = "sk_msg_verdict",
  93. [BPF_LIRC_MODE2] = "lirc_mode2",
  94. [BPF_FLOW_DISSECTOR] = "flow_dissector",
  95. [BPF_TRACE_RAW_TP] = "trace_raw_tp",
  96. [BPF_TRACE_FENTRY] = "trace_fentry",
  97. [BPF_TRACE_FEXIT] = "trace_fexit",
  98. [BPF_MODIFY_RETURN] = "modify_return",
  99. [BPF_LSM_MAC] = "lsm_mac",
  100. [BPF_LSM_CGROUP] = "lsm_cgroup",
  101. [BPF_SK_LOOKUP] = "sk_lookup",
  102. [BPF_TRACE_ITER] = "trace_iter",
  103. [BPF_XDP_DEVMAP] = "xdp_devmap",
  104. [BPF_XDP_CPUMAP] = "xdp_cpumap",
  105. [BPF_XDP] = "xdp",
  106. [BPF_SK_REUSEPORT_SELECT] = "sk_reuseport_select",
  107. [BPF_SK_REUSEPORT_SELECT_OR_MIGRATE] = "sk_reuseport_select_or_migrate",
  108. [BPF_PERF_EVENT] = "perf_event",
  109. [BPF_TRACE_KPROBE_MULTI] = "trace_kprobe_multi",
  110. };
  111. static const char * const link_type_name[] = {
  112. [BPF_LINK_TYPE_UNSPEC] = "unspec",
  113. [BPF_LINK_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
  114. [BPF_LINK_TYPE_TRACING] = "tracing",
  115. [BPF_LINK_TYPE_CGROUP] = "cgroup",
  116. [BPF_LINK_TYPE_ITER] = "iter",
  117. [BPF_LINK_TYPE_NETNS] = "netns",
  118. [BPF_LINK_TYPE_XDP] = "xdp",
  119. [BPF_LINK_TYPE_PERF_EVENT] = "perf_event",
  120. [BPF_LINK_TYPE_KPROBE_MULTI] = "kprobe_multi",
  121. [BPF_LINK_TYPE_STRUCT_OPS] = "struct_ops",
  122. };
  123. static const char * const map_type_name[] = {
  124. [BPF_MAP_TYPE_UNSPEC] = "unspec",
  125. [BPF_MAP_TYPE_HASH] = "hash",
  126. [BPF_MAP_TYPE_ARRAY] = "array",
  127. [BPF_MAP_TYPE_PROG_ARRAY] = "prog_array",
  128. [BPF_MAP_TYPE_PERF_EVENT_ARRAY] = "perf_event_array",
  129. [BPF_MAP_TYPE_PERCPU_HASH] = "percpu_hash",
  130. [BPF_MAP_TYPE_PERCPU_ARRAY] = "percpu_array",
  131. [BPF_MAP_TYPE_STACK_TRACE] = "stack_trace",
  132. [BPF_MAP_TYPE_CGROUP_ARRAY] = "cgroup_array",
  133. [BPF_MAP_TYPE_LRU_HASH] = "lru_hash",
  134. [BPF_MAP_TYPE_LRU_PERCPU_HASH] = "lru_percpu_hash",
  135. [BPF_MAP_TYPE_LPM_TRIE] = "lpm_trie",
  136. [BPF_MAP_TYPE_ARRAY_OF_MAPS] = "array_of_maps",
  137. [BPF_MAP_TYPE_HASH_OF_MAPS] = "hash_of_maps",
  138. [BPF_MAP_TYPE_DEVMAP] = "devmap",
  139. [BPF_MAP_TYPE_DEVMAP_HASH] = "devmap_hash",
  140. [BPF_MAP_TYPE_SOCKMAP] = "sockmap",
  141. [BPF_MAP_TYPE_CPUMAP] = "cpumap",
  142. [BPF_MAP_TYPE_XSKMAP] = "xskmap",
  143. [BPF_MAP_TYPE_SOCKHASH] = "sockhash",
  144. [BPF_MAP_TYPE_CGROUP_STORAGE] = "cgroup_storage",
  145. [BPF_MAP_TYPE_REUSEPORT_SOCKARRAY] = "reuseport_sockarray",
  146. [BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE] = "percpu_cgroup_storage",
  147. [BPF_MAP_TYPE_QUEUE] = "queue",
  148. [BPF_MAP_TYPE_STACK] = "stack",
  149. [BPF_MAP_TYPE_SK_STORAGE] = "sk_storage",
  150. [BPF_MAP_TYPE_STRUCT_OPS] = "struct_ops",
  151. [BPF_MAP_TYPE_RINGBUF] = "ringbuf",
  152. [BPF_MAP_TYPE_INODE_STORAGE] = "inode_storage",
  153. [BPF_MAP_TYPE_TASK_STORAGE] = "task_storage",
  154. [BPF_MAP_TYPE_BLOOM_FILTER] = "bloom_filter",
  155. [BPF_MAP_TYPE_USER_RINGBUF] = "user_ringbuf",
  156. };
  157. static const char * const prog_type_name[] = {
  158. [BPF_PROG_TYPE_UNSPEC] = "unspec",
  159. [BPF_PROG_TYPE_SOCKET_FILTER] = "socket_filter",
  160. [BPF_PROG_TYPE_KPROBE] = "kprobe",
  161. [BPF_PROG_TYPE_SCHED_CLS] = "sched_cls",
  162. [BPF_PROG_TYPE_SCHED_ACT] = "sched_act",
  163. [BPF_PROG_TYPE_TRACEPOINT] = "tracepoint",
  164. [BPF_PROG_TYPE_XDP] = "xdp",
  165. [BPF_PROG_TYPE_PERF_EVENT] = "perf_event",
  166. [BPF_PROG_TYPE_CGROUP_SKB] = "cgroup_skb",
  167. [BPF_PROG_TYPE_CGROUP_SOCK] = "cgroup_sock",
  168. [BPF_PROG_TYPE_LWT_IN] = "lwt_in",
  169. [BPF_PROG_TYPE_LWT_OUT] = "lwt_out",
  170. [BPF_PROG_TYPE_LWT_XMIT] = "lwt_xmit",
  171. [BPF_PROG_TYPE_SOCK_OPS] = "sock_ops",
  172. [BPF_PROG_TYPE_SK_SKB] = "sk_skb",
  173. [BPF_PROG_TYPE_CGROUP_DEVICE] = "cgroup_device",
  174. [BPF_PROG_TYPE_SK_MSG] = "sk_msg",
  175. [BPF_PROG_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
  176. [BPF_PROG_TYPE_CGROUP_SOCK_ADDR] = "cgroup_sock_addr",
  177. [BPF_PROG_TYPE_LWT_SEG6LOCAL] = "lwt_seg6local",
  178. [BPF_PROG_TYPE_LIRC_MODE2] = "lirc_mode2",
  179. [BPF_PROG_TYPE_SK_REUSEPORT] = "sk_reuseport",
  180. [BPF_PROG_TYPE_FLOW_DISSECTOR] = "flow_dissector",
  181. [BPF_PROG_TYPE_CGROUP_SYSCTL] = "cgroup_sysctl",
  182. [BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE] = "raw_tracepoint_writable",
  183. [BPF_PROG_TYPE_CGROUP_SOCKOPT] = "cgroup_sockopt",
  184. [BPF_PROG_TYPE_TRACING] = "tracing",
  185. [BPF_PROG_TYPE_STRUCT_OPS] = "struct_ops",
  186. [BPF_PROG_TYPE_EXT] = "ext",
  187. [BPF_PROG_TYPE_LSM] = "lsm",
  188. [BPF_PROG_TYPE_SK_LOOKUP] = "sk_lookup",
  189. [BPF_PROG_TYPE_SYSCALL] = "syscall",
  190. };
  191. static int __base_pr(enum libbpf_print_level level, const char *format,
  192. va_list args)
  193. {
  194. if (level == LIBBPF_DEBUG)
  195. return 0;
  196. return vfprintf(stderr, format, args);
  197. }
  198. static libbpf_print_fn_t __libbpf_pr = __base_pr;
  199. libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
  200. {
  201. libbpf_print_fn_t old_print_fn = __libbpf_pr;
  202. __libbpf_pr = fn;
  203. return old_print_fn;
  204. }
  205. __printf(2, 3)
  206. void libbpf_print(enum libbpf_print_level level, const char *format, ...)
  207. {
  208. va_list args;
  209. int old_errno;
  210. if (!__libbpf_pr)
  211. return;
  212. old_errno = errno;
  213. va_start(args, format);
  214. __libbpf_pr(level, format, args);
  215. va_end(args);
  216. errno = old_errno;
  217. }
  218. static void pr_perm_msg(int err)
  219. {
  220. struct rlimit limit;
  221. char buf[100];
  222. if (err != -EPERM || geteuid() != 0)
  223. return;
  224. err = getrlimit(RLIMIT_MEMLOCK, &limit);
  225. if (err)
  226. return;
  227. if (limit.rlim_cur == RLIM_INFINITY)
  228. return;
  229. if (limit.rlim_cur < 1024)
  230. snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
  231. else if (limit.rlim_cur < 1024*1024)
  232. snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
  233. else
  234. snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
  235. pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
  236. buf);
  237. }
  238. #define STRERR_BUFSIZE 128
  239. /* Copied from tools/perf/util/util.h */
  240. #ifndef zfree
  241. # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
  242. #endif
  243. #ifndef zclose
  244. # define zclose(fd) ({ \
  245. int ___err = 0; \
  246. if ((fd) >= 0) \
  247. ___err = close((fd)); \
  248. fd = -1; \
  249. ___err; })
  250. #endif
  251. static inline __u64 ptr_to_u64(const void *ptr)
  252. {
  253. return (__u64) (unsigned long) ptr;
  254. }
  255. int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
  256. {
  257. /* as of v1.0 libbpf_set_strict_mode() is a no-op */
  258. return 0;
  259. }
  260. __u32 libbpf_major_version(void)
  261. {
  262. return LIBBPF_MAJOR_VERSION;
  263. }
  264. __u32 libbpf_minor_version(void)
  265. {
  266. return LIBBPF_MINOR_VERSION;
  267. }
  268. const char *libbpf_version_string(void)
  269. {
  270. #define __S(X) #X
  271. #define _S(X) __S(X)
  272. return "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
  273. #undef _S
  274. #undef __S
  275. }
  276. enum reloc_type {
  277. RELO_LD64,
  278. RELO_CALL,
  279. RELO_DATA,
  280. RELO_EXTERN_VAR,
  281. RELO_EXTERN_FUNC,
  282. RELO_SUBPROG_ADDR,
  283. RELO_CORE,
  284. };
  285. struct reloc_desc {
  286. enum reloc_type type;
  287. int insn_idx;
  288. union {
  289. const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
  290. struct {
  291. int map_idx;
  292. int sym_off;
  293. };
  294. };
  295. };
  296. /* stored as sec_def->cookie for all libbpf-supported SEC()s */
  297. enum sec_def_flags {
  298. SEC_NONE = 0,
  299. /* expected_attach_type is optional, if kernel doesn't support that */
  300. SEC_EXP_ATTACH_OPT = 1,
  301. /* legacy, only used by libbpf_get_type_names() and
  302. * libbpf_attach_type_by_name(), not used by libbpf itself at all.
  303. * This used to be associated with cgroup (and few other) BPF programs
  304. * that were attachable through BPF_PROG_ATTACH command. Pretty
  305. * meaningless nowadays, though.
  306. */
  307. SEC_ATTACHABLE = 2,
  308. SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
  309. /* attachment target is specified through BTF ID in either kernel or
  310. * other BPF program's BTF object */
  311. SEC_ATTACH_BTF = 4,
  312. /* BPF program type allows sleeping/blocking in kernel */
  313. SEC_SLEEPABLE = 8,
  314. /* BPF program support non-linear XDP buffer */
  315. SEC_XDP_FRAGS = 16,
  316. };
  317. struct bpf_sec_def {
  318. char *sec;
  319. enum bpf_prog_type prog_type;
  320. enum bpf_attach_type expected_attach_type;
  321. long cookie;
  322. int handler_id;
  323. libbpf_prog_setup_fn_t prog_setup_fn;
  324. libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
  325. libbpf_prog_attach_fn_t prog_attach_fn;
  326. };
  327. /*
  328. * bpf_prog should be a better name but it has been used in
  329. * linux/filter.h.
  330. */
  331. struct bpf_program {
  332. char *name;
  333. char *sec_name;
  334. size_t sec_idx;
  335. const struct bpf_sec_def *sec_def;
  336. /* this program's instruction offset (in number of instructions)
  337. * within its containing ELF section
  338. */
  339. size_t sec_insn_off;
  340. /* number of original instructions in ELF section belonging to this
  341. * program, not taking into account subprogram instructions possible
  342. * appended later during relocation
  343. */
  344. size_t sec_insn_cnt;
  345. /* Offset (in number of instructions) of the start of instruction
  346. * belonging to this BPF program within its containing main BPF
  347. * program. For the entry-point (main) BPF program, this is always
  348. * zero. For a sub-program, this gets reset before each of main BPF
  349. * programs are processed and relocated and is used to determined
  350. * whether sub-program was already appended to the main program, and
  351. * if yes, at which instruction offset.
  352. */
  353. size_t sub_insn_off;
  354. /* instructions that belong to BPF program; insns[0] is located at
  355. * sec_insn_off instruction within its ELF section in ELF file, so
  356. * when mapping ELF file instruction index to the local instruction,
  357. * one needs to subtract sec_insn_off; and vice versa.
  358. */
  359. struct bpf_insn *insns;
  360. /* actual number of instruction in this BPF program's image; for
  361. * entry-point BPF programs this includes the size of main program
  362. * itself plus all the used sub-programs, appended at the end
  363. */
  364. size_t insns_cnt;
  365. struct reloc_desc *reloc_desc;
  366. int nr_reloc;
  367. /* BPF verifier log settings */
  368. char *log_buf;
  369. size_t log_size;
  370. __u32 log_level;
  371. struct bpf_object *obj;
  372. int fd;
  373. bool autoload;
  374. bool autoattach;
  375. bool mark_btf_static;
  376. enum bpf_prog_type type;
  377. enum bpf_attach_type expected_attach_type;
  378. int prog_ifindex;
  379. __u32 attach_btf_obj_fd;
  380. __u32 attach_btf_id;
  381. __u32 attach_prog_fd;
  382. void *func_info;
  383. __u32 func_info_rec_size;
  384. __u32 func_info_cnt;
  385. void *line_info;
  386. __u32 line_info_rec_size;
  387. __u32 line_info_cnt;
  388. __u32 prog_flags;
  389. };
  390. struct bpf_struct_ops {
  391. const char *tname;
  392. const struct btf_type *type;
  393. struct bpf_program **progs;
  394. __u32 *kern_func_off;
  395. /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
  396. void *data;
  397. /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
  398. * btf_vmlinux's format.
  399. * struct bpf_struct_ops_tcp_congestion_ops {
  400. * [... some other kernel fields ...]
  401. * struct tcp_congestion_ops data;
  402. * }
  403. * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
  404. * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
  405. * from "data".
  406. */
  407. void *kern_vdata;
  408. __u32 type_id;
  409. };
  410. #define DATA_SEC ".data"
  411. #define BSS_SEC ".bss"
  412. #define RODATA_SEC ".rodata"
  413. #define KCONFIG_SEC ".kconfig"
  414. #define KSYMS_SEC ".ksyms"
  415. #define STRUCT_OPS_SEC ".struct_ops"
  416. enum libbpf_map_type {
  417. LIBBPF_MAP_UNSPEC,
  418. LIBBPF_MAP_DATA,
  419. LIBBPF_MAP_BSS,
  420. LIBBPF_MAP_RODATA,
  421. LIBBPF_MAP_KCONFIG,
  422. };
  423. struct bpf_map_def {
  424. unsigned int type;
  425. unsigned int key_size;
  426. unsigned int value_size;
  427. unsigned int max_entries;
  428. unsigned int map_flags;
  429. };
  430. struct bpf_map {
  431. struct bpf_object *obj;
  432. char *name;
  433. /* real_name is defined for special internal maps (.rodata*,
  434. * .data*, .bss, .kconfig) and preserves their original ELF section
  435. * name. This is important to be be able to find corresponding BTF
  436. * DATASEC information.
  437. */
  438. char *real_name;
  439. int fd;
  440. int sec_idx;
  441. size_t sec_offset;
  442. int map_ifindex;
  443. int inner_map_fd;
  444. struct bpf_map_def def;
  445. __u32 numa_node;
  446. __u32 btf_var_idx;
  447. __u32 btf_key_type_id;
  448. __u32 btf_value_type_id;
  449. __u32 btf_vmlinux_value_type_id;
  450. enum libbpf_map_type libbpf_type;
  451. void *mmaped;
  452. struct bpf_struct_ops *st_ops;
  453. struct bpf_map *inner_map;
  454. void **init_slots;
  455. int init_slots_sz;
  456. char *pin_path;
  457. bool pinned;
  458. bool reused;
  459. bool autocreate;
  460. __u64 map_extra;
  461. };
  462. enum extern_type {
  463. EXT_UNKNOWN,
  464. EXT_KCFG,
  465. EXT_KSYM,
  466. };
  467. enum kcfg_type {
  468. KCFG_UNKNOWN,
  469. KCFG_CHAR,
  470. KCFG_BOOL,
  471. KCFG_INT,
  472. KCFG_TRISTATE,
  473. KCFG_CHAR_ARR,
  474. };
  475. struct extern_desc {
  476. enum extern_type type;
  477. int sym_idx;
  478. int btf_id;
  479. int sec_btf_id;
  480. const char *name;
  481. bool is_set;
  482. bool is_weak;
  483. union {
  484. struct {
  485. enum kcfg_type type;
  486. int sz;
  487. int align;
  488. int data_off;
  489. bool is_signed;
  490. } kcfg;
  491. struct {
  492. unsigned long long addr;
  493. /* target btf_id of the corresponding kernel var. */
  494. int kernel_btf_obj_fd;
  495. int kernel_btf_id;
  496. /* local btf_id of the ksym extern's type. */
  497. __u32 type_id;
  498. /* BTF fd index to be patched in for insn->off, this is
  499. * 0 for vmlinux BTF, index in obj->fd_array for module
  500. * BTF
  501. */
  502. __s16 btf_fd_idx;
  503. } ksym;
  504. };
  505. };
  506. struct module_btf {
  507. struct btf *btf;
  508. char *name;
  509. __u32 id;
  510. int fd;
  511. int fd_array_idx;
  512. };
  513. enum sec_type {
  514. SEC_UNUSED = 0,
  515. SEC_RELO,
  516. SEC_BSS,
  517. SEC_DATA,
  518. SEC_RODATA,
  519. };
  520. struct elf_sec_desc {
  521. enum sec_type sec_type;
  522. Elf64_Shdr *shdr;
  523. Elf_Data *data;
  524. };
  525. struct elf_state {
  526. int fd;
  527. const void *obj_buf;
  528. size_t obj_buf_sz;
  529. Elf *elf;
  530. Elf64_Ehdr *ehdr;
  531. Elf_Data *symbols;
  532. Elf_Data *st_ops_data;
  533. size_t shstrndx; /* section index for section name strings */
  534. size_t strtabidx;
  535. struct elf_sec_desc *secs;
  536. size_t sec_cnt;
  537. int btf_maps_shndx;
  538. __u32 btf_maps_sec_btf_id;
  539. int text_shndx;
  540. int symbols_shndx;
  541. int st_ops_shndx;
  542. };
  543. struct usdt_manager;
  544. struct bpf_object {
  545. char name[BPF_OBJ_NAME_LEN];
  546. char license[64];
  547. __u32 kern_version;
  548. struct bpf_program *programs;
  549. size_t nr_programs;
  550. struct bpf_map *maps;
  551. size_t nr_maps;
  552. size_t maps_cap;
  553. char *kconfig;
  554. struct extern_desc *externs;
  555. int nr_extern;
  556. int kconfig_map_idx;
  557. bool loaded;
  558. bool has_subcalls;
  559. bool has_rodata;
  560. struct bpf_gen *gen_loader;
  561. /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
  562. struct elf_state efile;
  563. struct btf *btf;
  564. struct btf_ext *btf_ext;
  565. /* Parse and load BTF vmlinux if any of the programs in the object need
  566. * it at load time.
  567. */
  568. struct btf *btf_vmlinux;
  569. /* Path to the custom BTF to be used for BPF CO-RE relocations as an
  570. * override for vmlinux BTF.
  571. */
  572. char *btf_custom_path;
  573. /* vmlinux BTF override for CO-RE relocations */
  574. struct btf *btf_vmlinux_override;
  575. /* Lazily initialized kernel module BTFs */
  576. struct module_btf *btf_modules;
  577. bool btf_modules_loaded;
  578. size_t btf_module_cnt;
  579. size_t btf_module_cap;
  580. /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
  581. char *log_buf;
  582. size_t log_size;
  583. __u32 log_level;
  584. int *fd_array;
  585. size_t fd_array_cap;
  586. size_t fd_array_cnt;
  587. struct usdt_manager *usdt_man;
  588. char path[];
  589. };
  590. static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
  591. static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
  592. static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
  593. static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
  594. static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
  595. static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
  596. static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
  597. static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
  598. static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
  599. void bpf_program__unload(struct bpf_program *prog)
  600. {
  601. if (!prog)
  602. return;
  603. zclose(prog->fd);
  604. zfree(&prog->func_info);
  605. zfree(&prog->line_info);
  606. }
  607. static void bpf_program__exit(struct bpf_program *prog)
  608. {
  609. if (!prog)
  610. return;
  611. bpf_program__unload(prog);
  612. zfree(&prog->name);
  613. zfree(&prog->sec_name);
  614. zfree(&prog->insns);
  615. zfree(&prog->reloc_desc);
  616. prog->nr_reloc = 0;
  617. prog->insns_cnt = 0;
  618. prog->sec_idx = -1;
  619. }
  620. static bool insn_is_subprog_call(const struct bpf_insn *insn)
  621. {
  622. return BPF_CLASS(insn->code) == BPF_JMP &&
  623. BPF_OP(insn->code) == BPF_CALL &&
  624. BPF_SRC(insn->code) == BPF_K &&
  625. insn->src_reg == BPF_PSEUDO_CALL &&
  626. insn->dst_reg == 0 &&
  627. insn->off == 0;
  628. }
  629. static bool is_call_insn(const struct bpf_insn *insn)
  630. {
  631. return insn->code == (BPF_JMP | BPF_CALL);
  632. }
  633. static bool insn_is_pseudo_func(struct bpf_insn *insn)
  634. {
  635. return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
  636. }
  637. static int
  638. bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
  639. const char *name, size_t sec_idx, const char *sec_name,
  640. size_t sec_off, void *insn_data, size_t insn_data_sz)
  641. {
  642. if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
  643. pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
  644. sec_name, name, sec_off, insn_data_sz);
  645. return -EINVAL;
  646. }
  647. memset(prog, 0, sizeof(*prog));
  648. prog->obj = obj;
  649. prog->sec_idx = sec_idx;
  650. prog->sec_insn_off = sec_off / BPF_INSN_SZ;
  651. prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
  652. /* insns_cnt can later be increased by appending used subprograms */
  653. prog->insns_cnt = prog->sec_insn_cnt;
  654. prog->type = BPF_PROG_TYPE_UNSPEC;
  655. prog->fd = -1;
  656. /* libbpf's convention for SEC("?abc...") is that it's just like
  657. * SEC("abc...") but the corresponding bpf_program starts out with
  658. * autoload set to false.
  659. */
  660. if (sec_name[0] == '?') {
  661. prog->autoload = false;
  662. /* from now on forget there was ? in section name */
  663. sec_name++;
  664. } else {
  665. prog->autoload = true;
  666. }
  667. prog->autoattach = true;
  668. /* inherit object's log_level */
  669. prog->log_level = obj->log_level;
  670. prog->sec_name = strdup(sec_name);
  671. if (!prog->sec_name)
  672. goto errout;
  673. prog->name = strdup(name);
  674. if (!prog->name)
  675. goto errout;
  676. prog->insns = malloc(insn_data_sz);
  677. if (!prog->insns)
  678. goto errout;
  679. memcpy(prog->insns, insn_data, insn_data_sz);
  680. return 0;
  681. errout:
  682. pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
  683. bpf_program__exit(prog);
  684. return -ENOMEM;
  685. }
  686. static int
  687. bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
  688. const char *sec_name, int sec_idx)
  689. {
  690. Elf_Data *symbols = obj->efile.symbols;
  691. struct bpf_program *prog, *progs;
  692. void *data = sec_data->d_buf;
  693. size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
  694. int nr_progs, err, i;
  695. const char *name;
  696. Elf64_Sym *sym;
  697. progs = obj->programs;
  698. nr_progs = obj->nr_programs;
  699. nr_syms = symbols->d_size / sizeof(Elf64_Sym);
  700. sec_off = 0;
  701. for (i = 0; i < nr_syms; i++) {
  702. sym = elf_sym_by_idx(obj, i);
  703. if (sym->st_shndx != sec_idx)
  704. continue;
  705. if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
  706. continue;
  707. prog_sz = sym->st_size;
  708. sec_off = sym->st_value;
  709. name = elf_sym_str(obj, sym->st_name);
  710. if (!name) {
  711. pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
  712. sec_name, sec_off);
  713. return -LIBBPF_ERRNO__FORMAT;
  714. }
  715. if (sec_off + prog_sz > sec_sz) {
  716. pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
  717. sec_name, sec_off);
  718. return -LIBBPF_ERRNO__FORMAT;
  719. }
  720. if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
  721. pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
  722. return -ENOTSUP;
  723. }
  724. pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
  725. sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
  726. progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
  727. if (!progs) {
  728. /*
  729. * In this case the original obj->programs
  730. * is still valid, so don't need special treat for
  731. * bpf_close_object().
  732. */
  733. pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
  734. sec_name, name);
  735. return -ENOMEM;
  736. }
  737. obj->programs = progs;
  738. prog = &progs[nr_progs];
  739. err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
  740. sec_off, data + sec_off, prog_sz);
  741. if (err)
  742. return err;
  743. /* if function is a global/weak symbol, but has restricted
  744. * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
  745. * as static to enable more permissive BPF verification mode
  746. * with more outside context available to BPF verifier
  747. */
  748. if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
  749. && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
  750. || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
  751. prog->mark_btf_static = true;
  752. nr_progs++;
  753. obj->nr_programs = nr_progs;
  754. }
  755. return 0;
  756. }
  757. __u32 get_kernel_version(void)
  758. {
  759. /* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
  760. * but Ubuntu provides /proc/version_signature file, as described at
  761. * https://ubuntu.com/kernel, with an example contents below, which we
  762. * can use to get a proper LINUX_VERSION_CODE.
  763. *
  764. * Ubuntu 5.4.0-12.15-generic 5.4.8
  765. *
  766. * In the above, 5.4.8 is what kernel is actually expecting, while
  767. * uname() call will return 5.4.0 in info.release.
  768. */
  769. const char *ubuntu_kver_file = "/proc/version_signature";
  770. __u32 major, minor, patch;
  771. struct utsname info;
  772. if (faccessat(AT_FDCWD, ubuntu_kver_file, R_OK, AT_EACCESS) == 0) {
  773. FILE *f;
  774. f = fopen(ubuntu_kver_file, "r");
  775. if (f) {
  776. if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
  777. fclose(f);
  778. return KERNEL_VERSION(major, minor, patch);
  779. }
  780. fclose(f);
  781. }
  782. /* something went wrong, fall back to uname() approach */
  783. }
  784. uname(&info);
  785. if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
  786. return 0;
  787. return KERNEL_VERSION(major, minor, patch);
  788. }
  789. static const struct btf_member *
  790. find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
  791. {
  792. struct btf_member *m;
  793. int i;
  794. for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
  795. if (btf_member_bit_offset(t, i) == bit_offset)
  796. return m;
  797. }
  798. return NULL;
  799. }
  800. static const struct btf_member *
  801. find_member_by_name(const struct btf *btf, const struct btf_type *t,
  802. const char *name)
  803. {
  804. struct btf_member *m;
  805. int i;
  806. for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
  807. if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
  808. return m;
  809. }
  810. return NULL;
  811. }
  812. #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
  813. static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
  814. const char *name, __u32 kind);
  815. static int
  816. find_struct_ops_kern_types(const struct btf *btf, const char *tname,
  817. const struct btf_type **type, __u32 *type_id,
  818. const struct btf_type **vtype, __u32 *vtype_id,
  819. const struct btf_member **data_member)
  820. {
  821. const struct btf_type *kern_type, *kern_vtype;
  822. const struct btf_member *kern_data_member;
  823. __s32 kern_vtype_id, kern_type_id;
  824. __u32 i;
  825. kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
  826. if (kern_type_id < 0) {
  827. pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
  828. tname);
  829. return kern_type_id;
  830. }
  831. kern_type = btf__type_by_id(btf, kern_type_id);
  832. /* Find the corresponding "map_value" type that will be used
  833. * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
  834. * find "struct bpf_struct_ops_tcp_congestion_ops" from the
  835. * btf_vmlinux.
  836. */
  837. kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
  838. tname, BTF_KIND_STRUCT);
  839. if (kern_vtype_id < 0) {
  840. pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
  841. STRUCT_OPS_VALUE_PREFIX, tname);
  842. return kern_vtype_id;
  843. }
  844. kern_vtype = btf__type_by_id(btf, kern_vtype_id);
  845. /* Find "struct tcp_congestion_ops" from
  846. * struct bpf_struct_ops_tcp_congestion_ops {
  847. * [ ... ]
  848. * struct tcp_congestion_ops data;
  849. * }
  850. */
  851. kern_data_member = btf_members(kern_vtype);
  852. for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
  853. if (kern_data_member->type == kern_type_id)
  854. break;
  855. }
  856. if (i == btf_vlen(kern_vtype)) {
  857. pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
  858. tname, STRUCT_OPS_VALUE_PREFIX, tname);
  859. return -EINVAL;
  860. }
  861. *type = kern_type;
  862. *type_id = kern_type_id;
  863. *vtype = kern_vtype;
  864. *vtype_id = kern_vtype_id;
  865. *data_member = kern_data_member;
  866. return 0;
  867. }
  868. static bool bpf_map__is_struct_ops(const struct bpf_map *map)
  869. {
  870. return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
  871. }
  872. /* Init the map's fields that depend on kern_btf */
  873. static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
  874. const struct btf *btf,
  875. const struct btf *kern_btf)
  876. {
  877. const struct btf_member *member, *kern_member, *kern_data_member;
  878. const struct btf_type *type, *kern_type, *kern_vtype;
  879. __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
  880. struct bpf_struct_ops *st_ops;
  881. void *data, *kern_data;
  882. const char *tname;
  883. int err;
  884. st_ops = map->st_ops;
  885. type = st_ops->type;
  886. tname = st_ops->tname;
  887. err = find_struct_ops_kern_types(kern_btf, tname,
  888. &kern_type, &kern_type_id,
  889. &kern_vtype, &kern_vtype_id,
  890. &kern_data_member);
  891. if (err)
  892. return err;
  893. pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
  894. map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
  895. map->def.value_size = kern_vtype->size;
  896. map->btf_vmlinux_value_type_id = kern_vtype_id;
  897. st_ops->kern_vdata = calloc(1, kern_vtype->size);
  898. if (!st_ops->kern_vdata)
  899. return -ENOMEM;
  900. data = st_ops->data;
  901. kern_data_off = kern_data_member->offset / 8;
  902. kern_data = st_ops->kern_vdata + kern_data_off;
  903. member = btf_members(type);
  904. for (i = 0; i < btf_vlen(type); i++, member++) {
  905. const struct btf_type *mtype, *kern_mtype;
  906. __u32 mtype_id, kern_mtype_id;
  907. void *mdata, *kern_mdata;
  908. __s64 msize, kern_msize;
  909. __u32 moff, kern_moff;
  910. __u32 kern_member_idx;
  911. const char *mname;
  912. mname = btf__name_by_offset(btf, member->name_off);
  913. kern_member = find_member_by_name(kern_btf, kern_type, mname);
  914. if (!kern_member) {
  915. pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
  916. map->name, mname);
  917. return -ENOTSUP;
  918. }
  919. kern_member_idx = kern_member - btf_members(kern_type);
  920. if (btf_member_bitfield_size(type, i) ||
  921. btf_member_bitfield_size(kern_type, kern_member_idx)) {
  922. pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
  923. map->name, mname);
  924. return -ENOTSUP;
  925. }
  926. moff = member->offset / 8;
  927. kern_moff = kern_member->offset / 8;
  928. mdata = data + moff;
  929. kern_mdata = kern_data + kern_moff;
  930. mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
  931. kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
  932. &kern_mtype_id);
  933. if (BTF_INFO_KIND(mtype->info) !=
  934. BTF_INFO_KIND(kern_mtype->info)) {
  935. pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
  936. map->name, mname, BTF_INFO_KIND(mtype->info),
  937. BTF_INFO_KIND(kern_mtype->info));
  938. return -ENOTSUP;
  939. }
  940. if (btf_is_ptr(mtype)) {
  941. struct bpf_program *prog;
  942. prog = st_ops->progs[i];
  943. if (!prog)
  944. continue;
  945. kern_mtype = skip_mods_and_typedefs(kern_btf,
  946. kern_mtype->type,
  947. &kern_mtype_id);
  948. /* mtype->type must be a func_proto which was
  949. * guaranteed in bpf_object__collect_st_ops_relos(),
  950. * so only check kern_mtype for func_proto here.
  951. */
  952. if (!btf_is_func_proto(kern_mtype)) {
  953. pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
  954. map->name, mname);
  955. return -ENOTSUP;
  956. }
  957. prog->attach_btf_id = kern_type_id;
  958. prog->expected_attach_type = kern_member_idx;
  959. st_ops->kern_func_off[i] = kern_data_off + kern_moff;
  960. pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
  961. map->name, mname, prog->name, moff,
  962. kern_moff);
  963. continue;
  964. }
  965. msize = btf__resolve_size(btf, mtype_id);
  966. kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
  967. if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
  968. pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
  969. map->name, mname, (ssize_t)msize,
  970. (ssize_t)kern_msize);
  971. return -ENOTSUP;
  972. }
  973. pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
  974. map->name, mname, (unsigned int)msize,
  975. moff, kern_moff);
  976. memcpy(kern_mdata, mdata, msize);
  977. }
  978. return 0;
  979. }
  980. static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
  981. {
  982. struct bpf_map *map;
  983. size_t i;
  984. int err;
  985. for (i = 0; i < obj->nr_maps; i++) {
  986. map = &obj->maps[i];
  987. if (!bpf_map__is_struct_ops(map))
  988. continue;
  989. err = bpf_map__init_kern_struct_ops(map, obj->btf,
  990. obj->btf_vmlinux);
  991. if (err)
  992. return err;
  993. }
  994. return 0;
  995. }
  996. static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
  997. {
  998. const struct btf_type *type, *datasec;
  999. const struct btf_var_secinfo *vsi;
  1000. struct bpf_struct_ops *st_ops;
  1001. const char *tname, *var_name;
  1002. __s32 type_id, datasec_id;
  1003. const struct btf *btf;
  1004. struct bpf_map *map;
  1005. __u32 i;
  1006. if (obj->efile.st_ops_shndx == -1)
  1007. return 0;
  1008. btf = obj->btf;
  1009. datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
  1010. BTF_KIND_DATASEC);
  1011. if (datasec_id < 0) {
  1012. pr_warn("struct_ops init: DATASEC %s not found\n",
  1013. STRUCT_OPS_SEC);
  1014. return -EINVAL;
  1015. }
  1016. datasec = btf__type_by_id(btf, datasec_id);
  1017. vsi = btf_var_secinfos(datasec);
  1018. for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
  1019. type = btf__type_by_id(obj->btf, vsi->type);
  1020. var_name = btf__name_by_offset(obj->btf, type->name_off);
  1021. type_id = btf__resolve_type(obj->btf, vsi->type);
  1022. if (type_id < 0) {
  1023. pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
  1024. vsi->type, STRUCT_OPS_SEC);
  1025. return -EINVAL;
  1026. }
  1027. type = btf__type_by_id(obj->btf, type_id);
  1028. tname = btf__name_by_offset(obj->btf, type->name_off);
  1029. if (!tname[0]) {
  1030. pr_warn("struct_ops init: anonymous type is not supported\n");
  1031. return -ENOTSUP;
  1032. }
  1033. if (!btf_is_struct(type)) {
  1034. pr_warn("struct_ops init: %s is not a struct\n", tname);
  1035. return -EINVAL;
  1036. }
  1037. map = bpf_object__add_map(obj);
  1038. if (IS_ERR(map))
  1039. return PTR_ERR(map);
  1040. map->sec_idx = obj->efile.st_ops_shndx;
  1041. map->sec_offset = vsi->offset;
  1042. map->name = strdup(var_name);
  1043. if (!map->name)
  1044. return -ENOMEM;
  1045. map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
  1046. map->def.key_size = sizeof(int);
  1047. map->def.value_size = type->size;
  1048. map->def.max_entries = 1;
  1049. map->st_ops = calloc(1, sizeof(*map->st_ops));
  1050. if (!map->st_ops)
  1051. return -ENOMEM;
  1052. st_ops = map->st_ops;
  1053. st_ops->data = malloc(type->size);
  1054. st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
  1055. st_ops->kern_func_off = malloc(btf_vlen(type) *
  1056. sizeof(*st_ops->kern_func_off));
  1057. if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
  1058. return -ENOMEM;
  1059. if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
  1060. pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
  1061. var_name, STRUCT_OPS_SEC);
  1062. return -EINVAL;
  1063. }
  1064. memcpy(st_ops->data,
  1065. obj->efile.st_ops_data->d_buf + vsi->offset,
  1066. type->size);
  1067. st_ops->tname = tname;
  1068. st_ops->type = type;
  1069. st_ops->type_id = type_id;
  1070. pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
  1071. tname, type_id, var_name, vsi->offset);
  1072. }
  1073. return 0;
  1074. }
  1075. static struct bpf_object *bpf_object__new(const char *path,
  1076. const void *obj_buf,
  1077. size_t obj_buf_sz,
  1078. const char *obj_name)
  1079. {
  1080. struct bpf_object *obj;
  1081. char *end;
  1082. obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
  1083. if (!obj) {
  1084. pr_warn("alloc memory failed for %s\n", path);
  1085. return ERR_PTR(-ENOMEM);
  1086. }
  1087. strcpy(obj->path, path);
  1088. if (obj_name) {
  1089. libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
  1090. } else {
  1091. /* Using basename() GNU version which doesn't modify arg. */
  1092. libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
  1093. end = strchr(obj->name, '.');
  1094. if (end)
  1095. *end = 0;
  1096. }
  1097. obj->efile.fd = -1;
  1098. /*
  1099. * Caller of this function should also call
  1100. * bpf_object__elf_finish() after data collection to return
  1101. * obj_buf to user. If not, we should duplicate the buffer to
  1102. * avoid user freeing them before elf finish.
  1103. */
  1104. obj->efile.obj_buf = obj_buf;
  1105. obj->efile.obj_buf_sz = obj_buf_sz;
  1106. obj->efile.btf_maps_shndx = -1;
  1107. obj->efile.st_ops_shndx = -1;
  1108. obj->kconfig_map_idx = -1;
  1109. obj->kern_version = get_kernel_version();
  1110. obj->loaded = false;
  1111. return obj;
  1112. }
  1113. static void bpf_object__elf_finish(struct bpf_object *obj)
  1114. {
  1115. if (!obj->efile.elf)
  1116. return;
  1117. elf_end(obj->efile.elf);
  1118. obj->efile.elf = NULL;
  1119. obj->efile.symbols = NULL;
  1120. obj->efile.st_ops_data = NULL;
  1121. zfree(&obj->efile.secs);
  1122. obj->efile.sec_cnt = 0;
  1123. zclose(obj->efile.fd);
  1124. obj->efile.obj_buf = NULL;
  1125. obj->efile.obj_buf_sz = 0;
  1126. }
  1127. static int bpf_object__elf_init(struct bpf_object *obj)
  1128. {
  1129. Elf64_Ehdr *ehdr;
  1130. int err = 0;
  1131. Elf *elf;
  1132. if (obj->efile.elf) {
  1133. pr_warn("elf: init internal error\n");
  1134. return -LIBBPF_ERRNO__LIBELF;
  1135. }
  1136. if (obj->efile.obj_buf_sz > 0) {
  1137. /* obj_buf should have been validated by bpf_object__open_mem(). */
  1138. elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
  1139. } else {
  1140. obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
  1141. if (obj->efile.fd < 0) {
  1142. char errmsg[STRERR_BUFSIZE], *cp;
  1143. err = -errno;
  1144. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  1145. pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
  1146. return err;
  1147. }
  1148. elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
  1149. }
  1150. if (!elf) {
  1151. pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
  1152. err = -LIBBPF_ERRNO__LIBELF;
  1153. goto errout;
  1154. }
  1155. obj->efile.elf = elf;
  1156. if (elf_kind(elf) != ELF_K_ELF) {
  1157. err = -LIBBPF_ERRNO__FORMAT;
  1158. pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
  1159. goto errout;
  1160. }
  1161. if (gelf_getclass(elf) != ELFCLASS64) {
  1162. err = -LIBBPF_ERRNO__FORMAT;
  1163. pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
  1164. goto errout;
  1165. }
  1166. obj->efile.ehdr = ehdr = elf64_getehdr(elf);
  1167. if (!obj->efile.ehdr) {
  1168. pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
  1169. err = -LIBBPF_ERRNO__FORMAT;
  1170. goto errout;
  1171. }
  1172. if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
  1173. pr_warn("elf: failed to get section names section index for %s: %s\n",
  1174. obj->path, elf_errmsg(-1));
  1175. err = -LIBBPF_ERRNO__FORMAT;
  1176. goto errout;
  1177. }
  1178. /* Elf is corrupted/truncated, avoid calling elf_strptr. */
  1179. if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
  1180. pr_warn("elf: failed to get section names strings from %s: %s\n",
  1181. obj->path, elf_errmsg(-1));
  1182. err = -LIBBPF_ERRNO__FORMAT;
  1183. goto errout;
  1184. }
  1185. /* Old LLVM set e_machine to EM_NONE */
  1186. if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
  1187. pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
  1188. err = -LIBBPF_ERRNO__FORMAT;
  1189. goto errout;
  1190. }
  1191. return 0;
  1192. errout:
  1193. bpf_object__elf_finish(obj);
  1194. return err;
  1195. }
  1196. static int bpf_object__check_endianness(struct bpf_object *obj)
  1197. {
  1198. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  1199. if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
  1200. return 0;
  1201. #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  1202. if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
  1203. return 0;
  1204. #else
  1205. # error "Unrecognized __BYTE_ORDER__"
  1206. #endif
  1207. pr_warn("elf: endianness mismatch in %s.\n", obj->path);
  1208. return -LIBBPF_ERRNO__ENDIAN;
  1209. }
  1210. static int
  1211. bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
  1212. {
  1213. if (!data) {
  1214. pr_warn("invalid license section in %s\n", obj->path);
  1215. return -LIBBPF_ERRNO__FORMAT;
  1216. }
  1217. /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
  1218. * go over allowed ELF data section buffer
  1219. */
  1220. libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
  1221. pr_debug("license of %s is %s\n", obj->path, obj->license);
  1222. return 0;
  1223. }
  1224. static int
  1225. bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
  1226. {
  1227. __u32 kver;
  1228. if (!data || size != sizeof(kver)) {
  1229. pr_warn("invalid kver section in %s\n", obj->path);
  1230. return -LIBBPF_ERRNO__FORMAT;
  1231. }
  1232. memcpy(&kver, data, sizeof(kver));
  1233. obj->kern_version = kver;
  1234. pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
  1235. return 0;
  1236. }
  1237. static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
  1238. {
  1239. if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
  1240. type == BPF_MAP_TYPE_HASH_OF_MAPS)
  1241. return true;
  1242. return false;
  1243. }
  1244. static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
  1245. {
  1246. Elf_Data *data;
  1247. Elf_Scn *scn;
  1248. if (!name)
  1249. return -EINVAL;
  1250. scn = elf_sec_by_name(obj, name);
  1251. data = elf_sec_data(obj, scn);
  1252. if (data) {
  1253. *size = data->d_size;
  1254. return 0; /* found it */
  1255. }
  1256. return -ENOENT;
  1257. }
  1258. static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
  1259. {
  1260. Elf_Data *symbols = obj->efile.symbols;
  1261. const char *sname;
  1262. size_t si;
  1263. if (!name || !off)
  1264. return -EINVAL;
  1265. for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
  1266. Elf64_Sym *sym = elf_sym_by_idx(obj, si);
  1267. if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
  1268. continue;
  1269. if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
  1270. ELF64_ST_BIND(sym->st_info) != STB_WEAK)
  1271. continue;
  1272. sname = elf_sym_str(obj, sym->st_name);
  1273. if (!sname) {
  1274. pr_warn("failed to get sym name string for var %s\n", name);
  1275. return -EIO;
  1276. }
  1277. if (strcmp(name, sname) == 0) {
  1278. *off = sym->st_value;
  1279. return 0;
  1280. }
  1281. }
  1282. return -ENOENT;
  1283. }
  1284. static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
  1285. {
  1286. struct bpf_map *map;
  1287. int err;
  1288. err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
  1289. sizeof(*obj->maps), obj->nr_maps + 1);
  1290. if (err)
  1291. return ERR_PTR(err);
  1292. map = &obj->maps[obj->nr_maps++];
  1293. map->obj = obj;
  1294. map->fd = -1;
  1295. map->inner_map_fd = -1;
  1296. map->autocreate = true;
  1297. return map;
  1298. }
  1299. static size_t bpf_map_mmap_sz(const struct bpf_map *map)
  1300. {
  1301. long page_sz = sysconf(_SC_PAGE_SIZE);
  1302. size_t map_sz;
  1303. map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
  1304. map_sz = roundup(map_sz, page_sz);
  1305. return map_sz;
  1306. }
  1307. static char *internal_map_name(struct bpf_object *obj, const char *real_name)
  1308. {
  1309. char map_name[BPF_OBJ_NAME_LEN], *p;
  1310. int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
  1311. /* This is one of the more confusing parts of libbpf for various
  1312. * reasons, some of which are historical. The original idea for naming
  1313. * internal names was to include as much of BPF object name prefix as
  1314. * possible, so that it can be distinguished from similar internal
  1315. * maps of a different BPF object.
  1316. * As an example, let's say we have bpf_object named 'my_object_name'
  1317. * and internal map corresponding to '.rodata' ELF section. The final
  1318. * map name advertised to user and to the kernel will be
  1319. * 'my_objec.rodata', taking first 8 characters of object name and
  1320. * entire 7 characters of '.rodata'.
  1321. * Somewhat confusingly, if internal map ELF section name is shorter
  1322. * than 7 characters, e.g., '.bss', we still reserve 7 characters
  1323. * for the suffix, even though we only have 4 actual characters, and
  1324. * resulting map will be called 'my_objec.bss', not even using all 15
  1325. * characters allowed by the kernel. Oh well, at least the truncated
  1326. * object name is somewhat consistent in this case. But if the map
  1327. * name is '.kconfig', we'll still have entirety of '.kconfig' added
  1328. * (8 chars) and thus will be left with only first 7 characters of the
  1329. * object name ('my_obje'). Happy guessing, user, that the final map
  1330. * name will be "my_obje.kconfig".
  1331. * Now, with libbpf starting to support arbitrarily named .rodata.*
  1332. * and .data.* data sections, it's possible that ELF section name is
  1333. * longer than allowed 15 chars, so we now need to be careful to take
  1334. * only up to 15 first characters of ELF name, taking no BPF object
  1335. * name characters at all. So '.rodata.abracadabra' will result in
  1336. * '.rodata.abracad' kernel and user-visible name.
  1337. * We need to keep this convoluted logic intact for .data, .bss and
  1338. * .rodata maps, but for new custom .data.custom and .rodata.custom
  1339. * maps we use their ELF names as is, not prepending bpf_object name
  1340. * in front. We still need to truncate them to 15 characters for the
  1341. * kernel. Full name can be recovered for such maps by using DATASEC
  1342. * BTF type associated with such map's value type, though.
  1343. */
  1344. if (sfx_len >= BPF_OBJ_NAME_LEN)
  1345. sfx_len = BPF_OBJ_NAME_LEN - 1;
  1346. /* if there are two or more dots in map name, it's a custom dot map */
  1347. if (strchr(real_name + 1, '.') != NULL)
  1348. pfx_len = 0;
  1349. else
  1350. pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
  1351. snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
  1352. sfx_len, real_name);
  1353. /* sanitise map name to characters allowed by kernel */
  1354. for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
  1355. if (!isalnum(*p) && *p != '_' && *p != '.')
  1356. *p = '_';
  1357. return strdup(map_name);
  1358. }
  1359. static int
  1360. bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map);
  1361. static int
  1362. bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
  1363. const char *real_name, int sec_idx, void *data, size_t data_sz)
  1364. {
  1365. struct bpf_map_def *def;
  1366. struct bpf_map *map;
  1367. int err;
  1368. map = bpf_object__add_map(obj);
  1369. if (IS_ERR(map))
  1370. return PTR_ERR(map);
  1371. map->libbpf_type = type;
  1372. map->sec_idx = sec_idx;
  1373. map->sec_offset = 0;
  1374. map->real_name = strdup(real_name);
  1375. map->name = internal_map_name(obj, real_name);
  1376. if (!map->real_name || !map->name) {
  1377. zfree(&map->real_name);
  1378. zfree(&map->name);
  1379. return -ENOMEM;
  1380. }
  1381. def = &map->def;
  1382. def->type = BPF_MAP_TYPE_ARRAY;
  1383. def->key_size = sizeof(int);
  1384. def->value_size = data_sz;
  1385. def->max_entries = 1;
  1386. def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
  1387. ? BPF_F_RDONLY_PROG : 0;
  1388. def->map_flags |= BPF_F_MMAPABLE;
  1389. pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
  1390. map->name, map->sec_idx, map->sec_offset, def->map_flags);
  1391. map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
  1392. MAP_SHARED | MAP_ANONYMOUS, -1, 0);
  1393. if (map->mmaped == MAP_FAILED) {
  1394. err = -errno;
  1395. map->mmaped = NULL;
  1396. pr_warn("failed to alloc map '%s' content buffer: %d\n",
  1397. map->name, err);
  1398. zfree(&map->real_name);
  1399. zfree(&map->name);
  1400. return err;
  1401. }
  1402. /* failures are fine because of maps like .rodata.str1.1 */
  1403. (void) bpf_map_find_btf_info(obj, map);
  1404. if (data)
  1405. memcpy(map->mmaped, data, data_sz);
  1406. pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
  1407. return 0;
  1408. }
  1409. static int bpf_object__init_global_data_maps(struct bpf_object *obj)
  1410. {
  1411. struct elf_sec_desc *sec_desc;
  1412. const char *sec_name;
  1413. int err = 0, sec_idx;
  1414. /*
  1415. * Populate obj->maps with libbpf internal maps.
  1416. */
  1417. for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
  1418. sec_desc = &obj->efile.secs[sec_idx];
  1419. /* Skip recognized sections with size 0. */
  1420. if (!sec_desc->data || sec_desc->data->d_size == 0)
  1421. continue;
  1422. switch (sec_desc->sec_type) {
  1423. case SEC_DATA:
  1424. sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
  1425. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
  1426. sec_name, sec_idx,
  1427. sec_desc->data->d_buf,
  1428. sec_desc->data->d_size);
  1429. break;
  1430. case SEC_RODATA:
  1431. obj->has_rodata = true;
  1432. sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
  1433. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
  1434. sec_name, sec_idx,
  1435. sec_desc->data->d_buf,
  1436. sec_desc->data->d_size);
  1437. break;
  1438. case SEC_BSS:
  1439. sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
  1440. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
  1441. sec_name, sec_idx,
  1442. NULL,
  1443. sec_desc->data->d_size);
  1444. break;
  1445. default:
  1446. /* skip */
  1447. break;
  1448. }
  1449. if (err)
  1450. return err;
  1451. }
  1452. return 0;
  1453. }
  1454. static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
  1455. const void *name)
  1456. {
  1457. int i;
  1458. for (i = 0; i < obj->nr_extern; i++) {
  1459. if (strcmp(obj->externs[i].name, name) == 0)
  1460. return &obj->externs[i];
  1461. }
  1462. return NULL;
  1463. }
  1464. static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
  1465. char value)
  1466. {
  1467. switch (ext->kcfg.type) {
  1468. case KCFG_BOOL:
  1469. if (value == 'm') {
  1470. pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
  1471. ext->name, value);
  1472. return -EINVAL;
  1473. }
  1474. *(bool *)ext_val = value == 'y' ? true : false;
  1475. break;
  1476. case KCFG_TRISTATE:
  1477. if (value == 'y')
  1478. *(enum libbpf_tristate *)ext_val = TRI_YES;
  1479. else if (value == 'm')
  1480. *(enum libbpf_tristate *)ext_val = TRI_MODULE;
  1481. else /* value == 'n' */
  1482. *(enum libbpf_tristate *)ext_val = TRI_NO;
  1483. break;
  1484. case KCFG_CHAR:
  1485. *(char *)ext_val = value;
  1486. break;
  1487. case KCFG_UNKNOWN:
  1488. case KCFG_INT:
  1489. case KCFG_CHAR_ARR:
  1490. default:
  1491. pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
  1492. ext->name, value);
  1493. return -EINVAL;
  1494. }
  1495. ext->is_set = true;
  1496. return 0;
  1497. }
  1498. static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
  1499. const char *value)
  1500. {
  1501. size_t len;
  1502. if (ext->kcfg.type != KCFG_CHAR_ARR) {
  1503. pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
  1504. ext->name, value);
  1505. return -EINVAL;
  1506. }
  1507. len = strlen(value);
  1508. if (value[len - 1] != '"') {
  1509. pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
  1510. ext->name, value);
  1511. return -EINVAL;
  1512. }
  1513. /* strip quotes */
  1514. len -= 2;
  1515. if (len >= ext->kcfg.sz) {
  1516. pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
  1517. ext->name, value, len, ext->kcfg.sz - 1);
  1518. len = ext->kcfg.sz - 1;
  1519. }
  1520. memcpy(ext_val, value + 1, len);
  1521. ext_val[len] = '\0';
  1522. ext->is_set = true;
  1523. return 0;
  1524. }
  1525. static int parse_u64(const char *value, __u64 *res)
  1526. {
  1527. char *value_end;
  1528. int err;
  1529. errno = 0;
  1530. *res = strtoull(value, &value_end, 0);
  1531. if (errno) {
  1532. err = -errno;
  1533. pr_warn("failed to parse '%s' as integer: %d\n", value, err);
  1534. return err;
  1535. }
  1536. if (*value_end) {
  1537. pr_warn("failed to parse '%s' as integer completely\n", value);
  1538. return -EINVAL;
  1539. }
  1540. return 0;
  1541. }
  1542. static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
  1543. {
  1544. int bit_sz = ext->kcfg.sz * 8;
  1545. if (ext->kcfg.sz == 8)
  1546. return true;
  1547. /* Validate that value stored in u64 fits in integer of `ext->sz`
  1548. * bytes size without any loss of information. If the target integer
  1549. * is signed, we rely on the following limits of integer type of
  1550. * Y bits and subsequent transformation:
  1551. *
  1552. * -2^(Y-1) <= X <= 2^(Y-1) - 1
  1553. * 0 <= X + 2^(Y-1) <= 2^Y - 1
  1554. * 0 <= X + 2^(Y-1) < 2^Y
  1555. *
  1556. * For unsigned target integer, check that all the (64 - Y) bits are
  1557. * zero.
  1558. */
  1559. if (ext->kcfg.is_signed)
  1560. return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
  1561. else
  1562. return (v >> bit_sz) == 0;
  1563. }
  1564. static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
  1565. __u64 value)
  1566. {
  1567. if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
  1568. ext->kcfg.type != KCFG_BOOL) {
  1569. pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
  1570. ext->name, (unsigned long long)value);
  1571. return -EINVAL;
  1572. }
  1573. if (ext->kcfg.type == KCFG_BOOL && value > 1) {
  1574. pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
  1575. ext->name, (unsigned long long)value);
  1576. return -EINVAL;
  1577. }
  1578. if (!is_kcfg_value_in_range(ext, value)) {
  1579. pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
  1580. ext->name, (unsigned long long)value, ext->kcfg.sz);
  1581. return -ERANGE;
  1582. }
  1583. switch (ext->kcfg.sz) {
  1584. case 1: *(__u8 *)ext_val = value; break;
  1585. case 2: *(__u16 *)ext_val = value; break;
  1586. case 4: *(__u32 *)ext_val = value; break;
  1587. case 8: *(__u64 *)ext_val = value; break;
  1588. default:
  1589. return -EINVAL;
  1590. }
  1591. ext->is_set = true;
  1592. return 0;
  1593. }
  1594. static int bpf_object__process_kconfig_line(struct bpf_object *obj,
  1595. char *buf, void *data)
  1596. {
  1597. struct extern_desc *ext;
  1598. char *sep, *value;
  1599. int len, err = 0;
  1600. void *ext_val;
  1601. __u64 num;
  1602. if (!str_has_pfx(buf, "CONFIG_"))
  1603. return 0;
  1604. sep = strchr(buf, '=');
  1605. if (!sep) {
  1606. pr_warn("failed to parse '%s': no separator\n", buf);
  1607. return -EINVAL;
  1608. }
  1609. /* Trim ending '\n' */
  1610. len = strlen(buf);
  1611. if (buf[len - 1] == '\n')
  1612. buf[len - 1] = '\0';
  1613. /* Split on '=' and ensure that a value is present. */
  1614. *sep = '\0';
  1615. if (!sep[1]) {
  1616. *sep = '=';
  1617. pr_warn("failed to parse '%s': no value\n", buf);
  1618. return -EINVAL;
  1619. }
  1620. ext = find_extern_by_name(obj, buf);
  1621. if (!ext || ext->is_set)
  1622. return 0;
  1623. ext_val = data + ext->kcfg.data_off;
  1624. value = sep + 1;
  1625. switch (*value) {
  1626. case 'y': case 'n': case 'm':
  1627. err = set_kcfg_value_tri(ext, ext_val, *value);
  1628. break;
  1629. case '"':
  1630. err = set_kcfg_value_str(ext, ext_val, value);
  1631. break;
  1632. default:
  1633. /* assume integer */
  1634. err = parse_u64(value, &num);
  1635. if (err) {
  1636. pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
  1637. return err;
  1638. }
  1639. if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
  1640. pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
  1641. return -EINVAL;
  1642. }
  1643. err = set_kcfg_value_num(ext, ext_val, num);
  1644. break;
  1645. }
  1646. if (err)
  1647. return err;
  1648. pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
  1649. return 0;
  1650. }
  1651. static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
  1652. {
  1653. char buf[PATH_MAX];
  1654. struct utsname uts;
  1655. int len, err = 0;
  1656. gzFile file;
  1657. uname(&uts);
  1658. len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
  1659. if (len < 0)
  1660. return -EINVAL;
  1661. else if (len >= PATH_MAX)
  1662. return -ENAMETOOLONG;
  1663. /* gzopen also accepts uncompressed files. */
  1664. file = gzopen(buf, "r");
  1665. if (!file)
  1666. file = gzopen("/proc/config.gz", "r");
  1667. if (!file) {
  1668. pr_warn("failed to open system Kconfig\n");
  1669. return -ENOENT;
  1670. }
  1671. while (gzgets(file, buf, sizeof(buf))) {
  1672. err = bpf_object__process_kconfig_line(obj, buf, data);
  1673. if (err) {
  1674. pr_warn("error parsing system Kconfig line '%s': %d\n",
  1675. buf, err);
  1676. goto out;
  1677. }
  1678. }
  1679. out:
  1680. gzclose(file);
  1681. return err;
  1682. }
  1683. static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
  1684. const char *config, void *data)
  1685. {
  1686. char buf[PATH_MAX];
  1687. int err = 0;
  1688. FILE *file;
  1689. file = fmemopen((void *)config, strlen(config), "r");
  1690. if (!file) {
  1691. err = -errno;
  1692. pr_warn("failed to open in-memory Kconfig: %d\n", err);
  1693. return err;
  1694. }
  1695. while (fgets(buf, sizeof(buf), file)) {
  1696. err = bpf_object__process_kconfig_line(obj, buf, data);
  1697. if (err) {
  1698. pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
  1699. buf, err);
  1700. break;
  1701. }
  1702. }
  1703. fclose(file);
  1704. return err;
  1705. }
  1706. static int bpf_object__init_kconfig_map(struct bpf_object *obj)
  1707. {
  1708. struct extern_desc *last_ext = NULL, *ext;
  1709. size_t map_sz;
  1710. int i, err;
  1711. for (i = 0; i < obj->nr_extern; i++) {
  1712. ext = &obj->externs[i];
  1713. if (ext->type == EXT_KCFG)
  1714. last_ext = ext;
  1715. }
  1716. if (!last_ext)
  1717. return 0;
  1718. map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
  1719. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
  1720. ".kconfig", obj->efile.symbols_shndx,
  1721. NULL, map_sz);
  1722. if (err)
  1723. return err;
  1724. obj->kconfig_map_idx = obj->nr_maps - 1;
  1725. return 0;
  1726. }
  1727. const struct btf_type *
  1728. skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
  1729. {
  1730. const struct btf_type *t = btf__type_by_id(btf, id);
  1731. if (res_id)
  1732. *res_id = id;
  1733. while (btf_is_mod(t) || btf_is_typedef(t)) {
  1734. if (res_id)
  1735. *res_id = t->type;
  1736. t = btf__type_by_id(btf, t->type);
  1737. }
  1738. return t;
  1739. }
  1740. static const struct btf_type *
  1741. resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
  1742. {
  1743. const struct btf_type *t;
  1744. t = skip_mods_and_typedefs(btf, id, NULL);
  1745. if (!btf_is_ptr(t))
  1746. return NULL;
  1747. t = skip_mods_and_typedefs(btf, t->type, res_id);
  1748. return btf_is_func_proto(t) ? t : NULL;
  1749. }
  1750. static const char *__btf_kind_str(__u16 kind)
  1751. {
  1752. switch (kind) {
  1753. case BTF_KIND_UNKN: return "void";
  1754. case BTF_KIND_INT: return "int";
  1755. case BTF_KIND_PTR: return "ptr";
  1756. case BTF_KIND_ARRAY: return "array";
  1757. case BTF_KIND_STRUCT: return "struct";
  1758. case BTF_KIND_UNION: return "union";
  1759. case BTF_KIND_ENUM: return "enum";
  1760. case BTF_KIND_FWD: return "fwd";
  1761. case BTF_KIND_TYPEDEF: return "typedef";
  1762. case BTF_KIND_VOLATILE: return "volatile";
  1763. case BTF_KIND_CONST: return "const";
  1764. case BTF_KIND_RESTRICT: return "restrict";
  1765. case BTF_KIND_FUNC: return "func";
  1766. case BTF_KIND_FUNC_PROTO: return "func_proto";
  1767. case BTF_KIND_VAR: return "var";
  1768. case BTF_KIND_DATASEC: return "datasec";
  1769. case BTF_KIND_FLOAT: return "float";
  1770. case BTF_KIND_DECL_TAG: return "decl_tag";
  1771. case BTF_KIND_TYPE_TAG: return "type_tag";
  1772. case BTF_KIND_ENUM64: return "enum64";
  1773. default: return "unknown";
  1774. }
  1775. }
  1776. const char *btf_kind_str(const struct btf_type *t)
  1777. {
  1778. return __btf_kind_str(btf_kind(t));
  1779. }
  1780. /*
  1781. * Fetch integer attribute of BTF map definition. Such attributes are
  1782. * represented using a pointer to an array, in which dimensionality of array
  1783. * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
  1784. * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
  1785. * type definition, while using only sizeof(void *) space in ELF data section.
  1786. */
  1787. static bool get_map_field_int(const char *map_name, const struct btf *btf,
  1788. const struct btf_member *m, __u32 *res)
  1789. {
  1790. const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
  1791. const char *name = btf__name_by_offset(btf, m->name_off);
  1792. const struct btf_array *arr_info;
  1793. const struct btf_type *arr_t;
  1794. if (!btf_is_ptr(t)) {
  1795. pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
  1796. map_name, name, btf_kind_str(t));
  1797. return false;
  1798. }
  1799. arr_t = btf__type_by_id(btf, t->type);
  1800. if (!arr_t) {
  1801. pr_warn("map '%s': attr '%s': type [%u] not found.\n",
  1802. map_name, name, t->type);
  1803. return false;
  1804. }
  1805. if (!btf_is_array(arr_t)) {
  1806. pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
  1807. map_name, name, btf_kind_str(arr_t));
  1808. return false;
  1809. }
  1810. arr_info = btf_array(arr_t);
  1811. *res = arr_info->nelems;
  1812. return true;
  1813. }
  1814. static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
  1815. {
  1816. int len;
  1817. len = snprintf(buf, buf_sz, "%s/%s", path, name);
  1818. if (len < 0)
  1819. return -EINVAL;
  1820. if (len >= buf_sz)
  1821. return -ENAMETOOLONG;
  1822. return 0;
  1823. }
  1824. static int build_map_pin_path(struct bpf_map *map, const char *path)
  1825. {
  1826. char buf[PATH_MAX];
  1827. int err;
  1828. if (!path)
  1829. path = "/sys/fs/bpf";
  1830. err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
  1831. if (err)
  1832. return err;
  1833. return bpf_map__set_pin_path(map, buf);
  1834. }
  1835. /* should match definition in bpf_helpers.h */
  1836. enum libbpf_pin_type {
  1837. LIBBPF_PIN_NONE,
  1838. /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
  1839. LIBBPF_PIN_BY_NAME,
  1840. };
  1841. int parse_btf_map_def(const char *map_name, struct btf *btf,
  1842. const struct btf_type *def_t, bool strict,
  1843. struct btf_map_def *map_def, struct btf_map_def *inner_def)
  1844. {
  1845. const struct btf_type *t;
  1846. const struct btf_member *m;
  1847. bool is_inner = inner_def == NULL;
  1848. int vlen, i;
  1849. vlen = btf_vlen(def_t);
  1850. m = btf_members(def_t);
  1851. for (i = 0; i < vlen; i++, m++) {
  1852. const char *name = btf__name_by_offset(btf, m->name_off);
  1853. if (!name) {
  1854. pr_warn("map '%s': invalid field #%d.\n", map_name, i);
  1855. return -EINVAL;
  1856. }
  1857. if (strcmp(name, "type") == 0) {
  1858. if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
  1859. return -EINVAL;
  1860. map_def->parts |= MAP_DEF_MAP_TYPE;
  1861. } else if (strcmp(name, "max_entries") == 0) {
  1862. if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
  1863. return -EINVAL;
  1864. map_def->parts |= MAP_DEF_MAX_ENTRIES;
  1865. } else if (strcmp(name, "map_flags") == 0) {
  1866. if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
  1867. return -EINVAL;
  1868. map_def->parts |= MAP_DEF_MAP_FLAGS;
  1869. } else if (strcmp(name, "numa_node") == 0) {
  1870. if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
  1871. return -EINVAL;
  1872. map_def->parts |= MAP_DEF_NUMA_NODE;
  1873. } else if (strcmp(name, "key_size") == 0) {
  1874. __u32 sz;
  1875. if (!get_map_field_int(map_name, btf, m, &sz))
  1876. return -EINVAL;
  1877. if (map_def->key_size && map_def->key_size != sz) {
  1878. pr_warn("map '%s': conflicting key size %u != %u.\n",
  1879. map_name, map_def->key_size, sz);
  1880. return -EINVAL;
  1881. }
  1882. map_def->key_size = sz;
  1883. map_def->parts |= MAP_DEF_KEY_SIZE;
  1884. } else if (strcmp(name, "key") == 0) {
  1885. __s64 sz;
  1886. t = btf__type_by_id(btf, m->type);
  1887. if (!t) {
  1888. pr_warn("map '%s': key type [%d] not found.\n",
  1889. map_name, m->type);
  1890. return -EINVAL;
  1891. }
  1892. if (!btf_is_ptr(t)) {
  1893. pr_warn("map '%s': key spec is not PTR: %s.\n",
  1894. map_name, btf_kind_str(t));
  1895. return -EINVAL;
  1896. }
  1897. sz = btf__resolve_size(btf, t->type);
  1898. if (sz < 0) {
  1899. pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
  1900. map_name, t->type, (ssize_t)sz);
  1901. return sz;
  1902. }
  1903. if (map_def->key_size && map_def->key_size != sz) {
  1904. pr_warn("map '%s': conflicting key size %u != %zd.\n",
  1905. map_name, map_def->key_size, (ssize_t)sz);
  1906. return -EINVAL;
  1907. }
  1908. map_def->key_size = sz;
  1909. map_def->key_type_id = t->type;
  1910. map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
  1911. } else if (strcmp(name, "value_size") == 0) {
  1912. __u32 sz;
  1913. if (!get_map_field_int(map_name, btf, m, &sz))
  1914. return -EINVAL;
  1915. if (map_def->value_size && map_def->value_size != sz) {
  1916. pr_warn("map '%s': conflicting value size %u != %u.\n",
  1917. map_name, map_def->value_size, sz);
  1918. return -EINVAL;
  1919. }
  1920. map_def->value_size = sz;
  1921. map_def->parts |= MAP_DEF_VALUE_SIZE;
  1922. } else if (strcmp(name, "value") == 0) {
  1923. __s64 sz;
  1924. t = btf__type_by_id(btf, m->type);
  1925. if (!t) {
  1926. pr_warn("map '%s': value type [%d] not found.\n",
  1927. map_name, m->type);
  1928. return -EINVAL;
  1929. }
  1930. if (!btf_is_ptr(t)) {
  1931. pr_warn("map '%s': value spec is not PTR: %s.\n",
  1932. map_name, btf_kind_str(t));
  1933. return -EINVAL;
  1934. }
  1935. sz = btf__resolve_size(btf, t->type);
  1936. if (sz < 0) {
  1937. pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
  1938. map_name, t->type, (ssize_t)sz);
  1939. return sz;
  1940. }
  1941. if (map_def->value_size && map_def->value_size != sz) {
  1942. pr_warn("map '%s': conflicting value size %u != %zd.\n",
  1943. map_name, map_def->value_size, (ssize_t)sz);
  1944. return -EINVAL;
  1945. }
  1946. map_def->value_size = sz;
  1947. map_def->value_type_id = t->type;
  1948. map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
  1949. }
  1950. else if (strcmp(name, "values") == 0) {
  1951. bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
  1952. bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
  1953. const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
  1954. char inner_map_name[128];
  1955. int err;
  1956. if (is_inner) {
  1957. pr_warn("map '%s': multi-level inner maps not supported.\n",
  1958. map_name);
  1959. return -ENOTSUP;
  1960. }
  1961. if (i != vlen - 1) {
  1962. pr_warn("map '%s': '%s' member should be last.\n",
  1963. map_name, name);
  1964. return -EINVAL;
  1965. }
  1966. if (!is_map_in_map && !is_prog_array) {
  1967. pr_warn("map '%s': should be map-in-map or prog-array.\n",
  1968. map_name);
  1969. return -ENOTSUP;
  1970. }
  1971. if (map_def->value_size && map_def->value_size != 4) {
  1972. pr_warn("map '%s': conflicting value size %u != 4.\n",
  1973. map_name, map_def->value_size);
  1974. return -EINVAL;
  1975. }
  1976. map_def->value_size = 4;
  1977. t = btf__type_by_id(btf, m->type);
  1978. if (!t) {
  1979. pr_warn("map '%s': %s type [%d] not found.\n",
  1980. map_name, desc, m->type);
  1981. return -EINVAL;
  1982. }
  1983. if (!btf_is_array(t) || btf_array(t)->nelems) {
  1984. pr_warn("map '%s': %s spec is not a zero-sized array.\n",
  1985. map_name, desc);
  1986. return -EINVAL;
  1987. }
  1988. t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
  1989. if (!btf_is_ptr(t)) {
  1990. pr_warn("map '%s': %s def is of unexpected kind %s.\n",
  1991. map_name, desc, btf_kind_str(t));
  1992. return -EINVAL;
  1993. }
  1994. t = skip_mods_and_typedefs(btf, t->type, NULL);
  1995. if (is_prog_array) {
  1996. if (!btf_is_func_proto(t)) {
  1997. pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
  1998. map_name, btf_kind_str(t));
  1999. return -EINVAL;
  2000. }
  2001. continue;
  2002. }
  2003. if (!btf_is_struct(t)) {
  2004. pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
  2005. map_name, btf_kind_str(t));
  2006. return -EINVAL;
  2007. }
  2008. snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
  2009. err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
  2010. if (err)
  2011. return err;
  2012. map_def->parts |= MAP_DEF_INNER_MAP;
  2013. } else if (strcmp(name, "pinning") == 0) {
  2014. __u32 val;
  2015. if (is_inner) {
  2016. pr_warn("map '%s': inner def can't be pinned.\n", map_name);
  2017. return -EINVAL;
  2018. }
  2019. if (!get_map_field_int(map_name, btf, m, &val))
  2020. return -EINVAL;
  2021. if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
  2022. pr_warn("map '%s': invalid pinning value %u.\n",
  2023. map_name, val);
  2024. return -EINVAL;
  2025. }
  2026. map_def->pinning = val;
  2027. map_def->parts |= MAP_DEF_PINNING;
  2028. } else if (strcmp(name, "map_extra") == 0) {
  2029. __u32 map_extra;
  2030. if (!get_map_field_int(map_name, btf, m, &map_extra))
  2031. return -EINVAL;
  2032. map_def->map_extra = map_extra;
  2033. map_def->parts |= MAP_DEF_MAP_EXTRA;
  2034. } else {
  2035. if (strict) {
  2036. pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
  2037. return -ENOTSUP;
  2038. }
  2039. pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
  2040. }
  2041. }
  2042. if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
  2043. pr_warn("map '%s': map type isn't specified.\n", map_name);
  2044. return -EINVAL;
  2045. }
  2046. return 0;
  2047. }
  2048. static size_t adjust_ringbuf_sz(size_t sz)
  2049. {
  2050. __u32 page_sz = sysconf(_SC_PAGE_SIZE);
  2051. __u32 mul;
  2052. /* if user forgot to set any size, make sure they see error */
  2053. if (sz == 0)
  2054. return 0;
  2055. /* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
  2056. * a power-of-2 multiple of kernel's page size. If user diligently
  2057. * satisified these conditions, pass the size through.
  2058. */
  2059. if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
  2060. return sz;
  2061. /* Otherwise find closest (page_sz * power_of_2) product bigger than
  2062. * user-set size to satisfy both user size request and kernel
  2063. * requirements and substitute correct max_entries for map creation.
  2064. */
  2065. for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
  2066. if (mul * page_sz > sz)
  2067. return mul * page_sz;
  2068. }
  2069. /* if it's impossible to satisfy the conditions (i.e., user size is
  2070. * very close to UINT_MAX but is not a power-of-2 multiple of
  2071. * page_size) then just return original size and let kernel reject it
  2072. */
  2073. return sz;
  2074. }
  2075. static bool map_is_ringbuf(const struct bpf_map *map)
  2076. {
  2077. return map->def.type == BPF_MAP_TYPE_RINGBUF ||
  2078. map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
  2079. }
  2080. static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
  2081. {
  2082. map->def.type = def->map_type;
  2083. map->def.key_size = def->key_size;
  2084. map->def.value_size = def->value_size;
  2085. map->def.max_entries = def->max_entries;
  2086. map->def.map_flags = def->map_flags;
  2087. map->map_extra = def->map_extra;
  2088. map->numa_node = def->numa_node;
  2089. map->btf_key_type_id = def->key_type_id;
  2090. map->btf_value_type_id = def->value_type_id;
  2091. /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
  2092. if (map_is_ringbuf(map))
  2093. map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
  2094. if (def->parts & MAP_DEF_MAP_TYPE)
  2095. pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
  2096. if (def->parts & MAP_DEF_KEY_TYPE)
  2097. pr_debug("map '%s': found key [%u], sz = %u.\n",
  2098. map->name, def->key_type_id, def->key_size);
  2099. else if (def->parts & MAP_DEF_KEY_SIZE)
  2100. pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
  2101. if (def->parts & MAP_DEF_VALUE_TYPE)
  2102. pr_debug("map '%s': found value [%u], sz = %u.\n",
  2103. map->name, def->value_type_id, def->value_size);
  2104. else if (def->parts & MAP_DEF_VALUE_SIZE)
  2105. pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
  2106. if (def->parts & MAP_DEF_MAX_ENTRIES)
  2107. pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
  2108. if (def->parts & MAP_DEF_MAP_FLAGS)
  2109. pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
  2110. if (def->parts & MAP_DEF_MAP_EXTRA)
  2111. pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
  2112. (unsigned long long)def->map_extra);
  2113. if (def->parts & MAP_DEF_PINNING)
  2114. pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
  2115. if (def->parts & MAP_DEF_NUMA_NODE)
  2116. pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
  2117. if (def->parts & MAP_DEF_INNER_MAP)
  2118. pr_debug("map '%s': found inner map definition.\n", map->name);
  2119. }
  2120. static const char *btf_var_linkage_str(__u32 linkage)
  2121. {
  2122. switch (linkage) {
  2123. case BTF_VAR_STATIC: return "static";
  2124. case BTF_VAR_GLOBAL_ALLOCATED: return "global";
  2125. case BTF_VAR_GLOBAL_EXTERN: return "extern";
  2126. default: return "unknown";
  2127. }
  2128. }
  2129. static int bpf_object__init_user_btf_map(struct bpf_object *obj,
  2130. const struct btf_type *sec,
  2131. int var_idx, int sec_idx,
  2132. const Elf_Data *data, bool strict,
  2133. const char *pin_root_path)
  2134. {
  2135. struct btf_map_def map_def = {}, inner_def = {};
  2136. const struct btf_type *var, *def;
  2137. const struct btf_var_secinfo *vi;
  2138. const struct btf_var *var_extra;
  2139. const char *map_name;
  2140. struct bpf_map *map;
  2141. int err;
  2142. vi = btf_var_secinfos(sec) + var_idx;
  2143. var = btf__type_by_id(obj->btf, vi->type);
  2144. var_extra = btf_var(var);
  2145. map_name = btf__name_by_offset(obj->btf, var->name_off);
  2146. if (map_name == NULL || map_name[0] == '\0') {
  2147. pr_warn("map #%d: empty name.\n", var_idx);
  2148. return -EINVAL;
  2149. }
  2150. if ((__u64)vi->offset + vi->size > data->d_size) {
  2151. pr_warn("map '%s' BTF data is corrupted.\n", map_name);
  2152. return -EINVAL;
  2153. }
  2154. if (!btf_is_var(var)) {
  2155. pr_warn("map '%s': unexpected var kind %s.\n",
  2156. map_name, btf_kind_str(var));
  2157. return -EINVAL;
  2158. }
  2159. if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
  2160. pr_warn("map '%s': unsupported map linkage %s.\n",
  2161. map_name, btf_var_linkage_str(var_extra->linkage));
  2162. return -EOPNOTSUPP;
  2163. }
  2164. def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
  2165. if (!btf_is_struct(def)) {
  2166. pr_warn("map '%s': unexpected def kind %s.\n",
  2167. map_name, btf_kind_str(var));
  2168. return -EINVAL;
  2169. }
  2170. if (def->size > vi->size) {
  2171. pr_warn("map '%s': invalid def size.\n", map_name);
  2172. return -EINVAL;
  2173. }
  2174. map = bpf_object__add_map(obj);
  2175. if (IS_ERR(map))
  2176. return PTR_ERR(map);
  2177. map->name = strdup(map_name);
  2178. if (!map->name) {
  2179. pr_warn("map '%s': failed to alloc map name.\n", map_name);
  2180. return -ENOMEM;
  2181. }
  2182. map->libbpf_type = LIBBPF_MAP_UNSPEC;
  2183. map->def.type = BPF_MAP_TYPE_UNSPEC;
  2184. map->sec_idx = sec_idx;
  2185. map->sec_offset = vi->offset;
  2186. map->btf_var_idx = var_idx;
  2187. pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
  2188. map_name, map->sec_idx, map->sec_offset);
  2189. err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
  2190. if (err)
  2191. return err;
  2192. fill_map_from_def(map, &map_def);
  2193. if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
  2194. err = build_map_pin_path(map, pin_root_path);
  2195. if (err) {
  2196. pr_warn("map '%s': couldn't build pin path.\n", map->name);
  2197. return err;
  2198. }
  2199. }
  2200. if (map_def.parts & MAP_DEF_INNER_MAP) {
  2201. map->inner_map = calloc(1, sizeof(*map->inner_map));
  2202. if (!map->inner_map)
  2203. return -ENOMEM;
  2204. map->inner_map->fd = -1;
  2205. map->inner_map->sec_idx = sec_idx;
  2206. map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
  2207. if (!map->inner_map->name)
  2208. return -ENOMEM;
  2209. sprintf(map->inner_map->name, "%s.inner", map_name);
  2210. fill_map_from_def(map->inner_map, &inner_def);
  2211. }
  2212. err = bpf_map_find_btf_info(obj, map);
  2213. if (err)
  2214. return err;
  2215. return 0;
  2216. }
  2217. static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
  2218. const char *pin_root_path)
  2219. {
  2220. const struct btf_type *sec = NULL;
  2221. int nr_types, i, vlen, err;
  2222. const struct btf_type *t;
  2223. const char *name;
  2224. Elf_Data *data;
  2225. Elf_Scn *scn;
  2226. if (obj->efile.btf_maps_shndx < 0)
  2227. return 0;
  2228. scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
  2229. data = elf_sec_data(obj, scn);
  2230. if (!scn || !data) {
  2231. pr_warn("elf: failed to get %s map definitions for %s\n",
  2232. MAPS_ELF_SEC, obj->path);
  2233. return -EINVAL;
  2234. }
  2235. nr_types = btf__type_cnt(obj->btf);
  2236. for (i = 1; i < nr_types; i++) {
  2237. t = btf__type_by_id(obj->btf, i);
  2238. if (!btf_is_datasec(t))
  2239. continue;
  2240. name = btf__name_by_offset(obj->btf, t->name_off);
  2241. if (strcmp(name, MAPS_ELF_SEC) == 0) {
  2242. sec = t;
  2243. obj->efile.btf_maps_sec_btf_id = i;
  2244. break;
  2245. }
  2246. }
  2247. if (!sec) {
  2248. pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
  2249. return -ENOENT;
  2250. }
  2251. vlen = btf_vlen(sec);
  2252. for (i = 0; i < vlen; i++) {
  2253. err = bpf_object__init_user_btf_map(obj, sec, i,
  2254. obj->efile.btf_maps_shndx,
  2255. data, strict,
  2256. pin_root_path);
  2257. if (err)
  2258. return err;
  2259. }
  2260. return 0;
  2261. }
  2262. static int bpf_object__init_maps(struct bpf_object *obj,
  2263. const struct bpf_object_open_opts *opts)
  2264. {
  2265. const char *pin_root_path;
  2266. bool strict;
  2267. int err = 0;
  2268. strict = !OPTS_GET(opts, relaxed_maps, false);
  2269. pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
  2270. err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
  2271. err = err ?: bpf_object__init_global_data_maps(obj);
  2272. err = err ?: bpf_object__init_kconfig_map(obj);
  2273. err = err ?: bpf_object__init_struct_ops_maps(obj);
  2274. return err;
  2275. }
  2276. static bool section_have_execinstr(struct bpf_object *obj, int idx)
  2277. {
  2278. Elf64_Shdr *sh;
  2279. sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
  2280. if (!sh)
  2281. return false;
  2282. return sh->sh_flags & SHF_EXECINSTR;
  2283. }
  2284. static bool btf_needs_sanitization(struct bpf_object *obj)
  2285. {
  2286. bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
  2287. bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
  2288. bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
  2289. bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
  2290. bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
  2291. bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
  2292. bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
  2293. return !has_func || !has_datasec || !has_func_global || !has_float ||
  2294. !has_decl_tag || !has_type_tag || !has_enum64;
  2295. }
  2296. static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
  2297. {
  2298. bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
  2299. bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
  2300. bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
  2301. bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
  2302. bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
  2303. bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
  2304. bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
  2305. int enum64_placeholder_id = 0;
  2306. struct btf_type *t;
  2307. int i, j, vlen;
  2308. for (i = 1; i < btf__type_cnt(btf); i++) {
  2309. t = (struct btf_type *)btf__type_by_id(btf, i);
  2310. if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
  2311. /* replace VAR/DECL_TAG with INT */
  2312. t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
  2313. /*
  2314. * using size = 1 is the safest choice, 4 will be too
  2315. * big and cause kernel BTF validation failure if
  2316. * original variable took less than 4 bytes
  2317. */
  2318. t->size = 1;
  2319. *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
  2320. } else if (!has_datasec && btf_is_datasec(t)) {
  2321. /* replace DATASEC with STRUCT */
  2322. const struct btf_var_secinfo *v = btf_var_secinfos(t);
  2323. struct btf_member *m = btf_members(t);
  2324. struct btf_type *vt;
  2325. char *name;
  2326. name = (char *)btf__name_by_offset(btf, t->name_off);
  2327. while (*name) {
  2328. if (*name == '.')
  2329. *name = '_';
  2330. name++;
  2331. }
  2332. vlen = btf_vlen(t);
  2333. t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
  2334. for (j = 0; j < vlen; j++, v++, m++) {
  2335. /* order of field assignments is important */
  2336. m->offset = v->offset * 8;
  2337. m->type = v->type;
  2338. /* preserve variable name as member name */
  2339. vt = (void *)btf__type_by_id(btf, v->type);
  2340. m->name_off = vt->name_off;
  2341. }
  2342. } else if (!has_func && btf_is_func_proto(t)) {
  2343. /* replace FUNC_PROTO with ENUM */
  2344. vlen = btf_vlen(t);
  2345. t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
  2346. t->size = sizeof(__u32); /* kernel enforced */
  2347. } else if (!has_func && btf_is_func(t)) {
  2348. /* replace FUNC with TYPEDEF */
  2349. t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
  2350. } else if (!has_func_global && btf_is_func(t)) {
  2351. /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
  2352. t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
  2353. } else if (!has_float && btf_is_float(t)) {
  2354. /* replace FLOAT with an equally-sized empty STRUCT;
  2355. * since C compilers do not accept e.g. "float" as a
  2356. * valid struct name, make it anonymous
  2357. */
  2358. t->name_off = 0;
  2359. t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
  2360. } else if (!has_type_tag && btf_is_type_tag(t)) {
  2361. /* replace TYPE_TAG with a CONST */
  2362. t->name_off = 0;
  2363. t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
  2364. } else if (!has_enum64 && btf_is_enum(t)) {
  2365. /* clear the kflag */
  2366. t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
  2367. } else if (!has_enum64 && btf_is_enum64(t)) {
  2368. /* replace ENUM64 with a union */
  2369. struct btf_member *m;
  2370. if (enum64_placeholder_id == 0) {
  2371. enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
  2372. if (enum64_placeholder_id < 0)
  2373. return enum64_placeholder_id;
  2374. t = (struct btf_type *)btf__type_by_id(btf, i);
  2375. }
  2376. m = btf_members(t);
  2377. vlen = btf_vlen(t);
  2378. t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
  2379. for (j = 0; j < vlen; j++, m++) {
  2380. m->type = enum64_placeholder_id;
  2381. m->offset = 0;
  2382. }
  2383. }
  2384. }
  2385. return 0;
  2386. }
  2387. static bool libbpf_needs_btf(const struct bpf_object *obj)
  2388. {
  2389. return obj->efile.btf_maps_shndx >= 0 ||
  2390. obj->efile.st_ops_shndx >= 0 ||
  2391. obj->nr_extern > 0;
  2392. }
  2393. static bool kernel_needs_btf(const struct bpf_object *obj)
  2394. {
  2395. return obj->efile.st_ops_shndx >= 0;
  2396. }
  2397. static int bpf_object__init_btf(struct bpf_object *obj,
  2398. Elf_Data *btf_data,
  2399. Elf_Data *btf_ext_data)
  2400. {
  2401. int err = -ENOENT;
  2402. if (btf_data) {
  2403. obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
  2404. err = libbpf_get_error(obj->btf);
  2405. if (err) {
  2406. obj->btf = NULL;
  2407. pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
  2408. goto out;
  2409. }
  2410. /* enforce 8-byte pointers for BPF-targeted BTFs */
  2411. btf__set_pointer_size(obj->btf, 8);
  2412. }
  2413. if (btf_ext_data) {
  2414. struct btf_ext_info *ext_segs[3];
  2415. int seg_num, sec_num;
  2416. if (!obj->btf) {
  2417. pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
  2418. BTF_EXT_ELF_SEC, BTF_ELF_SEC);
  2419. goto out;
  2420. }
  2421. obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
  2422. err = libbpf_get_error(obj->btf_ext);
  2423. if (err) {
  2424. pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
  2425. BTF_EXT_ELF_SEC, err);
  2426. obj->btf_ext = NULL;
  2427. goto out;
  2428. }
  2429. /* setup .BTF.ext to ELF section mapping */
  2430. ext_segs[0] = &obj->btf_ext->func_info;
  2431. ext_segs[1] = &obj->btf_ext->line_info;
  2432. ext_segs[2] = &obj->btf_ext->core_relo_info;
  2433. for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
  2434. struct btf_ext_info *seg = ext_segs[seg_num];
  2435. const struct btf_ext_info_sec *sec;
  2436. const char *sec_name;
  2437. Elf_Scn *scn;
  2438. if (seg->sec_cnt == 0)
  2439. continue;
  2440. seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
  2441. if (!seg->sec_idxs) {
  2442. err = -ENOMEM;
  2443. goto out;
  2444. }
  2445. sec_num = 0;
  2446. for_each_btf_ext_sec(seg, sec) {
  2447. /* preventively increment index to avoid doing
  2448. * this before every continue below
  2449. */
  2450. sec_num++;
  2451. sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
  2452. if (str_is_empty(sec_name))
  2453. continue;
  2454. scn = elf_sec_by_name(obj, sec_name);
  2455. if (!scn)
  2456. continue;
  2457. seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
  2458. }
  2459. }
  2460. }
  2461. out:
  2462. if (err && libbpf_needs_btf(obj)) {
  2463. pr_warn("BTF is required, but is missing or corrupted.\n");
  2464. return err;
  2465. }
  2466. return 0;
  2467. }
  2468. static int compare_vsi_off(const void *_a, const void *_b)
  2469. {
  2470. const struct btf_var_secinfo *a = _a;
  2471. const struct btf_var_secinfo *b = _b;
  2472. return a->offset - b->offset;
  2473. }
  2474. static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
  2475. struct btf_type *t)
  2476. {
  2477. __u32 size = 0, off = 0, i, vars = btf_vlen(t);
  2478. const char *name = btf__name_by_offset(btf, t->name_off);
  2479. const struct btf_type *t_var;
  2480. struct btf_var_secinfo *vsi;
  2481. const struct btf_var *var;
  2482. int ret;
  2483. if (!name) {
  2484. pr_debug("No name found in string section for DATASEC kind.\n");
  2485. return -ENOENT;
  2486. }
  2487. /* .extern datasec size and var offsets were set correctly during
  2488. * extern collection step, so just skip straight to sorting variables
  2489. */
  2490. if (t->size)
  2491. goto sort_vars;
  2492. ret = find_elf_sec_sz(obj, name, &size);
  2493. if (ret || !size) {
  2494. pr_debug("Invalid size for section %s: %u bytes\n", name, size);
  2495. return -ENOENT;
  2496. }
  2497. t->size = size;
  2498. for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
  2499. t_var = btf__type_by_id(btf, vsi->type);
  2500. if (!t_var || !btf_is_var(t_var)) {
  2501. pr_debug("Non-VAR type seen in section %s\n", name);
  2502. return -EINVAL;
  2503. }
  2504. var = btf_var(t_var);
  2505. if (var->linkage == BTF_VAR_STATIC)
  2506. continue;
  2507. name = btf__name_by_offset(btf, t_var->name_off);
  2508. if (!name) {
  2509. pr_debug("No name found in string section for VAR kind\n");
  2510. return -ENOENT;
  2511. }
  2512. ret = find_elf_var_offset(obj, name, &off);
  2513. if (ret) {
  2514. pr_debug("No offset found in symbol table for VAR %s\n",
  2515. name);
  2516. return -ENOENT;
  2517. }
  2518. vsi->offset = off;
  2519. }
  2520. sort_vars:
  2521. qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
  2522. return 0;
  2523. }
  2524. static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
  2525. {
  2526. int err = 0;
  2527. __u32 i, n = btf__type_cnt(btf);
  2528. for (i = 1; i < n; i++) {
  2529. struct btf_type *t = btf_type_by_id(btf, i);
  2530. /* Loader needs to fix up some of the things compiler
  2531. * couldn't get its hands on while emitting BTF. This
  2532. * is section size and global variable offset. We use
  2533. * the info from the ELF itself for this purpose.
  2534. */
  2535. if (btf_is_datasec(t)) {
  2536. err = btf_fixup_datasec(obj, btf, t);
  2537. if (err)
  2538. break;
  2539. }
  2540. }
  2541. return libbpf_err(err);
  2542. }
  2543. static int bpf_object__finalize_btf(struct bpf_object *obj)
  2544. {
  2545. int err;
  2546. if (!obj->btf)
  2547. return 0;
  2548. err = btf_finalize_data(obj, obj->btf);
  2549. if (err) {
  2550. pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
  2551. return err;
  2552. }
  2553. return 0;
  2554. }
  2555. static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
  2556. {
  2557. if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
  2558. prog->type == BPF_PROG_TYPE_LSM)
  2559. return true;
  2560. /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
  2561. * also need vmlinux BTF
  2562. */
  2563. if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
  2564. return true;
  2565. return false;
  2566. }
  2567. static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
  2568. {
  2569. struct bpf_program *prog;
  2570. int i;
  2571. /* CO-RE relocations need kernel BTF, only when btf_custom_path
  2572. * is not specified
  2573. */
  2574. if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
  2575. return true;
  2576. /* Support for typed ksyms needs kernel BTF */
  2577. for (i = 0; i < obj->nr_extern; i++) {
  2578. const struct extern_desc *ext;
  2579. ext = &obj->externs[i];
  2580. if (ext->type == EXT_KSYM && ext->ksym.type_id)
  2581. return true;
  2582. }
  2583. bpf_object__for_each_program(prog, obj) {
  2584. if (!prog->autoload)
  2585. continue;
  2586. if (prog_needs_vmlinux_btf(prog))
  2587. return true;
  2588. }
  2589. return false;
  2590. }
  2591. static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
  2592. {
  2593. int err;
  2594. /* btf_vmlinux could be loaded earlier */
  2595. if (obj->btf_vmlinux || obj->gen_loader)
  2596. return 0;
  2597. if (!force && !obj_needs_vmlinux_btf(obj))
  2598. return 0;
  2599. obj->btf_vmlinux = btf__load_vmlinux_btf();
  2600. err = libbpf_get_error(obj->btf_vmlinux);
  2601. if (err) {
  2602. pr_warn("Error loading vmlinux BTF: %d\n", err);
  2603. obj->btf_vmlinux = NULL;
  2604. return err;
  2605. }
  2606. return 0;
  2607. }
  2608. static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
  2609. {
  2610. struct btf *kern_btf = obj->btf;
  2611. bool btf_mandatory, sanitize;
  2612. int i, err = 0;
  2613. if (!obj->btf)
  2614. return 0;
  2615. if (!kernel_supports(obj, FEAT_BTF)) {
  2616. if (kernel_needs_btf(obj)) {
  2617. err = -EOPNOTSUPP;
  2618. goto report;
  2619. }
  2620. pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
  2621. return 0;
  2622. }
  2623. /* Even though some subprogs are global/weak, user might prefer more
  2624. * permissive BPF verification process that BPF verifier performs for
  2625. * static functions, taking into account more context from the caller
  2626. * functions. In such case, they need to mark such subprogs with
  2627. * __attribute__((visibility("hidden"))) and libbpf will adjust
  2628. * corresponding FUNC BTF type to be marked as static and trigger more
  2629. * involved BPF verification process.
  2630. */
  2631. for (i = 0; i < obj->nr_programs; i++) {
  2632. struct bpf_program *prog = &obj->programs[i];
  2633. struct btf_type *t;
  2634. const char *name;
  2635. int j, n;
  2636. if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
  2637. continue;
  2638. n = btf__type_cnt(obj->btf);
  2639. for (j = 1; j < n; j++) {
  2640. t = btf_type_by_id(obj->btf, j);
  2641. if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
  2642. continue;
  2643. name = btf__str_by_offset(obj->btf, t->name_off);
  2644. if (strcmp(name, prog->name) != 0)
  2645. continue;
  2646. t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
  2647. break;
  2648. }
  2649. }
  2650. sanitize = btf_needs_sanitization(obj);
  2651. if (sanitize) {
  2652. const void *raw_data;
  2653. __u32 sz;
  2654. /* clone BTF to sanitize a copy and leave the original intact */
  2655. raw_data = btf__raw_data(obj->btf, &sz);
  2656. kern_btf = btf__new(raw_data, sz);
  2657. err = libbpf_get_error(kern_btf);
  2658. if (err)
  2659. return err;
  2660. /* enforce 8-byte pointers for BPF-targeted BTFs */
  2661. btf__set_pointer_size(obj->btf, 8);
  2662. err = bpf_object__sanitize_btf(obj, kern_btf);
  2663. if (err)
  2664. return err;
  2665. }
  2666. if (obj->gen_loader) {
  2667. __u32 raw_size = 0;
  2668. const void *raw_data = btf__raw_data(kern_btf, &raw_size);
  2669. if (!raw_data)
  2670. return -ENOMEM;
  2671. bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
  2672. /* Pretend to have valid FD to pass various fd >= 0 checks.
  2673. * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
  2674. */
  2675. btf__set_fd(kern_btf, 0);
  2676. } else {
  2677. /* currently BPF_BTF_LOAD only supports log_level 1 */
  2678. err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
  2679. obj->log_level ? 1 : 0);
  2680. }
  2681. if (sanitize) {
  2682. if (!err) {
  2683. /* move fd to libbpf's BTF */
  2684. btf__set_fd(obj->btf, btf__fd(kern_btf));
  2685. btf__set_fd(kern_btf, -1);
  2686. }
  2687. btf__free(kern_btf);
  2688. }
  2689. report:
  2690. if (err) {
  2691. btf_mandatory = kernel_needs_btf(obj);
  2692. pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
  2693. btf_mandatory ? "BTF is mandatory, can't proceed."
  2694. : "BTF is optional, ignoring.");
  2695. if (!btf_mandatory)
  2696. err = 0;
  2697. }
  2698. return err;
  2699. }
  2700. static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
  2701. {
  2702. const char *name;
  2703. name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
  2704. if (!name) {
  2705. pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
  2706. off, obj->path, elf_errmsg(-1));
  2707. return NULL;
  2708. }
  2709. return name;
  2710. }
  2711. static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
  2712. {
  2713. const char *name;
  2714. name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
  2715. if (!name) {
  2716. pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
  2717. off, obj->path, elf_errmsg(-1));
  2718. return NULL;
  2719. }
  2720. return name;
  2721. }
  2722. static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
  2723. {
  2724. Elf_Scn *scn;
  2725. scn = elf_getscn(obj->efile.elf, idx);
  2726. if (!scn) {
  2727. pr_warn("elf: failed to get section(%zu) from %s: %s\n",
  2728. idx, obj->path, elf_errmsg(-1));
  2729. return NULL;
  2730. }
  2731. return scn;
  2732. }
  2733. static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
  2734. {
  2735. Elf_Scn *scn = NULL;
  2736. Elf *elf = obj->efile.elf;
  2737. const char *sec_name;
  2738. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  2739. sec_name = elf_sec_name(obj, scn);
  2740. if (!sec_name)
  2741. return NULL;
  2742. if (strcmp(sec_name, name) != 0)
  2743. continue;
  2744. return scn;
  2745. }
  2746. return NULL;
  2747. }
  2748. static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
  2749. {
  2750. Elf64_Shdr *shdr;
  2751. if (!scn)
  2752. return NULL;
  2753. shdr = elf64_getshdr(scn);
  2754. if (!shdr) {
  2755. pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
  2756. elf_ndxscn(scn), obj->path, elf_errmsg(-1));
  2757. return NULL;
  2758. }
  2759. return shdr;
  2760. }
  2761. static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
  2762. {
  2763. const char *name;
  2764. Elf64_Shdr *sh;
  2765. if (!scn)
  2766. return NULL;
  2767. sh = elf_sec_hdr(obj, scn);
  2768. if (!sh)
  2769. return NULL;
  2770. name = elf_sec_str(obj, sh->sh_name);
  2771. if (!name) {
  2772. pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
  2773. elf_ndxscn(scn), obj->path, elf_errmsg(-1));
  2774. return NULL;
  2775. }
  2776. return name;
  2777. }
  2778. static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
  2779. {
  2780. Elf_Data *data;
  2781. if (!scn)
  2782. return NULL;
  2783. data = elf_getdata(scn, 0);
  2784. if (!data) {
  2785. pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
  2786. elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
  2787. obj->path, elf_errmsg(-1));
  2788. return NULL;
  2789. }
  2790. return data;
  2791. }
  2792. static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
  2793. {
  2794. if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
  2795. return NULL;
  2796. return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
  2797. }
  2798. static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
  2799. {
  2800. if (idx >= data->d_size / sizeof(Elf64_Rel))
  2801. return NULL;
  2802. return (Elf64_Rel *)data->d_buf + idx;
  2803. }
  2804. static bool is_sec_name_dwarf(const char *name)
  2805. {
  2806. /* approximation, but the actual list is too long */
  2807. return str_has_pfx(name, ".debug_");
  2808. }
  2809. static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
  2810. {
  2811. /* no special handling of .strtab */
  2812. if (hdr->sh_type == SHT_STRTAB)
  2813. return true;
  2814. /* ignore .llvm_addrsig section as well */
  2815. if (hdr->sh_type == SHT_LLVM_ADDRSIG)
  2816. return true;
  2817. /* no subprograms will lead to an empty .text section, ignore it */
  2818. if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
  2819. strcmp(name, ".text") == 0)
  2820. return true;
  2821. /* DWARF sections */
  2822. if (is_sec_name_dwarf(name))
  2823. return true;
  2824. if (str_has_pfx(name, ".rel")) {
  2825. name += sizeof(".rel") - 1;
  2826. /* DWARF section relocations */
  2827. if (is_sec_name_dwarf(name))
  2828. return true;
  2829. /* .BTF and .BTF.ext don't need relocations */
  2830. if (strcmp(name, BTF_ELF_SEC) == 0 ||
  2831. strcmp(name, BTF_EXT_ELF_SEC) == 0)
  2832. return true;
  2833. }
  2834. return false;
  2835. }
  2836. static int cmp_progs(const void *_a, const void *_b)
  2837. {
  2838. const struct bpf_program *a = _a;
  2839. const struct bpf_program *b = _b;
  2840. if (a->sec_idx != b->sec_idx)
  2841. return a->sec_idx < b->sec_idx ? -1 : 1;
  2842. /* sec_insn_off can't be the same within the section */
  2843. return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
  2844. }
  2845. static int bpf_object__elf_collect(struct bpf_object *obj)
  2846. {
  2847. struct elf_sec_desc *sec_desc;
  2848. Elf *elf = obj->efile.elf;
  2849. Elf_Data *btf_ext_data = NULL;
  2850. Elf_Data *btf_data = NULL;
  2851. int idx = 0, err = 0;
  2852. const char *name;
  2853. Elf_Data *data;
  2854. Elf_Scn *scn;
  2855. Elf64_Shdr *sh;
  2856. /* ELF section indices are 0-based, but sec #0 is special "invalid"
  2857. * section. Since section count retrieved by elf_getshdrnum() does
  2858. * include sec #0, it is already the necessary size of an array to keep
  2859. * all the sections.
  2860. */
  2861. if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
  2862. pr_warn("elf: failed to get the number of sections for %s: %s\n",
  2863. obj->path, elf_errmsg(-1));
  2864. return -LIBBPF_ERRNO__FORMAT;
  2865. }
  2866. obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
  2867. if (!obj->efile.secs)
  2868. return -ENOMEM;
  2869. /* a bunch of ELF parsing functionality depends on processing symbols,
  2870. * so do the first pass and find the symbol table
  2871. */
  2872. scn = NULL;
  2873. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  2874. sh = elf_sec_hdr(obj, scn);
  2875. if (!sh)
  2876. return -LIBBPF_ERRNO__FORMAT;
  2877. if (sh->sh_type == SHT_SYMTAB) {
  2878. if (obj->efile.symbols) {
  2879. pr_warn("elf: multiple symbol tables in %s\n", obj->path);
  2880. return -LIBBPF_ERRNO__FORMAT;
  2881. }
  2882. data = elf_sec_data(obj, scn);
  2883. if (!data)
  2884. return -LIBBPF_ERRNO__FORMAT;
  2885. idx = elf_ndxscn(scn);
  2886. obj->efile.symbols = data;
  2887. obj->efile.symbols_shndx = idx;
  2888. obj->efile.strtabidx = sh->sh_link;
  2889. }
  2890. }
  2891. if (!obj->efile.symbols) {
  2892. pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
  2893. obj->path);
  2894. return -ENOENT;
  2895. }
  2896. scn = NULL;
  2897. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  2898. idx = elf_ndxscn(scn);
  2899. sec_desc = &obj->efile.secs[idx];
  2900. sh = elf_sec_hdr(obj, scn);
  2901. if (!sh)
  2902. return -LIBBPF_ERRNO__FORMAT;
  2903. name = elf_sec_str(obj, sh->sh_name);
  2904. if (!name)
  2905. return -LIBBPF_ERRNO__FORMAT;
  2906. if (ignore_elf_section(sh, name))
  2907. continue;
  2908. data = elf_sec_data(obj, scn);
  2909. if (!data)
  2910. return -LIBBPF_ERRNO__FORMAT;
  2911. pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
  2912. idx, name, (unsigned long)data->d_size,
  2913. (int)sh->sh_link, (unsigned long)sh->sh_flags,
  2914. (int)sh->sh_type);
  2915. if (strcmp(name, "license") == 0) {
  2916. err = bpf_object__init_license(obj, data->d_buf, data->d_size);
  2917. if (err)
  2918. return err;
  2919. } else if (strcmp(name, "version") == 0) {
  2920. err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
  2921. if (err)
  2922. return err;
  2923. } else if (strcmp(name, "maps") == 0) {
  2924. pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
  2925. return -ENOTSUP;
  2926. } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
  2927. obj->efile.btf_maps_shndx = idx;
  2928. } else if (strcmp(name, BTF_ELF_SEC) == 0) {
  2929. if (sh->sh_type != SHT_PROGBITS)
  2930. return -LIBBPF_ERRNO__FORMAT;
  2931. btf_data = data;
  2932. } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
  2933. if (sh->sh_type != SHT_PROGBITS)
  2934. return -LIBBPF_ERRNO__FORMAT;
  2935. btf_ext_data = data;
  2936. } else if (sh->sh_type == SHT_SYMTAB) {
  2937. /* already processed during the first pass above */
  2938. } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
  2939. if (sh->sh_flags & SHF_EXECINSTR) {
  2940. if (strcmp(name, ".text") == 0)
  2941. obj->efile.text_shndx = idx;
  2942. err = bpf_object__add_programs(obj, data, name, idx);
  2943. if (err)
  2944. return err;
  2945. } else if (strcmp(name, DATA_SEC) == 0 ||
  2946. str_has_pfx(name, DATA_SEC ".")) {
  2947. sec_desc->sec_type = SEC_DATA;
  2948. sec_desc->shdr = sh;
  2949. sec_desc->data = data;
  2950. } else if (strcmp(name, RODATA_SEC) == 0 ||
  2951. str_has_pfx(name, RODATA_SEC ".")) {
  2952. sec_desc->sec_type = SEC_RODATA;
  2953. sec_desc->shdr = sh;
  2954. sec_desc->data = data;
  2955. } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
  2956. obj->efile.st_ops_data = data;
  2957. obj->efile.st_ops_shndx = idx;
  2958. } else {
  2959. pr_info("elf: skipping unrecognized data section(%d) %s\n",
  2960. idx, name);
  2961. }
  2962. } else if (sh->sh_type == SHT_REL) {
  2963. int targ_sec_idx = sh->sh_info; /* points to other section */
  2964. if (sh->sh_entsize != sizeof(Elf64_Rel) ||
  2965. targ_sec_idx >= obj->efile.sec_cnt)
  2966. return -LIBBPF_ERRNO__FORMAT;
  2967. /* Only do relo for section with exec instructions */
  2968. if (!section_have_execinstr(obj, targ_sec_idx) &&
  2969. strcmp(name, ".rel" STRUCT_OPS_SEC) &&
  2970. strcmp(name, ".rel" MAPS_ELF_SEC)) {
  2971. pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
  2972. idx, name, targ_sec_idx,
  2973. elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
  2974. continue;
  2975. }
  2976. sec_desc->sec_type = SEC_RELO;
  2977. sec_desc->shdr = sh;
  2978. sec_desc->data = data;
  2979. } else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
  2980. sec_desc->sec_type = SEC_BSS;
  2981. sec_desc->shdr = sh;
  2982. sec_desc->data = data;
  2983. } else {
  2984. pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
  2985. (size_t)sh->sh_size);
  2986. }
  2987. }
  2988. if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
  2989. pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
  2990. return -LIBBPF_ERRNO__FORMAT;
  2991. }
  2992. /* sort BPF programs by section name and in-section instruction offset
  2993. * for faster search */
  2994. if (obj->nr_programs)
  2995. qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
  2996. return bpf_object__init_btf(obj, btf_data, btf_ext_data);
  2997. }
  2998. static bool sym_is_extern(const Elf64_Sym *sym)
  2999. {
  3000. int bind = ELF64_ST_BIND(sym->st_info);
  3001. /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
  3002. return sym->st_shndx == SHN_UNDEF &&
  3003. (bind == STB_GLOBAL || bind == STB_WEAK) &&
  3004. ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
  3005. }
  3006. static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
  3007. {
  3008. int bind = ELF64_ST_BIND(sym->st_info);
  3009. int type = ELF64_ST_TYPE(sym->st_info);
  3010. /* in .text section */
  3011. if (sym->st_shndx != text_shndx)
  3012. return false;
  3013. /* local function */
  3014. if (bind == STB_LOCAL && type == STT_SECTION)
  3015. return true;
  3016. /* global function */
  3017. return bind == STB_GLOBAL && type == STT_FUNC;
  3018. }
  3019. static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
  3020. {
  3021. const struct btf_type *t;
  3022. const char *tname;
  3023. int i, n;
  3024. if (!btf)
  3025. return -ESRCH;
  3026. n = btf__type_cnt(btf);
  3027. for (i = 1; i < n; i++) {
  3028. t = btf__type_by_id(btf, i);
  3029. if (!btf_is_var(t) && !btf_is_func(t))
  3030. continue;
  3031. tname = btf__name_by_offset(btf, t->name_off);
  3032. if (strcmp(tname, ext_name))
  3033. continue;
  3034. if (btf_is_var(t) &&
  3035. btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
  3036. return -EINVAL;
  3037. if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
  3038. return -EINVAL;
  3039. return i;
  3040. }
  3041. return -ENOENT;
  3042. }
  3043. static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
  3044. const struct btf_var_secinfo *vs;
  3045. const struct btf_type *t;
  3046. int i, j, n;
  3047. if (!btf)
  3048. return -ESRCH;
  3049. n = btf__type_cnt(btf);
  3050. for (i = 1; i < n; i++) {
  3051. t = btf__type_by_id(btf, i);
  3052. if (!btf_is_datasec(t))
  3053. continue;
  3054. vs = btf_var_secinfos(t);
  3055. for (j = 0; j < btf_vlen(t); j++, vs++) {
  3056. if (vs->type == ext_btf_id)
  3057. return i;
  3058. }
  3059. }
  3060. return -ENOENT;
  3061. }
  3062. static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
  3063. bool *is_signed)
  3064. {
  3065. const struct btf_type *t;
  3066. const char *name;
  3067. t = skip_mods_and_typedefs(btf, id, NULL);
  3068. name = btf__name_by_offset(btf, t->name_off);
  3069. if (is_signed)
  3070. *is_signed = false;
  3071. switch (btf_kind(t)) {
  3072. case BTF_KIND_INT: {
  3073. int enc = btf_int_encoding(t);
  3074. if (enc & BTF_INT_BOOL)
  3075. return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
  3076. if (is_signed)
  3077. *is_signed = enc & BTF_INT_SIGNED;
  3078. if (t->size == 1)
  3079. return KCFG_CHAR;
  3080. if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
  3081. return KCFG_UNKNOWN;
  3082. return KCFG_INT;
  3083. }
  3084. case BTF_KIND_ENUM:
  3085. if (t->size != 4)
  3086. return KCFG_UNKNOWN;
  3087. if (strcmp(name, "libbpf_tristate"))
  3088. return KCFG_UNKNOWN;
  3089. return KCFG_TRISTATE;
  3090. case BTF_KIND_ENUM64:
  3091. if (strcmp(name, "libbpf_tristate"))
  3092. return KCFG_UNKNOWN;
  3093. return KCFG_TRISTATE;
  3094. case BTF_KIND_ARRAY:
  3095. if (btf_array(t)->nelems == 0)
  3096. return KCFG_UNKNOWN;
  3097. if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
  3098. return KCFG_UNKNOWN;
  3099. return KCFG_CHAR_ARR;
  3100. default:
  3101. return KCFG_UNKNOWN;
  3102. }
  3103. }
  3104. static int cmp_externs(const void *_a, const void *_b)
  3105. {
  3106. const struct extern_desc *a = _a;
  3107. const struct extern_desc *b = _b;
  3108. if (a->type != b->type)
  3109. return a->type < b->type ? -1 : 1;
  3110. if (a->type == EXT_KCFG) {
  3111. /* descending order by alignment requirements */
  3112. if (a->kcfg.align != b->kcfg.align)
  3113. return a->kcfg.align > b->kcfg.align ? -1 : 1;
  3114. /* ascending order by size, within same alignment class */
  3115. if (a->kcfg.sz != b->kcfg.sz)
  3116. return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
  3117. }
  3118. /* resolve ties by name */
  3119. return strcmp(a->name, b->name);
  3120. }
  3121. static int find_int_btf_id(const struct btf *btf)
  3122. {
  3123. const struct btf_type *t;
  3124. int i, n;
  3125. n = btf__type_cnt(btf);
  3126. for (i = 1; i < n; i++) {
  3127. t = btf__type_by_id(btf, i);
  3128. if (btf_is_int(t) && btf_int_bits(t) == 32)
  3129. return i;
  3130. }
  3131. return 0;
  3132. }
  3133. static int add_dummy_ksym_var(struct btf *btf)
  3134. {
  3135. int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
  3136. const struct btf_var_secinfo *vs;
  3137. const struct btf_type *sec;
  3138. if (!btf)
  3139. return 0;
  3140. sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
  3141. BTF_KIND_DATASEC);
  3142. if (sec_btf_id < 0)
  3143. return 0;
  3144. sec = btf__type_by_id(btf, sec_btf_id);
  3145. vs = btf_var_secinfos(sec);
  3146. for (i = 0; i < btf_vlen(sec); i++, vs++) {
  3147. const struct btf_type *vt;
  3148. vt = btf__type_by_id(btf, vs->type);
  3149. if (btf_is_func(vt))
  3150. break;
  3151. }
  3152. /* No func in ksyms sec. No need to add dummy var. */
  3153. if (i == btf_vlen(sec))
  3154. return 0;
  3155. int_btf_id = find_int_btf_id(btf);
  3156. dummy_var_btf_id = btf__add_var(btf,
  3157. "dummy_ksym",
  3158. BTF_VAR_GLOBAL_ALLOCATED,
  3159. int_btf_id);
  3160. if (dummy_var_btf_id < 0)
  3161. pr_warn("cannot create a dummy_ksym var\n");
  3162. return dummy_var_btf_id;
  3163. }
  3164. static int bpf_object__collect_externs(struct bpf_object *obj)
  3165. {
  3166. struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
  3167. const struct btf_type *t;
  3168. struct extern_desc *ext;
  3169. int i, n, off, dummy_var_btf_id;
  3170. const char *ext_name, *sec_name;
  3171. Elf_Scn *scn;
  3172. Elf64_Shdr *sh;
  3173. if (!obj->efile.symbols)
  3174. return 0;
  3175. scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
  3176. sh = elf_sec_hdr(obj, scn);
  3177. if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
  3178. return -LIBBPF_ERRNO__FORMAT;
  3179. dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
  3180. if (dummy_var_btf_id < 0)
  3181. return dummy_var_btf_id;
  3182. n = sh->sh_size / sh->sh_entsize;
  3183. pr_debug("looking for externs among %d symbols...\n", n);
  3184. for (i = 0; i < n; i++) {
  3185. Elf64_Sym *sym = elf_sym_by_idx(obj, i);
  3186. if (!sym)
  3187. return -LIBBPF_ERRNO__FORMAT;
  3188. if (!sym_is_extern(sym))
  3189. continue;
  3190. ext_name = elf_sym_str(obj, sym->st_name);
  3191. if (!ext_name || !ext_name[0])
  3192. continue;
  3193. ext = obj->externs;
  3194. ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
  3195. if (!ext)
  3196. return -ENOMEM;
  3197. obj->externs = ext;
  3198. ext = &ext[obj->nr_extern];
  3199. memset(ext, 0, sizeof(*ext));
  3200. obj->nr_extern++;
  3201. ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
  3202. if (ext->btf_id <= 0) {
  3203. pr_warn("failed to find BTF for extern '%s': %d\n",
  3204. ext_name, ext->btf_id);
  3205. return ext->btf_id;
  3206. }
  3207. t = btf__type_by_id(obj->btf, ext->btf_id);
  3208. ext->name = btf__name_by_offset(obj->btf, t->name_off);
  3209. ext->sym_idx = i;
  3210. ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
  3211. ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
  3212. if (ext->sec_btf_id <= 0) {
  3213. pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
  3214. ext_name, ext->btf_id, ext->sec_btf_id);
  3215. return ext->sec_btf_id;
  3216. }
  3217. sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
  3218. sec_name = btf__name_by_offset(obj->btf, sec->name_off);
  3219. if (strcmp(sec_name, KCONFIG_SEC) == 0) {
  3220. if (btf_is_func(t)) {
  3221. pr_warn("extern function %s is unsupported under %s section\n",
  3222. ext->name, KCONFIG_SEC);
  3223. return -ENOTSUP;
  3224. }
  3225. kcfg_sec = sec;
  3226. ext->type = EXT_KCFG;
  3227. ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
  3228. if (ext->kcfg.sz <= 0) {
  3229. pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
  3230. ext_name, ext->kcfg.sz);
  3231. return ext->kcfg.sz;
  3232. }
  3233. ext->kcfg.align = btf__align_of(obj->btf, t->type);
  3234. if (ext->kcfg.align <= 0) {
  3235. pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
  3236. ext_name, ext->kcfg.align);
  3237. return -EINVAL;
  3238. }
  3239. ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
  3240. &ext->kcfg.is_signed);
  3241. if (ext->kcfg.type == KCFG_UNKNOWN) {
  3242. pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
  3243. return -ENOTSUP;
  3244. }
  3245. } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
  3246. ksym_sec = sec;
  3247. ext->type = EXT_KSYM;
  3248. skip_mods_and_typedefs(obj->btf, t->type,
  3249. &ext->ksym.type_id);
  3250. } else {
  3251. pr_warn("unrecognized extern section '%s'\n", sec_name);
  3252. return -ENOTSUP;
  3253. }
  3254. }
  3255. pr_debug("collected %d externs total\n", obj->nr_extern);
  3256. if (!obj->nr_extern)
  3257. return 0;
  3258. /* sort externs by type, for kcfg ones also by (align, size, name) */
  3259. qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
  3260. /* for .ksyms section, we need to turn all externs into allocated
  3261. * variables in BTF to pass kernel verification; we do this by
  3262. * pretending that each extern is a 8-byte variable
  3263. */
  3264. if (ksym_sec) {
  3265. /* find existing 4-byte integer type in BTF to use for fake
  3266. * extern variables in DATASEC
  3267. */
  3268. int int_btf_id = find_int_btf_id(obj->btf);
  3269. /* For extern function, a dummy_var added earlier
  3270. * will be used to replace the vs->type and
  3271. * its name string will be used to refill
  3272. * the missing param's name.
  3273. */
  3274. const struct btf_type *dummy_var;
  3275. dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
  3276. for (i = 0; i < obj->nr_extern; i++) {
  3277. ext = &obj->externs[i];
  3278. if (ext->type != EXT_KSYM)
  3279. continue;
  3280. pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
  3281. i, ext->sym_idx, ext->name);
  3282. }
  3283. sec = ksym_sec;
  3284. n = btf_vlen(sec);
  3285. for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
  3286. struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
  3287. struct btf_type *vt;
  3288. vt = (void *)btf__type_by_id(obj->btf, vs->type);
  3289. ext_name = btf__name_by_offset(obj->btf, vt->name_off);
  3290. ext = find_extern_by_name(obj, ext_name);
  3291. if (!ext) {
  3292. pr_warn("failed to find extern definition for BTF %s '%s'\n",
  3293. btf_kind_str(vt), ext_name);
  3294. return -ESRCH;
  3295. }
  3296. if (btf_is_func(vt)) {
  3297. const struct btf_type *func_proto;
  3298. struct btf_param *param;
  3299. int j;
  3300. func_proto = btf__type_by_id(obj->btf,
  3301. vt->type);
  3302. param = btf_params(func_proto);
  3303. /* Reuse the dummy_var string if the
  3304. * func proto does not have param name.
  3305. */
  3306. for (j = 0; j < btf_vlen(func_proto); j++)
  3307. if (param[j].type && !param[j].name_off)
  3308. param[j].name_off =
  3309. dummy_var->name_off;
  3310. vs->type = dummy_var_btf_id;
  3311. vt->info &= ~0xffff;
  3312. vt->info |= BTF_FUNC_GLOBAL;
  3313. } else {
  3314. btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
  3315. vt->type = int_btf_id;
  3316. }
  3317. vs->offset = off;
  3318. vs->size = sizeof(int);
  3319. }
  3320. sec->size = off;
  3321. }
  3322. if (kcfg_sec) {
  3323. sec = kcfg_sec;
  3324. /* for kcfg externs calculate their offsets within a .kconfig map */
  3325. off = 0;
  3326. for (i = 0; i < obj->nr_extern; i++) {
  3327. ext = &obj->externs[i];
  3328. if (ext->type != EXT_KCFG)
  3329. continue;
  3330. ext->kcfg.data_off = roundup(off, ext->kcfg.align);
  3331. off = ext->kcfg.data_off + ext->kcfg.sz;
  3332. pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
  3333. i, ext->sym_idx, ext->kcfg.data_off, ext->name);
  3334. }
  3335. sec->size = off;
  3336. n = btf_vlen(sec);
  3337. for (i = 0; i < n; i++) {
  3338. struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
  3339. t = btf__type_by_id(obj->btf, vs->type);
  3340. ext_name = btf__name_by_offset(obj->btf, t->name_off);
  3341. ext = find_extern_by_name(obj, ext_name);
  3342. if (!ext) {
  3343. pr_warn("failed to find extern definition for BTF var '%s'\n",
  3344. ext_name);
  3345. return -ESRCH;
  3346. }
  3347. btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
  3348. vs->offset = ext->kcfg.data_off;
  3349. }
  3350. }
  3351. return 0;
  3352. }
  3353. static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
  3354. {
  3355. return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
  3356. }
  3357. struct bpf_program *
  3358. bpf_object__find_program_by_name(const struct bpf_object *obj,
  3359. const char *name)
  3360. {
  3361. struct bpf_program *prog;
  3362. bpf_object__for_each_program(prog, obj) {
  3363. if (prog_is_subprog(obj, prog))
  3364. continue;
  3365. if (!strcmp(prog->name, name))
  3366. return prog;
  3367. }
  3368. return errno = ENOENT, NULL;
  3369. }
  3370. static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
  3371. int shndx)
  3372. {
  3373. switch (obj->efile.secs[shndx].sec_type) {
  3374. case SEC_BSS:
  3375. case SEC_DATA:
  3376. case SEC_RODATA:
  3377. return true;
  3378. default:
  3379. return false;
  3380. }
  3381. }
  3382. static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
  3383. int shndx)
  3384. {
  3385. return shndx == obj->efile.btf_maps_shndx;
  3386. }
  3387. static enum libbpf_map_type
  3388. bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
  3389. {
  3390. if (shndx == obj->efile.symbols_shndx)
  3391. return LIBBPF_MAP_KCONFIG;
  3392. switch (obj->efile.secs[shndx].sec_type) {
  3393. case SEC_BSS:
  3394. return LIBBPF_MAP_BSS;
  3395. case SEC_DATA:
  3396. return LIBBPF_MAP_DATA;
  3397. case SEC_RODATA:
  3398. return LIBBPF_MAP_RODATA;
  3399. default:
  3400. return LIBBPF_MAP_UNSPEC;
  3401. }
  3402. }
  3403. static int bpf_program__record_reloc(struct bpf_program *prog,
  3404. struct reloc_desc *reloc_desc,
  3405. __u32 insn_idx, const char *sym_name,
  3406. const Elf64_Sym *sym, const Elf64_Rel *rel)
  3407. {
  3408. struct bpf_insn *insn = &prog->insns[insn_idx];
  3409. size_t map_idx, nr_maps = prog->obj->nr_maps;
  3410. struct bpf_object *obj = prog->obj;
  3411. __u32 shdr_idx = sym->st_shndx;
  3412. enum libbpf_map_type type;
  3413. const char *sym_sec_name;
  3414. struct bpf_map *map;
  3415. if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
  3416. pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
  3417. prog->name, sym_name, insn_idx, insn->code);
  3418. return -LIBBPF_ERRNO__RELOC;
  3419. }
  3420. if (sym_is_extern(sym)) {
  3421. int sym_idx = ELF64_R_SYM(rel->r_info);
  3422. int i, n = obj->nr_extern;
  3423. struct extern_desc *ext;
  3424. for (i = 0; i < n; i++) {
  3425. ext = &obj->externs[i];
  3426. if (ext->sym_idx == sym_idx)
  3427. break;
  3428. }
  3429. if (i >= n) {
  3430. pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
  3431. prog->name, sym_name, sym_idx);
  3432. return -LIBBPF_ERRNO__RELOC;
  3433. }
  3434. pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
  3435. prog->name, i, ext->name, ext->sym_idx, insn_idx);
  3436. if (insn->code == (BPF_JMP | BPF_CALL))
  3437. reloc_desc->type = RELO_EXTERN_FUNC;
  3438. else
  3439. reloc_desc->type = RELO_EXTERN_VAR;
  3440. reloc_desc->insn_idx = insn_idx;
  3441. reloc_desc->sym_off = i; /* sym_off stores extern index */
  3442. return 0;
  3443. }
  3444. /* sub-program call relocation */
  3445. if (is_call_insn(insn)) {
  3446. if (insn->src_reg != BPF_PSEUDO_CALL) {
  3447. pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
  3448. return -LIBBPF_ERRNO__RELOC;
  3449. }
  3450. /* text_shndx can be 0, if no default "main" program exists */
  3451. if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
  3452. sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
  3453. pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
  3454. prog->name, sym_name, sym_sec_name);
  3455. return -LIBBPF_ERRNO__RELOC;
  3456. }
  3457. if (sym->st_value % BPF_INSN_SZ) {
  3458. pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
  3459. prog->name, sym_name, (size_t)sym->st_value);
  3460. return -LIBBPF_ERRNO__RELOC;
  3461. }
  3462. reloc_desc->type = RELO_CALL;
  3463. reloc_desc->insn_idx = insn_idx;
  3464. reloc_desc->sym_off = sym->st_value;
  3465. return 0;
  3466. }
  3467. if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
  3468. pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
  3469. prog->name, sym_name, shdr_idx);
  3470. return -LIBBPF_ERRNO__RELOC;
  3471. }
  3472. /* loading subprog addresses */
  3473. if (sym_is_subprog(sym, obj->efile.text_shndx)) {
  3474. /* global_func: sym->st_value = offset in the section, insn->imm = 0.
  3475. * local_func: sym->st_value = 0, insn->imm = offset in the section.
  3476. */
  3477. if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
  3478. pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
  3479. prog->name, sym_name, (size_t)sym->st_value, insn->imm);
  3480. return -LIBBPF_ERRNO__RELOC;
  3481. }
  3482. reloc_desc->type = RELO_SUBPROG_ADDR;
  3483. reloc_desc->insn_idx = insn_idx;
  3484. reloc_desc->sym_off = sym->st_value;
  3485. return 0;
  3486. }
  3487. type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
  3488. sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
  3489. /* generic map reference relocation */
  3490. if (type == LIBBPF_MAP_UNSPEC) {
  3491. if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
  3492. pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
  3493. prog->name, sym_name, sym_sec_name);
  3494. return -LIBBPF_ERRNO__RELOC;
  3495. }
  3496. for (map_idx = 0; map_idx < nr_maps; map_idx++) {
  3497. map = &obj->maps[map_idx];
  3498. if (map->libbpf_type != type ||
  3499. map->sec_idx != sym->st_shndx ||
  3500. map->sec_offset != sym->st_value)
  3501. continue;
  3502. pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
  3503. prog->name, map_idx, map->name, map->sec_idx,
  3504. map->sec_offset, insn_idx);
  3505. break;
  3506. }
  3507. if (map_idx >= nr_maps) {
  3508. pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
  3509. prog->name, sym_sec_name, (size_t)sym->st_value);
  3510. return -LIBBPF_ERRNO__RELOC;
  3511. }
  3512. reloc_desc->type = RELO_LD64;
  3513. reloc_desc->insn_idx = insn_idx;
  3514. reloc_desc->map_idx = map_idx;
  3515. reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
  3516. return 0;
  3517. }
  3518. /* global data map relocation */
  3519. if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
  3520. pr_warn("prog '%s': bad data relo against section '%s'\n",
  3521. prog->name, sym_sec_name);
  3522. return -LIBBPF_ERRNO__RELOC;
  3523. }
  3524. for (map_idx = 0; map_idx < nr_maps; map_idx++) {
  3525. map = &obj->maps[map_idx];
  3526. if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
  3527. continue;
  3528. pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
  3529. prog->name, map_idx, map->name, map->sec_idx,
  3530. map->sec_offset, insn_idx);
  3531. break;
  3532. }
  3533. if (map_idx >= nr_maps) {
  3534. pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
  3535. prog->name, sym_sec_name);
  3536. return -LIBBPF_ERRNO__RELOC;
  3537. }
  3538. reloc_desc->type = RELO_DATA;
  3539. reloc_desc->insn_idx = insn_idx;
  3540. reloc_desc->map_idx = map_idx;
  3541. reloc_desc->sym_off = sym->st_value;
  3542. return 0;
  3543. }
  3544. static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
  3545. {
  3546. return insn_idx >= prog->sec_insn_off &&
  3547. insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
  3548. }
  3549. static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
  3550. size_t sec_idx, size_t insn_idx)
  3551. {
  3552. int l = 0, r = obj->nr_programs - 1, m;
  3553. struct bpf_program *prog;
  3554. if (!obj->nr_programs)
  3555. return NULL;
  3556. while (l < r) {
  3557. m = l + (r - l + 1) / 2;
  3558. prog = &obj->programs[m];
  3559. if (prog->sec_idx < sec_idx ||
  3560. (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
  3561. l = m;
  3562. else
  3563. r = m - 1;
  3564. }
  3565. /* matching program could be at index l, but it still might be the
  3566. * wrong one, so we need to double check conditions for the last time
  3567. */
  3568. prog = &obj->programs[l];
  3569. if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
  3570. return prog;
  3571. return NULL;
  3572. }
  3573. static int
  3574. bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
  3575. {
  3576. const char *relo_sec_name, *sec_name;
  3577. size_t sec_idx = shdr->sh_info, sym_idx;
  3578. struct bpf_program *prog;
  3579. struct reloc_desc *relos;
  3580. int err, i, nrels;
  3581. const char *sym_name;
  3582. __u32 insn_idx;
  3583. Elf_Scn *scn;
  3584. Elf_Data *scn_data;
  3585. Elf64_Sym *sym;
  3586. Elf64_Rel *rel;
  3587. if (sec_idx >= obj->efile.sec_cnt)
  3588. return -EINVAL;
  3589. scn = elf_sec_by_idx(obj, sec_idx);
  3590. scn_data = elf_sec_data(obj, scn);
  3591. relo_sec_name = elf_sec_str(obj, shdr->sh_name);
  3592. sec_name = elf_sec_name(obj, scn);
  3593. if (!relo_sec_name || !sec_name)
  3594. return -EINVAL;
  3595. pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
  3596. relo_sec_name, sec_idx, sec_name);
  3597. nrels = shdr->sh_size / shdr->sh_entsize;
  3598. for (i = 0; i < nrels; i++) {
  3599. rel = elf_rel_by_idx(data, i);
  3600. if (!rel) {
  3601. pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
  3602. return -LIBBPF_ERRNO__FORMAT;
  3603. }
  3604. sym_idx = ELF64_R_SYM(rel->r_info);
  3605. sym = elf_sym_by_idx(obj, sym_idx);
  3606. if (!sym) {
  3607. pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
  3608. relo_sec_name, sym_idx, i);
  3609. return -LIBBPF_ERRNO__FORMAT;
  3610. }
  3611. if (sym->st_shndx >= obj->efile.sec_cnt) {
  3612. pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
  3613. relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
  3614. return -LIBBPF_ERRNO__FORMAT;
  3615. }
  3616. if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
  3617. pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
  3618. relo_sec_name, (size_t)rel->r_offset, i);
  3619. return -LIBBPF_ERRNO__FORMAT;
  3620. }
  3621. insn_idx = rel->r_offset / BPF_INSN_SZ;
  3622. /* relocations against static functions are recorded as
  3623. * relocations against the section that contains a function;
  3624. * in such case, symbol will be STT_SECTION and sym.st_name
  3625. * will point to empty string (0), so fetch section name
  3626. * instead
  3627. */
  3628. if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
  3629. sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
  3630. else
  3631. sym_name = elf_sym_str(obj, sym->st_name);
  3632. sym_name = sym_name ?: "<?";
  3633. pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
  3634. relo_sec_name, i, insn_idx, sym_name);
  3635. prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
  3636. if (!prog) {
  3637. pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
  3638. relo_sec_name, i, sec_name, insn_idx);
  3639. continue;
  3640. }
  3641. relos = libbpf_reallocarray(prog->reloc_desc,
  3642. prog->nr_reloc + 1, sizeof(*relos));
  3643. if (!relos)
  3644. return -ENOMEM;
  3645. prog->reloc_desc = relos;
  3646. /* adjust insn_idx to local BPF program frame of reference */
  3647. insn_idx -= prog->sec_insn_off;
  3648. err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
  3649. insn_idx, sym_name, sym, rel);
  3650. if (err)
  3651. return err;
  3652. prog->nr_reloc++;
  3653. }
  3654. return 0;
  3655. }
  3656. static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
  3657. {
  3658. int id;
  3659. if (!obj->btf)
  3660. return -ENOENT;
  3661. /* if it's BTF-defined map, we don't need to search for type IDs.
  3662. * For struct_ops map, it does not need btf_key_type_id and
  3663. * btf_value_type_id.
  3664. */
  3665. if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
  3666. return 0;
  3667. /*
  3668. * LLVM annotates global data differently in BTF, that is,
  3669. * only as '.data', '.bss' or '.rodata'.
  3670. */
  3671. if (!bpf_map__is_internal(map))
  3672. return -ENOENT;
  3673. id = btf__find_by_name(obj->btf, map->real_name);
  3674. if (id < 0)
  3675. return id;
  3676. map->btf_key_type_id = 0;
  3677. map->btf_value_type_id = id;
  3678. return 0;
  3679. }
  3680. static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
  3681. {
  3682. char file[PATH_MAX], buff[4096];
  3683. FILE *fp;
  3684. __u32 val;
  3685. int err;
  3686. snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
  3687. memset(info, 0, sizeof(*info));
  3688. fp = fopen(file, "r");
  3689. if (!fp) {
  3690. err = -errno;
  3691. pr_warn("failed to open %s: %d. No procfs support?\n", file,
  3692. err);
  3693. return err;
  3694. }
  3695. while (fgets(buff, sizeof(buff), fp)) {
  3696. if (sscanf(buff, "map_type:\t%u", &val) == 1)
  3697. info->type = val;
  3698. else if (sscanf(buff, "key_size:\t%u", &val) == 1)
  3699. info->key_size = val;
  3700. else if (sscanf(buff, "value_size:\t%u", &val) == 1)
  3701. info->value_size = val;
  3702. else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
  3703. info->max_entries = val;
  3704. else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
  3705. info->map_flags = val;
  3706. }
  3707. fclose(fp);
  3708. return 0;
  3709. }
  3710. bool bpf_map__autocreate(const struct bpf_map *map)
  3711. {
  3712. return map->autocreate;
  3713. }
  3714. int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
  3715. {
  3716. if (map->obj->loaded)
  3717. return libbpf_err(-EBUSY);
  3718. map->autocreate = autocreate;
  3719. return 0;
  3720. }
  3721. int bpf_map__reuse_fd(struct bpf_map *map, int fd)
  3722. {
  3723. struct bpf_map_info info;
  3724. __u32 len = sizeof(info), name_len;
  3725. int new_fd, err;
  3726. char *new_name;
  3727. memset(&info, 0, len);
  3728. err = bpf_obj_get_info_by_fd(fd, &info, &len);
  3729. if (err && errno == EINVAL)
  3730. err = bpf_get_map_info_from_fdinfo(fd, &info);
  3731. if (err)
  3732. return libbpf_err(err);
  3733. name_len = strlen(info.name);
  3734. if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
  3735. new_name = strdup(map->name);
  3736. else
  3737. new_name = strdup(info.name);
  3738. if (!new_name)
  3739. return libbpf_err(-errno);
  3740. new_fd = open("/", O_RDONLY | O_CLOEXEC);
  3741. if (new_fd < 0) {
  3742. err = -errno;
  3743. goto err_free_new_name;
  3744. }
  3745. new_fd = dup3(fd, new_fd, O_CLOEXEC);
  3746. if (new_fd < 0) {
  3747. err = -errno;
  3748. goto err_close_new_fd;
  3749. }
  3750. err = zclose(map->fd);
  3751. if (err) {
  3752. err = -errno;
  3753. goto err_close_new_fd;
  3754. }
  3755. free(map->name);
  3756. map->fd = new_fd;
  3757. map->name = new_name;
  3758. map->def.type = info.type;
  3759. map->def.key_size = info.key_size;
  3760. map->def.value_size = info.value_size;
  3761. map->def.max_entries = info.max_entries;
  3762. map->def.map_flags = info.map_flags;
  3763. map->btf_key_type_id = info.btf_key_type_id;
  3764. map->btf_value_type_id = info.btf_value_type_id;
  3765. map->reused = true;
  3766. map->map_extra = info.map_extra;
  3767. return 0;
  3768. err_close_new_fd:
  3769. close(new_fd);
  3770. err_free_new_name:
  3771. free(new_name);
  3772. return libbpf_err(err);
  3773. }
  3774. __u32 bpf_map__max_entries(const struct bpf_map *map)
  3775. {
  3776. return map->def.max_entries;
  3777. }
  3778. struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
  3779. {
  3780. if (!bpf_map_type__is_map_in_map(map->def.type))
  3781. return errno = EINVAL, NULL;
  3782. return map->inner_map;
  3783. }
  3784. int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
  3785. {
  3786. if (map->obj->loaded)
  3787. return libbpf_err(-EBUSY);
  3788. map->def.max_entries = max_entries;
  3789. /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
  3790. if (map_is_ringbuf(map))
  3791. map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
  3792. return 0;
  3793. }
  3794. static int
  3795. bpf_object__probe_loading(struct bpf_object *obj)
  3796. {
  3797. char *cp, errmsg[STRERR_BUFSIZE];
  3798. struct bpf_insn insns[] = {
  3799. BPF_MOV64_IMM(BPF_REG_0, 0),
  3800. BPF_EXIT_INSN(),
  3801. };
  3802. int ret, insn_cnt = ARRAY_SIZE(insns);
  3803. if (obj->gen_loader)
  3804. return 0;
  3805. ret = bump_rlimit_memlock();
  3806. if (ret)
  3807. pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
  3808. /* make sure basic loading works */
  3809. ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
  3810. if (ret < 0)
  3811. ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
  3812. if (ret < 0) {
  3813. ret = errno;
  3814. cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
  3815. pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
  3816. "program. Make sure your kernel supports BPF "
  3817. "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
  3818. "set to big enough value.\n", __func__, cp, ret);
  3819. return -ret;
  3820. }
  3821. close(ret);
  3822. return 0;
  3823. }
  3824. static int probe_fd(int fd)
  3825. {
  3826. if (fd >= 0)
  3827. close(fd);
  3828. return fd >= 0;
  3829. }
  3830. static int probe_kern_prog_name(void)
  3831. {
  3832. const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
  3833. struct bpf_insn insns[] = {
  3834. BPF_MOV64_IMM(BPF_REG_0, 0),
  3835. BPF_EXIT_INSN(),
  3836. };
  3837. union bpf_attr attr;
  3838. int ret;
  3839. memset(&attr, 0, attr_sz);
  3840. attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
  3841. attr.license = ptr_to_u64("GPL");
  3842. attr.insns = ptr_to_u64(insns);
  3843. attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
  3844. libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
  3845. /* make sure loading with name works */
  3846. ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
  3847. return probe_fd(ret);
  3848. }
  3849. static int probe_kern_global_data(void)
  3850. {
  3851. char *cp, errmsg[STRERR_BUFSIZE];
  3852. struct bpf_insn insns[] = {
  3853. BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
  3854. BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
  3855. BPF_MOV64_IMM(BPF_REG_0, 0),
  3856. BPF_EXIT_INSN(),
  3857. };
  3858. int ret, map, insn_cnt = ARRAY_SIZE(insns);
  3859. map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
  3860. if (map < 0) {
  3861. ret = -errno;
  3862. cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
  3863. pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
  3864. __func__, cp, -ret);
  3865. return ret;
  3866. }
  3867. insns[0].imm = map;
  3868. ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
  3869. close(map);
  3870. return probe_fd(ret);
  3871. }
  3872. static int probe_kern_btf(void)
  3873. {
  3874. static const char strs[] = "\0int";
  3875. __u32 types[] = {
  3876. /* int */
  3877. BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
  3878. };
  3879. return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
  3880. strs, sizeof(strs)));
  3881. }
  3882. static int probe_kern_btf_func(void)
  3883. {
  3884. static const char strs[] = "\0int\0x\0a";
  3885. /* void x(int a) {} */
  3886. __u32 types[] = {
  3887. /* int */
  3888. BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
  3889. /* FUNC_PROTO */ /* [2] */
  3890. BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
  3891. BTF_PARAM_ENC(7, 1),
  3892. /* FUNC x */ /* [3] */
  3893. BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
  3894. };
  3895. return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
  3896. strs, sizeof(strs)));
  3897. }
  3898. static int probe_kern_btf_func_global(void)
  3899. {
  3900. static const char strs[] = "\0int\0x\0a";
  3901. /* static void x(int a) {} */
  3902. __u32 types[] = {
  3903. /* int */
  3904. BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
  3905. /* FUNC_PROTO */ /* [2] */
  3906. BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
  3907. BTF_PARAM_ENC(7, 1),
  3908. /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
  3909. BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
  3910. };
  3911. return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
  3912. strs, sizeof(strs)));
  3913. }
  3914. static int probe_kern_btf_datasec(void)
  3915. {
  3916. static const char strs[] = "\0x\0.data";
  3917. /* static int a; */
  3918. __u32 types[] = {
  3919. /* int */
  3920. BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
  3921. /* VAR x */ /* [2] */
  3922. BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
  3923. BTF_VAR_STATIC,
  3924. /* DATASEC val */ /* [3] */
  3925. BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
  3926. BTF_VAR_SECINFO_ENC(2, 0, 4),
  3927. };
  3928. return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
  3929. strs, sizeof(strs)));
  3930. }
  3931. static int probe_kern_btf_float(void)
  3932. {
  3933. static const char strs[] = "\0float";
  3934. __u32 types[] = {
  3935. /* float */
  3936. BTF_TYPE_FLOAT_ENC(1, 4),
  3937. };
  3938. return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
  3939. strs, sizeof(strs)));
  3940. }
  3941. static int probe_kern_btf_decl_tag(void)
  3942. {
  3943. static const char strs[] = "\0tag";
  3944. __u32 types[] = {
  3945. /* int */
  3946. BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
  3947. /* VAR x */ /* [2] */
  3948. BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
  3949. BTF_VAR_STATIC,
  3950. /* attr */
  3951. BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
  3952. };
  3953. return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
  3954. strs, sizeof(strs)));
  3955. }
  3956. static int probe_kern_btf_type_tag(void)
  3957. {
  3958. static const char strs[] = "\0tag";
  3959. __u32 types[] = {
  3960. /* int */
  3961. BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
  3962. /* attr */
  3963. BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
  3964. /* ptr */
  3965. BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
  3966. };
  3967. return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
  3968. strs, sizeof(strs)));
  3969. }
  3970. static int probe_kern_array_mmap(void)
  3971. {
  3972. LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
  3973. int fd;
  3974. fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
  3975. return probe_fd(fd);
  3976. }
  3977. static int probe_kern_exp_attach_type(void)
  3978. {
  3979. LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
  3980. struct bpf_insn insns[] = {
  3981. BPF_MOV64_IMM(BPF_REG_0, 0),
  3982. BPF_EXIT_INSN(),
  3983. };
  3984. int fd, insn_cnt = ARRAY_SIZE(insns);
  3985. /* use any valid combination of program type and (optional)
  3986. * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
  3987. * to see if kernel supports expected_attach_type field for
  3988. * BPF_PROG_LOAD command
  3989. */
  3990. fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
  3991. return probe_fd(fd);
  3992. }
  3993. static int probe_kern_probe_read_kernel(void)
  3994. {
  3995. struct bpf_insn insns[] = {
  3996. BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
  3997. BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
  3998. BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
  3999. BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
  4000. BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
  4001. BPF_EXIT_INSN(),
  4002. };
  4003. int fd, insn_cnt = ARRAY_SIZE(insns);
  4004. fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
  4005. return probe_fd(fd);
  4006. }
  4007. static int probe_prog_bind_map(void)
  4008. {
  4009. char *cp, errmsg[STRERR_BUFSIZE];
  4010. struct bpf_insn insns[] = {
  4011. BPF_MOV64_IMM(BPF_REG_0, 0),
  4012. BPF_EXIT_INSN(),
  4013. };
  4014. int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
  4015. map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
  4016. if (map < 0) {
  4017. ret = -errno;
  4018. cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
  4019. pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
  4020. __func__, cp, -ret);
  4021. return ret;
  4022. }
  4023. prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
  4024. if (prog < 0) {
  4025. close(map);
  4026. return 0;
  4027. }
  4028. ret = bpf_prog_bind_map(prog, map, NULL);
  4029. close(map);
  4030. close(prog);
  4031. return ret >= 0;
  4032. }
  4033. static int probe_module_btf(void)
  4034. {
  4035. static const char strs[] = "\0int";
  4036. __u32 types[] = {
  4037. /* int */
  4038. BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
  4039. };
  4040. struct bpf_btf_info info;
  4041. __u32 len = sizeof(info);
  4042. char name[16];
  4043. int fd, err;
  4044. fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
  4045. if (fd < 0)
  4046. return 0; /* BTF not supported at all */
  4047. memset(&info, 0, sizeof(info));
  4048. info.name = ptr_to_u64(name);
  4049. info.name_len = sizeof(name);
  4050. /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
  4051. * kernel's module BTF support coincides with support for
  4052. * name/name_len fields in struct bpf_btf_info.
  4053. */
  4054. err = bpf_obj_get_info_by_fd(fd, &info, &len);
  4055. close(fd);
  4056. return !err;
  4057. }
  4058. static int probe_perf_link(void)
  4059. {
  4060. struct bpf_insn insns[] = {
  4061. BPF_MOV64_IMM(BPF_REG_0, 0),
  4062. BPF_EXIT_INSN(),
  4063. };
  4064. int prog_fd, link_fd, err;
  4065. prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
  4066. insns, ARRAY_SIZE(insns), NULL);
  4067. if (prog_fd < 0)
  4068. return -errno;
  4069. /* use invalid perf_event FD to get EBADF, if link is supported;
  4070. * otherwise EINVAL should be returned
  4071. */
  4072. link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
  4073. err = -errno; /* close() can clobber errno */
  4074. if (link_fd >= 0)
  4075. close(link_fd);
  4076. close(prog_fd);
  4077. return link_fd < 0 && err == -EBADF;
  4078. }
  4079. static int probe_kern_bpf_cookie(void)
  4080. {
  4081. struct bpf_insn insns[] = {
  4082. BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
  4083. BPF_EXIT_INSN(),
  4084. };
  4085. int ret, insn_cnt = ARRAY_SIZE(insns);
  4086. ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
  4087. return probe_fd(ret);
  4088. }
  4089. static int probe_kern_btf_enum64(void)
  4090. {
  4091. static const char strs[] = "\0enum64";
  4092. __u32 types[] = {
  4093. BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
  4094. };
  4095. return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
  4096. strs, sizeof(strs)));
  4097. }
  4098. static int probe_kern_syscall_wrapper(void);
  4099. enum kern_feature_result {
  4100. FEAT_UNKNOWN = 0,
  4101. FEAT_SUPPORTED = 1,
  4102. FEAT_MISSING = 2,
  4103. };
  4104. typedef int (*feature_probe_fn)(void);
  4105. static struct kern_feature_desc {
  4106. const char *desc;
  4107. feature_probe_fn probe;
  4108. enum kern_feature_result res;
  4109. } feature_probes[__FEAT_CNT] = {
  4110. [FEAT_PROG_NAME] = {
  4111. "BPF program name", probe_kern_prog_name,
  4112. },
  4113. [FEAT_GLOBAL_DATA] = {
  4114. "global variables", probe_kern_global_data,
  4115. },
  4116. [FEAT_BTF] = {
  4117. "minimal BTF", probe_kern_btf,
  4118. },
  4119. [FEAT_BTF_FUNC] = {
  4120. "BTF functions", probe_kern_btf_func,
  4121. },
  4122. [FEAT_BTF_GLOBAL_FUNC] = {
  4123. "BTF global function", probe_kern_btf_func_global,
  4124. },
  4125. [FEAT_BTF_DATASEC] = {
  4126. "BTF data section and variable", probe_kern_btf_datasec,
  4127. },
  4128. [FEAT_ARRAY_MMAP] = {
  4129. "ARRAY map mmap()", probe_kern_array_mmap,
  4130. },
  4131. [FEAT_EXP_ATTACH_TYPE] = {
  4132. "BPF_PROG_LOAD expected_attach_type attribute",
  4133. probe_kern_exp_attach_type,
  4134. },
  4135. [FEAT_PROBE_READ_KERN] = {
  4136. "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
  4137. },
  4138. [FEAT_PROG_BIND_MAP] = {
  4139. "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
  4140. },
  4141. [FEAT_MODULE_BTF] = {
  4142. "module BTF support", probe_module_btf,
  4143. },
  4144. [FEAT_BTF_FLOAT] = {
  4145. "BTF_KIND_FLOAT support", probe_kern_btf_float,
  4146. },
  4147. [FEAT_PERF_LINK] = {
  4148. "BPF perf link support", probe_perf_link,
  4149. },
  4150. [FEAT_BTF_DECL_TAG] = {
  4151. "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
  4152. },
  4153. [FEAT_BTF_TYPE_TAG] = {
  4154. "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
  4155. },
  4156. [FEAT_MEMCG_ACCOUNT] = {
  4157. "memcg-based memory accounting", probe_memcg_account,
  4158. },
  4159. [FEAT_BPF_COOKIE] = {
  4160. "BPF cookie support", probe_kern_bpf_cookie,
  4161. },
  4162. [FEAT_BTF_ENUM64] = {
  4163. "BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
  4164. },
  4165. [FEAT_SYSCALL_WRAPPER] = {
  4166. "Kernel using syscall wrapper", probe_kern_syscall_wrapper,
  4167. },
  4168. };
  4169. bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
  4170. {
  4171. struct kern_feature_desc *feat = &feature_probes[feat_id];
  4172. int ret;
  4173. if (obj && obj->gen_loader)
  4174. /* To generate loader program assume the latest kernel
  4175. * to avoid doing extra prog_load, map_create syscalls.
  4176. */
  4177. return true;
  4178. if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
  4179. ret = feat->probe();
  4180. if (ret > 0) {
  4181. WRITE_ONCE(feat->res, FEAT_SUPPORTED);
  4182. } else if (ret == 0) {
  4183. WRITE_ONCE(feat->res, FEAT_MISSING);
  4184. } else {
  4185. pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
  4186. WRITE_ONCE(feat->res, FEAT_MISSING);
  4187. }
  4188. }
  4189. return READ_ONCE(feat->res) == FEAT_SUPPORTED;
  4190. }
  4191. static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
  4192. {
  4193. struct bpf_map_info map_info;
  4194. char msg[STRERR_BUFSIZE];
  4195. __u32 map_info_len = sizeof(map_info);
  4196. int err;
  4197. memset(&map_info, 0, map_info_len);
  4198. err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
  4199. if (err && errno == EINVAL)
  4200. err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
  4201. if (err) {
  4202. pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
  4203. libbpf_strerror_r(errno, msg, sizeof(msg)));
  4204. return false;
  4205. }
  4206. return (map_info.type == map->def.type &&
  4207. map_info.key_size == map->def.key_size &&
  4208. map_info.value_size == map->def.value_size &&
  4209. map_info.max_entries == map->def.max_entries &&
  4210. map_info.map_flags == map->def.map_flags &&
  4211. map_info.map_extra == map->map_extra);
  4212. }
  4213. static int
  4214. bpf_object__reuse_map(struct bpf_map *map)
  4215. {
  4216. char *cp, errmsg[STRERR_BUFSIZE];
  4217. int err, pin_fd;
  4218. pin_fd = bpf_obj_get(map->pin_path);
  4219. if (pin_fd < 0) {
  4220. err = -errno;
  4221. if (err == -ENOENT) {
  4222. pr_debug("found no pinned map to reuse at '%s'\n",
  4223. map->pin_path);
  4224. return 0;
  4225. }
  4226. cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
  4227. pr_warn("couldn't retrieve pinned map '%s': %s\n",
  4228. map->pin_path, cp);
  4229. return err;
  4230. }
  4231. if (!map_is_reuse_compat(map, pin_fd)) {
  4232. pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
  4233. map->pin_path);
  4234. close(pin_fd);
  4235. return -EINVAL;
  4236. }
  4237. err = bpf_map__reuse_fd(map, pin_fd);
  4238. close(pin_fd);
  4239. if (err) {
  4240. return err;
  4241. }
  4242. map->pinned = true;
  4243. pr_debug("reused pinned map at '%s'\n", map->pin_path);
  4244. return 0;
  4245. }
  4246. static int
  4247. bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
  4248. {
  4249. enum libbpf_map_type map_type = map->libbpf_type;
  4250. char *cp, errmsg[STRERR_BUFSIZE];
  4251. int err, zero = 0;
  4252. if (obj->gen_loader) {
  4253. bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
  4254. map->mmaped, map->def.value_size);
  4255. if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
  4256. bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
  4257. return 0;
  4258. }
  4259. err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
  4260. if (err) {
  4261. err = -errno;
  4262. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  4263. pr_warn("Error setting initial map(%s) contents: %s\n",
  4264. map->name, cp);
  4265. return err;
  4266. }
  4267. /* Freeze .rodata and .kconfig map as read-only from syscall side. */
  4268. if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
  4269. err = bpf_map_freeze(map->fd);
  4270. if (err) {
  4271. err = -errno;
  4272. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  4273. pr_warn("Error freezing map(%s) as read-only: %s\n",
  4274. map->name, cp);
  4275. return err;
  4276. }
  4277. }
  4278. return 0;
  4279. }
  4280. static void bpf_map__destroy(struct bpf_map *map);
  4281. static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
  4282. {
  4283. LIBBPF_OPTS(bpf_map_create_opts, create_attr);
  4284. struct bpf_map_def *def = &map->def;
  4285. const char *map_name = NULL;
  4286. int err = 0;
  4287. if (kernel_supports(obj, FEAT_PROG_NAME))
  4288. map_name = map->name;
  4289. create_attr.map_ifindex = map->map_ifindex;
  4290. create_attr.map_flags = def->map_flags;
  4291. create_attr.numa_node = map->numa_node;
  4292. create_attr.map_extra = map->map_extra;
  4293. if (bpf_map__is_struct_ops(map))
  4294. create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
  4295. if (obj->btf && btf__fd(obj->btf) >= 0) {
  4296. create_attr.btf_fd = btf__fd(obj->btf);
  4297. create_attr.btf_key_type_id = map->btf_key_type_id;
  4298. create_attr.btf_value_type_id = map->btf_value_type_id;
  4299. }
  4300. if (bpf_map_type__is_map_in_map(def->type)) {
  4301. if (map->inner_map) {
  4302. err = bpf_object__create_map(obj, map->inner_map, true);
  4303. if (err) {
  4304. pr_warn("map '%s': failed to create inner map: %d\n",
  4305. map->name, err);
  4306. return err;
  4307. }
  4308. map->inner_map_fd = bpf_map__fd(map->inner_map);
  4309. }
  4310. if (map->inner_map_fd >= 0)
  4311. create_attr.inner_map_fd = map->inner_map_fd;
  4312. }
  4313. switch (def->type) {
  4314. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  4315. case BPF_MAP_TYPE_CGROUP_ARRAY:
  4316. case BPF_MAP_TYPE_STACK_TRACE:
  4317. case BPF_MAP_TYPE_ARRAY_OF_MAPS:
  4318. case BPF_MAP_TYPE_HASH_OF_MAPS:
  4319. case BPF_MAP_TYPE_DEVMAP:
  4320. case BPF_MAP_TYPE_DEVMAP_HASH:
  4321. case BPF_MAP_TYPE_CPUMAP:
  4322. case BPF_MAP_TYPE_XSKMAP:
  4323. case BPF_MAP_TYPE_SOCKMAP:
  4324. case BPF_MAP_TYPE_SOCKHASH:
  4325. case BPF_MAP_TYPE_QUEUE:
  4326. case BPF_MAP_TYPE_STACK:
  4327. create_attr.btf_fd = 0;
  4328. create_attr.btf_key_type_id = 0;
  4329. create_attr.btf_value_type_id = 0;
  4330. map->btf_key_type_id = 0;
  4331. map->btf_value_type_id = 0;
  4332. default:
  4333. break;
  4334. }
  4335. if (obj->gen_loader) {
  4336. bpf_gen__map_create(obj->gen_loader, def->type, map_name,
  4337. def->key_size, def->value_size, def->max_entries,
  4338. &create_attr, is_inner ? -1 : map - obj->maps);
  4339. /* Pretend to have valid FD to pass various fd >= 0 checks.
  4340. * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
  4341. */
  4342. map->fd = 0;
  4343. } else {
  4344. map->fd = bpf_map_create(def->type, map_name,
  4345. def->key_size, def->value_size,
  4346. def->max_entries, &create_attr);
  4347. }
  4348. if (map->fd < 0 && (create_attr.btf_key_type_id ||
  4349. create_attr.btf_value_type_id)) {
  4350. char *cp, errmsg[STRERR_BUFSIZE];
  4351. err = -errno;
  4352. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  4353. pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
  4354. map->name, cp, err);
  4355. create_attr.btf_fd = 0;
  4356. create_attr.btf_key_type_id = 0;
  4357. create_attr.btf_value_type_id = 0;
  4358. map->btf_key_type_id = 0;
  4359. map->btf_value_type_id = 0;
  4360. map->fd = bpf_map_create(def->type, map_name,
  4361. def->key_size, def->value_size,
  4362. def->max_entries, &create_attr);
  4363. }
  4364. err = map->fd < 0 ? -errno : 0;
  4365. if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
  4366. if (obj->gen_loader)
  4367. map->inner_map->fd = -1;
  4368. bpf_map__destroy(map->inner_map);
  4369. zfree(&map->inner_map);
  4370. }
  4371. return err;
  4372. }
  4373. static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
  4374. {
  4375. const struct bpf_map *targ_map;
  4376. unsigned int i;
  4377. int fd, err = 0;
  4378. for (i = 0; i < map->init_slots_sz; i++) {
  4379. if (!map->init_slots[i])
  4380. continue;
  4381. targ_map = map->init_slots[i];
  4382. fd = bpf_map__fd(targ_map);
  4383. if (obj->gen_loader) {
  4384. bpf_gen__populate_outer_map(obj->gen_loader,
  4385. map - obj->maps, i,
  4386. targ_map - obj->maps);
  4387. } else {
  4388. err = bpf_map_update_elem(map->fd, &i, &fd, 0);
  4389. }
  4390. if (err) {
  4391. err = -errno;
  4392. pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
  4393. map->name, i, targ_map->name, fd, err);
  4394. return err;
  4395. }
  4396. pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
  4397. map->name, i, targ_map->name, fd);
  4398. }
  4399. zfree(&map->init_slots);
  4400. map->init_slots_sz = 0;
  4401. return 0;
  4402. }
  4403. static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
  4404. {
  4405. const struct bpf_program *targ_prog;
  4406. unsigned int i;
  4407. int fd, err;
  4408. if (obj->gen_loader)
  4409. return -ENOTSUP;
  4410. for (i = 0; i < map->init_slots_sz; i++) {
  4411. if (!map->init_slots[i])
  4412. continue;
  4413. targ_prog = map->init_slots[i];
  4414. fd = bpf_program__fd(targ_prog);
  4415. err = bpf_map_update_elem(map->fd, &i, &fd, 0);
  4416. if (err) {
  4417. err = -errno;
  4418. pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
  4419. map->name, i, targ_prog->name, fd, err);
  4420. return err;
  4421. }
  4422. pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
  4423. map->name, i, targ_prog->name, fd);
  4424. }
  4425. zfree(&map->init_slots);
  4426. map->init_slots_sz = 0;
  4427. return 0;
  4428. }
  4429. static int bpf_object_init_prog_arrays(struct bpf_object *obj)
  4430. {
  4431. struct bpf_map *map;
  4432. int i, err;
  4433. for (i = 0; i < obj->nr_maps; i++) {
  4434. map = &obj->maps[i];
  4435. if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
  4436. continue;
  4437. err = init_prog_array_slots(obj, map);
  4438. if (err < 0) {
  4439. zclose(map->fd);
  4440. return err;
  4441. }
  4442. }
  4443. return 0;
  4444. }
  4445. static int map_set_def_max_entries(struct bpf_map *map)
  4446. {
  4447. if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
  4448. int nr_cpus;
  4449. nr_cpus = libbpf_num_possible_cpus();
  4450. if (nr_cpus < 0) {
  4451. pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
  4452. map->name, nr_cpus);
  4453. return nr_cpus;
  4454. }
  4455. pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
  4456. map->def.max_entries = nr_cpus;
  4457. }
  4458. return 0;
  4459. }
  4460. static int
  4461. bpf_object__create_maps(struct bpf_object *obj)
  4462. {
  4463. struct bpf_map *map;
  4464. char *cp, errmsg[STRERR_BUFSIZE];
  4465. unsigned int i, j;
  4466. int err;
  4467. bool retried;
  4468. for (i = 0; i < obj->nr_maps; i++) {
  4469. map = &obj->maps[i];
  4470. /* To support old kernels, we skip creating global data maps
  4471. * (.rodata, .data, .kconfig, etc); later on, during program
  4472. * loading, if we detect that at least one of the to-be-loaded
  4473. * programs is referencing any global data map, we'll error
  4474. * out with program name and relocation index logged.
  4475. * This approach allows to accommodate Clang emitting
  4476. * unnecessary .rodata.str1.1 sections for string literals,
  4477. * but also it allows to have CO-RE applications that use
  4478. * global variables in some of BPF programs, but not others.
  4479. * If those global variable-using programs are not loaded at
  4480. * runtime due to bpf_program__set_autoload(prog, false),
  4481. * bpf_object loading will succeed just fine even on old
  4482. * kernels.
  4483. */
  4484. if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
  4485. map->autocreate = false;
  4486. if (!map->autocreate) {
  4487. pr_debug("map '%s': skipped auto-creating...\n", map->name);
  4488. continue;
  4489. }
  4490. err = map_set_def_max_entries(map);
  4491. if (err)
  4492. goto err_out;
  4493. retried = false;
  4494. retry:
  4495. if (map->pin_path) {
  4496. err = bpf_object__reuse_map(map);
  4497. if (err) {
  4498. pr_warn("map '%s': error reusing pinned map\n",
  4499. map->name);
  4500. goto err_out;
  4501. }
  4502. if (retried && map->fd < 0) {
  4503. pr_warn("map '%s': cannot find pinned map\n",
  4504. map->name);
  4505. err = -ENOENT;
  4506. goto err_out;
  4507. }
  4508. }
  4509. if (map->fd >= 0) {
  4510. pr_debug("map '%s': skipping creation (preset fd=%d)\n",
  4511. map->name, map->fd);
  4512. } else {
  4513. err = bpf_object__create_map(obj, map, false);
  4514. if (err)
  4515. goto err_out;
  4516. pr_debug("map '%s': created successfully, fd=%d\n",
  4517. map->name, map->fd);
  4518. if (bpf_map__is_internal(map)) {
  4519. err = bpf_object__populate_internal_map(obj, map);
  4520. if (err < 0) {
  4521. zclose(map->fd);
  4522. goto err_out;
  4523. }
  4524. }
  4525. if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
  4526. err = init_map_in_map_slots(obj, map);
  4527. if (err < 0) {
  4528. zclose(map->fd);
  4529. goto err_out;
  4530. }
  4531. }
  4532. }
  4533. if (map->pin_path && !map->pinned) {
  4534. err = bpf_map__pin(map, NULL);
  4535. if (err) {
  4536. zclose(map->fd);
  4537. if (!retried && err == -EEXIST) {
  4538. retried = true;
  4539. goto retry;
  4540. }
  4541. pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
  4542. map->name, map->pin_path, err);
  4543. goto err_out;
  4544. }
  4545. }
  4546. }
  4547. return 0;
  4548. err_out:
  4549. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  4550. pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
  4551. pr_perm_msg(err);
  4552. for (j = 0; j < i; j++)
  4553. zclose(obj->maps[j].fd);
  4554. return err;
  4555. }
  4556. static bool bpf_core_is_flavor_sep(const char *s)
  4557. {
  4558. /* check X___Y name pattern, where X and Y are not underscores */
  4559. return s[0] != '_' && /* X */
  4560. s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
  4561. s[4] != '_'; /* Y */
  4562. }
  4563. /* Given 'some_struct_name___with_flavor' return the length of a name prefix
  4564. * before last triple underscore. Struct name part after last triple
  4565. * underscore is ignored by BPF CO-RE relocation during relocation matching.
  4566. */
  4567. size_t bpf_core_essential_name_len(const char *name)
  4568. {
  4569. size_t n = strlen(name);
  4570. int i;
  4571. for (i = n - 5; i >= 0; i--) {
  4572. if (bpf_core_is_flavor_sep(name + i))
  4573. return i + 1;
  4574. }
  4575. return n;
  4576. }
  4577. void bpf_core_free_cands(struct bpf_core_cand_list *cands)
  4578. {
  4579. if (!cands)
  4580. return;
  4581. free(cands->cands);
  4582. free(cands);
  4583. }
  4584. int bpf_core_add_cands(struct bpf_core_cand *local_cand,
  4585. size_t local_essent_len,
  4586. const struct btf *targ_btf,
  4587. const char *targ_btf_name,
  4588. int targ_start_id,
  4589. struct bpf_core_cand_list *cands)
  4590. {
  4591. struct bpf_core_cand *new_cands, *cand;
  4592. const struct btf_type *t, *local_t;
  4593. const char *targ_name, *local_name;
  4594. size_t targ_essent_len;
  4595. int n, i;
  4596. local_t = btf__type_by_id(local_cand->btf, local_cand->id);
  4597. local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
  4598. n = btf__type_cnt(targ_btf);
  4599. for (i = targ_start_id; i < n; i++) {
  4600. t = btf__type_by_id(targ_btf, i);
  4601. if (!btf_kind_core_compat(t, local_t))
  4602. continue;
  4603. targ_name = btf__name_by_offset(targ_btf, t->name_off);
  4604. if (str_is_empty(targ_name))
  4605. continue;
  4606. targ_essent_len = bpf_core_essential_name_len(targ_name);
  4607. if (targ_essent_len != local_essent_len)
  4608. continue;
  4609. if (strncmp(local_name, targ_name, local_essent_len) != 0)
  4610. continue;
  4611. pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
  4612. local_cand->id, btf_kind_str(local_t),
  4613. local_name, i, btf_kind_str(t), targ_name,
  4614. targ_btf_name);
  4615. new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
  4616. sizeof(*cands->cands));
  4617. if (!new_cands)
  4618. return -ENOMEM;
  4619. cand = &new_cands[cands->len];
  4620. cand->btf = targ_btf;
  4621. cand->id = i;
  4622. cands->cands = new_cands;
  4623. cands->len++;
  4624. }
  4625. return 0;
  4626. }
  4627. static int load_module_btfs(struct bpf_object *obj)
  4628. {
  4629. struct bpf_btf_info info;
  4630. struct module_btf *mod_btf;
  4631. struct btf *btf;
  4632. char name[64];
  4633. __u32 id = 0, len;
  4634. int err, fd;
  4635. if (obj->btf_modules_loaded)
  4636. return 0;
  4637. if (obj->gen_loader)
  4638. return 0;
  4639. /* don't do this again, even if we find no module BTFs */
  4640. obj->btf_modules_loaded = true;
  4641. /* kernel too old to support module BTFs */
  4642. if (!kernel_supports(obj, FEAT_MODULE_BTF))
  4643. return 0;
  4644. while (true) {
  4645. err = bpf_btf_get_next_id(id, &id);
  4646. if (err && errno == ENOENT)
  4647. return 0;
  4648. if (err) {
  4649. err = -errno;
  4650. pr_warn("failed to iterate BTF objects: %d\n", err);
  4651. return err;
  4652. }
  4653. fd = bpf_btf_get_fd_by_id(id);
  4654. if (fd < 0) {
  4655. if (errno == ENOENT)
  4656. continue; /* expected race: BTF was unloaded */
  4657. err = -errno;
  4658. pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
  4659. return err;
  4660. }
  4661. len = sizeof(info);
  4662. memset(&info, 0, sizeof(info));
  4663. info.name = ptr_to_u64(name);
  4664. info.name_len = sizeof(name);
  4665. err = bpf_obj_get_info_by_fd(fd, &info, &len);
  4666. if (err) {
  4667. err = -errno;
  4668. pr_warn("failed to get BTF object #%d info: %d\n", id, err);
  4669. goto err_out;
  4670. }
  4671. /* ignore non-module BTFs */
  4672. if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
  4673. close(fd);
  4674. continue;
  4675. }
  4676. btf = btf_get_from_fd(fd, obj->btf_vmlinux);
  4677. err = libbpf_get_error(btf);
  4678. if (err) {
  4679. pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
  4680. name, id, err);
  4681. goto err_out;
  4682. }
  4683. err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
  4684. sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
  4685. if (err)
  4686. goto err_out;
  4687. mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
  4688. mod_btf->btf = btf;
  4689. mod_btf->id = id;
  4690. mod_btf->fd = fd;
  4691. mod_btf->name = strdup(name);
  4692. if (!mod_btf->name) {
  4693. err = -ENOMEM;
  4694. goto err_out;
  4695. }
  4696. continue;
  4697. err_out:
  4698. close(fd);
  4699. return err;
  4700. }
  4701. return 0;
  4702. }
  4703. static struct bpf_core_cand_list *
  4704. bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
  4705. {
  4706. struct bpf_core_cand local_cand = {};
  4707. struct bpf_core_cand_list *cands;
  4708. const struct btf *main_btf;
  4709. const struct btf_type *local_t;
  4710. const char *local_name;
  4711. size_t local_essent_len;
  4712. int err, i;
  4713. local_cand.btf = local_btf;
  4714. local_cand.id = local_type_id;
  4715. local_t = btf__type_by_id(local_btf, local_type_id);
  4716. if (!local_t)
  4717. return ERR_PTR(-EINVAL);
  4718. local_name = btf__name_by_offset(local_btf, local_t->name_off);
  4719. if (str_is_empty(local_name))
  4720. return ERR_PTR(-EINVAL);
  4721. local_essent_len = bpf_core_essential_name_len(local_name);
  4722. cands = calloc(1, sizeof(*cands));
  4723. if (!cands)
  4724. return ERR_PTR(-ENOMEM);
  4725. /* Attempt to find target candidates in vmlinux BTF first */
  4726. main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
  4727. err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
  4728. if (err)
  4729. goto err_out;
  4730. /* if vmlinux BTF has any candidate, don't got for module BTFs */
  4731. if (cands->len)
  4732. return cands;
  4733. /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
  4734. if (obj->btf_vmlinux_override)
  4735. return cands;
  4736. /* now look through module BTFs, trying to still find candidates */
  4737. err = load_module_btfs(obj);
  4738. if (err)
  4739. goto err_out;
  4740. for (i = 0; i < obj->btf_module_cnt; i++) {
  4741. err = bpf_core_add_cands(&local_cand, local_essent_len,
  4742. obj->btf_modules[i].btf,
  4743. obj->btf_modules[i].name,
  4744. btf__type_cnt(obj->btf_vmlinux),
  4745. cands);
  4746. if (err)
  4747. goto err_out;
  4748. }
  4749. return cands;
  4750. err_out:
  4751. bpf_core_free_cands(cands);
  4752. return ERR_PTR(err);
  4753. }
  4754. /* Check local and target types for compatibility. This check is used for
  4755. * type-based CO-RE relocations and follow slightly different rules than
  4756. * field-based relocations. This function assumes that root types were already
  4757. * checked for name match. Beyond that initial root-level name check, names
  4758. * are completely ignored. Compatibility rules are as follows:
  4759. * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
  4760. * kind should match for local and target types (i.e., STRUCT is not
  4761. * compatible with UNION);
  4762. * - for ENUMs, the size is ignored;
  4763. * - for INT, size and signedness are ignored;
  4764. * - for ARRAY, dimensionality is ignored, element types are checked for
  4765. * compatibility recursively;
  4766. * - CONST/VOLATILE/RESTRICT modifiers are ignored;
  4767. * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
  4768. * - FUNC_PROTOs are compatible if they have compatible signature: same
  4769. * number of input args and compatible return and argument types.
  4770. * These rules are not set in stone and probably will be adjusted as we get
  4771. * more experience with using BPF CO-RE relocations.
  4772. */
  4773. int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
  4774. const struct btf *targ_btf, __u32 targ_id)
  4775. {
  4776. return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
  4777. }
  4778. int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
  4779. const struct btf *targ_btf, __u32 targ_id)
  4780. {
  4781. return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
  4782. }
  4783. static size_t bpf_core_hash_fn(const void *key, void *ctx)
  4784. {
  4785. return (size_t)key;
  4786. }
  4787. static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
  4788. {
  4789. return k1 == k2;
  4790. }
  4791. static void *u32_as_hash_key(__u32 x)
  4792. {
  4793. return (void *)(uintptr_t)x;
  4794. }
  4795. static int record_relo_core(struct bpf_program *prog,
  4796. const struct bpf_core_relo *core_relo, int insn_idx)
  4797. {
  4798. struct reloc_desc *relos, *relo;
  4799. relos = libbpf_reallocarray(prog->reloc_desc,
  4800. prog->nr_reloc + 1, sizeof(*relos));
  4801. if (!relos)
  4802. return -ENOMEM;
  4803. relo = &relos[prog->nr_reloc];
  4804. relo->type = RELO_CORE;
  4805. relo->insn_idx = insn_idx;
  4806. relo->core_relo = core_relo;
  4807. prog->reloc_desc = relos;
  4808. prog->nr_reloc++;
  4809. return 0;
  4810. }
  4811. static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
  4812. {
  4813. struct reloc_desc *relo;
  4814. int i;
  4815. for (i = 0; i < prog->nr_reloc; i++) {
  4816. relo = &prog->reloc_desc[i];
  4817. if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
  4818. continue;
  4819. return relo->core_relo;
  4820. }
  4821. return NULL;
  4822. }
  4823. static int bpf_core_resolve_relo(struct bpf_program *prog,
  4824. const struct bpf_core_relo *relo,
  4825. int relo_idx,
  4826. const struct btf *local_btf,
  4827. struct hashmap *cand_cache,
  4828. struct bpf_core_relo_res *targ_res)
  4829. {
  4830. struct bpf_core_spec specs_scratch[3] = {};
  4831. const void *type_key = u32_as_hash_key(relo->type_id);
  4832. struct bpf_core_cand_list *cands = NULL;
  4833. const char *prog_name = prog->name;
  4834. const struct btf_type *local_type;
  4835. const char *local_name;
  4836. __u32 local_id = relo->type_id;
  4837. int err;
  4838. local_type = btf__type_by_id(local_btf, local_id);
  4839. if (!local_type)
  4840. return -EINVAL;
  4841. local_name = btf__name_by_offset(local_btf, local_type->name_off);
  4842. if (!local_name)
  4843. return -EINVAL;
  4844. if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
  4845. !hashmap__find(cand_cache, type_key, (void **)&cands)) {
  4846. cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
  4847. if (IS_ERR(cands)) {
  4848. pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
  4849. prog_name, relo_idx, local_id, btf_kind_str(local_type),
  4850. local_name, PTR_ERR(cands));
  4851. return PTR_ERR(cands);
  4852. }
  4853. err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
  4854. if (err) {
  4855. bpf_core_free_cands(cands);
  4856. return err;
  4857. }
  4858. }
  4859. return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
  4860. targ_res);
  4861. }
  4862. static int
  4863. bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
  4864. {
  4865. const struct btf_ext_info_sec *sec;
  4866. struct bpf_core_relo_res targ_res;
  4867. const struct bpf_core_relo *rec;
  4868. const struct btf_ext_info *seg;
  4869. struct hashmap_entry *entry;
  4870. struct hashmap *cand_cache = NULL;
  4871. struct bpf_program *prog;
  4872. struct bpf_insn *insn;
  4873. const char *sec_name;
  4874. int i, err = 0, insn_idx, sec_idx, sec_num;
  4875. if (obj->btf_ext->core_relo_info.len == 0)
  4876. return 0;
  4877. if (targ_btf_path) {
  4878. obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
  4879. err = libbpf_get_error(obj->btf_vmlinux_override);
  4880. if (err) {
  4881. pr_warn("failed to parse target BTF: %d\n", err);
  4882. return err;
  4883. }
  4884. }
  4885. cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
  4886. if (IS_ERR(cand_cache)) {
  4887. err = PTR_ERR(cand_cache);
  4888. goto out;
  4889. }
  4890. seg = &obj->btf_ext->core_relo_info;
  4891. sec_num = 0;
  4892. for_each_btf_ext_sec(seg, sec) {
  4893. sec_idx = seg->sec_idxs[sec_num];
  4894. sec_num++;
  4895. sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
  4896. if (str_is_empty(sec_name)) {
  4897. err = -EINVAL;
  4898. goto out;
  4899. }
  4900. pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
  4901. for_each_btf_ext_rec(seg, sec, i, rec) {
  4902. if (rec->insn_off % BPF_INSN_SZ)
  4903. return -EINVAL;
  4904. insn_idx = rec->insn_off / BPF_INSN_SZ;
  4905. prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
  4906. if (!prog) {
  4907. /* When __weak subprog is "overridden" by another instance
  4908. * of the subprog from a different object file, linker still
  4909. * appends all the .BTF.ext info that used to belong to that
  4910. * eliminated subprogram.
  4911. * This is similar to what x86-64 linker does for relocations.
  4912. * So just ignore such relocations just like we ignore
  4913. * subprog instructions when discovering subprograms.
  4914. */
  4915. pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
  4916. sec_name, i, insn_idx);
  4917. continue;
  4918. }
  4919. /* no need to apply CO-RE relocation if the program is
  4920. * not going to be loaded
  4921. */
  4922. if (!prog->autoload)
  4923. continue;
  4924. /* adjust insn_idx from section frame of reference to the local
  4925. * program's frame of reference; (sub-)program code is not yet
  4926. * relocated, so it's enough to just subtract in-section offset
  4927. */
  4928. insn_idx = insn_idx - prog->sec_insn_off;
  4929. if (insn_idx >= prog->insns_cnt)
  4930. return -EINVAL;
  4931. insn = &prog->insns[insn_idx];
  4932. err = record_relo_core(prog, rec, insn_idx);
  4933. if (err) {
  4934. pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
  4935. prog->name, i, err);
  4936. goto out;
  4937. }
  4938. if (prog->obj->gen_loader)
  4939. continue;
  4940. err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
  4941. if (err) {
  4942. pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
  4943. prog->name, i, err);
  4944. goto out;
  4945. }
  4946. err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
  4947. if (err) {
  4948. pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
  4949. prog->name, i, insn_idx, err);
  4950. goto out;
  4951. }
  4952. }
  4953. }
  4954. out:
  4955. /* obj->btf_vmlinux and module BTFs are freed after object load */
  4956. btf__free(obj->btf_vmlinux_override);
  4957. obj->btf_vmlinux_override = NULL;
  4958. if (!IS_ERR_OR_NULL(cand_cache)) {
  4959. hashmap__for_each_entry(cand_cache, entry, i) {
  4960. bpf_core_free_cands(entry->value);
  4961. }
  4962. hashmap__free(cand_cache);
  4963. }
  4964. return err;
  4965. }
  4966. /* base map load ldimm64 special constant, used also for log fixup logic */
  4967. #define MAP_LDIMM64_POISON_BASE 2001000000
  4968. #define MAP_LDIMM64_POISON_PFX "200100"
  4969. static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
  4970. int insn_idx, struct bpf_insn *insn,
  4971. int map_idx, const struct bpf_map *map)
  4972. {
  4973. int i;
  4974. pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
  4975. prog->name, relo_idx, insn_idx, map_idx, map->name);
  4976. /* we turn single ldimm64 into two identical invalid calls */
  4977. for (i = 0; i < 2; i++) {
  4978. insn->code = BPF_JMP | BPF_CALL;
  4979. insn->dst_reg = 0;
  4980. insn->src_reg = 0;
  4981. insn->off = 0;
  4982. /* if this instruction is reachable (not a dead code),
  4983. * verifier will complain with something like:
  4984. * invalid func unknown#2001000123
  4985. * where lower 123 is map index into obj->maps[] array
  4986. */
  4987. insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
  4988. insn++;
  4989. }
  4990. }
  4991. /* Relocate data references within program code:
  4992. * - map references;
  4993. * - global variable references;
  4994. * - extern references.
  4995. */
  4996. static int
  4997. bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
  4998. {
  4999. int i;
  5000. for (i = 0; i < prog->nr_reloc; i++) {
  5001. struct reloc_desc *relo = &prog->reloc_desc[i];
  5002. struct bpf_insn *insn = &prog->insns[relo->insn_idx];
  5003. const struct bpf_map *map;
  5004. struct extern_desc *ext;
  5005. switch (relo->type) {
  5006. case RELO_LD64:
  5007. map = &obj->maps[relo->map_idx];
  5008. if (obj->gen_loader) {
  5009. insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
  5010. insn[0].imm = relo->map_idx;
  5011. } else if (map->autocreate) {
  5012. insn[0].src_reg = BPF_PSEUDO_MAP_FD;
  5013. insn[0].imm = map->fd;
  5014. } else {
  5015. poison_map_ldimm64(prog, i, relo->insn_idx, insn,
  5016. relo->map_idx, map);
  5017. }
  5018. break;
  5019. case RELO_DATA:
  5020. map = &obj->maps[relo->map_idx];
  5021. insn[1].imm = insn[0].imm + relo->sym_off;
  5022. if (obj->gen_loader) {
  5023. insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
  5024. insn[0].imm = relo->map_idx;
  5025. } else if (map->autocreate) {
  5026. insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
  5027. insn[0].imm = map->fd;
  5028. } else {
  5029. poison_map_ldimm64(prog, i, relo->insn_idx, insn,
  5030. relo->map_idx, map);
  5031. }
  5032. break;
  5033. case RELO_EXTERN_VAR:
  5034. ext = &obj->externs[relo->sym_off];
  5035. if (ext->type == EXT_KCFG) {
  5036. if (obj->gen_loader) {
  5037. insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
  5038. insn[0].imm = obj->kconfig_map_idx;
  5039. } else {
  5040. insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
  5041. insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
  5042. }
  5043. insn[1].imm = ext->kcfg.data_off;
  5044. } else /* EXT_KSYM */ {
  5045. if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
  5046. insn[0].src_reg = BPF_PSEUDO_BTF_ID;
  5047. insn[0].imm = ext->ksym.kernel_btf_id;
  5048. insn[1].imm = ext->ksym.kernel_btf_obj_fd;
  5049. } else { /* typeless ksyms or unresolved typed ksyms */
  5050. insn[0].imm = (__u32)ext->ksym.addr;
  5051. insn[1].imm = ext->ksym.addr >> 32;
  5052. }
  5053. }
  5054. break;
  5055. case RELO_EXTERN_FUNC:
  5056. ext = &obj->externs[relo->sym_off];
  5057. insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
  5058. if (ext->is_set) {
  5059. insn[0].imm = ext->ksym.kernel_btf_id;
  5060. insn[0].off = ext->ksym.btf_fd_idx;
  5061. } else { /* unresolved weak kfunc */
  5062. insn[0].imm = 0;
  5063. insn[0].off = 0;
  5064. }
  5065. break;
  5066. case RELO_SUBPROG_ADDR:
  5067. if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
  5068. pr_warn("prog '%s': relo #%d: bad insn\n",
  5069. prog->name, i);
  5070. return -EINVAL;
  5071. }
  5072. /* handled already */
  5073. break;
  5074. case RELO_CALL:
  5075. /* handled already */
  5076. break;
  5077. case RELO_CORE:
  5078. /* will be handled by bpf_program_record_relos() */
  5079. break;
  5080. default:
  5081. pr_warn("prog '%s': relo #%d: bad relo type %d\n",
  5082. prog->name, i, relo->type);
  5083. return -EINVAL;
  5084. }
  5085. }
  5086. return 0;
  5087. }
  5088. static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
  5089. const struct bpf_program *prog,
  5090. const struct btf_ext_info *ext_info,
  5091. void **prog_info, __u32 *prog_rec_cnt,
  5092. __u32 *prog_rec_sz)
  5093. {
  5094. void *copy_start = NULL, *copy_end = NULL;
  5095. void *rec, *rec_end, *new_prog_info;
  5096. const struct btf_ext_info_sec *sec;
  5097. size_t old_sz, new_sz;
  5098. int i, sec_num, sec_idx, off_adj;
  5099. sec_num = 0;
  5100. for_each_btf_ext_sec(ext_info, sec) {
  5101. sec_idx = ext_info->sec_idxs[sec_num];
  5102. sec_num++;
  5103. if (prog->sec_idx != sec_idx)
  5104. continue;
  5105. for_each_btf_ext_rec(ext_info, sec, i, rec) {
  5106. __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
  5107. if (insn_off < prog->sec_insn_off)
  5108. continue;
  5109. if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
  5110. break;
  5111. if (!copy_start)
  5112. copy_start = rec;
  5113. copy_end = rec + ext_info->rec_size;
  5114. }
  5115. if (!copy_start)
  5116. return -ENOENT;
  5117. /* append func/line info of a given (sub-)program to the main
  5118. * program func/line info
  5119. */
  5120. old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
  5121. new_sz = old_sz + (copy_end - copy_start);
  5122. new_prog_info = realloc(*prog_info, new_sz);
  5123. if (!new_prog_info)
  5124. return -ENOMEM;
  5125. *prog_info = new_prog_info;
  5126. *prog_rec_cnt = new_sz / ext_info->rec_size;
  5127. memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
  5128. /* Kernel instruction offsets are in units of 8-byte
  5129. * instructions, while .BTF.ext instruction offsets generated
  5130. * by Clang are in units of bytes. So convert Clang offsets
  5131. * into kernel offsets and adjust offset according to program
  5132. * relocated position.
  5133. */
  5134. off_adj = prog->sub_insn_off - prog->sec_insn_off;
  5135. rec = new_prog_info + old_sz;
  5136. rec_end = new_prog_info + new_sz;
  5137. for (; rec < rec_end; rec += ext_info->rec_size) {
  5138. __u32 *insn_off = rec;
  5139. *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
  5140. }
  5141. *prog_rec_sz = ext_info->rec_size;
  5142. return 0;
  5143. }
  5144. return -ENOENT;
  5145. }
  5146. static int
  5147. reloc_prog_func_and_line_info(const struct bpf_object *obj,
  5148. struct bpf_program *main_prog,
  5149. const struct bpf_program *prog)
  5150. {
  5151. int err;
  5152. /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
  5153. * supprot func/line info
  5154. */
  5155. if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
  5156. return 0;
  5157. /* only attempt func info relocation if main program's func_info
  5158. * relocation was successful
  5159. */
  5160. if (main_prog != prog && !main_prog->func_info)
  5161. goto line_info;
  5162. err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
  5163. &main_prog->func_info,
  5164. &main_prog->func_info_cnt,
  5165. &main_prog->func_info_rec_size);
  5166. if (err) {
  5167. if (err != -ENOENT) {
  5168. pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
  5169. prog->name, err);
  5170. return err;
  5171. }
  5172. if (main_prog->func_info) {
  5173. /*
  5174. * Some info has already been found but has problem
  5175. * in the last btf_ext reloc. Must have to error out.
  5176. */
  5177. pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
  5178. return err;
  5179. }
  5180. /* Have problem loading the very first info. Ignore the rest. */
  5181. pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
  5182. prog->name);
  5183. }
  5184. line_info:
  5185. /* don't relocate line info if main program's relocation failed */
  5186. if (main_prog != prog && !main_prog->line_info)
  5187. return 0;
  5188. err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
  5189. &main_prog->line_info,
  5190. &main_prog->line_info_cnt,
  5191. &main_prog->line_info_rec_size);
  5192. if (err) {
  5193. if (err != -ENOENT) {
  5194. pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
  5195. prog->name, err);
  5196. return err;
  5197. }
  5198. if (main_prog->line_info) {
  5199. /*
  5200. * Some info has already been found but has problem
  5201. * in the last btf_ext reloc. Must have to error out.
  5202. */
  5203. pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
  5204. return err;
  5205. }
  5206. /* Have problem loading the very first info. Ignore the rest. */
  5207. pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
  5208. prog->name);
  5209. }
  5210. return 0;
  5211. }
  5212. static int cmp_relo_by_insn_idx(const void *key, const void *elem)
  5213. {
  5214. size_t insn_idx = *(const size_t *)key;
  5215. const struct reloc_desc *relo = elem;
  5216. if (insn_idx == relo->insn_idx)
  5217. return 0;
  5218. return insn_idx < relo->insn_idx ? -1 : 1;
  5219. }
  5220. static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
  5221. {
  5222. if (!prog->nr_reloc)
  5223. return NULL;
  5224. return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
  5225. sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
  5226. }
  5227. static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
  5228. {
  5229. int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
  5230. struct reloc_desc *relos;
  5231. int i;
  5232. if (main_prog == subprog)
  5233. return 0;
  5234. relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
  5235. /* if new count is zero, reallocarray can return a valid NULL result;
  5236. * in this case the previous pointer will be freed, so we *have to*
  5237. * reassign old pointer to the new value (even if it's NULL)
  5238. */
  5239. if (!relos && new_cnt)
  5240. return -ENOMEM;
  5241. if (subprog->nr_reloc)
  5242. memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
  5243. sizeof(*relos) * subprog->nr_reloc);
  5244. for (i = main_prog->nr_reloc; i < new_cnt; i++)
  5245. relos[i].insn_idx += subprog->sub_insn_off;
  5246. /* After insn_idx adjustment the 'relos' array is still sorted
  5247. * by insn_idx and doesn't break bsearch.
  5248. */
  5249. main_prog->reloc_desc = relos;
  5250. main_prog->nr_reloc = new_cnt;
  5251. return 0;
  5252. }
  5253. static int
  5254. bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
  5255. struct bpf_program *prog)
  5256. {
  5257. size_t sub_insn_idx, insn_idx, new_cnt;
  5258. struct bpf_program *subprog;
  5259. struct bpf_insn *insns, *insn;
  5260. struct reloc_desc *relo;
  5261. int err;
  5262. err = reloc_prog_func_and_line_info(obj, main_prog, prog);
  5263. if (err)
  5264. return err;
  5265. for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
  5266. insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
  5267. if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
  5268. continue;
  5269. relo = find_prog_insn_relo(prog, insn_idx);
  5270. if (relo && relo->type == RELO_EXTERN_FUNC)
  5271. /* kfunc relocations will be handled later
  5272. * in bpf_object__relocate_data()
  5273. */
  5274. continue;
  5275. if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
  5276. pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
  5277. prog->name, insn_idx, relo->type);
  5278. return -LIBBPF_ERRNO__RELOC;
  5279. }
  5280. if (relo) {
  5281. /* sub-program instruction index is a combination of
  5282. * an offset of a symbol pointed to by relocation and
  5283. * call instruction's imm field; for global functions,
  5284. * call always has imm = -1, but for static functions
  5285. * relocation is against STT_SECTION and insn->imm
  5286. * points to a start of a static function
  5287. *
  5288. * for subprog addr relocation, the relo->sym_off + insn->imm is
  5289. * the byte offset in the corresponding section.
  5290. */
  5291. if (relo->type == RELO_CALL)
  5292. sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
  5293. else
  5294. sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
  5295. } else if (insn_is_pseudo_func(insn)) {
  5296. /*
  5297. * RELO_SUBPROG_ADDR relo is always emitted even if both
  5298. * functions are in the same section, so it shouldn't reach here.
  5299. */
  5300. pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
  5301. prog->name, insn_idx);
  5302. return -LIBBPF_ERRNO__RELOC;
  5303. } else {
  5304. /* if subprogram call is to a static function within
  5305. * the same ELF section, there won't be any relocation
  5306. * emitted, but it also means there is no additional
  5307. * offset necessary, insns->imm is relative to
  5308. * instruction's original position within the section
  5309. */
  5310. sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
  5311. }
  5312. /* we enforce that sub-programs should be in .text section */
  5313. subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
  5314. if (!subprog) {
  5315. pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
  5316. prog->name);
  5317. return -LIBBPF_ERRNO__RELOC;
  5318. }
  5319. /* if it's the first call instruction calling into this
  5320. * subprogram (meaning this subprog hasn't been processed
  5321. * yet) within the context of current main program:
  5322. * - append it at the end of main program's instructions blog;
  5323. * - process is recursively, while current program is put on hold;
  5324. * - if that subprogram calls some other not yet processes
  5325. * subprogram, same thing will happen recursively until
  5326. * there are no more unprocesses subprograms left to append
  5327. * and relocate.
  5328. */
  5329. if (subprog->sub_insn_off == 0) {
  5330. subprog->sub_insn_off = main_prog->insns_cnt;
  5331. new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
  5332. insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
  5333. if (!insns) {
  5334. pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
  5335. return -ENOMEM;
  5336. }
  5337. main_prog->insns = insns;
  5338. main_prog->insns_cnt = new_cnt;
  5339. memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
  5340. subprog->insns_cnt * sizeof(*insns));
  5341. pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
  5342. main_prog->name, subprog->insns_cnt, subprog->name);
  5343. /* The subprog insns are now appended. Append its relos too. */
  5344. err = append_subprog_relos(main_prog, subprog);
  5345. if (err)
  5346. return err;
  5347. err = bpf_object__reloc_code(obj, main_prog, subprog);
  5348. if (err)
  5349. return err;
  5350. }
  5351. /* main_prog->insns memory could have been re-allocated, so
  5352. * calculate pointer again
  5353. */
  5354. insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
  5355. /* calculate correct instruction position within current main
  5356. * prog; each main prog can have a different set of
  5357. * subprograms appended (potentially in different order as
  5358. * well), so position of any subprog can be different for
  5359. * different main programs */
  5360. insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
  5361. pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
  5362. prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
  5363. }
  5364. return 0;
  5365. }
  5366. /*
  5367. * Relocate sub-program calls.
  5368. *
  5369. * Algorithm operates as follows. Each entry-point BPF program (referred to as
  5370. * main prog) is processed separately. For each subprog (non-entry functions,
  5371. * that can be called from either entry progs or other subprogs) gets their
  5372. * sub_insn_off reset to zero. This serves as indicator that this subprogram
  5373. * hasn't been yet appended and relocated within current main prog. Once its
  5374. * relocated, sub_insn_off will point at the position within current main prog
  5375. * where given subprog was appended. This will further be used to relocate all
  5376. * the call instructions jumping into this subprog.
  5377. *
  5378. * We start with main program and process all call instructions. If the call
  5379. * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
  5380. * is zero), subprog instructions are appended at the end of main program's
  5381. * instruction array. Then main program is "put on hold" while we recursively
  5382. * process newly appended subprogram. If that subprogram calls into another
  5383. * subprogram that hasn't been appended, new subprogram is appended again to
  5384. * the *main* prog's instructions (subprog's instructions are always left
  5385. * untouched, as they need to be in unmodified state for subsequent main progs
  5386. * and subprog instructions are always sent only as part of a main prog) and
  5387. * the process continues recursively. Once all the subprogs called from a main
  5388. * prog or any of its subprogs are appended (and relocated), all their
  5389. * positions within finalized instructions array are known, so it's easy to
  5390. * rewrite call instructions with correct relative offsets, corresponding to
  5391. * desired target subprog.
  5392. *
  5393. * Its important to realize that some subprogs might not be called from some
  5394. * main prog and any of its called/used subprogs. Those will keep their
  5395. * subprog->sub_insn_off as zero at all times and won't be appended to current
  5396. * main prog and won't be relocated within the context of current main prog.
  5397. * They might still be used from other main progs later.
  5398. *
  5399. * Visually this process can be shown as below. Suppose we have two main
  5400. * programs mainA and mainB and BPF object contains three subprogs: subA,
  5401. * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
  5402. * subC both call subB:
  5403. *
  5404. * +--------+ +-------+
  5405. * | v v |
  5406. * +--+---+ +--+-+-+ +---+--+
  5407. * | subA | | subB | | subC |
  5408. * +--+---+ +------+ +---+--+
  5409. * ^ ^
  5410. * | |
  5411. * +---+-------+ +------+----+
  5412. * | mainA | | mainB |
  5413. * +-----------+ +-----------+
  5414. *
  5415. * We'll start relocating mainA, will find subA, append it and start
  5416. * processing sub A recursively:
  5417. *
  5418. * +-----------+------+
  5419. * | mainA | subA |
  5420. * +-----------+------+
  5421. *
  5422. * At this point we notice that subB is used from subA, so we append it and
  5423. * relocate (there are no further subcalls from subB):
  5424. *
  5425. * +-----------+------+------+
  5426. * | mainA | subA | subB |
  5427. * +-----------+------+------+
  5428. *
  5429. * At this point, we relocate subA calls, then go one level up and finish with
  5430. * relocatin mainA calls. mainA is done.
  5431. *
  5432. * For mainB process is similar but results in different order. We start with
  5433. * mainB and skip subA and subB, as mainB never calls them (at least
  5434. * directly), but we see subC is needed, so we append and start processing it:
  5435. *
  5436. * +-----------+------+
  5437. * | mainB | subC |
  5438. * +-----------+------+
  5439. * Now we see subC needs subB, so we go back to it, append and relocate it:
  5440. *
  5441. * +-----------+------+------+
  5442. * | mainB | subC | subB |
  5443. * +-----------+------+------+
  5444. *
  5445. * At this point we unwind recursion, relocate calls in subC, then in mainB.
  5446. */
  5447. static int
  5448. bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
  5449. {
  5450. struct bpf_program *subprog;
  5451. int i, err;
  5452. /* mark all subprogs as not relocated (yet) within the context of
  5453. * current main program
  5454. */
  5455. for (i = 0; i < obj->nr_programs; i++) {
  5456. subprog = &obj->programs[i];
  5457. if (!prog_is_subprog(obj, subprog))
  5458. continue;
  5459. subprog->sub_insn_off = 0;
  5460. }
  5461. err = bpf_object__reloc_code(obj, prog, prog);
  5462. if (err)
  5463. return err;
  5464. return 0;
  5465. }
  5466. static void
  5467. bpf_object__free_relocs(struct bpf_object *obj)
  5468. {
  5469. struct bpf_program *prog;
  5470. int i;
  5471. /* free up relocation descriptors */
  5472. for (i = 0; i < obj->nr_programs; i++) {
  5473. prog = &obj->programs[i];
  5474. zfree(&prog->reloc_desc);
  5475. prog->nr_reloc = 0;
  5476. }
  5477. }
  5478. static int cmp_relocs(const void *_a, const void *_b)
  5479. {
  5480. const struct reloc_desc *a = _a;
  5481. const struct reloc_desc *b = _b;
  5482. if (a->insn_idx != b->insn_idx)
  5483. return a->insn_idx < b->insn_idx ? -1 : 1;
  5484. /* no two relocations should have the same insn_idx, but ... */
  5485. if (a->type != b->type)
  5486. return a->type < b->type ? -1 : 1;
  5487. return 0;
  5488. }
  5489. static void bpf_object__sort_relos(struct bpf_object *obj)
  5490. {
  5491. int i;
  5492. for (i = 0; i < obj->nr_programs; i++) {
  5493. struct bpf_program *p = &obj->programs[i];
  5494. if (!p->nr_reloc)
  5495. continue;
  5496. qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
  5497. }
  5498. }
  5499. static int
  5500. bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
  5501. {
  5502. struct bpf_program *prog;
  5503. size_t i, j;
  5504. int err;
  5505. if (obj->btf_ext) {
  5506. err = bpf_object__relocate_core(obj, targ_btf_path);
  5507. if (err) {
  5508. pr_warn("failed to perform CO-RE relocations: %d\n",
  5509. err);
  5510. return err;
  5511. }
  5512. bpf_object__sort_relos(obj);
  5513. }
  5514. /* Before relocating calls pre-process relocations and mark
  5515. * few ld_imm64 instructions that points to subprogs.
  5516. * Otherwise bpf_object__reloc_code() later would have to consider
  5517. * all ld_imm64 insns as relocation candidates. That would
  5518. * reduce relocation speed, since amount of find_prog_insn_relo()
  5519. * would increase and most of them will fail to find a relo.
  5520. */
  5521. for (i = 0; i < obj->nr_programs; i++) {
  5522. prog = &obj->programs[i];
  5523. for (j = 0; j < prog->nr_reloc; j++) {
  5524. struct reloc_desc *relo = &prog->reloc_desc[j];
  5525. struct bpf_insn *insn = &prog->insns[relo->insn_idx];
  5526. /* mark the insn, so it's recognized by insn_is_pseudo_func() */
  5527. if (relo->type == RELO_SUBPROG_ADDR)
  5528. insn[0].src_reg = BPF_PSEUDO_FUNC;
  5529. }
  5530. }
  5531. /* relocate subprogram calls and append used subprograms to main
  5532. * programs; each copy of subprogram code needs to be relocated
  5533. * differently for each main program, because its code location might
  5534. * have changed.
  5535. * Append subprog relos to main programs to allow data relos to be
  5536. * processed after text is completely relocated.
  5537. */
  5538. for (i = 0; i < obj->nr_programs; i++) {
  5539. prog = &obj->programs[i];
  5540. /* sub-program's sub-calls are relocated within the context of
  5541. * its main program only
  5542. */
  5543. if (prog_is_subprog(obj, prog))
  5544. continue;
  5545. if (!prog->autoload)
  5546. continue;
  5547. err = bpf_object__relocate_calls(obj, prog);
  5548. if (err) {
  5549. pr_warn("prog '%s': failed to relocate calls: %d\n",
  5550. prog->name, err);
  5551. return err;
  5552. }
  5553. }
  5554. /* Process data relos for main programs */
  5555. for (i = 0; i < obj->nr_programs; i++) {
  5556. prog = &obj->programs[i];
  5557. if (prog_is_subprog(obj, prog))
  5558. continue;
  5559. if (!prog->autoload)
  5560. continue;
  5561. err = bpf_object__relocate_data(obj, prog);
  5562. if (err) {
  5563. pr_warn("prog '%s': failed to relocate data references: %d\n",
  5564. prog->name, err);
  5565. return err;
  5566. }
  5567. }
  5568. return 0;
  5569. }
  5570. static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
  5571. Elf64_Shdr *shdr, Elf_Data *data);
  5572. static int bpf_object__collect_map_relos(struct bpf_object *obj,
  5573. Elf64_Shdr *shdr, Elf_Data *data)
  5574. {
  5575. const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
  5576. int i, j, nrels, new_sz;
  5577. const struct btf_var_secinfo *vi = NULL;
  5578. const struct btf_type *sec, *var, *def;
  5579. struct bpf_map *map = NULL, *targ_map = NULL;
  5580. struct bpf_program *targ_prog = NULL;
  5581. bool is_prog_array, is_map_in_map;
  5582. const struct btf_member *member;
  5583. const char *name, *mname, *type;
  5584. unsigned int moff;
  5585. Elf64_Sym *sym;
  5586. Elf64_Rel *rel;
  5587. void *tmp;
  5588. if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
  5589. return -EINVAL;
  5590. sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
  5591. if (!sec)
  5592. return -EINVAL;
  5593. nrels = shdr->sh_size / shdr->sh_entsize;
  5594. for (i = 0; i < nrels; i++) {
  5595. rel = elf_rel_by_idx(data, i);
  5596. if (!rel) {
  5597. pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
  5598. return -LIBBPF_ERRNO__FORMAT;
  5599. }
  5600. sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
  5601. if (!sym) {
  5602. pr_warn(".maps relo #%d: symbol %zx not found\n",
  5603. i, (size_t)ELF64_R_SYM(rel->r_info));
  5604. return -LIBBPF_ERRNO__FORMAT;
  5605. }
  5606. name = elf_sym_str(obj, sym->st_name) ?: "<?>";
  5607. pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
  5608. i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
  5609. (size_t)rel->r_offset, sym->st_name, name);
  5610. for (j = 0; j < obj->nr_maps; j++) {
  5611. map = &obj->maps[j];
  5612. if (map->sec_idx != obj->efile.btf_maps_shndx)
  5613. continue;
  5614. vi = btf_var_secinfos(sec) + map->btf_var_idx;
  5615. if (vi->offset <= rel->r_offset &&
  5616. rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
  5617. break;
  5618. }
  5619. if (j == obj->nr_maps) {
  5620. pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
  5621. i, name, (size_t)rel->r_offset);
  5622. return -EINVAL;
  5623. }
  5624. is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
  5625. is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
  5626. type = is_map_in_map ? "map" : "prog";
  5627. if (is_map_in_map) {
  5628. if (sym->st_shndx != obj->efile.btf_maps_shndx) {
  5629. pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
  5630. i, name);
  5631. return -LIBBPF_ERRNO__RELOC;
  5632. }
  5633. if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
  5634. map->def.key_size != sizeof(int)) {
  5635. pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
  5636. i, map->name, sizeof(int));
  5637. return -EINVAL;
  5638. }
  5639. targ_map = bpf_object__find_map_by_name(obj, name);
  5640. if (!targ_map) {
  5641. pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
  5642. i, name);
  5643. return -ESRCH;
  5644. }
  5645. } else if (is_prog_array) {
  5646. targ_prog = bpf_object__find_program_by_name(obj, name);
  5647. if (!targ_prog) {
  5648. pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
  5649. i, name);
  5650. return -ESRCH;
  5651. }
  5652. if (targ_prog->sec_idx != sym->st_shndx ||
  5653. targ_prog->sec_insn_off * 8 != sym->st_value ||
  5654. prog_is_subprog(obj, targ_prog)) {
  5655. pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
  5656. i, name);
  5657. return -LIBBPF_ERRNO__RELOC;
  5658. }
  5659. } else {
  5660. return -EINVAL;
  5661. }
  5662. var = btf__type_by_id(obj->btf, vi->type);
  5663. def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
  5664. if (btf_vlen(def) == 0)
  5665. return -EINVAL;
  5666. member = btf_members(def) + btf_vlen(def) - 1;
  5667. mname = btf__name_by_offset(obj->btf, member->name_off);
  5668. if (strcmp(mname, "values"))
  5669. return -EINVAL;
  5670. moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
  5671. if (rel->r_offset - vi->offset < moff)
  5672. return -EINVAL;
  5673. moff = rel->r_offset - vi->offset - moff;
  5674. /* here we use BPF pointer size, which is always 64 bit, as we
  5675. * are parsing ELF that was built for BPF target
  5676. */
  5677. if (moff % bpf_ptr_sz)
  5678. return -EINVAL;
  5679. moff /= bpf_ptr_sz;
  5680. if (moff >= map->init_slots_sz) {
  5681. new_sz = moff + 1;
  5682. tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
  5683. if (!tmp)
  5684. return -ENOMEM;
  5685. map->init_slots = tmp;
  5686. memset(map->init_slots + map->init_slots_sz, 0,
  5687. (new_sz - map->init_slots_sz) * host_ptr_sz);
  5688. map->init_slots_sz = new_sz;
  5689. }
  5690. map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
  5691. pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
  5692. i, map->name, moff, type, name);
  5693. }
  5694. return 0;
  5695. }
  5696. static int bpf_object__collect_relos(struct bpf_object *obj)
  5697. {
  5698. int i, err;
  5699. for (i = 0; i < obj->efile.sec_cnt; i++) {
  5700. struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
  5701. Elf64_Shdr *shdr;
  5702. Elf_Data *data;
  5703. int idx;
  5704. if (sec_desc->sec_type != SEC_RELO)
  5705. continue;
  5706. shdr = sec_desc->shdr;
  5707. data = sec_desc->data;
  5708. idx = shdr->sh_info;
  5709. if (shdr->sh_type != SHT_REL) {
  5710. pr_warn("internal error at %d\n", __LINE__);
  5711. return -LIBBPF_ERRNO__INTERNAL;
  5712. }
  5713. if (idx == obj->efile.st_ops_shndx)
  5714. err = bpf_object__collect_st_ops_relos(obj, shdr, data);
  5715. else if (idx == obj->efile.btf_maps_shndx)
  5716. err = bpf_object__collect_map_relos(obj, shdr, data);
  5717. else
  5718. err = bpf_object__collect_prog_relos(obj, shdr, data);
  5719. if (err)
  5720. return err;
  5721. }
  5722. bpf_object__sort_relos(obj);
  5723. return 0;
  5724. }
  5725. static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
  5726. {
  5727. if (BPF_CLASS(insn->code) == BPF_JMP &&
  5728. BPF_OP(insn->code) == BPF_CALL &&
  5729. BPF_SRC(insn->code) == BPF_K &&
  5730. insn->src_reg == 0 &&
  5731. insn->dst_reg == 0) {
  5732. *func_id = insn->imm;
  5733. return true;
  5734. }
  5735. return false;
  5736. }
  5737. static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
  5738. {
  5739. struct bpf_insn *insn = prog->insns;
  5740. enum bpf_func_id func_id;
  5741. int i;
  5742. if (obj->gen_loader)
  5743. return 0;
  5744. for (i = 0; i < prog->insns_cnt; i++, insn++) {
  5745. if (!insn_is_helper_call(insn, &func_id))
  5746. continue;
  5747. /* on kernels that don't yet support
  5748. * bpf_probe_read_{kernel,user}[_str] helpers, fall back
  5749. * to bpf_probe_read() which works well for old kernels
  5750. */
  5751. switch (func_id) {
  5752. case BPF_FUNC_probe_read_kernel:
  5753. case BPF_FUNC_probe_read_user:
  5754. if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
  5755. insn->imm = BPF_FUNC_probe_read;
  5756. break;
  5757. case BPF_FUNC_probe_read_kernel_str:
  5758. case BPF_FUNC_probe_read_user_str:
  5759. if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
  5760. insn->imm = BPF_FUNC_probe_read_str;
  5761. break;
  5762. default:
  5763. break;
  5764. }
  5765. }
  5766. return 0;
  5767. }
  5768. static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
  5769. int *btf_obj_fd, int *btf_type_id);
  5770. /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
  5771. static int libbpf_prepare_prog_load(struct bpf_program *prog,
  5772. struct bpf_prog_load_opts *opts, long cookie)
  5773. {
  5774. enum sec_def_flags def = cookie;
  5775. /* old kernels might not support specifying expected_attach_type */
  5776. if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
  5777. opts->expected_attach_type = 0;
  5778. if (def & SEC_SLEEPABLE)
  5779. opts->prog_flags |= BPF_F_SLEEPABLE;
  5780. if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
  5781. opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
  5782. if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
  5783. int btf_obj_fd = 0, btf_type_id = 0, err;
  5784. const char *attach_name;
  5785. attach_name = strchr(prog->sec_name, '/');
  5786. if (!attach_name) {
  5787. /* if BPF program is annotated with just SEC("fentry")
  5788. * (or similar) without declaratively specifying
  5789. * target, then it is expected that target will be
  5790. * specified with bpf_program__set_attach_target() at
  5791. * runtime before BPF object load step. If not, then
  5792. * there is nothing to load into the kernel as BPF
  5793. * verifier won't be able to validate BPF program
  5794. * correctness anyways.
  5795. */
  5796. pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
  5797. prog->name);
  5798. return -EINVAL;
  5799. }
  5800. attach_name++; /* skip over / */
  5801. err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
  5802. if (err)
  5803. return err;
  5804. /* cache resolved BTF FD and BTF type ID in the prog */
  5805. prog->attach_btf_obj_fd = btf_obj_fd;
  5806. prog->attach_btf_id = btf_type_id;
  5807. /* but by now libbpf common logic is not utilizing
  5808. * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
  5809. * this callback is called after opts were populated by
  5810. * libbpf, so this callback has to update opts explicitly here
  5811. */
  5812. opts->attach_btf_obj_fd = btf_obj_fd;
  5813. opts->attach_btf_id = btf_type_id;
  5814. }
  5815. return 0;
  5816. }
  5817. static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
  5818. static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
  5819. struct bpf_insn *insns, int insns_cnt,
  5820. const char *license, __u32 kern_version, int *prog_fd)
  5821. {
  5822. LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
  5823. const char *prog_name = NULL;
  5824. char *cp, errmsg[STRERR_BUFSIZE];
  5825. size_t log_buf_size = 0;
  5826. char *log_buf = NULL, *tmp;
  5827. int btf_fd, ret, err;
  5828. bool own_log_buf = true;
  5829. __u32 log_level = prog->log_level;
  5830. if (prog->type == BPF_PROG_TYPE_UNSPEC) {
  5831. /*
  5832. * The program type must be set. Most likely we couldn't find a proper
  5833. * section definition at load time, and thus we didn't infer the type.
  5834. */
  5835. pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
  5836. prog->name, prog->sec_name);
  5837. return -EINVAL;
  5838. }
  5839. if (!insns || !insns_cnt)
  5840. return -EINVAL;
  5841. load_attr.expected_attach_type = prog->expected_attach_type;
  5842. if (kernel_supports(obj, FEAT_PROG_NAME))
  5843. prog_name = prog->name;
  5844. load_attr.attach_prog_fd = prog->attach_prog_fd;
  5845. load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
  5846. load_attr.attach_btf_id = prog->attach_btf_id;
  5847. load_attr.kern_version = kern_version;
  5848. load_attr.prog_ifindex = prog->prog_ifindex;
  5849. /* specify func_info/line_info only if kernel supports them */
  5850. btf_fd = bpf_object__btf_fd(obj);
  5851. if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
  5852. load_attr.prog_btf_fd = btf_fd;
  5853. load_attr.func_info = prog->func_info;
  5854. load_attr.func_info_rec_size = prog->func_info_rec_size;
  5855. load_attr.func_info_cnt = prog->func_info_cnt;
  5856. load_attr.line_info = prog->line_info;
  5857. load_attr.line_info_rec_size = prog->line_info_rec_size;
  5858. load_attr.line_info_cnt = prog->line_info_cnt;
  5859. }
  5860. load_attr.log_level = log_level;
  5861. load_attr.prog_flags = prog->prog_flags;
  5862. load_attr.fd_array = obj->fd_array;
  5863. /* adjust load_attr if sec_def provides custom preload callback */
  5864. if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
  5865. err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
  5866. if (err < 0) {
  5867. pr_warn("prog '%s': failed to prepare load attributes: %d\n",
  5868. prog->name, err);
  5869. return err;
  5870. }
  5871. insns = prog->insns;
  5872. insns_cnt = prog->insns_cnt;
  5873. }
  5874. if (obj->gen_loader) {
  5875. bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
  5876. license, insns, insns_cnt, &load_attr,
  5877. prog - obj->programs);
  5878. *prog_fd = -1;
  5879. return 0;
  5880. }
  5881. retry_load:
  5882. /* if log_level is zero, we don't request logs initially even if
  5883. * custom log_buf is specified; if the program load fails, then we'll
  5884. * bump log_level to 1 and use either custom log_buf or we'll allocate
  5885. * our own and retry the load to get details on what failed
  5886. */
  5887. if (log_level) {
  5888. if (prog->log_buf) {
  5889. log_buf = prog->log_buf;
  5890. log_buf_size = prog->log_size;
  5891. own_log_buf = false;
  5892. } else if (obj->log_buf) {
  5893. log_buf = obj->log_buf;
  5894. log_buf_size = obj->log_size;
  5895. own_log_buf = false;
  5896. } else {
  5897. log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
  5898. tmp = realloc(log_buf, log_buf_size);
  5899. if (!tmp) {
  5900. ret = -ENOMEM;
  5901. goto out;
  5902. }
  5903. log_buf = tmp;
  5904. log_buf[0] = '\0';
  5905. own_log_buf = true;
  5906. }
  5907. }
  5908. load_attr.log_buf = log_buf;
  5909. load_attr.log_size = log_buf_size;
  5910. load_attr.log_level = log_level;
  5911. ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
  5912. if (ret >= 0) {
  5913. if (log_level && own_log_buf) {
  5914. pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
  5915. prog->name, log_buf);
  5916. }
  5917. if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
  5918. struct bpf_map *map;
  5919. int i;
  5920. for (i = 0; i < obj->nr_maps; i++) {
  5921. map = &prog->obj->maps[i];
  5922. if (map->libbpf_type != LIBBPF_MAP_RODATA)
  5923. continue;
  5924. if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
  5925. cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
  5926. pr_warn("prog '%s': failed to bind map '%s': %s\n",
  5927. prog->name, map->real_name, cp);
  5928. /* Don't fail hard if can't bind rodata. */
  5929. }
  5930. }
  5931. }
  5932. *prog_fd = ret;
  5933. ret = 0;
  5934. goto out;
  5935. }
  5936. if (log_level == 0) {
  5937. log_level = 1;
  5938. goto retry_load;
  5939. }
  5940. /* On ENOSPC, increase log buffer size and retry, unless custom
  5941. * log_buf is specified.
  5942. * Be careful to not overflow u32, though. Kernel's log buf size limit
  5943. * isn't part of UAPI so it can always be bumped to full 4GB. So don't
  5944. * multiply by 2 unless we are sure we'll fit within 32 bits.
  5945. * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
  5946. */
  5947. if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
  5948. goto retry_load;
  5949. ret = -errno;
  5950. /* post-process verifier log to improve error descriptions */
  5951. fixup_verifier_log(prog, log_buf, log_buf_size);
  5952. cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
  5953. pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
  5954. pr_perm_msg(ret);
  5955. if (own_log_buf && log_buf && log_buf[0] != '\0') {
  5956. pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
  5957. prog->name, log_buf);
  5958. }
  5959. out:
  5960. if (own_log_buf)
  5961. free(log_buf);
  5962. return ret;
  5963. }
  5964. static char *find_prev_line(char *buf, char *cur)
  5965. {
  5966. char *p;
  5967. if (cur == buf) /* end of a log buf */
  5968. return NULL;
  5969. p = cur - 1;
  5970. while (p - 1 >= buf && *(p - 1) != '\n')
  5971. p--;
  5972. return p;
  5973. }
  5974. static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
  5975. char *orig, size_t orig_sz, const char *patch)
  5976. {
  5977. /* size of the remaining log content to the right from the to-be-replaced part */
  5978. size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
  5979. size_t patch_sz = strlen(patch);
  5980. if (patch_sz != orig_sz) {
  5981. /* If patch line(s) are longer than original piece of verifier log,
  5982. * shift log contents by (patch_sz - orig_sz) bytes to the right
  5983. * starting from after to-be-replaced part of the log.
  5984. *
  5985. * If patch line(s) are shorter than original piece of verifier log,
  5986. * shift log contents by (orig_sz - patch_sz) bytes to the left
  5987. * starting from after to-be-replaced part of the log
  5988. *
  5989. * We need to be careful about not overflowing available
  5990. * buf_sz capacity. If that's the case, we'll truncate the end
  5991. * of the original log, as necessary.
  5992. */
  5993. if (patch_sz > orig_sz) {
  5994. if (orig + patch_sz >= buf + buf_sz) {
  5995. /* patch is big enough to cover remaining space completely */
  5996. patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
  5997. rem_sz = 0;
  5998. } else if (patch_sz - orig_sz > buf_sz - log_sz) {
  5999. /* patch causes part of remaining log to be truncated */
  6000. rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
  6001. }
  6002. }
  6003. /* shift remaining log to the right by calculated amount */
  6004. memmove(orig + patch_sz, orig + orig_sz, rem_sz);
  6005. }
  6006. memcpy(orig, patch, patch_sz);
  6007. }
  6008. static void fixup_log_failed_core_relo(struct bpf_program *prog,
  6009. char *buf, size_t buf_sz, size_t log_sz,
  6010. char *line1, char *line2, char *line3)
  6011. {
  6012. /* Expected log for failed and not properly guarded CO-RE relocation:
  6013. * line1 -> 123: (85) call unknown#195896080
  6014. * line2 -> invalid func unknown#195896080
  6015. * line3 -> <anything else or end of buffer>
  6016. *
  6017. * "123" is the index of the instruction that was poisoned. We extract
  6018. * instruction index to find corresponding CO-RE relocation and
  6019. * replace this part of the log with more relevant information about
  6020. * failed CO-RE relocation.
  6021. */
  6022. const struct bpf_core_relo *relo;
  6023. struct bpf_core_spec spec;
  6024. char patch[512], spec_buf[256];
  6025. int insn_idx, err, spec_len;
  6026. if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
  6027. return;
  6028. relo = find_relo_core(prog, insn_idx);
  6029. if (!relo)
  6030. return;
  6031. err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
  6032. if (err)
  6033. return;
  6034. spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
  6035. snprintf(patch, sizeof(patch),
  6036. "%d: <invalid CO-RE relocation>\n"
  6037. "failed to resolve CO-RE relocation %s%s\n",
  6038. insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
  6039. patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
  6040. }
  6041. static void fixup_log_missing_map_load(struct bpf_program *prog,
  6042. char *buf, size_t buf_sz, size_t log_sz,
  6043. char *line1, char *line2, char *line3)
  6044. {
  6045. /* Expected log for failed and not properly guarded CO-RE relocation:
  6046. * line1 -> 123: (85) call unknown#2001000345
  6047. * line2 -> invalid func unknown#2001000345
  6048. * line3 -> <anything else or end of buffer>
  6049. *
  6050. * "123" is the index of the instruction that was poisoned.
  6051. * "345" in "2001000345" are map index in obj->maps to fetch map name.
  6052. */
  6053. struct bpf_object *obj = prog->obj;
  6054. const struct bpf_map *map;
  6055. int insn_idx, map_idx;
  6056. char patch[128];
  6057. if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
  6058. return;
  6059. map_idx -= MAP_LDIMM64_POISON_BASE;
  6060. if (map_idx < 0 || map_idx >= obj->nr_maps)
  6061. return;
  6062. map = &obj->maps[map_idx];
  6063. snprintf(patch, sizeof(patch),
  6064. "%d: <invalid BPF map reference>\n"
  6065. "BPF map '%s' is referenced but wasn't created\n",
  6066. insn_idx, map->name);
  6067. patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
  6068. }
  6069. static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
  6070. {
  6071. /* look for familiar error patterns in last N lines of the log */
  6072. const size_t max_last_line_cnt = 10;
  6073. char *prev_line, *cur_line, *next_line;
  6074. size_t log_sz;
  6075. int i;
  6076. if (!buf)
  6077. return;
  6078. log_sz = strlen(buf) + 1;
  6079. next_line = buf + log_sz - 1;
  6080. for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
  6081. cur_line = find_prev_line(buf, next_line);
  6082. if (!cur_line)
  6083. return;
  6084. /* failed CO-RE relocation case */
  6085. if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
  6086. prev_line = find_prev_line(buf, cur_line);
  6087. if (!prev_line)
  6088. continue;
  6089. fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
  6090. prev_line, cur_line, next_line);
  6091. return;
  6092. } else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
  6093. prev_line = find_prev_line(buf, cur_line);
  6094. if (!prev_line)
  6095. continue;
  6096. fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
  6097. prev_line, cur_line, next_line);
  6098. return;
  6099. }
  6100. }
  6101. }
  6102. static int bpf_program_record_relos(struct bpf_program *prog)
  6103. {
  6104. struct bpf_object *obj = prog->obj;
  6105. int i;
  6106. for (i = 0; i < prog->nr_reloc; i++) {
  6107. struct reloc_desc *relo = &prog->reloc_desc[i];
  6108. struct extern_desc *ext = &obj->externs[relo->sym_off];
  6109. switch (relo->type) {
  6110. case RELO_EXTERN_VAR:
  6111. if (ext->type != EXT_KSYM)
  6112. continue;
  6113. bpf_gen__record_extern(obj->gen_loader, ext->name,
  6114. ext->is_weak, !ext->ksym.type_id,
  6115. BTF_KIND_VAR, relo->insn_idx);
  6116. break;
  6117. case RELO_EXTERN_FUNC:
  6118. bpf_gen__record_extern(obj->gen_loader, ext->name,
  6119. ext->is_weak, false, BTF_KIND_FUNC,
  6120. relo->insn_idx);
  6121. break;
  6122. case RELO_CORE: {
  6123. struct bpf_core_relo cr = {
  6124. .insn_off = relo->insn_idx * 8,
  6125. .type_id = relo->core_relo->type_id,
  6126. .access_str_off = relo->core_relo->access_str_off,
  6127. .kind = relo->core_relo->kind,
  6128. };
  6129. bpf_gen__record_relo_core(obj->gen_loader, &cr);
  6130. break;
  6131. }
  6132. default:
  6133. continue;
  6134. }
  6135. }
  6136. return 0;
  6137. }
  6138. static int
  6139. bpf_object__load_progs(struct bpf_object *obj, int log_level)
  6140. {
  6141. struct bpf_program *prog;
  6142. size_t i;
  6143. int err;
  6144. for (i = 0; i < obj->nr_programs; i++) {
  6145. prog = &obj->programs[i];
  6146. err = bpf_object__sanitize_prog(obj, prog);
  6147. if (err)
  6148. return err;
  6149. }
  6150. for (i = 0; i < obj->nr_programs; i++) {
  6151. prog = &obj->programs[i];
  6152. if (prog_is_subprog(obj, prog))
  6153. continue;
  6154. if (!prog->autoload) {
  6155. pr_debug("prog '%s': skipped loading\n", prog->name);
  6156. continue;
  6157. }
  6158. prog->log_level |= log_level;
  6159. if (obj->gen_loader)
  6160. bpf_program_record_relos(prog);
  6161. err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
  6162. obj->license, obj->kern_version, &prog->fd);
  6163. if (err) {
  6164. pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
  6165. return err;
  6166. }
  6167. }
  6168. bpf_object__free_relocs(obj);
  6169. return 0;
  6170. }
  6171. static const struct bpf_sec_def *find_sec_def(const char *sec_name);
  6172. static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
  6173. {
  6174. struct bpf_program *prog;
  6175. int err;
  6176. bpf_object__for_each_program(prog, obj) {
  6177. prog->sec_def = find_sec_def(prog->sec_name);
  6178. if (!prog->sec_def) {
  6179. /* couldn't guess, but user might manually specify */
  6180. pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
  6181. prog->name, prog->sec_name);
  6182. continue;
  6183. }
  6184. prog->type = prog->sec_def->prog_type;
  6185. prog->expected_attach_type = prog->sec_def->expected_attach_type;
  6186. /* sec_def can have custom callback which should be called
  6187. * after bpf_program is initialized to adjust its properties
  6188. */
  6189. if (prog->sec_def->prog_setup_fn) {
  6190. err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
  6191. if (err < 0) {
  6192. pr_warn("prog '%s': failed to initialize: %d\n",
  6193. prog->name, err);
  6194. return err;
  6195. }
  6196. }
  6197. }
  6198. return 0;
  6199. }
  6200. static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
  6201. const struct bpf_object_open_opts *opts)
  6202. {
  6203. const char *obj_name, *kconfig, *btf_tmp_path;
  6204. struct bpf_object *obj;
  6205. char tmp_name[64];
  6206. int err;
  6207. char *log_buf;
  6208. size_t log_size;
  6209. __u32 log_level;
  6210. if (elf_version(EV_CURRENT) == EV_NONE) {
  6211. pr_warn("failed to init libelf for %s\n",
  6212. path ? : "(mem buf)");
  6213. return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
  6214. }
  6215. if (!OPTS_VALID(opts, bpf_object_open_opts))
  6216. return ERR_PTR(-EINVAL);
  6217. obj_name = OPTS_GET(opts, object_name, NULL);
  6218. if (obj_buf) {
  6219. if (!obj_name) {
  6220. snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
  6221. (unsigned long)obj_buf,
  6222. (unsigned long)obj_buf_sz);
  6223. obj_name = tmp_name;
  6224. }
  6225. path = obj_name;
  6226. pr_debug("loading object '%s' from buffer\n", obj_name);
  6227. }
  6228. log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
  6229. log_size = OPTS_GET(opts, kernel_log_size, 0);
  6230. log_level = OPTS_GET(opts, kernel_log_level, 0);
  6231. if (log_size > UINT_MAX)
  6232. return ERR_PTR(-EINVAL);
  6233. if (log_size && !log_buf)
  6234. return ERR_PTR(-EINVAL);
  6235. obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
  6236. if (IS_ERR(obj))
  6237. return obj;
  6238. obj->log_buf = log_buf;
  6239. obj->log_size = log_size;
  6240. obj->log_level = log_level;
  6241. btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
  6242. if (btf_tmp_path) {
  6243. if (strlen(btf_tmp_path) >= PATH_MAX) {
  6244. err = -ENAMETOOLONG;
  6245. goto out;
  6246. }
  6247. obj->btf_custom_path = strdup(btf_tmp_path);
  6248. if (!obj->btf_custom_path) {
  6249. err = -ENOMEM;
  6250. goto out;
  6251. }
  6252. }
  6253. kconfig = OPTS_GET(opts, kconfig, NULL);
  6254. if (kconfig) {
  6255. obj->kconfig = strdup(kconfig);
  6256. if (!obj->kconfig) {
  6257. err = -ENOMEM;
  6258. goto out;
  6259. }
  6260. }
  6261. err = bpf_object__elf_init(obj);
  6262. err = err ? : bpf_object__check_endianness(obj);
  6263. err = err ? : bpf_object__elf_collect(obj);
  6264. err = err ? : bpf_object__collect_externs(obj);
  6265. err = err ? : bpf_object__finalize_btf(obj);
  6266. err = err ? : bpf_object__init_maps(obj, opts);
  6267. err = err ? : bpf_object_init_progs(obj, opts);
  6268. err = err ? : bpf_object__collect_relos(obj);
  6269. if (err)
  6270. goto out;
  6271. bpf_object__elf_finish(obj);
  6272. return obj;
  6273. out:
  6274. bpf_object__close(obj);
  6275. return ERR_PTR(err);
  6276. }
  6277. struct bpf_object *
  6278. bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
  6279. {
  6280. if (!path)
  6281. return libbpf_err_ptr(-EINVAL);
  6282. pr_debug("loading %s\n", path);
  6283. return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
  6284. }
  6285. struct bpf_object *bpf_object__open(const char *path)
  6286. {
  6287. return bpf_object__open_file(path, NULL);
  6288. }
  6289. struct bpf_object *
  6290. bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
  6291. const struct bpf_object_open_opts *opts)
  6292. {
  6293. if (!obj_buf || obj_buf_sz == 0)
  6294. return libbpf_err_ptr(-EINVAL);
  6295. return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
  6296. }
  6297. static int bpf_object_unload(struct bpf_object *obj)
  6298. {
  6299. size_t i;
  6300. if (!obj)
  6301. return libbpf_err(-EINVAL);
  6302. for (i = 0; i < obj->nr_maps; i++) {
  6303. zclose(obj->maps[i].fd);
  6304. if (obj->maps[i].st_ops)
  6305. zfree(&obj->maps[i].st_ops->kern_vdata);
  6306. }
  6307. for (i = 0; i < obj->nr_programs; i++)
  6308. bpf_program__unload(&obj->programs[i]);
  6309. return 0;
  6310. }
  6311. static int bpf_object__sanitize_maps(struct bpf_object *obj)
  6312. {
  6313. struct bpf_map *m;
  6314. bpf_object__for_each_map(m, obj) {
  6315. if (!bpf_map__is_internal(m))
  6316. continue;
  6317. if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
  6318. m->def.map_flags ^= BPF_F_MMAPABLE;
  6319. }
  6320. return 0;
  6321. }
  6322. int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
  6323. {
  6324. char sym_type, sym_name[500];
  6325. unsigned long long sym_addr;
  6326. int ret, err = 0;
  6327. FILE *f;
  6328. f = fopen("/proc/kallsyms", "r");
  6329. if (!f) {
  6330. err = -errno;
  6331. pr_warn("failed to open /proc/kallsyms: %d\n", err);
  6332. return err;
  6333. }
  6334. while (true) {
  6335. ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
  6336. &sym_addr, &sym_type, sym_name);
  6337. if (ret == EOF && feof(f))
  6338. break;
  6339. if (ret != 3) {
  6340. pr_warn("failed to read kallsyms entry: %d\n", ret);
  6341. err = -EINVAL;
  6342. break;
  6343. }
  6344. err = cb(sym_addr, sym_type, sym_name, ctx);
  6345. if (err)
  6346. break;
  6347. }
  6348. fclose(f);
  6349. return err;
  6350. }
  6351. static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
  6352. const char *sym_name, void *ctx)
  6353. {
  6354. struct bpf_object *obj = ctx;
  6355. const struct btf_type *t;
  6356. struct extern_desc *ext;
  6357. ext = find_extern_by_name(obj, sym_name);
  6358. if (!ext || ext->type != EXT_KSYM)
  6359. return 0;
  6360. t = btf__type_by_id(obj->btf, ext->btf_id);
  6361. if (!btf_is_var(t))
  6362. return 0;
  6363. if (ext->is_set && ext->ksym.addr != sym_addr) {
  6364. pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
  6365. sym_name, ext->ksym.addr, sym_addr);
  6366. return -EINVAL;
  6367. }
  6368. if (!ext->is_set) {
  6369. ext->is_set = true;
  6370. ext->ksym.addr = sym_addr;
  6371. pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
  6372. }
  6373. return 0;
  6374. }
  6375. static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
  6376. {
  6377. return libbpf_kallsyms_parse(kallsyms_cb, obj);
  6378. }
  6379. static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
  6380. __u16 kind, struct btf **res_btf,
  6381. struct module_btf **res_mod_btf)
  6382. {
  6383. struct module_btf *mod_btf;
  6384. struct btf *btf;
  6385. int i, id, err;
  6386. btf = obj->btf_vmlinux;
  6387. mod_btf = NULL;
  6388. id = btf__find_by_name_kind(btf, ksym_name, kind);
  6389. if (id == -ENOENT) {
  6390. err = load_module_btfs(obj);
  6391. if (err)
  6392. return err;
  6393. for (i = 0; i < obj->btf_module_cnt; i++) {
  6394. /* we assume module_btf's BTF FD is always >0 */
  6395. mod_btf = &obj->btf_modules[i];
  6396. btf = mod_btf->btf;
  6397. id = btf__find_by_name_kind_own(btf, ksym_name, kind);
  6398. if (id != -ENOENT)
  6399. break;
  6400. }
  6401. }
  6402. if (id <= 0)
  6403. return -ESRCH;
  6404. *res_btf = btf;
  6405. *res_mod_btf = mod_btf;
  6406. return id;
  6407. }
  6408. static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
  6409. struct extern_desc *ext)
  6410. {
  6411. const struct btf_type *targ_var, *targ_type;
  6412. __u32 targ_type_id, local_type_id;
  6413. struct module_btf *mod_btf = NULL;
  6414. const char *targ_var_name;
  6415. struct btf *btf = NULL;
  6416. int id, err;
  6417. id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
  6418. if (id < 0) {
  6419. if (id == -ESRCH && ext->is_weak)
  6420. return 0;
  6421. pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
  6422. ext->name);
  6423. return id;
  6424. }
  6425. /* find local type_id */
  6426. local_type_id = ext->ksym.type_id;
  6427. /* find target type_id */
  6428. targ_var = btf__type_by_id(btf, id);
  6429. targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
  6430. targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
  6431. err = bpf_core_types_are_compat(obj->btf, local_type_id,
  6432. btf, targ_type_id);
  6433. if (err <= 0) {
  6434. const struct btf_type *local_type;
  6435. const char *targ_name, *local_name;
  6436. local_type = btf__type_by_id(obj->btf, local_type_id);
  6437. local_name = btf__name_by_offset(obj->btf, local_type->name_off);
  6438. targ_name = btf__name_by_offset(btf, targ_type->name_off);
  6439. pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
  6440. ext->name, local_type_id,
  6441. btf_kind_str(local_type), local_name, targ_type_id,
  6442. btf_kind_str(targ_type), targ_name);
  6443. return -EINVAL;
  6444. }
  6445. ext->is_set = true;
  6446. ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
  6447. ext->ksym.kernel_btf_id = id;
  6448. pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
  6449. ext->name, id, btf_kind_str(targ_var), targ_var_name);
  6450. return 0;
  6451. }
  6452. static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
  6453. struct extern_desc *ext)
  6454. {
  6455. int local_func_proto_id, kfunc_proto_id, kfunc_id;
  6456. struct module_btf *mod_btf = NULL;
  6457. const struct btf_type *kern_func;
  6458. struct btf *kern_btf = NULL;
  6459. int ret;
  6460. local_func_proto_id = ext->ksym.type_id;
  6461. kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
  6462. if (kfunc_id < 0) {
  6463. if (kfunc_id == -ESRCH && ext->is_weak)
  6464. return 0;
  6465. pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
  6466. ext->name);
  6467. return kfunc_id;
  6468. }
  6469. kern_func = btf__type_by_id(kern_btf, kfunc_id);
  6470. kfunc_proto_id = kern_func->type;
  6471. ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
  6472. kern_btf, kfunc_proto_id);
  6473. if (ret <= 0) {
  6474. pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
  6475. ext->name, local_func_proto_id, kfunc_proto_id);
  6476. return -EINVAL;
  6477. }
  6478. /* set index for module BTF fd in fd_array, if unset */
  6479. if (mod_btf && !mod_btf->fd_array_idx) {
  6480. /* insn->off is s16 */
  6481. if (obj->fd_array_cnt == INT16_MAX) {
  6482. pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
  6483. ext->name, mod_btf->fd_array_idx);
  6484. return -E2BIG;
  6485. }
  6486. /* Cannot use index 0 for module BTF fd */
  6487. if (!obj->fd_array_cnt)
  6488. obj->fd_array_cnt = 1;
  6489. ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
  6490. obj->fd_array_cnt + 1);
  6491. if (ret)
  6492. return ret;
  6493. mod_btf->fd_array_idx = obj->fd_array_cnt;
  6494. /* we assume module BTF FD is always >0 */
  6495. obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
  6496. }
  6497. ext->is_set = true;
  6498. ext->ksym.kernel_btf_id = kfunc_id;
  6499. ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
  6500. pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
  6501. ext->name, kfunc_id);
  6502. return 0;
  6503. }
  6504. static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
  6505. {
  6506. const struct btf_type *t;
  6507. struct extern_desc *ext;
  6508. int i, err;
  6509. for (i = 0; i < obj->nr_extern; i++) {
  6510. ext = &obj->externs[i];
  6511. if (ext->type != EXT_KSYM || !ext->ksym.type_id)
  6512. continue;
  6513. if (obj->gen_loader) {
  6514. ext->is_set = true;
  6515. ext->ksym.kernel_btf_obj_fd = 0;
  6516. ext->ksym.kernel_btf_id = 0;
  6517. continue;
  6518. }
  6519. t = btf__type_by_id(obj->btf, ext->btf_id);
  6520. if (btf_is_var(t))
  6521. err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
  6522. else
  6523. err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
  6524. if (err)
  6525. return err;
  6526. }
  6527. return 0;
  6528. }
  6529. static int bpf_object__resolve_externs(struct bpf_object *obj,
  6530. const char *extra_kconfig)
  6531. {
  6532. bool need_config = false, need_kallsyms = false;
  6533. bool need_vmlinux_btf = false;
  6534. struct extern_desc *ext;
  6535. void *kcfg_data = NULL;
  6536. int err, i;
  6537. if (obj->nr_extern == 0)
  6538. return 0;
  6539. if (obj->kconfig_map_idx >= 0)
  6540. kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
  6541. for (i = 0; i < obj->nr_extern; i++) {
  6542. ext = &obj->externs[i];
  6543. if (ext->type == EXT_KSYM) {
  6544. if (ext->ksym.type_id)
  6545. need_vmlinux_btf = true;
  6546. else
  6547. need_kallsyms = true;
  6548. continue;
  6549. } else if (ext->type == EXT_KCFG) {
  6550. void *ext_ptr = kcfg_data + ext->kcfg.data_off;
  6551. __u64 value = 0;
  6552. /* Kconfig externs need actual /proc/config.gz */
  6553. if (str_has_pfx(ext->name, "CONFIG_")) {
  6554. need_config = true;
  6555. continue;
  6556. }
  6557. /* Virtual kcfg externs are customly handled by libbpf */
  6558. if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
  6559. value = get_kernel_version();
  6560. if (!value) {
  6561. pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
  6562. return -EINVAL;
  6563. }
  6564. } else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
  6565. value = kernel_supports(obj, FEAT_BPF_COOKIE);
  6566. } else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
  6567. value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
  6568. } else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
  6569. /* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
  6570. * __kconfig externs, where LINUX_ ones are virtual and filled out
  6571. * customly by libbpf (their values don't come from Kconfig).
  6572. * If LINUX_xxx variable is not recognized by libbpf, but is marked
  6573. * __weak, it defaults to zero value, just like for CONFIG_xxx
  6574. * externs.
  6575. */
  6576. pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
  6577. return -EINVAL;
  6578. }
  6579. err = set_kcfg_value_num(ext, ext_ptr, value);
  6580. if (err)
  6581. return err;
  6582. pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
  6583. ext->name, (long long)value);
  6584. } else {
  6585. pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
  6586. return -EINVAL;
  6587. }
  6588. }
  6589. if (need_config && extra_kconfig) {
  6590. err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
  6591. if (err)
  6592. return -EINVAL;
  6593. need_config = false;
  6594. for (i = 0; i < obj->nr_extern; i++) {
  6595. ext = &obj->externs[i];
  6596. if (ext->type == EXT_KCFG && !ext->is_set) {
  6597. need_config = true;
  6598. break;
  6599. }
  6600. }
  6601. }
  6602. if (need_config) {
  6603. err = bpf_object__read_kconfig_file(obj, kcfg_data);
  6604. if (err)
  6605. return -EINVAL;
  6606. }
  6607. if (need_kallsyms) {
  6608. err = bpf_object__read_kallsyms_file(obj);
  6609. if (err)
  6610. return -EINVAL;
  6611. }
  6612. if (need_vmlinux_btf) {
  6613. err = bpf_object__resolve_ksyms_btf_id(obj);
  6614. if (err)
  6615. return -EINVAL;
  6616. }
  6617. for (i = 0; i < obj->nr_extern; i++) {
  6618. ext = &obj->externs[i];
  6619. if (!ext->is_set && !ext->is_weak) {
  6620. pr_warn("extern '%s' (strong): not resolved\n", ext->name);
  6621. return -ESRCH;
  6622. } else if (!ext->is_set) {
  6623. pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
  6624. ext->name);
  6625. }
  6626. }
  6627. return 0;
  6628. }
  6629. static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
  6630. {
  6631. int err, i;
  6632. if (!obj)
  6633. return libbpf_err(-EINVAL);
  6634. if (obj->loaded) {
  6635. pr_warn("object '%s': load can't be attempted twice\n", obj->name);
  6636. return libbpf_err(-EINVAL);
  6637. }
  6638. if (obj->gen_loader)
  6639. bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
  6640. err = bpf_object__probe_loading(obj);
  6641. err = err ? : bpf_object__load_vmlinux_btf(obj, false);
  6642. err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
  6643. err = err ? : bpf_object__sanitize_and_load_btf(obj);
  6644. err = err ? : bpf_object__sanitize_maps(obj);
  6645. err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
  6646. err = err ? : bpf_object__create_maps(obj);
  6647. err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
  6648. err = err ? : bpf_object__load_progs(obj, extra_log_level);
  6649. err = err ? : bpf_object_init_prog_arrays(obj);
  6650. if (obj->gen_loader) {
  6651. /* reset FDs */
  6652. if (obj->btf)
  6653. btf__set_fd(obj->btf, -1);
  6654. for (i = 0; i < obj->nr_maps; i++)
  6655. obj->maps[i].fd = -1;
  6656. if (!err)
  6657. err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
  6658. }
  6659. /* clean up fd_array */
  6660. zfree(&obj->fd_array);
  6661. /* clean up module BTFs */
  6662. for (i = 0; i < obj->btf_module_cnt; i++) {
  6663. close(obj->btf_modules[i].fd);
  6664. btf__free(obj->btf_modules[i].btf);
  6665. free(obj->btf_modules[i].name);
  6666. }
  6667. free(obj->btf_modules);
  6668. /* clean up vmlinux BTF */
  6669. btf__free(obj->btf_vmlinux);
  6670. obj->btf_vmlinux = NULL;
  6671. obj->loaded = true; /* doesn't matter if successfully or not */
  6672. if (err)
  6673. goto out;
  6674. return 0;
  6675. out:
  6676. /* unpin any maps that were auto-pinned during load */
  6677. for (i = 0; i < obj->nr_maps; i++)
  6678. if (obj->maps[i].pinned && !obj->maps[i].reused)
  6679. bpf_map__unpin(&obj->maps[i], NULL);
  6680. bpf_object_unload(obj);
  6681. pr_warn("failed to load object '%s'\n", obj->path);
  6682. return libbpf_err(err);
  6683. }
  6684. int bpf_object__load(struct bpf_object *obj)
  6685. {
  6686. return bpf_object_load(obj, 0, NULL);
  6687. }
  6688. static int make_parent_dir(const char *path)
  6689. {
  6690. char *cp, errmsg[STRERR_BUFSIZE];
  6691. char *dname, *dir;
  6692. int err = 0;
  6693. dname = strdup(path);
  6694. if (dname == NULL)
  6695. return -ENOMEM;
  6696. dir = dirname(dname);
  6697. if (mkdir(dir, 0700) && errno != EEXIST)
  6698. err = -errno;
  6699. free(dname);
  6700. if (err) {
  6701. cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
  6702. pr_warn("failed to mkdir %s: %s\n", path, cp);
  6703. }
  6704. return err;
  6705. }
  6706. static int check_path(const char *path)
  6707. {
  6708. char *cp, errmsg[STRERR_BUFSIZE];
  6709. struct statfs st_fs;
  6710. char *dname, *dir;
  6711. int err = 0;
  6712. if (path == NULL)
  6713. return -EINVAL;
  6714. dname = strdup(path);
  6715. if (dname == NULL)
  6716. return -ENOMEM;
  6717. dir = dirname(dname);
  6718. if (statfs(dir, &st_fs)) {
  6719. cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
  6720. pr_warn("failed to statfs %s: %s\n", dir, cp);
  6721. err = -errno;
  6722. }
  6723. free(dname);
  6724. if (!err && st_fs.f_type != BPF_FS_MAGIC) {
  6725. pr_warn("specified path %s is not on BPF FS\n", path);
  6726. err = -EINVAL;
  6727. }
  6728. return err;
  6729. }
  6730. int bpf_program__pin(struct bpf_program *prog, const char *path)
  6731. {
  6732. char *cp, errmsg[STRERR_BUFSIZE];
  6733. int err;
  6734. if (prog->fd < 0) {
  6735. pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
  6736. return libbpf_err(-EINVAL);
  6737. }
  6738. err = make_parent_dir(path);
  6739. if (err)
  6740. return libbpf_err(err);
  6741. err = check_path(path);
  6742. if (err)
  6743. return libbpf_err(err);
  6744. if (bpf_obj_pin(prog->fd, path)) {
  6745. err = -errno;
  6746. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  6747. pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
  6748. return libbpf_err(err);
  6749. }
  6750. pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
  6751. return 0;
  6752. }
  6753. int bpf_program__unpin(struct bpf_program *prog, const char *path)
  6754. {
  6755. int err;
  6756. if (prog->fd < 0) {
  6757. pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
  6758. return libbpf_err(-EINVAL);
  6759. }
  6760. err = check_path(path);
  6761. if (err)
  6762. return libbpf_err(err);
  6763. err = unlink(path);
  6764. if (err)
  6765. return libbpf_err(-errno);
  6766. pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
  6767. return 0;
  6768. }
  6769. int bpf_map__pin(struct bpf_map *map, const char *path)
  6770. {
  6771. char *cp, errmsg[STRERR_BUFSIZE];
  6772. int err;
  6773. if (map == NULL) {
  6774. pr_warn("invalid map pointer\n");
  6775. return libbpf_err(-EINVAL);
  6776. }
  6777. if (map->pin_path) {
  6778. if (path && strcmp(path, map->pin_path)) {
  6779. pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
  6780. bpf_map__name(map), map->pin_path, path);
  6781. return libbpf_err(-EINVAL);
  6782. } else if (map->pinned) {
  6783. pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
  6784. bpf_map__name(map), map->pin_path);
  6785. return 0;
  6786. }
  6787. } else {
  6788. if (!path) {
  6789. pr_warn("missing a path to pin map '%s' at\n",
  6790. bpf_map__name(map));
  6791. return libbpf_err(-EINVAL);
  6792. } else if (map->pinned) {
  6793. pr_warn("map '%s' already pinned\n", bpf_map__name(map));
  6794. return libbpf_err(-EEXIST);
  6795. }
  6796. map->pin_path = strdup(path);
  6797. if (!map->pin_path) {
  6798. err = -errno;
  6799. goto out_err;
  6800. }
  6801. }
  6802. err = make_parent_dir(map->pin_path);
  6803. if (err)
  6804. return libbpf_err(err);
  6805. err = check_path(map->pin_path);
  6806. if (err)
  6807. return libbpf_err(err);
  6808. if (bpf_obj_pin(map->fd, map->pin_path)) {
  6809. err = -errno;
  6810. goto out_err;
  6811. }
  6812. map->pinned = true;
  6813. pr_debug("pinned map '%s'\n", map->pin_path);
  6814. return 0;
  6815. out_err:
  6816. cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
  6817. pr_warn("failed to pin map: %s\n", cp);
  6818. return libbpf_err(err);
  6819. }
  6820. int bpf_map__unpin(struct bpf_map *map, const char *path)
  6821. {
  6822. int err;
  6823. if (map == NULL) {
  6824. pr_warn("invalid map pointer\n");
  6825. return libbpf_err(-EINVAL);
  6826. }
  6827. if (map->pin_path) {
  6828. if (path && strcmp(path, map->pin_path)) {
  6829. pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
  6830. bpf_map__name(map), map->pin_path, path);
  6831. return libbpf_err(-EINVAL);
  6832. }
  6833. path = map->pin_path;
  6834. } else if (!path) {
  6835. pr_warn("no path to unpin map '%s' from\n",
  6836. bpf_map__name(map));
  6837. return libbpf_err(-EINVAL);
  6838. }
  6839. err = check_path(path);
  6840. if (err)
  6841. return libbpf_err(err);
  6842. err = unlink(path);
  6843. if (err != 0)
  6844. return libbpf_err(-errno);
  6845. map->pinned = false;
  6846. pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
  6847. return 0;
  6848. }
  6849. int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
  6850. {
  6851. char *new = NULL;
  6852. if (path) {
  6853. new = strdup(path);
  6854. if (!new)
  6855. return libbpf_err(-errno);
  6856. }
  6857. free(map->pin_path);
  6858. map->pin_path = new;
  6859. return 0;
  6860. }
  6861. __alias(bpf_map__pin_path)
  6862. const char *bpf_map__get_pin_path(const struct bpf_map *map);
  6863. const char *bpf_map__pin_path(const struct bpf_map *map)
  6864. {
  6865. return map->pin_path;
  6866. }
  6867. bool bpf_map__is_pinned(const struct bpf_map *map)
  6868. {
  6869. return map->pinned;
  6870. }
  6871. static void sanitize_pin_path(char *s)
  6872. {
  6873. /* bpffs disallows periods in path names */
  6874. while (*s) {
  6875. if (*s == '.')
  6876. *s = '_';
  6877. s++;
  6878. }
  6879. }
  6880. int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
  6881. {
  6882. struct bpf_map *map;
  6883. int err;
  6884. if (!obj)
  6885. return libbpf_err(-ENOENT);
  6886. if (!obj->loaded) {
  6887. pr_warn("object not yet loaded; load it first\n");
  6888. return libbpf_err(-ENOENT);
  6889. }
  6890. bpf_object__for_each_map(map, obj) {
  6891. char *pin_path = NULL;
  6892. char buf[PATH_MAX];
  6893. if (!map->autocreate)
  6894. continue;
  6895. if (path) {
  6896. err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
  6897. if (err)
  6898. goto err_unpin_maps;
  6899. sanitize_pin_path(buf);
  6900. pin_path = buf;
  6901. } else if (!map->pin_path) {
  6902. continue;
  6903. }
  6904. err = bpf_map__pin(map, pin_path);
  6905. if (err)
  6906. goto err_unpin_maps;
  6907. }
  6908. return 0;
  6909. err_unpin_maps:
  6910. while ((map = bpf_object__prev_map(obj, map))) {
  6911. if (!map->pin_path)
  6912. continue;
  6913. bpf_map__unpin(map, NULL);
  6914. }
  6915. return libbpf_err(err);
  6916. }
  6917. int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
  6918. {
  6919. struct bpf_map *map;
  6920. int err;
  6921. if (!obj)
  6922. return libbpf_err(-ENOENT);
  6923. bpf_object__for_each_map(map, obj) {
  6924. char *pin_path = NULL;
  6925. char buf[PATH_MAX];
  6926. if (path) {
  6927. err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
  6928. if (err)
  6929. return libbpf_err(err);
  6930. sanitize_pin_path(buf);
  6931. pin_path = buf;
  6932. } else if (!map->pin_path) {
  6933. continue;
  6934. }
  6935. err = bpf_map__unpin(map, pin_path);
  6936. if (err)
  6937. return libbpf_err(err);
  6938. }
  6939. return 0;
  6940. }
  6941. int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
  6942. {
  6943. struct bpf_program *prog;
  6944. char buf[PATH_MAX];
  6945. int err;
  6946. if (!obj)
  6947. return libbpf_err(-ENOENT);
  6948. if (!obj->loaded) {
  6949. pr_warn("object not yet loaded; load it first\n");
  6950. return libbpf_err(-ENOENT);
  6951. }
  6952. bpf_object__for_each_program(prog, obj) {
  6953. err = pathname_concat(buf, sizeof(buf), path, prog->name);
  6954. if (err)
  6955. goto err_unpin_programs;
  6956. err = bpf_program__pin(prog, buf);
  6957. if (err)
  6958. goto err_unpin_programs;
  6959. }
  6960. return 0;
  6961. err_unpin_programs:
  6962. while ((prog = bpf_object__prev_program(obj, prog))) {
  6963. if (pathname_concat(buf, sizeof(buf), path, prog->name))
  6964. continue;
  6965. bpf_program__unpin(prog, buf);
  6966. }
  6967. return libbpf_err(err);
  6968. }
  6969. int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
  6970. {
  6971. struct bpf_program *prog;
  6972. int err;
  6973. if (!obj)
  6974. return libbpf_err(-ENOENT);
  6975. bpf_object__for_each_program(prog, obj) {
  6976. char buf[PATH_MAX];
  6977. err = pathname_concat(buf, sizeof(buf), path, prog->name);
  6978. if (err)
  6979. return libbpf_err(err);
  6980. err = bpf_program__unpin(prog, buf);
  6981. if (err)
  6982. return libbpf_err(err);
  6983. }
  6984. return 0;
  6985. }
  6986. int bpf_object__pin(struct bpf_object *obj, const char *path)
  6987. {
  6988. int err;
  6989. err = bpf_object__pin_maps(obj, path);
  6990. if (err)
  6991. return libbpf_err(err);
  6992. err = bpf_object__pin_programs(obj, path);
  6993. if (err) {
  6994. bpf_object__unpin_maps(obj, path);
  6995. return libbpf_err(err);
  6996. }
  6997. return 0;
  6998. }
  6999. static void bpf_map__destroy(struct bpf_map *map)
  7000. {
  7001. if (map->inner_map) {
  7002. bpf_map__destroy(map->inner_map);
  7003. zfree(&map->inner_map);
  7004. }
  7005. zfree(&map->init_slots);
  7006. map->init_slots_sz = 0;
  7007. if (map->mmaped) {
  7008. munmap(map->mmaped, bpf_map_mmap_sz(map));
  7009. map->mmaped = NULL;
  7010. }
  7011. if (map->st_ops) {
  7012. zfree(&map->st_ops->data);
  7013. zfree(&map->st_ops->progs);
  7014. zfree(&map->st_ops->kern_func_off);
  7015. zfree(&map->st_ops);
  7016. }
  7017. zfree(&map->name);
  7018. zfree(&map->real_name);
  7019. zfree(&map->pin_path);
  7020. if (map->fd >= 0)
  7021. zclose(map->fd);
  7022. }
  7023. void bpf_object__close(struct bpf_object *obj)
  7024. {
  7025. size_t i;
  7026. if (IS_ERR_OR_NULL(obj))
  7027. return;
  7028. usdt_manager_free(obj->usdt_man);
  7029. obj->usdt_man = NULL;
  7030. bpf_gen__free(obj->gen_loader);
  7031. bpf_object__elf_finish(obj);
  7032. bpf_object_unload(obj);
  7033. btf__free(obj->btf);
  7034. btf__free(obj->btf_vmlinux);
  7035. btf_ext__free(obj->btf_ext);
  7036. for (i = 0; i < obj->nr_maps; i++)
  7037. bpf_map__destroy(&obj->maps[i]);
  7038. zfree(&obj->btf_custom_path);
  7039. zfree(&obj->kconfig);
  7040. zfree(&obj->externs);
  7041. obj->nr_extern = 0;
  7042. zfree(&obj->maps);
  7043. obj->nr_maps = 0;
  7044. if (obj->programs && obj->nr_programs) {
  7045. for (i = 0; i < obj->nr_programs; i++)
  7046. bpf_program__exit(&obj->programs[i]);
  7047. }
  7048. zfree(&obj->programs);
  7049. free(obj);
  7050. }
  7051. const char *bpf_object__name(const struct bpf_object *obj)
  7052. {
  7053. return obj ? obj->name : libbpf_err_ptr(-EINVAL);
  7054. }
  7055. unsigned int bpf_object__kversion(const struct bpf_object *obj)
  7056. {
  7057. return obj ? obj->kern_version : 0;
  7058. }
  7059. struct btf *bpf_object__btf(const struct bpf_object *obj)
  7060. {
  7061. return obj ? obj->btf : NULL;
  7062. }
  7063. int bpf_object__btf_fd(const struct bpf_object *obj)
  7064. {
  7065. return obj->btf ? btf__fd(obj->btf) : -1;
  7066. }
  7067. int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
  7068. {
  7069. if (obj->loaded)
  7070. return libbpf_err(-EINVAL);
  7071. obj->kern_version = kern_version;
  7072. return 0;
  7073. }
  7074. int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
  7075. {
  7076. struct bpf_gen *gen;
  7077. if (!opts)
  7078. return -EFAULT;
  7079. if (!OPTS_VALID(opts, gen_loader_opts))
  7080. return -EINVAL;
  7081. gen = calloc(sizeof(*gen), 1);
  7082. if (!gen)
  7083. return -ENOMEM;
  7084. gen->opts = opts;
  7085. obj->gen_loader = gen;
  7086. return 0;
  7087. }
  7088. static struct bpf_program *
  7089. __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
  7090. bool forward)
  7091. {
  7092. size_t nr_programs = obj->nr_programs;
  7093. ssize_t idx;
  7094. if (!nr_programs)
  7095. return NULL;
  7096. if (!p)
  7097. /* Iter from the beginning */
  7098. return forward ? &obj->programs[0] :
  7099. &obj->programs[nr_programs - 1];
  7100. if (p->obj != obj) {
  7101. pr_warn("error: program handler doesn't match object\n");
  7102. return errno = EINVAL, NULL;
  7103. }
  7104. idx = (p - obj->programs) + (forward ? 1 : -1);
  7105. if (idx >= obj->nr_programs || idx < 0)
  7106. return NULL;
  7107. return &obj->programs[idx];
  7108. }
  7109. struct bpf_program *
  7110. bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
  7111. {
  7112. struct bpf_program *prog = prev;
  7113. do {
  7114. prog = __bpf_program__iter(prog, obj, true);
  7115. } while (prog && prog_is_subprog(obj, prog));
  7116. return prog;
  7117. }
  7118. struct bpf_program *
  7119. bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
  7120. {
  7121. struct bpf_program *prog = next;
  7122. do {
  7123. prog = __bpf_program__iter(prog, obj, false);
  7124. } while (prog && prog_is_subprog(obj, prog));
  7125. return prog;
  7126. }
  7127. void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
  7128. {
  7129. prog->prog_ifindex = ifindex;
  7130. }
  7131. const char *bpf_program__name(const struct bpf_program *prog)
  7132. {
  7133. return prog->name;
  7134. }
  7135. const char *bpf_program__section_name(const struct bpf_program *prog)
  7136. {
  7137. return prog->sec_name;
  7138. }
  7139. bool bpf_program__autoload(const struct bpf_program *prog)
  7140. {
  7141. return prog->autoload;
  7142. }
  7143. int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
  7144. {
  7145. if (prog->obj->loaded)
  7146. return libbpf_err(-EINVAL);
  7147. prog->autoload = autoload;
  7148. return 0;
  7149. }
  7150. bool bpf_program__autoattach(const struct bpf_program *prog)
  7151. {
  7152. return prog->autoattach;
  7153. }
  7154. void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
  7155. {
  7156. prog->autoattach = autoattach;
  7157. }
  7158. const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
  7159. {
  7160. return prog->insns;
  7161. }
  7162. size_t bpf_program__insn_cnt(const struct bpf_program *prog)
  7163. {
  7164. return prog->insns_cnt;
  7165. }
  7166. int bpf_program__set_insns(struct bpf_program *prog,
  7167. struct bpf_insn *new_insns, size_t new_insn_cnt)
  7168. {
  7169. struct bpf_insn *insns;
  7170. if (prog->obj->loaded)
  7171. return -EBUSY;
  7172. insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
  7173. /* NULL is a valid return from reallocarray if the new count is zero */
  7174. if (!insns && new_insn_cnt) {
  7175. pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
  7176. return -ENOMEM;
  7177. }
  7178. memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
  7179. prog->insns = insns;
  7180. prog->insns_cnt = new_insn_cnt;
  7181. return 0;
  7182. }
  7183. int bpf_program__fd(const struct bpf_program *prog)
  7184. {
  7185. if (!prog)
  7186. return libbpf_err(-EINVAL);
  7187. if (prog->fd < 0)
  7188. return libbpf_err(-ENOENT);
  7189. return prog->fd;
  7190. }
  7191. __alias(bpf_program__type)
  7192. enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
  7193. enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
  7194. {
  7195. return prog->type;
  7196. }
  7197. int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
  7198. {
  7199. if (prog->obj->loaded)
  7200. return libbpf_err(-EBUSY);
  7201. prog->type = type;
  7202. return 0;
  7203. }
  7204. __alias(bpf_program__expected_attach_type)
  7205. enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
  7206. enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
  7207. {
  7208. return prog->expected_attach_type;
  7209. }
  7210. int bpf_program__set_expected_attach_type(struct bpf_program *prog,
  7211. enum bpf_attach_type type)
  7212. {
  7213. if (prog->obj->loaded)
  7214. return libbpf_err(-EBUSY);
  7215. prog->expected_attach_type = type;
  7216. return 0;
  7217. }
  7218. __u32 bpf_program__flags(const struct bpf_program *prog)
  7219. {
  7220. return prog->prog_flags;
  7221. }
  7222. int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
  7223. {
  7224. if (prog->obj->loaded)
  7225. return libbpf_err(-EBUSY);
  7226. prog->prog_flags = flags;
  7227. return 0;
  7228. }
  7229. __u32 bpf_program__log_level(const struct bpf_program *prog)
  7230. {
  7231. return prog->log_level;
  7232. }
  7233. int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
  7234. {
  7235. if (prog->obj->loaded)
  7236. return libbpf_err(-EBUSY);
  7237. prog->log_level = log_level;
  7238. return 0;
  7239. }
  7240. const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
  7241. {
  7242. *log_size = prog->log_size;
  7243. return prog->log_buf;
  7244. }
  7245. int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
  7246. {
  7247. if (log_size && !log_buf)
  7248. return -EINVAL;
  7249. if (prog->log_size > UINT_MAX)
  7250. return -EINVAL;
  7251. if (prog->obj->loaded)
  7252. return -EBUSY;
  7253. prog->log_buf = log_buf;
  7254. prog->log_size = log_size;
  7255. return 0;
  7256. }
  7257. #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
  7258. .sec = (char *)sec_pfx, \
  7259. .prog_type = BPF_PROG_TYPE_##ptype, \
  7260. .expected_attach_type = atype, \
  7261. .cookie = (long)(flags), \
  7262. .prog_prepare_load_fn = libbpf_prepare_prog_load, \
  7263. __VA_ARGS__ \
  7264. }
  7265. static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  7266. static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  7267. static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  7268. static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  7269. static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  7270. static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  7271. static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  7272. static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  7273. static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  7274. static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  7275. static const struct bpf_sec_def section_defs[] = {
  7276. SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE),
  7277. SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
  7278. SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
  7279. SEC_DEF("kprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
  7280. SEC_DEF("uprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
  7281. SEC_DEF("uprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
  7282. SEC_DEF("kretprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
  7283. SEC_DEF("uretprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
  7284. SEC_DEF("uretprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
  7285. SEC_DEF("kprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
  7286. SEC_DEF("kretprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
  7287. SEC_DEF("ksyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
  7288. SEC_DEF("kretsyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
  7289. SEC_DEF("usdt+", KPROBE, 0, SEC_NONE, attach_usdt),
  7290. SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE),
  7291. SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE),
  7292. SEC_DEF("action", SCHED_ACT, 0, SEC_NONE),
  7293. SEC_DEF("tracepoint+", TRACEPOINT, 0, SEC_NONE, attach_tp),
  7294. SEC_DEF("tp+", TRACEPOINT, 0, SEC_NONE, attach_tp),
  7295. SEC_DEF("raw_tracepoint+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
  7296. SEC_DEF("raw_tp+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
  7297. SEC_DEF("raw_tracepoint.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
  7298. SEC_DEF("raw_tp.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
  7299. SEC_DEF("tp_btf+", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
  7300. SEC_DEF("fentry+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
  7301. SEC_DEF("fmod_ret+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
  7302. SEC_DEF("fexit+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
  7303. SEC_DEF("fentry.s+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
  7304. SEC_DEF("fmod_ret.s+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
  7305. SEC_DEF("fexit.s+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
  7306. SEC_DEF("freplace+", EXT, 0, SEC_ATTACH_BTF, attach_trace),
  7307. SEC_DEF("lsm+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
  7308. SEC_DEF("lsm.s+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
  7309. SEC_DEF("lsm_cgroup+", LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
  7310. SEC_DEF("iter+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
  7311. SEC_DEF("iter.s+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
  7312. SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
  7313. SEC_DEF("xdp.frags/devmap", XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
  7314. SEC_DEF("xdp/devmap", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
  7315. SEC_DEF("xdp.frags/cpumap", XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
  7316. SEC_DEF("xdp/cpumap", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
  7317. SEC_DEF("xdp.frags", XDP, BPF_XDP, SEC_XDP_FRAGS),
  7318. SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
  7319. SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE),
  7320. SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE),
  7321. SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE),
  7322. SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE),
  7323. SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE),
  7324. SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
  7325. SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
  7326. SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
  7327. SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE),
  7328. SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
  7329. SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
  7330. SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
  7331. SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
  7332. SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
  7333. SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE),
  7334. SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
  7335. SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
  7336. SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
  7337. SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
  7338. SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
  7339. SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
  7340. SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
  7341. SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
  7342. SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
  7343. SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
  7344. SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
  7345. SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
  7346. SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
  7347. SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
  7348. SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
  7349. SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
  7350. SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
  7351. SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
  7352. SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
  7353. SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
  7354. SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
  7355. SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
  7356. SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
  7357. };
  7358. static size_t custom_sec_def_cnt;
  7359. static struct bpf_sec_def *custom_sec_defs;
  7360. static struct bpf_sec_def custom_fallback_def;
  7361. static bool has_custom_fallback_def;
  7362. static int last_custom_sec_def_handler_id;
  7363. int libbpf_register_prog_handler(const char *sec,
  7364. enum bpf_prog_type prog_type,
  7365. enum bpf_attach_type exp_attach_type,
  7366. const struct libbpf_prog_handler_opts *opts)
  7367. {
  7368. struct bpf_sec_def *sec_def;
  7369. if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
  7370. return libbpf_err(-EINVAL);
  7371. if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
  7372. return libbpf_err(-E2BIG);
  7373. if (sec) {
  7374. sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
  7375. sizeof(*sec_def));
  7376. if (!sec_def)
  7377. return libbpf_err(-ENOMEM);
  7378. custom_sec_defs = sec_def;
  7379. sec_def = &custom_sec_defs[custom_sec_def_cnt];
  7380. } else {
  7381. if (has_custom_fallback_def)
  7382. return libbpf_err(-EBUSY);
  7383. sec_def = &custom_fallback_def;
  7384. }
  7385. sec_def->sec = sec ? strdup(sec) : NULL;
  7386. if (sec && !sec_def->sec)
  7387. return libbpf_err(-ENOMEM);
  7388. sec_def->prog_type = prog_type;
  7389. sec_def->expected_attach_type = exp_attach_type;
  7390. sec_def->cookie = OPTS_GET(opts, cookie, 0);
  7391. sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
  7392. sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
  7393. sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
  7394. sec_def->handler_id = ++last_custom_sec_def_handler_id;
  7395. if (sec)
  7396. custom_sec_def_cnt++;
  7397. else
  7398. has_custom_fallback_def = true;
  7399. return sec_def->handler_id;
  7400. }
  7401. int libbpf_unregister_prog_handler(int handler_id)
  7402. {
  7403. struct bpf_sec_def *sec_defs;
  7404. int i;
  7405. if (handler_id <= 0)
  7406. return libbpf_err(-EINVAL);
  7407. if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
  7408. memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
  7409. has_custom_fallback_def = false;
  7410. return 0;
  7411. }
  7412. for (i = 0; i < custom_sec_def_cnt; i++) {
  7413. if (custom_sec_defs[i].handler_id == handler_id)
  7414. break;
  7415. }
  7416. if (i == custom_sec_def_cnt)
  7417. return libbpf_err(-ENOENT);
  7418. free(custom_sec_defs[i].sec);
  7419. for (i = i + 1; i < custom_sec_def_cnt; i++)
  7420. custom_sec_defs[i - 1] = custom_sec_defs[i];
  7421. custom_sec_def_cnt--;
  7422. /* try to shrink the array, but it's ok if we couldn't */
  7423. sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
  7424. /* if new count is zero, reallocarray can return a valid NULL result;
  7425. * in this case the previous pointer will be freed, so we *have to*
  7426. * reassign old pointer to the new value (even if it's NULL)
  7427. */
  7428. if (sec_defs || custom_sec_def_cnt == 0)
  7429. custom_sec_defs = sec_defs;
  7430. return 0;
  7431. }
  7432. static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
  7433. {
  7434. size_t len = strlen(sec_def->sec);
  7435. /* "type/" always has to have proper SEC("type/extras") form */
  7436. if (sec_def->sec[len - 1] == '/') {
  7437. if (str_has_pfx(sec_name, sec_def->sec))
  7438. return true;
  7439. return false;
  7440. }
  7441. /* "type+" means it can be either exact SEC("type") or
  7442. * well-formed SEC("type/extras") with proper '/' separator
  7443. */
  7444. if (sec_def->sec[len - 1] == '+') {
  7445. len--;
  7446. /* not even a prefix */
  7447. if (strncmp(sec_name, sec_def->sec, len) != 0)
  7448. return false;
  7449. /* exact match or has '/' separator */
  7450. if (sec_name[len] == '\0' || sec_name[len] == '/')
  7451. return true;
  7452. return false;
  7453. }
  7454. return strcmp(sec_name, sec_def->sec) == 0;
  7455. }
  7456. static const struct bpf_sec_def *find_sec_def(const char *sec_name)
  7457. {
  7458. const struct bpf_sec_def *sec_def;
  7459. int i, n;
  7460. n = custom_sec_def_cnt;
  7461. for (i = 0; i < n; i++) {
  7462. sec_def = &custom_sec_defs[i];
  7463. if (sec_def_matches(sec_def, sec_name))
  7464. return sec_def;
  7465. }
  7466. n = ARRAY_SIZE(section_defs);
  7467. for (i = 0; i < n; i++) {
  7468. sec_def = &section_defs[i];
  7469. if (sec_def_matches(sec_def, sec_name))
  7470. return sec_def;
  7471. }
  7472. if (has_custom_fallback_def)
  7473. return &custom_fallback_def;
  7474. return NULL;
  7475. }
  7476. #define MAX_TYPE_NAME_SIZE 32
  7477. static char *libbpf_get_type_names(bool attach_type)
  7478. {
  7479. int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
  7480. char *buf;
  7481. buf = malloc(len);
  7482. if (!buf)
  7483. return NULL;
  7484. buf[0] = '\0';
  7485. /* Forge string buf with all available names */
  7486. for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
  7487. const struct bpf_sec_def *sec_def = &section_defs[i];
  7488. if (attach_type) {
  7489. if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
  7490. continue;
  7491. if (!(sec_def->cookie & SEC_ATTACHABLE))
  7492. continue;
  7493. }
  7494. if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
  7495. free(buf);
  7496. return NULL;
  7497. }
  7498. strcat(buf, " ");
  7499. strcat(buf, section_defs[i].sec);
  7500. }
  7501. return buf;
  7502. }
  7503. int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
  7504. enum bpf_attach_type *expected_attach_type)
  7505. {
  7506. const struct bpf_sec_def *sec_def;
  7507. char *type_names;
  7508. if (!name)
  7509. return libbpf_err(-EINVAL);
  7510. sec_def = find_sec_def(name);
  7511. if (sec_def) {
  7512. *prog_type = sec_def->prog_type;
  7513. *expected_attach_type = sec_def->expected_attach_type;
  7514. return 0;
  7515. }
  7516. pr_debug("failed to guess program type from ELF section '%s'\n", name);
  7517. type_names = libbpf_get_type_names(false);
  7518. if (type_names != NULL) {
  7519. pr_debug("supported section(type) names are:%s\n", type_names);
  7520. free(type_names);
  7521. }
  7522. return libbpf_err(-ESRCH);
  7523. }
  7524. const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
  7525. {
  7526. if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
  7527. return NULL;
  7528. return attach_type_name[t];
  7529. }
  7530. const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
  7531. {
  7532. if (t < 0 || t >= ARRAY_SIZE(link_type_name))
  7533. return NULL;
  7534. return link_type_name[t];
  7535. }
  7536. const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
  7537. {
  7538. if (t < 0 || t >= ARRAY_SIZE(map_type_name))
  7539. return NULL;
  7540. return map_type_name[t];
  7541. }
  7542. const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
  7543. {
  7544. if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
  7545. return NULL;
  7546. return prog_type_name[t];
  7547. }
  7548. static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
  7549. size_t offset)
  7550. {
  7551. struct bpf_map *map;
  7552. size_t i;
  7553. for (i = 0; i < obj->nr_maps; i++) {
  7554. map = &obj->maps[i];
  7555. if (!bpf_map__is_struct_ops(map))
  7556. continue;
  7557. if (map->sec_offset <= offset &&
  7558. offset - map->sec_offset < map->def.value_size)
  7559. return map;
  7560. }
  7561. return NULL;
  7562. }
  7563. /* Collect the reloc from ELF and populate the st_ops->progs[] */
  7564. static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
  7565. Elf64_Shdr *shdr, Elf_Data *data)
  7566. {
  7567. const struct btf_member *member;
  7568. struct bpf_struct_ops *st_ops;
  7569. struct bpf_program *prog;
  7570. unsigned int shdr_idx;
  7571. const struct btf *btf;
  7572. struct bpf_map *map;
  7573. unsigned int moff, insn_idx;
  7574. const char *name;
  7575. __u32 member_idx;
  7576. Elf64_Sym *sym;
  7577. Elf64_Rel *rel;
  7578. int i, nrels;
  7579. btf = obj->btf;
  7580. nrels = shdr->sh_size / shdr->sh_entsize;
  7581. for (i = 0; i < nrels; i++) {
  7582. rel = elf_rel_by_idx(data, i);
  7583. if (!rel) {
  7584. pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
  7585. return -LIBBPF_ERRNO__FORMAT;
  7586. }
  7587. sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
  7588. if (!sym) {
  7589. pr_warn("struct_ops reloc: symbol %zx not found\n",
  7590. (size_t)ELF64_R_SYM(rel->r_info));
  7591. return -LIBBPF_ERRNO__FORMAT;
  7592. }
  7593. name = elf_sym_str(obj, sym->st_name) ?: "<?>";
  7594. map = find_struct_ops_map_by_offset(obj, rel->r_offset);
  7595. if (!map) {
  7596. pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
  7597. (size_t)rel->r_offset);
  7598. return -EINVAL;
  7599. }
  7600. moff = rel->r_offset - map->sec_offset;
  7601. shdr_idx = sym->st_shndx;
  7602. st_ops = map->st_ops;
  7603. pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel->r_offset %zu map->sec_offset %zu name %d (\'%s\')\n",
  7604. map->name,
  7605. (long long)(rel->r_info >> 32),
  7606. (long long)sym->st_value,
  7607. shdr_idx, (size_t)rel->r_offset,
  7608. map->sec_offset, sym->st_name, name);
  7609. if (shdr_idx >= SHN_LORESERVE) {
  7610. pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
  7611. map->name, (size_t)rel->r_offset, shdr_idx);
  7612. return -LIBBPF_ERRNO__RELOC;
  7613. }
  7614. if (sym->st_value % BPF_INSN_SZ) {
  7615. pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
  7616. map->name, (unsigned long long)sym->st_value);
  7617. return -LIBBPF_ERRNO__FORMAT;
  7618. }
  7619. insn_idx = sym->st_value / BPF_INSN_SZ;
  7620. member = find_member_by_offset(st_ops->type, moff * 8);
  7621. if (!member) {
  7622. pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
  7623. map->name, moff);
  7624. return -EINVAL;
  7625. }
  7626. member_idx = member - btf_members(st_ops->type);
  7627. name = btf__name_by_offset(btf, member->name_off);
  7628. if (!resolve_func_ptr(btf, member->type, NULL)) {
  7629. pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
  7630. map->name, name);
  7631. return -EINVAL;
  7632. }
  7633. prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
  7634. if (!prog) {
  7635. pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
  7636. map->name, shdr_idx, name);
  7637. return -EINVAL;
  7638. }
  7639. /* prevent the use of BPF prog with invalid type */
  7640. if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
  7641. pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
  7642. map->name, prog->name);
  7643. return -EINVAL;
  7644. }
  7645. /* if we haven't yet processed this BPF program, record proper
  7646. * attach_btf_id and member_idx
  7647. */
  7648. if (!prog->attach_btf_id) {
  7649. prog->attach_btf_id = st_ops->type_id;
  7650. prog->expected_attach_type = member_idx;
  7651. }
  7652. /* struct_ops BPF prog can be re-used between multiple
  7653. * .struct_ops as long as it's the same struct_ops struct
  7654. * definition and the same function pointer field
  7655. */
  7656. if (prog->attach_btf_id != st_ops->type_id ||
  7657. prog->expected_attach_type != member_idx) {
  7658. pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n",
  7659. map->name, prog->name, prog->sec_name, prog->type,
  7660. prog->attach_btf_id, prog->expected_attach_type, name);
  7661. return -EINVAL;
  7662. }
  7663. st_ops->progs[member_idx] = prog;
  7664. }
  7665. return 0;
  7666. }
  7667. #define BTF_TRACE_PREFIX "btf_trace_"
  7668. #define BTF_LSM_PREFIX "bpf_lsm_"
  7669. #define BTF_ITER_PREFIX "bpf_iter_"
  7670. #define BTF_MAX_NAME_SIZE 128
  7671. void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
  7672. const char **prefix, int *kind)
  7673. {
  7674. switch (attach_type) {
  7675. case BPF_TRACE_RAW_TP:
  7676. *prefix = BTF_TRACE_PREFIX;
  7677. *kind = BTF_KIND_TYPEDEF;
  7678. break;
  7679. case BPF_LSM_MAC:
  7680. case BPF_LSM_CGROUP:
  7681. *prefix = BTF_LSM_PREFIX;
  7682. *kind = BTF_KIND_FUNC;
  7683. break;
  7684. case BPF_TRACE_ITER:
  7685. *prefix = BTF_ITER_PREFIX;
  7686. *kind = BTF_KIND_FUNC;
  7687. break;
  7688. default:
  7689. *prefix = "";
  7690. *kind = BTF_KIND_FUNC;
  7691. }
  7692. }
  7693. static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
  7694. const char *name, __u32 kind)
  7695. {
  7696. char btf_type_name[BTF_MAX_NAME_SIZE];
  7697. int ret;
  7698. ret = snprintf(btf_type_name, sizeof(btf_type_name),
  7699. "%s%s", prefix, name);
  7700. /* snprintf returns the number of characters written excluding the
  7701. * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
  7702. * indicates truncation.
  7703. */
  7704. if (ret < 0 || ret >= sizeof(btf_type_name))
  7705. return -ENAMETOOLONG;
  7706. return btf__find_by_name_kind(btf, btf_type_name, kind);
  7707. }
  7708. static inline int find_attach_btf_id(struct btf *btf, const char *name,
  7709. enum bpf_attach_type attach_type)
  7710. {
  7711. const char *prefix;
  7712. int kind;
  7713. btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
  7714. return find_btf_by_prefix_kind(btf, prefix, name, kind);
  7715. }
  7716. int libbpf_find_vmlinux_btf_id(const char *name,
  7717. enum bpf_attach_type attach_type)
  7718. {
  7719. struct btf *btf;
  7720. int err;
  7721. btf = btf__load_vmlinux_btf();
  7722. err = libbpf_get_error(btf);
  7723. if (err) {
  7724. pr_warn("vmlinux BTF is not found\n");
  7725. return libbpf_err(err);
  7726. }
  7727. err = find_attach_btf_id(btf, name, attach_type);
  7728. if (err <= 0)
  7729. pr_warn("%s is not found in vmlinux BTF\n", name);
  7730. btf__free(btf);
  7731. return libbpf_err(err);
  7732. }
  7733. static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
  7734. {
  7735. struct bpf_prog_info info;
  7736. __u32 info_len = sizeof(info);
  7737. struct btf *btf;
  7738. int err;
  7739. memset(&info, 0, info_len);
  7740. err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
  7741. if (err) {
  7742. pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
  7743. attach_prog_fd, err);
  7744. return err;
  7745. }
  7746. err = -EINVAL;
  7747. if (!info.btf_id) {
  7748. pr_warn("The target program doesn't have BTF\n");
  7749. goto out;
  7750. }
  7751. btf = btf__load_from_kernel_by_id(info.btf_id);
  7752. err = libbpf_get_error(btf);
  7753. if (err) {
  7754. pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
  7755. goto out;
  7756. }
  7757. err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
  7758. btf__free(btf);
  7759. if (err <= 0) {
  7760. pr_warn("%s is not found in prog's BTF\n", name);
  7761. goto out;
  7762. }
  7763. out:
  7764. return err;
  7765. }
  7766. static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
  7767. enum bpf_attach_type attach_type,
  7768. int *btf_obj_fd, int *btf_type_id)
  7769. {
  7770. int ret, i;
  7771. ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
  7772. if (ret > 0) {
  7773. *btf_obj_fd = 0; /* vmlinux BTF */
  7774. *btf_type_id = ret;
  7775. return 0;
  7776. }
  7777. if (ret != -ENOENT)
  7778. return ret;
  7779. ret = load_module_btfs(obj);
  7780. if (ret)
  7781. return ret;
  7782. for (i = 0; i < obj->btf_module_cnt; i++) {
  7783. const struct module_btf *mod = &obj->btf_modules[i];
  7784. ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
  7785. if (ret > 0) {
  7786. *btf_obj_fd = mod->fd;
  7787. *btf_type_id = ret;
  7788. return 0;
  7789. }
  7790. if (ret == -ENOENT)
  7791. continue;
  7792. return ret;
  7793. }
  7794. return -ESRCH;
  7795. }
  7796. static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
  7797. int *btf_obj_fd, int *btf_type_id)
  7798. {
  7799. enum bpf_attach_type attach_type = prog->expected_attach_type;
  7800. __u32 attach_prog_fd = prog->attach_prog_fd;
  7801. int err = 0;
  7802. /* BPF program's BTF ID */
  7803. if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
  7804. if (!attach_prog_fd) {
  7805. pr_warn("prog '%s': attach program FD is not set\n", prog->name);
  7806. return -EINVAL;
  7807. }
  7808. err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
  7809. if (err < 0) {
  7810. pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
  7811. prog->name, attach_prog_fd, attach_name, err);
  7812. return err;
  7813. }
  7814. *btf_obj_fd = 0;
  7815. *btf_type_id = err;
  7816. return 0;
  7817. }
  7818. /* kernel/module BTF ID */
  7819. if (prog->obj->gen_loader) {
  7820. bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
  7821. *btf_obj_fd = 0;
  7822. *btf_type_id = 1;
  7823. } else {
  7824. err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
  7825. }
  7826. if (err) {
  7827. pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
  7828. prog->name, attach_name, err);
  7829. return err;
  7830. }
  7831. return 0;
  7832. }
  7833. int libbpf_attach_type_by_name(const char *name,
  7834. enum bpf_attach_type *attach_type)
  7835. {
  7836. char *type_names;
  7837. const struct bpf_sec_def *sec_def;
  7838. if (!name)
  7839. return libbpf_err(-EINVAL);
  7840. sec_def = find_sec_def(name);
  7841. if (!sec_def) {
  7842. pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
  7843. type_names = libbpf_get_type_names(true);
  7844. if (type_names != NULL) {
  7845. pr_debug("attachable section(type) names are:%s\n", type_names);
  7846. free(type_names);
  7847. }
  7848. return libbpf_err(-EINVAL);
  7849. }
  7850. if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
  7851. return libbpf_err(-EINVAL);
  7852. if (!(sec_def->cookie & SEC_ATTACHABLE))
  7853. return libbpf_err(-EINVAL);
  7854. *attach_type = sec_def->expected_attach_type;
  7855. return 0;
  7856. }
  7857. int bpf_map__fd(const struct bpf_map *map)
  7858. {
  7859. return map ? map->fd : libbpf_err(-EINVAL);
  7860. }
  7861. static bool map_uses_real_name(const struct bpf_map *map)
  7862. {
  7863. /* Since libbpf started to support custom .data.* and .rodata.* maps,
  7864. * their user-visible name differs from kernel-visible name. Users see
  7865. * such map's corresponding ELF section name as a map name.
  7866. * This check distinguishes .data/.rodata from .data.* and .rodata.*
  7867. * maps to know which name has to be returned to the user.
  7868. */
  7869. if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
  7870. return true;
  7871. if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
  7872. return true;
  7873. return false;
  7874. }
  7875. const char *bpf_map__name(const struct bpf_map *map)
  7876. {
  7877. if (!map)
  7878. return NULL;
  7879. if (map_uses_real_name(map))
  7880. return map->real_name;
  7881. return map->name;
  7882. }
  7883. enum bpf_map_type bpf_map__type(const struct bpf_map *map)
  7884. {
  7885. return map->def.type;
  7886. }
  7887. int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
  7888. {
  7889. if (map->fd >= 0)
  7890. return libbpf_err(-EBUSY);
  7891. map->def.type = type;
  7892. return 0;
  7893. }
  7894. __u32 bpf_map__map_flags(const struct bpf_map *map)
  7895. {
  7896. return map->def.map_flags;
  7897. }
  7898. int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
  7899. {
  7900. if (map->fd >= 0)
  7901. return libbpf_err(-EBUSY);
  7902. map->def.map_flags = flags;
  7903. return 0;
  7904. }
  7905. __u64 bpf_map__map_extra(const struct bpf_map *map)
  7906. {
  7907. return map->map_extra;
  7908. }
  7909. int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
  7910. {
  7911. if (map->fd >= 0)
  7912. return libbpf_err(-EBUSY);
  7913. map->map_extra = map_extra;
  7914. return 0;
  7915. }
  7916. __u32 bpf_map__numa_node(const struct bpf_map *map)
  7917. {
  7918. return map->numa_node;
  7919. }
  7920. int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
  7921. {
  7922. if (map->fd >= 0)
  7923. return libbpf_err(-EBUSY);
  7924. map->numa_node = numa_node;
  7925. return 0;
  7926. }
  7927. __u32 bpf_map__key_size(const struct bpf_map *map)
  7928. {
  7929. return map->def.key_size;
  7930. }
  7931. int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
  7932. {
  7933. if (map->fd >= 0)
  7934. return libbpf_err(-EBUSY);
  7935. map->def.key_size = size;
  7936. return 0;
  7937. }
  7938. __u32 bpf_map__value_size(const struct bpf_map *map)
  7939. {
  7940. return map->def.value_size;
  7941. }
  7942. int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
  7943. {
  7944. if (map->fd >= 0)
  7945. return libbpf_err(-EBUSY);
  7946. map->def.value_size = size;
  7947. return 0;
  7948. }
  7949. __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
  7950. {
  7951. return map ? map->btf_key_type_id : 0;
  7952. }
  7953. __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
  7954. {
  7955. return map ? map->btf_value_type_id : 0;
  7956. }
  7957. int bpf_map__set_initial_value(struct bpf_map *map,
  7958. const void *data, size_t size)
  7959. {
  7960. if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
  7961. size != map->def.value_size || map->fd >= 0)
  7962. return libbpf_err(-EINVAL);
  7963. memcpy(map->mmaped, data, size);
  7964. return 0;
  7965. }
  7966. const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
  7967. {
  7968. if (!map->mmaped)
  7969. return NULL;
  7970. *psize = map->def.value_size;
  7971. return map->mmaped;
  7972. }
  7973. bool bpf_map__is_internal(const struct bpf_map *map)
  7974. {
  7975. return map->libbpf_type != LIBBPF_MAP_UNSPEC;
  7976. }
  7977. __u32 bpf_map__ifindex(const struct bpf_map *map)
  7978. {
  7979. return map->map_ifindex;
  7980. }
  7981. int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
  7982. {
  7983. if (map->fd >= 0)
  7984. return libbpf_err(-EBUSY);
  7985. map->map_ifindex = ifindex;
  7986. return 0;
  7987. }
  7988. int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
  7989. {
  7990. if (!bpf_map_type__is_map_in_map(map->def.type)) {
  7991. pr_warn("error: unsupported map type\n");
  7992. return libbpf_err(-EINVAL);
  7993. }
  7994. if (map->inner_map_fd != -1) {
  7995. pr_warn("error: inner_map_fd already specified\n");
  7996. return libbpf_err(-EINVAL);
  7997. }
  7998. if (map->inner_map) {
  7999. bpf_map__destroy(map->inner_map);
  8000. zfree(&map->inner_map);
  8001. }
  8002. map->inner_map_fd = fd;
  8003. return 0;
  8004. }
  8005. static struct bpf_map *
  8006. __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
  8007. {
  8008. ssize_t idx;
  8009. struct bpf_map *s, *e;
  8010. if (!obj || !obj->maps)
  8011. return errno = EINVAL, NULL;
  8012. s = obj->maps;
  8013. e = obj->maps + obj->nr_maps;
  8014. if ((m < s) || (m >= e)) {
  8015. pr_warn("error in %s: map handler doesn't belong to object\n",
  8016. __func__);
  8017. return errno = EINVAL, NULL;
  8018. }
  8019. idx = (m - obj->maps) + i;
  8020. if (idx >= obj->nr_maps || idx < 0)
  8021. return NULL;
  8022. return &obj->maps[idx];
  8023. }
  8024. struct bpf_map *
  8025. bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
  8026. {
  8027. if (prev == NULL)
  8028. return obj->maps;
  8029. return __bpf_map__iter(prev, obj, 1);
  8030. }
  8031. struct bpf_map *
  8032. bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
  8033. {
  8034. if (next == NULL) {
  8035. if (!obj->nr_maps)
  8036. return NULL;
  8037. return obj->maps + obj->nr_maps - 1;
  8038. }
  8039. return __bpf_map__iter(next, obj, -1);
  8040. }
  8041. struct bpf_map *
  8042. bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
  8043. {
  8044. struct bpf_map *pos;
  8045. bpf_object__for_each_map(pos, obj) {
  8046. /* if it's a special internal map name (which always starts
  8047. * with dot) then check if that special name matches the
  8048. * real map name (ELF section name)
  8049. */
  8050. if (name[0] == '.') {
  8051. if (pos->real_name && strcmp(pos->real_name, name) == 0)
  8052. return pos;
  8053. continue;
  8054. }
  8055. /* otherwise map name has to be an exact match */
  8056. if (map_uses_real_name(pos)) {
  8057. if (strcmp(pos->real_name, name) == 0)
  8058. return pos;
  8059. continue;
  8060. }
  8061. if (strcmp(pos->name, name) == 0)
  8062. return pos;
  8063. }
  8064. return errno = ENOENT, NULL;
  8065. }
  8066. int
  8067. bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
  8068. {
  8069. return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
  8070. }
  8071. static int validate_map_op(const struct bpf_map *map, size_t key_sz,
  8072. size_t value_sz, bool check_value_sz)
  8073. {
  8074. if (map->fd <= 0)
  8075. return -ENOENT;
  8076. if (map->def.key_size != key_sz) {
  8077. pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
  8078. map->name, key_sz, map->def.key_size);
  8079. return -EINVAL;
  8080. }
  8081. if (!check_value_sz)
  8082. return 0;
  8083. switch (map->def.type) {
  8084. case BPF_MAP_TYPE_PERCPU_ARRAY:
  8085. case BPF_MAP_TYPE_PERCPU_HASH:
  8086. case BPF_MAP_TYPE_LRU_PERCPU_HASH:
  8087. case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
  8088. int num_cpu = libbpf_num_possible_cpus();
  8089. size_t elem_sz = roundup(map->def.value_size, 8);
  8090. if (value_sz != num_cpu * elem_sz) {
  8091. pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
  8092. map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
  8093. return -EINVAL;
  8094. }
  8095. break;
  8096. }
  8097. default:
  8098. if (map->def.value_size != value_sz) {
  8099. pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
  8100. map->name, value_sz, map->def.value_size);
  8101. return -EINVAL;
  8102. }
  8103. break;
  8104. }
  8105. return 0;
  8106. }
  8107. int bpf_map__lookup_elem(const struct bpf_map *map,
  8108. const void *key, size_t key_sz,
  8109. void *value, size_t value_sz, __u64 flags)
  8110. {
  8111. int err;
  8112. err = validate_map_op(map, key_sz, value_sz, true);
  8113. if (err)
  8114. return libbpf_err(err);
  8115. return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
  8116. }
  8117. int bpf_map__update_elem(const struct bpf_map *map,
  8118. const void *key, size_t key_sz,
  8119. const void *value, size_t value_sz, __u64 flags)
  8120. {
  8121. int err;
  8122. err = validate_map_op(map, key_sz, value_sz, true);
  8123. if (err)
  8124. return libbpf_err(err);
  8125. return bpf_map_update_elem(map->fd, key, value, flags);
  8126. }
  8127. int bpf_map__delete_elem(const struct bpf_map *map,
  8128. const void *key, size_t key_sz, __u64 flags)
  8129. {
  8130. int err;
  8131. err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
  8132. if (err)
  8133. return libbpf_err(err);
  8134. return bpf_map_delete_elem_flags(map->fd, key, flags);
  8135. }
  8136. int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
  8137. const void *key, size_t key_sz,
  8138. void *value, size_t value_sz, __u64 flags)
  8139. {
  8140. int err;
  8141. err = validate_map_op(map, key_sz, value_sz, true);
  8142. if (err)
  8143. return libbpf_err(err);
  8144. return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
  8145. }
  8146. int bpf_map__get_next_key(const struct bpf_map *map,
  8147. const void *cur_key, void *next_key, size_t key_sz)
  8148. {
  8149. int err;
  8150. err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
  8151. if (err)
  8152. return libbpf_err(err);
  8153. return bpf_map_get_next_key(map->fd, cur_key, next_key);
  8154. }
  8155. long libbpf_get_error(const void *ptr)
  8156. {
  8157. if (!IS_ERR_OR_NULL(ptr))
  8158. return 0;
  8159. if (IS_ERR(ptr))
  8160. errno = -PTR_ERR(ptr);
  8161. /* If ptr == NULL, then errno should be already set by the failing
  8162. * API, because libbpf never returns NULL on success and it now always
  8163. * sets errno on error. So no extra errno handling for ptr == NULL
  8164. * case.
  8165. */
  8166. return -errno;
  8167. }
  8168. /* Replace link's underlying BPF program with the new one */
  8169. int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
  8170. {
  8171. int ret;
  8172. ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
  8173. return libbpf_err_errno(ret);
  8174. }
  8175. /* Release "ownership" of underlying BPF resource (typically, BPF program
  8176. * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
  8177. * link, when destructed through bpf_link__destroy() call won't attempt to
  8178. * detach/unregisted that BPF resource. This is useful in situations where,
  8179. * say, attached BPF program has to outlive userspace program that attached it
  8180. * in the system. Depending on type of BPF program, though, there might be
  8181. * additional steps (like pinning BPF program in BPF FS) necessary to ensure
  8182. * exit of userspace program doesn't trigger automatic detachment and clean up
  8183. * inside the kernel.
  8184. */
  8185. void bpf_link__disconnect(struct bpf_link *link)
  8186. {
  8187. link->disconnected = true;
  8188. }
  8189. int bpf_link__destroy(struct bpf_link *link)
  8190. {
  8191. int err = 0;
  8192. if (IS_ERR_OR_NULL(link))
  8193. return 0;
  8194. if (!link->disconnected && link->detach)
  8195. err = link->detach(link);
  8196. if (link->pin_path)
  8197. free(link->pin_path);
  8198. if (link->dealloc)
  8199. link->dealloc(link);
  8200. else
  8201. free(link);
  8202. return libbpf_err(err);
  8203. }
  8204. int bpf_link__fd(const struct bpf_link *link)
  8205. {
  8206. return link->fd;
  8207. }
  8208. const char *bpf_link__pin_path(const struct bpf_link *link)
  8209. {
  8210. return link->pin_path;
  8211. }
  8212. static int bpf_link__detach_fd(struct bpf_link *link)
  8213. {
  8214. return libbpf_err_errno(close(link->fd));
  8215. }
  8216. struct bpf_link *bpf_link__open(const char *path)
  8217. {
  8218. struct bpf_link *link;
  8219. int fd;
  8220. fd = bpf_obj_get(path);
  8221. if (fd < 0) {
  8222. fd = -errno;
  8223. pr_warn("failed to open link at %s: %d\n", path, fd);
  8224. return libbpf_err_ptr(fd);
  8225. }
  8226. link = calloc(1, sizeof(*link));
  8227. if (!link) {
  8228. close(fd);
  8229. return libbpf_err_ptr(-ENOMEM);
  8230. }
  8231. link->detach = &bpf_link__detach_fd;
  8232. link->fd = fd;
  8233. link->pin_path = strdup(path);
  8234. if (!link->pin_path) {
  8235. bpf_link__destroy(link);
  8236. return libbpf_err_ptr(-ENOMEM);
  8237. }
  8238. return link;
  8239. }
  8240. int bpf_link__detach(struct bpf_link *link)
  8241. {
  8242. return bpf_link_detach(link->fd) ? -errno : 0;
  8243. }
  8244. int bpf_link__pin(struct bpf_link *link, const char *path)
  8245. {
  8246. int err;
  8247. if (link->pin_path)
  8248. return libbpf_err(-EBUSY);
  8249. err = make_parent_dir(path);
  8250. if (err)
  8251. return libbpf_err(err);
  8252. err = check_path(path);
  8253. if (err)
  8254. return libbpf_err(err);
  8255. link->pin_path = strdup(path);
  8256. if (!link->pin_path)
  8257. return libbpf_err(-ENOMEM);
  8258. if (bpf_obj_pin(link->fd, link->pin_path)) {
  8259. err = -errno;
  8260. zfree(&link->pin_path);
  8261. return libbpf_err(err);
  8262. }
  8263. pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
  8264. return 0;
  8265. }
  8266. int bpf_link__unpin(struct bpf_link *link)
  8267. {
  8268. int err;
  8269. if (!link->pin_path)
  8270. return libbpf_err(-EINVAL);
  8271. err = unlink(link->pin_path);
  8272. if (err != 0)
  8273. return -errno;
  8274. pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
  8275. zfree(&link->pin_path);
  8276. return 0;
  8277. }
  8278. struct bpf_link_perf {
  8279. struct bpf_link link;
  8280. int perf_event_fd;
  8281. /* legacy kprobe support: keep track of probe identifier and type */
  8282. char *legacy_probe_name;
  8283. bool legacy_is_kprobe;
  8284. bool legacy_is_retprobe;
  8285. };
  8286. static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
  8287. static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
  8288. static int bpf_link_perf_detach(struct bpf_link *link)
  8289. {
  8290. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  8291. int err = 0;
  8292. if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
  8293. err = -errno;
  8294. if (perf_link->perf_event_fd != link->fd)
  8295. close(perf_link->perf_event_fd);
  8296. close(link->fd);
  8297. /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
  8298. if (perf_link->legacy_probe_name) {
  8299. if (perf_link->legacy_is_kprobe) {
  8300. err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
  8301. perf_link->legacy_is_retprobe);
  8302. } else {
  8303. err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
  8304. perf_link->legacy_is_retprobe);
  8305. }
  8306. }
  8307. return err;
  8308. }
  8309. static void bpf_link_perf_dealloc(struct bpf_link *link)
  8310. {
  8311. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  8312. free(perf_link->legacy_probe_name);
  8313. free(perf_link);
  8314. }
  8315. struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
  8316. const struct bpf_perf_event_opts *opts)
  8317. {
  8318. char errmsg[STRERR_BUFSIZE];
  8319. struct bpf_link_perf *link;
  8320. int prog_fd, link_fd = -1, err;
  8321. if (!OPTS_VALID(opts, bpf_perf_event_opts))
  8322. return libbpf_err_ptr(-EINVAL);
  8323. if (pfd < 0) {
  8324. pr_warn("prog '%s': invalid perf event FD %d\n",
  8325. prog->name, pfd);
  8326. return libbpf_err_ptr(-EINVAL);
  8327. }
  8328. prog_fd = bpf_program__fd(prog);
  8329. if (prog_fd < 0) {
  8330. pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
  8331. prog->name);
  8332. return libbpf_err_ptr(-EINVAL);
  8333. }
  8334. link = calloc(1, sizeof(*link));
  8335. if (!link)
  8336. return libbpf_err_ptr(-ENOMEM);
  8337. link->link.detach = &bpf_link_perf_detach;
  8338. link->link.dealloc = &bpf_link_perf_dealloc;
  8339. link->perf_event_fd = pfd;
  8340. if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
  8341. DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
  8342. .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
  8343. link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
  8344. if (link_fd < 0) {
  8345. err = -errno;
  8346. pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
  8347. prog->name, pfd,
  8348. err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  8349. goto err_out;
  8350. }
  8351. link->link.fd = link_fd;
  8352. } else {
  8353. if (OPTS_GET(opts, bpf_cookie, 0)) {
  8354. pr_warn("prog '%s': user context value is not supported\n", prog->name);
  8355. err = -EOPNOTSUPP;
  8356. goto err_out;
  8357. }
  8358. if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
  8359. err = -errno;
  8360. pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
  8361. prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  8362. if (err == -EPROTO)
  8363. pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
  8364. prog->name, pfd);
  8365. goto err_out;
  8366. }
  8367. link->link.fd = pfd;
  8368. }
  8369. if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
  8370. err = -errno;
  8371. pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
  8372. prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  8373. goto err_out;
  8374. }
  8375. return &link->link;
  8376. err_out:
  8377. if (link_fd >= 0)
  8378. close(link_fd);
  8379. free(link);
  8380. return libbpf_err_ptr(err);
  8381. }
  8382. struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
  8383. {
  8384. return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
  8385. }
  8386. /*
  8387. * this function is expected to parse integer in the range of [0, 2^31-1] from
  8388. * given file using scanf format string fmt. If actual parsed value is
  8389. * negative, the result might be indistinguishable from error
  8390. */
  8391. static int parse_uint_from_file(const char *file, const char *fmt)
  8392. {
  8393. char buf[STRERR_BUFSIZE];
  8394. int err, ret;
  8395. FILE *f;
  8396. f = fopen(file, "r");
  8397. if (!f) {
  8398. err = -errno;
  8399. pr_debug("failed to open '%s': %s\n", file,
  8400. libbpf_strerror_r(err, buf, sizeof(buf)));
  8401. return err;
  8402. }
  8403. err = fscanf(f, fmt, &ret);
  8404. if (err != 1) {
  8405. err = err == EOF ? -EIO : -errno;
  8406. pr_debug("failed to parse '%s': %s\n", file,
  8407. libbpf_strerror_r(err, buf, sizeof(buf)));
  8408. fclose(f);
  8409. return err;
  8410. }
  8411. fclose(f);
  8412. return ret;
  8413. }
  8414. static int determine_kprobe_perf_type(void)
  8415. {
  8416. const char *file = "/sys/bus/event_source/devices/kprobe/type";
  8417. return parse_uint_from_file(file, "%d\n");
  8418. }
  8419. static int determine_uprobe_perf_type(void)
  8420. {
  8421. const char *file = "/sys/bus/event_source/devices/uprobe/type";
  8422. return parse_uint_from_file(file, "%d\n");
  8423. }
  8424. static int determine_kprobe_retprobe_bit(void)
  8425. {
  8426. const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
  8427. return parse_uint_from_file(file, "config:%d\n");
  8428. }
  8429. static int determine_uprobe_retprobe_bit(void)
  8430. {
  8431. const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
  8432. return parse_uint_from_file(file, "config:%d\n");
  8433. }
  8434. #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
  8435. #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
  8436. static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
  8437. uint64_t offset, int pid, size_t ref_ctr_off)
  8438. {
  8439. const size_t attr_sz = sizeof(struct perf_event_attr);
  8440. struct perf_event_attr attr;
  8441. char errmsg[STRERR_BUFSIZE];
  8442. int type, pfd;
  8443. if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
  8444. return -EINVAL;
  8445. memset(&attr, 0, attr_sz);
  8446. type = uprobe ? determine_uprobe_perf_type()
  8447. : determine_kprobe_perf_type();
  8448. if (type < 0) {
  8449. pr_warn("failed to determine %s perf type: %s\n",
  8450. uprobe ? "uprobe" : "kprobe",
  8451. libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
  8452. return type;
  8453. }
  8454. if (retprobe) {
  8455. int bit = uprobe ? determine_uprobe_retprobe_bit()
  8456. : determine_kprobe_retprobe_bit();
  8457. if (bit < 0) {
  8458. pr_warn("failed to determine %s retprobe bit: %s\n",
  8459. uprobe ? "uprobe" : "kprobe",
  8460. libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
  8461. return bit;
  8462. }
  8463. attr.config |= 1 << bit;
  8464. }
  8465. attr.size = attr_sz;
  8466. attr.type = type;
  8467. attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
  8468. attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
  8469. attr.config2 = offset; /* kprobe_addr or probe_offset */
  8470. /* pid filter is meaningful only for uprobes */
  8471. pfd = syscall(__NR_perf_event_open, &attr,
  8472. pid < 0 ? -1 : pid /* pid */,
  8473. pid == -1 ? 0 : -1 /* cpu */,
  8474. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  8475. return pfd >= 0 ? pfd : -errno;
  8476. }
  8477. static int append_to_file(const char *file, const char *fmt, ...)
  8478. {
  8479. int fd, n, err = 0;
  8480. va_list ap;
  8481. fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
  8482. if (fd < 0)
  8483. return -errno;
  8484. va_start(ap, fmt);
  8485. n = vdprintf(fd, fmt, ap);
  8486. va_end(ap);
  8487. if (n < 0)
  8488. err = -errno;
  8489. close(fd);
  8490. return err;
  8491. }
  8492. #define DEBUGFS "/sys/kernel/debug/tracing"
  8493. #define TRACEFS "/sys/kernel/tracing"
  8494. static bool use_debugfs(void)
  8495. {
  8496. static int has_debugfs = -1;
  8497. if (has_debugfs < 0)
  8498. has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
  8499. return has_debugfs == 1;
  8500. }
  8501. static const char *tracefs_path(void)
  8502. {
  8503. return use_debugfs() ? DEBUGFS : TRACEFS;
  8504. }
  8505. static const char *tracefs_kprobe_events(void)
  8506. {
  8507. return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
  8508. }
  8509. static const char *tracefs_uprobe_events(void)
  8510. {
  8511. return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
  8512. }
  8513. static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
  8514. const char *kfunc_name, size_t offset)
  8515. {
  8516. static int index = 0;
  8517. snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
  8518. __sync_fetch_and_add(&index, 1));
  8519. }
  8520. static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
  8521. const char *kfunc_name, size_t offset)
  8522. {
  8523. return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
  8524. retprobe ? 'r' : 'p',
  8525. retprobe ? "kretprobes" : "kprobes",
  8526. probe_name, kfunc_name, offset);
  8527. }
  8528. static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
  8529. {
  8530. return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
  8531. retprobe ? "kretprobes" : "kprobes", probe_name);
  8532. }
  8533. static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
  8534. {
  8535. char file[256];
  8536. snprintf(file, sizeof(file), "%s/events/%s/%s/id",
  8537. tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
  8538. return parse_uint_from_file(file, "%d\n");
  8539. }
  8540. static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
  8541. const char *kfunc_name, size_t offset, int pid)
  8542. {
  8543. const size_t attr_sz = sizeof(struct perf_event_attr);
  8544. struct perf_event_attr attr;
  8545. char errmsg[STRERR_BUFSIZE];
  8546. int type, pfd, err;
  8547. err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
  8548. if (err < 0) {
  8549. pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
  8550. kfunc_name, offset,
  8551. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  8552. return err;
  8553. }
  8554. type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
  8555. if (type < 0) {
  8556. err = type;
  8557. pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
  8558. kfunc_name, offset,
  8559. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  8560. goto err_clean_legacy;
  8561. }
  8562. memset(&attr, 0, attr_sz);
  8563. attr.size = attr_sz;
  8564. attr.config = type;
  8565. attr.type = PERF_TYPE_TRACEPOINT;
  8566. pfd = syscall(__NR_perf_event_open, &attr,
  8567. pid < 0 ? -1 : pid, /* pid */
  8568. pid == -1 ? 0 : -1, /* cpu */
  8569. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  8570. if (pfd < 0) {
  8571. err = -errno;
  8572. pr_warn("legacy kprobe perf_event_open() failed: %s\n",
  8573. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  8574. goto err_clean_legacy;
  8575. }
  8576. return pfd;
  8577. err_clean_legacy:
  8578. /* Clear the newly added legacy kprobe_event */
  8579. remove_kprobe_event_legacy(probe_name, retprobe);
  8580. return err;
  8581. }
  8582. static const char *arch_specific_syscall_pfx(void)
  8583. {
  8584. #if defined(__x86_64__)
  8585. return "x64";
  8586. #elif defined(__i386__)
  8587. return "ia32";
  8588. #elif defined(__s390x__)
  8589. return "s390x";
  8590. #elif defined(__s390__)
  8591. return "s390";
  8592. #elif defined(__arm__)
  8593. return "arm";
  8594. #elif defined(__aarch64__)
  8595. return "arm64";
  8596. #elif defined(__mips__)
  8597. return "mips";
  8598. #elif defined(__riscv)
  8599. return "riscv";
  8600. #elif defined(__powerpc__)
  8601. return "powerpc";
  8602. #elif defined(__powerpc64__)
  8603. return "powerpc64";
  8604. #else
  8605. return NULL;
  8606. #endif
  8607. }
  8608. static int probe_kern_syscall_wrapper(void)
  8609. {
  8610. char syscall_name[64];
  8611. const char *ksys_pfx;
  8612. ksys_pfx = arch_specific_syscall_pfx();
  8613. if (!ksys_pfx)
  8614. return 0;
  8615. snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
  8616. if (determine_kprobe_perf_type() >= 0) {
  8617. int pfd;
  8618. pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
  8619. if (pfd >= 0)
  8620. close(pfd);
  8621. return pfd >= 0 ? 1 : 0;
  8622. } else { /* legacy mode */
  8623. char probe_name[128];
  8624. gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
  8625. if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
  8626. return 0;
  8627. (void)remove_kprobe_event_legacy(probe_name, false);
  8628. return 1;
  8629. }
  8630. }
  8631. struct bpf_link *
  8632. bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
  8633. const char *func_name,
  8634. const struct bpf_kprobe_opts *opts)
  8635. {
  8636. DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
  8637. char errmsg[STRERR_BUFSIZE];
  8638. char *legacy_probe = NULL;
  8639. struct bpf_link *link;
  8640. size_t offset;
  8641. bool retprobe, legacy;
  8642. int pfd, err;
  8643. if (!OPTS_VALID(opts, bpf_kprobe_opts))
  8644. return libbpf_err_ptr(-EINVAL);
  8645. retprobe = OPTS_GET(opts, retprobe, false);
  8646. offset = OPTS_GET(opts, offset, 0);
  8647. pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  8648. legacy = determine_kprobe_perf_type() < 0;
  8649. if (!legacy) {
  8650. pfd = perf_event_open_probe(false /* uprobe */, retprobe,
  8651. func_name, offset,
  8652. -1 /* pid */, 0 /* ref_ctr_off */);
  8653. } else {
  8654. char probe_name[256];
  8655. gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
  8656. func_name, offset);
  8657. legacy_probe = strdup(probe_name);
  8658. if (!legacy_probe)
  8659. return libbpf_err_ptr(-ENOMEM);
  8660. pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
  8661. offset, -1 /* pid */);
  8662. }
  8663. if (pfd < 0) {
  8664. err = -errno;
  8665. pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
  8666. prog->name, retprobe ? "kretprobe" : "kprobe",
  8667. func_name, offset,
  8668. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  8669. goto err_out;
  8670. }
  8671. link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
  8672. err = libbpf_get_error(link);
  8673. if (err) {
  8674. close(pfd);
  8675. pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
  8676. prog->name, retprobe ? "kretprobe" : "kprobe",
  8677. func_name, offset,
  8678. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  8679. goto err_clean_legacy;
  8680. }
  8681. if (legacy) {
  8682. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  8683. perf_link->legacy_probe_name = legacy_probe;
  8684. perf_link->legacy_is_kprobe = true;
  8685. perf_link->legacy_is_retprobe = retprobe;
  8686. }
  8687. return link;
  8688. err_clean_legacy:
  8689. if (legacy)
  8690. remove_kprobe_event_legacy(legacy_probe, retprobe);
  8691. err_out:
  8692. free(legacy_probe);
  8693. return libbpf_err_ptr(err);
  8694. }
  8695. struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
  8696. bool retprobe,
  8697. const char *func_name)
  8698. {
  8699. DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
  8700. .retprobe = retprobe,
  8701. );
  8702. return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
  8703. }
  8704. struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
  8705. const char *syscall_name,
  8706. const struct bpf_ksyscall_opts *opts)
  8707. {
  8708. LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
  8709. char func_name[128];
  8710. if (!OPTS_VALID(opts, bpf_ksyscall_opts))
  8711. return libbpf_err_ptr(-EINVAL);
  8712. if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
  8713. /* arch_specific_syscall_pfx() should never return NULL here
  8714. * because it is guarded by kernel_supports(). However, since
  8715. * compiler does not know that we have an explicit conditional
  8716. * as well.
  8717. */
  8718. snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
  8719. arch_specific_syscall_pfx() ? : "", syscall_name);
  8720. } else {
  8721. snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
  8722. }
  8723. kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
  8724. kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  8725. return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
  8726. }
  8727. /* Adapted from perf/util/string.c */
  8728. static bool glob_match(const char *str, const char *pat)
  8729. {
  8730. while (*str && *pat && *pat != '*') {
  8731. if (*pat == '?') { /* Matches any single character */
  8732. str++;
  8733. pat++;
  8734. continue;
  8735. }
  8736. if (*str != *pat)
  8737. return false;
  8738. str++;
  8739. pat++;
  8740. }
  8741. /* Check wild card */
  8742. if (*pat == '*') {
  8743. while (*pat == '*')
  8744. pat++;
  8745. if (!*pat) /* Tail wild card matches all */
  8746. return true;
  8747. while (*str)
  8748. if (glob_match(str++, pat))
  8749. return true;
  8750. }
  8751. return !*str && !*pat;
  8752. }
  8753. struct kprobe_multi_resolve {
  8754. const char *pattern;
  8755. unsigned long *addrs;
  8756. size_t cap;
  8757. size_t cnt;
  8758. };
  8759. static int
  8760. resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
  8761. const char *sym_name, void *ctx)
  8762. {
  8763. struct kprobe_multi_resolve *res = ctx;
  8764. int err;
  8765. if (!glob_match(sym_name, res->pattern))
  8766. return 0;
  8767. err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
  8768. res->cnt + 1);
  8769. if (err)
  8770. return err;
  8771. res->addrs[res->cnt++] = (unsigned long) sym_addr;
  8772. return 0;
  8773. }
  8774. struct bpf_link *
  8775. bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
  8776. const char *pattern,
  8777. const struct bpf_kprobe_multi_opts *opts)
  8778. {
  8779. LIBBPF_OPTS(bpf_link_create_opts, lopts);
  8780. struct kprobe_multi_resolve res = {
  8781. .pattern = pattern,
  8782. };
  8783. struct bpf_link *link = NULL;
  8784. char errmsg[STRERR_BUFSIZE];
  8785. const unsigned long *addrs;
  8786. int err, link_fd, prog_fd;
  8787. const __u64 *cookies;
  8788. const char **syms;
  8789. bool retprobe;
  8790. size_t cnt;
  8791. if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
  8792. return libbpf_err_ptr(-EINVAL);
  8793. syms = OPTS_GET(opts, syms, false);
  8794. addrs = OPTS_GET(opts, addrs, false);
  8795. cnt = OPTS_GET(opts, cnt, false);
  8796. cookies = OPTS_GET(opts, cookies, false);
  8797. if (!pattern && !addrs && !syms)
  8798. return libbpf_err_ptr(-EINVAL);
  8799. if (pattern && (addrs || syms || cookies || cnt))
  8800. return libbpf_err_ptr(-EINVAL);
  8801. if (!pattern && !cnt)
  8802. return libbpf_err_ptr(-EINVAL);
  8803. if (addrs && syms)
  8804. return libbpf_err_ptr(-EINVAL);
  8805. if (pattern) {
  8806. err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
  8807. if (err)
  8808. goto error;
  8809. if (!res.cnt) {
  8810. err = -ENOENT;
  8811. goto error;
  8812. }
  8813. addrs = res.addrs;
  8814. cnt = res.cnt;
  8815. }
  8816. retprobe = OPTS_GET(opts, retprobe, false);
  8817. lopts.kprobe_multi.syms = syms;
  8818. lopts.kprobe_multi.addrs = addrs;
  8819. lopts.kprobe_multi.cookies = cookies;
  8820. lopts.kprobe_multi.cnt = cnt;
  8821. lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
  8822. link = calloc(1, sizeof(*link));
  8823. if (!link) {
  8824. err = -ENOMEM;
  8825. goto error;
  8826. }
  8827. link->detach = &bpf_link__detach_fd;
  8828. prog_fd = bpf_program__fd(prog);
  8829. link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
  8830. if (link_fd < 0) {
  8831. err = -errno;
  8832. pr_warn("prog '%s': failed to attach: %s\n",
  8833. prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  8834. goto error;
  8835. }
  8836. link->fd = link_fd;
  8837. free(res.addrs);
  8838. return link;
  8839. error:
  8840. free(link);
  8841. free(res.addrs);
  8842. return libbpf_err_ptr(err);
  8843. }
  8844. static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  8845. {
  8846. DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
  8847. unsigned long offset = 0;
  8848. const char *func_name;
  8849. char *func;
  8850. int n;
  8851. *link = NULL;
  8852. /* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
  8853. if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
  8854. return 0;
  8855. opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
  8856. if (opts.retprobe)
  8857. func_name = prog->sec_name + sizeof("kretprobe/") - 1;
  8858. else
  8859. func_name = prog->sec_name + sizeof("kprobe/") - 1;
  8860. n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
  8861. if (n < 1) {
  8862. pr_warn("kprobe name is invalid: %s\n", func_name);
  8863. return -EINVAL;
  8864. }
  8865. if (opts.retprobe && offset != 0) {
  8866. free(func);
  8867. pr_warn("kretprobes do not support offset specification\n");
  8868. return -EINVAL;
  8869. }
  8870. opts.offset = offset;
  8871. *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
  8872. free(func);
  8873. return libbpf_get_error(*link);
  8874. }
  8875. static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  8876. {
  8877. LIBBPF_OPTS(bpf_ksyscall_opts, opts);
  8878. const char *syscall_name;
  8879. *link = NULL;
  8880. /* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
  8881. if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
  8882. return 0;
  8883. opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
  8884. if (opts.retprobe)
  8885. syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
  8886. else
  8887. syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
  8888. *link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
  8889. return *link ? 0 : -errno;
  8890. }
  8891. static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  8892. {
  8893. LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
  8894. const char *spec;
  8895. char *pattern;
  8896. int n;
  8897. *link = NULL;
  8898. /* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
  8899. if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
  8900. strcmp(prog->sec_name, "kretprobe.multi") == 0)
  8901. return 0;
  8902. opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
  8903. if (opts.retprobe)
  8904. spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
  8905. else
  8906. spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
  8907. n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
  8908. if (n < 1) {
  8909. pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
  8910. return -EINVAL;
  8911. }
  8912. *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
  8913. free(pattern);
  8914. return libbpf_get_error(*link);
  8915. }
  8916. static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
  8917. const char *binary_path, uint64_t offset)
  8918. {
  8919. int i;
  8920. snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
  8921. /* sanitize binary_path in the probe name */
  8922. for (i = 0; buf[i]; i++) {
  8923. if (!isalnum(buf[i]))
  8924. buf[i] = '_';
  8925. }
  8926. }
  8927. static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
  8928. const char *binary_path, size_t offset)
  8929. {
  8930. return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
  8931. retprobe ? 'r' : 'p',
  8932. retprobe ? "uretprobes" : "uprobes",
  8933. probe_name, binary_path, offset);
  8934. }
  8935. static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
  8936. {
  8937. return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
  8938. retprobe ? "uretprobes" : "uprobes", probe_name);
  8939. }
  8940. static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
  8941. {
  8942. char file[512];
  8943. snprintf(file, sizeof(file), "%s/events/%s/%s/id",
  8944. tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
  8945. return parse_uint_from_file(file, "%d\n");
  8946. }
  8947. static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
  8948. const char *binary_path, size_t offset, int pid)
  8949. {
  8950. const size_t attr_sz = sizeof(struct perf_event_attr);
  8951. struct perf_event_attr attr;
  8952. int type, pfd, err;
  8953. err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
  8954. if (err < 0) {
  8955. pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
  8956. binary_path, (size_t)offset, err);
  8957. return err;
  8958. }
  8959. type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
  8960. if (type < 0) {
  8961. err = type;
  8962. pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
  8963. binary_path, offset, err);
  8964. goto err_clean_legacy;
  8965. }
  8966. memset(&attr, 0, attr_sz);
  8967. attr.size = attr_sz;
  8968. attr.config = type;
  8969. attr.type = PERF_TYPE_TRACEPOINT;
  8970. pfd = syscall(__NR_perf_event_open, &attr,
  8971. pid < 0 ? -1 : pid, /* pid */
  8972. pid == -1 ? 0 : -1, /* cpu */
  8973. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  8974. if (pfd < 0) {
  8975. err = -errno;
  8976. pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
  8977. goto err_clean_legacy;
  8978. }
  8979. return pfd;
  8980. err_clean_legacy:
  8981. /* Clear the newly added legacy uprobe_event */
  8982. remove_uprobe_event_legacy(probe_name, retprobe);
  8983. return err;
  8984. }
  8985. /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
  8986. static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
  8987. {
  8988. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  8989. GElf_Shdr sh;
  8990. if (!gelf_getshdr(scn, &sh))
  8991. continue;
  8992. if (sh.sh_type == sh_type)
  8993. return scn;
  8994. }
  8995. return NULL;
  8996. }
  8997. /* Find offset of function name in object specified by path. "name" matches
  8998. * symbol name or name@@LIB for library functions.
  8999. */
  9000. static long elf_find_func_offset(const char *binary_path, const char *name)
  9001. {
  9002. int fd, i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
  9003. bool is_shared_lib, is_name_qualified;
  9004. char errmsg[STRERR_BUFSIZE];
  9005. long ret = -ENOENT;
  9006. size_t name_len;
  9007. GElf_Ehdr ehdr;
  9008. Elf *elf;
  9009. fd = open(binary_path, O_RDONLY | O_CLOEXEC);
  9010. if (fd < 0) {
  9011. ret = -errno;
  9012. pr_warn("failed to open %s: %s\n", binary_path,
  9013. libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
  9014. return ret;
  9015. }
  9016. elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
  9017. if (!elf) {
  9018. pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
  9019. close(fd);
  9020. return -LIBBPF_ERRNO__FORMAT;
  9021. }
  9022. if (!gelf_getehdr(elf, &ehdr)) {
  9023. pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
  9024. ret = -LIBBPF_ERRNO__FORMAT;
  9025. goto out;
  9026. }
  9027. /* for shared lib case, we do not need to calculate relative offset */
  9028. is_shared_lib = ehdr.e_type == ET_DYN;
  9029. name_len = strlen(name);
  9030. /* Does name specify "@@LIB"? */
  9031. is_name_qualified = strstr(name, "@@") != NULL;
  9032. /* Search SHT_DYNSYM, SHT_SYMTAB for symbol. This search order is used because if
  9033. * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
  9034. * linked binary may not have SHT_DYMSYM, so absence of a section should not be
  9035. * reported as a warning/error.
  9036. */
  9037. for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
  9038. size_t nr_syms, strtabidx, idx;
  9039. Elf_Data *symbols = NULL;
  9040. Elf_Scn *scn = NULL;
  9041. int last_bind = -1;
  9042. const char *sname;
  9043. GElf_Shdr sh;
  9044. scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
  9045. if (!scn) {
  9046. pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
  9047. binary_path);
  9048. continue;
  9049. }
  9050. if (!gelf_getshdr(scn, &sh))
  9051. continue;
  9052. strtabidx = sh.sh_link;
  9053. symbols = elf_getdata(scn, 0);
  9054. if (!symbols) {
  9055. pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
  9056. binary_path, elf_errmsg(-1));
  9057. ret = -LIBBPF_ERRNO__FORMAT;
  9058. goto out;
  9059. }
  9060. nr_syms = symbols->d_size / sh.sh_entsize;
  9061. for (idx = 0; idx < nr_syms; idx++) {
  9062. int curr_bind;
  9063. GElf_Sym sym;
  9064. Elf_Scn *sym_scn;
  9065. GElf_Shdr sym_sh;
  9066. if (!gelf_getsym(symbols, idx, &sym))
  9067. continue;
  9068. if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
  9069. continue;
  9070. sname = elf_strptr(elf, strtabidx, sym.st_name);
  9071. if (!sname)
  9072. continue;
  9073. curr_bind = GELF_ST_BIND(sym.st_info);
  9074. /* User can specify func, func@@LIB or func@@LIB_VERSION. */
  9075. if (strncmp(sname, name, name_len) != 0)
  9076. continue;
  9077. /* ...but we don't want a search for "foo" to match 'foo2" also, so any
  9078. * additional characters in sname should be of the form "@@LIB".
  9079. */
  9080. if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
  9081. continue;
  9082. if (ret >= 0) {
  9083. /* handle multiple matches */
  9084. if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
  9085. /* Only accept one non-weak bind. */
  9086. pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
  9087. sname, name, binary_path);
  9088. ret = -LIBBPF_ERRNO__FORMAT;
  9089. goto out;
  9090. } else if (curr_bind == STB_WEAK) {
  9091. /* already have a non-weak bind, and
  9092. * this is a weak bind, so ignore.
  9093. */
  9094. continue;
  9095. }
  9096. }
  9097. /* Transform symbol's virtual address (absolute for
  9098. * binaries and relative for shared libs) into file
  9099. * offset, which is what kernel is expecting for
  9100. * uprobe/uretprobe attachment.
  9101. * See Documentation/trace/uprobetracer.rst for more
  9102. * details.
  9103. * This is done by looking up symbol's containing
  9104. * section's header and using it's virtual address
  9105. * (sh_addr) and corresponding file offset (sh_offset)
  9106. * to transform sym.st_value (virtual address) into
  9107. * desired final file offset.
  9108. */
  9109. sym_scn = elf_getscn(elf, sym.st_shndx);
  9110. if (!sym_scn)
  9111. continue;
  9112. if (!gelf_getshdr(sym_scn, &sym_sh))
  9113. continue;
  9114. ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
  9115. last_bind = curr_bind;
  9116. }
  9117. if (ret > 0)
  9118. break;
  9119. }
  9120. if (ret > 0) {
  9121. pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
  9122. ret);
  9123. } else {
  9124. if (ret == 0) {
  9125. pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
  9126. is_shared_lib ? "should not be 0 in a shared library" :
  9127. "try using shared library path instead");
  9128. ret = -ENOENT;
  9129. } else {
  9130. pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
  9131. }
  9132. }
  9133. out:
  9134. elf_end(elf);
  9135. close(fd);
  9136. return ret;
  9137. }
  9138. static const char *arch_specific_lib_paths(void)
  9139. {
  9140. /*
  9141. * Based on https://packages.debian.org/sid/libc6.
  9142. *
  9143. * Assume that the traced program is built for the same architecture
  9144. * as libbpf, which should cover the vast majority of cases.
  9145. */
  9146. #if defined(__x86_64__)
  9147. return "/lib/x86_64-linux-gnu";
  9148. #elif defined(__i386__)
  9149. return "/lib/i386-linux-gnu";
  9150. #elif defined(__s390x__)
  9151. return "/lib/s390x-linux-gnu";
  9152. #elif defined(__s390__)
  9153. return "/lib/s390-linux-gnu";
  9154. #elif defined(__arm__) && defined(__SOFTFP__)
  9155. return "/lib/arm-linux-gnueabi";
  9156. #elif defined(__arm__) && !defined(__SOFTFP__)
  9157. return "/lib/arm-linux-gnueabihf";
  9158. #elif defined(__aarch64__)
  9159. return "/lib/aarch64-linux-gnu";
  9160. #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
  9161. return "/lib/mips64el-linux-gnuabi64";
  9162. #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
  9163. return "/lib/mipsel-linux-gnu";
  9164. #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  9165. return "/lib/powerpc64le-linux-gnu";
  9166. #elif defined(__sparc__) && defined(__arch64__)
  9167. return "/lib/sparc64-linux-gnu";
  9168. #elif defined(__riscv) && __riscv_xlen == 64
  9169. return "/lib/riscv64-linux-gnu";
  9170. #else
  9171. return NULL;
  9172. #endif
  9173. }
  9174. /* Get full path to program/shared library. */
  9175. static int resolve_full_path(const char *file, char *result, size_t result_sz)
  9176. {
  9177. const char *search_paths[3] = {};
  9178. int i, perm;
  9179. if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
  9180. search_paths[0] = getenv("LD_LIBRARY_PATH");
  9181. search_paths[1] = "/usr/lib64:/usr/lib";
  9182. search_paths[2] = arch_specific_lib_paths();
  9183. perm = R_OK;
  9184. } else {
  9185. search_paths[0] = getenv("PATH");
  9186. search_paths[1] = "/usr/bin:/usr/sbin";
  9187. perm = R_OK | X_OK;
  9188. }
  9189. for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
  9190. const char *s;
  9191. if (!search_paths[i])
  9192. continue;
  9193. for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
  9194. char *next_path;
  9195. int seg_len;
  9196. if (s[0] == ':')
  9197. s++;
  9198. next_path = strchr(s, ':');
  9199. seg_len = next_path ? next_path - s : strlen(s);
  9200. if (!seg_len)
  9201. continue;
  9202. snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
  9203. /* ensure it has required permissions */
  9204. if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
  9205. continue;
  9206. pr_debug("resolved '%s' to '%s'\n", file, result);
  9207. return 0;
  9208. }
  9209. }
  9210. return -ENOENT;
  9211. }
  9212. LIBBPF_API struct bpf_link *
  9213. bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
  9214. const char *binary_path, size_t func_offset,
  9215. const struct bpf_uprobe_opts *opts)
  9216. {
  9217. DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
  9218. char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
  9219. char full_binary_path[PATH_MAX];
  9220. struct bpf_link *link;
  9221. size_t ref_ctr_off;
  9222. int pfd, err;
  9223. bool retprobe, legacy;
  9224. const char *func_name;
  9225. if (!OPTS_VALID(opts, bpf_uprobe_opts))
  9226. return libbpf_err_ptr(-EINVAL);
  9227. retprobe = OPTS_GET(opts, retprobe, false);
  9228. ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
  9229. pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  9230. if (!binary_path)
  9231. return libbpf_err_ptr(-EINVAL);
  9232. if (!strchr(binary_path, '/')) {
  9233. err = resolve_full_path(binary_path, full_binary_path,
  9234. sizeof(full_binary_path));
  9235. if (err) {
  9236. pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
  9237. prog->name, binary_path, err);
  9238. return libbpf_err_ptr(err);
  9239. }
  9240. binary_path = full_binary_path;
  9241. }
  9242. func_name = OPTS_GET(opts, func_name, NULL);
  9243. if (func_name) {
  9244. long sym_off;
  9245. sym_off = elf_find_func_offset(binary_path, func_name);
  9246. if (sym_off < 0)
  9247. return libbpf_err_ptr(sym_off);
  9248. func_offset += sym_off;
  9249. }
  9250. legacy = determine_uprobe_perf_type() < 0;
  9251. if (!legacy) {
  9252. pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
  9253. func_offset, pid, ref_ctr_off);
  9254. } else {
  9255. char probe_name[PATH_MAX + 64];
  9256. if (ref_ctr_off)
  9257. return libbpf_err_ptr(-EINVAL);
  9258. gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
  9259. binary_path, func_offset);
  9260. legacy_probe = strdup(probe_name);
  9261. if (!legacy_probe)
  9262. return libbpf_err_ptr(-ENOMEM);
  9263. pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
  9264. binary_path, func_offset, pid);
  9265. }
  9266. if (pfd < 0) {
  9267. err = -errno;
  9268. pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
  9269. prog->name, retprobe ? "uretprobe" : "uprobe",
  9270. binary_path, func_offset,
  9271. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9272. goto err_out;
  9273. }
  9274. link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
  9275. err = libbpf_get_error(link);
  9276. if (err) {
  9277. close(pfd);
  9278. pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
  9279. prog->name, retprobe ? "uretprobe" : "uprobe",
  9280. binary_path, func_offset,
  9281. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9282. goto err_clean_legacy;
  9283. }
  9284. if (legacy) {
  9285. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  9286. perf_link->legacy_probe_name = legacy_probe;
  9287. perf_link->legacy_is_kprobe = false;
  9288. perf_link->legacy_is_retprobe = retprobe;
  9289. }
  9290. return link;
  9291. err_clean_legacy:
  9292. if (legacy)
  9293. remove_uprobe_event_legacy(legacy_probe, retprobe);
  9294. err_out:
  9295. free(legacy_probe);
  9296. return libbpf_err_ptr(err);
  9297. }
  9298. /* Format of u[ret]probe section definition supporting auto-attach:
  9299. * u[ret]probe/binary:function[+offset]
  9300. *
  9301. * binary can be an absolute/relative path or a filename; the latter is resolved to a
  9302. * full binary path via bpf_program__attach_uprobe_opts.
  9303. *
  9304. * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
  9305. * specified (and auto-attach is not possible) or the above format is specified for
  9306. * auto-attach.
  9307. */
  9308. static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  9309. {
  9310. DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
  9311. char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
  9312. int n, ret = -EINVAL;
  9313. long offset = 0;
  9314. *link = NULL;
  9315. n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
  9316. &probe_type, &binary_path, &func_name, &offset);
  9317. switch (n) {
  9318. case 1:
  9319. /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
  9320. ret = 0;
  9321. break;
  9322. case 2:
  9323. pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
  9324. prog->name, prog->sec_name);
  9325. break;
  9326. case 3:
  9327. case 4:
  9328. opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
  9329. strcmp(probe_type, "uretprobe.s") == 0;
  9330. if (opts.retprobe && offset != 0) {
  9331. pr_warn("prog '%s': uretprobes do not support offset specification\n",
  9332. prog->name);
  9333. break;
  9334. }
  9335. opts.func_name = func_name;
  9336. *link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
  9337. ret = libbpf_get_error(*link);
  9338. break;
  9339. default:
  9340. pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
  9341. prog->sec_name);
  9342. break;
  9343. }
  9344. free(probe_type);
  9345. free(binary_path);
  9346. free(func_name);
  9347. return ret;
  9348. }
  9349. struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
  9350. bool retprobe, pid_t pid,
  9351. const char *binary_path,
  9352. size_t func_offset)
  9353. {
  9354. DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
  9355. return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
  9356. }
  9357. struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
  9358. pid_t pid, const char *binary_path,
  9359. const char *usdt_provider, const char *usdt_name,
  9360. const struct bpf_usdt_opts *opts)
  9361. {
  9362. char resolved_path[512];
  9363. struct bpf_object *obj = prog->obj;
  9364. struct bpf_link *link;
  9365. __u64 usdt_cookie;
  9366. int err;
  9367. if (!OPTS_VALID(opts, bpf_uprobe_opts))
  9368. return libbpf_err_ptr(-EINVAL);
  9369. if (bpf_program__fd(prog) < 0) {
  9370. pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
  9371. prog->name);
  9372. return libbpf_err_ptr(-EINVAL);
  9373. }
  9374. if (!binary_path)
  9375. return libbpf_err_ptr(-EINVAL);
  9376. if (!strchr(binary_path, '/')) {
  9377. err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
  9378. if (err) {
  9379. pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
  9380. prog->name, binary_path, err);
  9381. return libbpf_err_ptr(err);
  9382. }
  9383. binary_path = resolved_path;
  9384. }
  9385. /* USDT manager is instantiated lazily on first USDT attach. It will
  9386. * be destroyed together with BPF object in bpf_object__close().
  9387. */
  9388. if (IS_ERR(obj->usdt_man))
  9389. return libbpf_ptr(obj->usdt_man);
  9390. if (!obj->usdt_man) {
  9391. obj->usdt_man = usdt_manager_new(obj);
  9392. if (IS_ERR(obj->usdt_man))
  9393. return libbpf_ptr(obj->usdt_man);
  9394. }
  9395. usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
  9396. link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
  9397. usdt_provider, usdt_name, usdt_cookie);
  9398. err = libbpf_get_error(link);
  9399. if (err)
  9400. return libbpf_err_ptr(err);
  9401. return link;
  9402. }
  9403. static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  9404. {
  9405. char *path = NULL, *provider = NULL, *name = NULL;
  9406. const char *sec_name;
  9407. int n, err;
  9408. sec_name = bpf_program__section_name(prog);
  9409. if (strcmp(sec_name, "usdt") == 0) {
  9410. /* no auto-attach for just SEC("usdt") */
  9411. *link = NULL;
  9412. return 0;
  9413. }
  9414. n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
  9415. if (n != 3) {
  9416. pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
  9417. sec_name);
  9418. err = -EINVAL;
  9419. } else {
  9420. *link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
  9421. provider, name, NULL);
  9422. err = libbpf_get_error(*link);
  9423. }
  9424. free(path);
  9425. free(provider);
  9426. free(name);
  9427. return err;
  9428. }
  9429. static int determine_tracepoint_id(const char *tp_category,
  9430. const char *tp_name)
  9431. {
  9432. char file[PATH_MAX];
  9433. int ret;
  9434. ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
  9435. tracefs_path(), tp_category, tp_name);
  9436. if (ret < 0)
  9437. return -errno;
  9438. if (ret >= sizeof(file)) {
  9439. pr_debug("tracepoint %s/%s path is too long\n",
  9440. tp_category, tp_name);
  9441. return -E2BIG;
  9442. }
  9443. return parse_uint_from_file(file, "%d\n");
  9444. }
  9445. static int perf_event_open_tracepoint(const char *tp_category,
  9446. const char *tp_name)
  9447. {
  9448. const size_t attr_sz = sizeof(struct perf_event_attr);
  9449. struct perf_event_attr attr;
  9450. char errmsg[STRERR_BUFSIZE];
  9451. int tp_id, pfd, err;
  9452. tp_id = determine_tracepoint_id(tp_category, tp_name);
  9453. if (tp_id < 0) {
  9454. pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
  9455. tp_category, tp_name,
  9456. libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
  9457. return tp_id;
  9458. }
  9459. memset(&attr, 0, attr_sz);
  9460. attr.type = PERF_TYPE_TRACEPOINT;
  9461. attr.size = attr_sz;
  9462. attr.config = tp_id;
  9463. pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
  9464. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  9465. if (pfd < 0) {
  9466. err = -errno;
  9467. pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
  9468. tp_category, tp_name,
  9469. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9470. return err;
  9471. }
  9472. return pfd;
  9473. }
  9474. struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
  9475. const char *tp_category,
  9476. const char *tp_name,
  9477. const struct bpf_tracepoint_opts *opts)
  9478. {
  9479. DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
  9480. char errmsg[STRERR_BUFSIZE];
  9481. struct bpf_link *link;
  9482. int pfd, err;
  9483. if (!OPTS_VALID(opts, bpf_tracepoint_opts))
  9484. return libbpf_err_ptr(-EINVAL);
  9485. pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  9486. pfd = perf_event_open_tracepoint(tp_category, tp_name);
  9487. if (pfd < 0) {
  9488. pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
  9489. prog->name, tp_category, tp_name,
  9490. libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
  9491. return libbpf_err_ptr(pfd);
  9492. }
  9493. link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
  9494. err = libbpf_get_error(link);
  9495. if (err) {
  9496. close(pfd);
  9497. pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
  9498. prog->name, tp_category, tp_name,
  9499. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9500. return libbpf_err_ptr(err);
  9501. }
  9502. return link;
  9503. }
  9504. struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
  9505. const char *tp_category,
  9506. const char *tp_name)
  9507. {
  9508. return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
  9509. }
  9510. static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  9511. {
  9512. char *sec_name, *tp_cat, *tp_name;
  9513. *link = NULL;
  9514. /* no auto-attach for SEC("tp") or SEC("tracepoint") */
  9515. if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
  9516. return 0;
  9517. sec_name = strdup(prog->sec_name);
  9518. if (!sec_name)
  9519. return -ENOMEM;
  9520. /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
  9521. if (str_has_pfx(prog->sec_name, "tp/"))
  9522. tp_cat = sec_name + sizeof("tp/") - 1;
  9523. else
  9524. tp_cat = sec_name + sizeof("tracepoint/") - 1;
  9525. tp_name = strchr(tp_cat, '/');
  9526. if (!tp_name) {
  9527. free(sec_name);
  9528. return -EINVAL;
  9529. }
  9530. *tp_name = '\0';
  9531. tp_name++;
  9532. *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
  9533. free(sec_name);
  9534. return libbpf_get_error(*link);
  9535. }
  9536. struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
  9537. const char *tp_name)
  9538. {
  9539. char errmsg[STRERR_BUFSIZE];
  9540. struct bpf_link *link;
  9541. int prog_fd, pfd;
  9542. prog_fd = bpf_program__fd(prog);
  9543. if (prog_fd < 0) {
  9544. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  9545. return libbpf_err_ptr(-EINVAL);
  9546. }
  9547. link = calloc(1, sizeof(*link));
  9548. if (!link)
  9549. return libbpf_err_ptr(-ENOMEM);
  9550. link->detach = &bpf_link__detach_fd;
  9551. pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
  9552. if (pfd < 0) {
  9553. pfd = -errno;
  9554. free(link);
  9555. pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
  9556. prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
  9557. return libbpf_err_ptr(pfd);
  9558. }
  9559. link->fd = pfd;
  9560. return link;
  9561. }
  9562. static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  9563. {
  9564. static const char *const prefixes[] = {
  9565. "raw_tp",
  9566. "raw_tracepoint",
  9567. "raw_tp.w",
  9568. "raw_tracepoint.w",
  9569. };
  9570. size_t i;
  9571. const char *tp_name = NULL;
  9572. *link = NULL;
  9573. for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
  9574. size_t pfx_len;
  9575. if (!str_has_pfx(prog->sec_name, prefixes[i]))
  9576. continue;
  9577. pfx_len = strlen(prefixes[i]);
  9578. /* no auto-attach case of, e.g., SEC("raw_tp") */
  9579. if (prog->sec_name[pfx_len] == '\0')
  9580. return 0;
  9581. if (prog->sec_name[pfx_len] != '/')
  9582. continue;
  9583. tp_name = prog->sec_name + pfx_len + 1;
  9584. break;
  9585. }
  9586. if (!tp_name) {
  9587. pr_warn("prog '%s': invalid section name '%s'\n",
  9588. prog->name, prog->sec_name);
  9589. return -EINVAL;
  9590. }
  9591. *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
  9592. return libbpf_get_error(*link);
  9593. }
  9594. /* Common logic for all BPF program types that attach to a btf_id */
  9595. static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
  9596. const struct bpf_trace_opts *opts)
  9597. {
  9598. LIBBPF_OPTS(bpf_link_create_opts, link_opts);
  9599. char errmsg[STRERR_BUFSIZE];
  9600. struct bpf_link *link;
  9601. int prog_fd, pfd;
  9602. if (!OPTS_VALID(opts, bpf_trace_opts))
  9603. return libbpf_err_ptr(-EINVAL);
  9604. prog_fd = bpf_program__fd(prog);
  9605. if (prog_fd < 0) {
  9606. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  9607. return libbpf_err_ptr(-EINVAL);
  9608. }
  9609. link = calloc(1, sizeof(*link));
  9610. if (!link)
  9611. return libbpf_err_ptr(-ENOMEM);
  9612. link->detach = &bpf_link__detach_fd;
  9613. /* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
  9614. link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
  9615. pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
  9616. if (pfd < 0) {
  9617. pfd = -errno;
  9618. free(link);
  9619. pr_warn("prog '%s': failed to attach: %s\n",
  9620. prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
  9621. return libbpf_err_ptr(pfd);
  9622. }
  9623. link->fd = pfd;
  9624. return link;
  9625. }
  9626. struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
  9627. {
  9628. return bpf_program__attach_btf_id(prog, NULL);
  9629. }
  9630. struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
  9631. const struct bpf_trace_opts *opts)
  9632. {
  9633. return bpf_program__attach_btf_id(prog, opts);
  9634. }
  9635. struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
  9636. {
  9637. return bpf_program__attach_btf_id(prog, NULL);
  9638. }
  9639. static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  9640. {
  9641. *link = bpf_program__attach_trace(prog);
  9642. return libbpf_get_error(*link);
  9643. }
  9644. static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  9645. {
  9646. *link = bpf_program__attach_lsm(prog);
  9647. return libbpf_get_error(*link);
  9648. }
  9649. static struct bpf_link *
  9650. bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
  9651. const char *target_name)
  9652. {
  9653. DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
  9654. .target_btf_id = btf_id);
  9655. enum bpf_attach_type attach_type;
  9656. char errmsg[STRERR_BUFSIZE];
  9657. struct bpf_link *link;
  9658. int prog_fd, link_fd;
  9659. prog_fd = bpf_program__fd(prog);
  9660. if (prog_fd < 0) {
  9661. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  9662. return libbpf_err_ptr(-EINVAL);
  9663. }
  9664. link = calloc(1, sizeof(*link));
  9665. if (!link)
  9666. return libbpf_err_ptr(-ENOMEM);
  9667. link->detach = &bpf_link__detach_fd;
  9668. attach_type = bpf_program__expected_attach_type(prog);
  9669. link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
  9670. if (link_fd < 0) {
  9671. link_fd = -errno;
  9672. free(link);
  9673. pr_warn("prog '%s': failed to attach to %s: %s\n",
  9674. prog->name, target_name,
  9675. libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
  9676. return libbpf_err_ptr(link_fd);
  9677. }
  9678. link->fd = link_fd;
  9679. return link;
  9680. }
  9681. struct bpf_link *
  9682. bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
  9683. {
  9684. return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
  9685. }
  9686. struct bpf_link *
  9687. bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
  9688. {
  9689. return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
  9690. }
  9691. struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
  9692. {
  9693. /* target_fd/target_ifindex use the same field in LINK_CREATE */
  9694. return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
  9695. }
  9696. struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
  9697. int target_fd,
  9698. const char *attach_func_name)
  9699. {
  9700. int btf_id;
  9701. if (!!target_fd != !!attach_func_name) {
  9702. pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
  9703. prog->name);
  9704. return libbpf_err_ptr(-EINVAL);
  9705. }
  9706. if (prog->type != BPF_PROG_TYPE_EXT) {
  9707. pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
  9708. prog->name);
  9709. return libbpf_err_ptr(-EINVAL);
  9710. }
  9711. if (target_fd) {
  9712. btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
  9713. if (btf_id < 0)
  9714. return libbpf_err_ptr(btf_id);
  9715. return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
  9716. } else {
  9717. /* no target, so use raw_tracepoint_open for compatibility
  9718. * with old kernels
  9719. */
  9720. return bpf_program__attach_trace(prog);
  9721. }
  9722. }
  9723. struct bpf_link *
  9724. bpf_program__attach_iter(const struct bpf_program *prog,
  9725. const struct bpf_iter_attach_opts *opts)
  9726. {
  9727. DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
  9728. char errmsg[STRERR_BUFSIZE];
  9729. struct bpf_link *link;
  9730. int prog_fd, link_fd;
  9731. __u32 target_fd = 0;
  9732. if (!OPTS_VALID(opts, bpf_iter_attach_opts))
  9733. return libbpf_err_ptr(-EINVAL);
  9734. link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
  9735. link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
  9736. prog_fd = bpf_program__fd(prog);
  9737. if (prog_fd < 0) {
  9738. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  9739. return libbpf_err_ptr(-EINVAL);
  9740. }
  9741. link = calloc(1, sizeof(*link));
  9742. if (!link)
  9743. return libbpf_err_ptr(-ENOMEM);
  9744. link->detach = &bpf_link__detach_fd;
  9745. link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
  9746. &link_create_opts);
  9747. if (link_fd < 0) {
  9748. link_fd = -errno;
  9749. free(link);
  9750. pr_warn("prog '%s': failed to attach to iterator: %s\n",
  9751. prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
  9752. return libbpf_err_ptr(link_fd);
  9753. }
  9754. link->fd = link_fd;
  9755. return link;
  9756. }
  9757. static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  9758. {
  9759. *link = bpf_program__attach_iter(prog, NULL);
  9760. return libbpf_get_error(*link);
  9761. }
  9762. struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
  9763. {
  9764. struct bpf_link *link = NULL;
  9765. int err;
  9766. if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
  9767. return libbpf_err_ptr(-EOPNOTSUPP);
  9768. err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
  9769. if (err)
  9770. return libbpf_err_ptr(err);
  9771. /* When calling bpf_program__attach() explicitly, auto-attach support
  9772. * is expected to work, so NULL returned link is considered an error.
  9773. * This is different for skeleton's attach, see comment in
  9774. * bpf_object__attach_skeleton().
  9775. */
  9776. if (!link)
  9777. return libbpf_err_ptr(-EOPNOTSUPP);
  9778. return link;
  9779. }
  9780. static int bpf_link__detach_struct_ops(struct bpf_link *link)
  9781. {
  9782. __u32 zero = 0;
  9783. if (bpf_map_delete_elem(link->fd, &zero))
  9784. return -errno;
  9785. return 0;
  9786. }
  9787. struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
  9788. {
  9789. struct bpf_struct_ops *st_ops;
  9790. struct bpf_link *link;
  9791. __u32 i, zero = 0;
  9792. int err;
  9793. if (!bpf_map__is_struct_ops(map) || map->fd == -1)
  9794. return libbpf_err_ptr(-EINVAL);
  9795. link = calloc(1, sizeof(*link));
  9796. if (!link)
  9797. return libbpf_err_ptr(-EINVAL);
  9798. st_ops = map->st_ops;
  9799. for (i = 0; i < btf_vlen(st_ops->type); i++) {
  9800. struct bpf_program *prog = st_ops->progs[i];
  9801. void *kern_data;
  9802. int prog_fd;
  9803. if (!prog)
  9804. continue;
  9805. prog_fd = bpf_program__fd(prog);
  9806. kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
  9807. *(unsigned long *)kern_data = prog_fd;
  9808. }
  9809. err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
  9810. if (err) {
  9811. err = -errno;
  9812. free(link);
  9813. return libbpf_err_ptr(err);
  9814. }
  9815. link->detach = bpf_link__detach_struct_ops;
  9816. link->fd = map->fd;
  9817. return link;
  9818. }
  9819. typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
  9820. void *private_data);
  9821. static enum bpf_perf_event_ret
  9822. perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
  9823. void **copy_mem, size_t *copy_size,
  9824. bpf_perf_event_print_t fn, void *private_data)
  9825. {
  9826. struct perf_event_mmap_page *header = mmap_mem;
  9827. __u64 data_head = ring_buffer_read_head(header);
  9828. __u64 data_tail = header->data_tail;
  9829. void *base = ((__u8 *)header) + page_size;
  9830. int ret = LIBBPF_PERF_EVENT_CONT;
  9831. struct perf_event_header *ehdr;
  9832. size_t ehdr_size;
  9833. while (data_head != data_tail) {
  9834. ehdr = base + (data_tail & (mmap_size - 1));
  9835. ehdr_size = ehdr->size;
  9836. if (((void *)ehdr) + ehdr_size > base + mmap_size) {
  9837. void *copy_start = ehdr;
  9838. size_t len_first = base + mmap_size - copy_start;
  9839. size_t len_secnd = ehdr_size - len_first;
  9840. if (*copy_size < ehdr_size) {
  9841. free(*copy_mem);
  9842. *copy_mem = malloc(ehdr_size);
  9843. if (!*copy_mem) {
  9844. *copy_size = 0;
  9845. ret = LIBBPF_PERF_EVENT_ERROR;
  9846. break;
  9847. }
  9848. *copy_size = ehdr_size;
  9849. }
  9850. memcpy(*copy_mem, copy_start, len_first);
  9851. memcpy(*copy_mem + len_first, base, len_secnd);
  9852. ehdr = *copy_mem;
  9853. }
  9854. ret = fn(ehdr, private_data);
  9855. data_tail += ehdr_size;
  9856. if (ret != LIBBPF_PERF_EVENT_CONT)
  9857. break;
  9858. }
  9859. ring_buffer_write_tail(header, data_tail);
  9860. return libbpf_err(ret);
  9861. }
  9862. struct perf_buffer;
  9863. struct perf_buffer_params {
  9864. struct perf_event_attr *attr;
  9865. /* if event_cb is specified, it takes precendence */
  9866. perf_buffer_event_fn event_cb;
  9867. /* sample_cb and lost_cb are higher-level common-case callbacks */
  9868. perf_buffer_sample_fn sample_cb;
  9869. perf_buffer_lost_fn lost_cb;
  9870. void *ctx;
  9871. int cpu_cnt;
  9872. int *cpus;
  9873. int *map_keys;
  9874. };
  9875. struct perf_cpu_buf {
  9876. struct perf_buffer *pb;
  9877. void *base; /* mmap()'ed memory */
  9878. void *buf; /* for reconstructing segmented data */
  9879. size_t buf_size;
  9880. int fd;
  9881. int cpu;
  9882. int map_key;
  9883. };
  9884. struct perf_buffer {
  9885. perf_buffer_event_fn event_cb;
  9886. perf_buffer_sample_fn sample_cb;
  9887. perf_buffer_lost_fn lost_cb;
  9888. void *ctx; /* passed into callbacks */
  9889. size_t page_size;
  9890. size_t mmap_size;
  9891. struct perf_cpu_buf **cpu_bufs;
  9892. struct epoll_event *events;
  9893. int cpu_cnt; /* number of allocated CPU buffers */
  9894. int epoll_fd; /* perf event FD */
  9895. int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
  9896. };
  9897. static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
  9898. struct perf_cpu_buf *cpu_buf)
  9899. {
  9900. if (!cpu_buf)
  9901. return;
  9902. if (cpu_buf->base &&
  9903. munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
  9904. pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
  9905. if (cpu_buf->fd >= 0) {
  9906. ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
  9907. close(cpu_buf->fd);
  9908. }
  9909. free(cpu_buf->buf);
  9910. free(cpu_buf);
  9911. }
  9912. void perf_buffer__free(struct perf_buffer *pb)
  9913. {
  9914. int i;
  9915. if (IS_ERR_OR_NULL(pb))
  9916. return;
  9917. if (pb->cpu_bufs) {
  9918. for (i = 0; i < pb->cpu_cnt; i++) {
  9919. struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
  9920. if (!cpu_buf)
  9921. continue;
  9922. bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
  9923. perf_buffer__free_cpu_buf(pb, cpu_buf);
  9924. }
  9925. free(pb->cpu_bufs);
  9926. }
  9927. if (pb->epoll_fd >= 0)
  9928. close(pb->epoll_fd);
  9929. free(pb->events);
  9930. free(pb);
  9931. }
  9932. static struct perf_cpu_buf *
  9933. perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
  9934. int cpu, int map_key)
  9935. {
  9936. struct perf_cpu_buf *cpu_buf;
  9937. char msg[STRERR_BUFSIZE];
  9938. int err;
  9939. cpu_buf = calloc(1, sizeof(*cpu_buf));
  9940. if (!cpu_buf)
  9941. return ERR_PTR(-ENOMEM);
  9942. cpu_buf->pb = pb;
  9943. cpu_buf->cpu = cpu;
  9944. cpu_buf->map_key = map_key;
  9945. cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
  9946. -1, PERF_FLAG_FD_CLOEXEC);
  9947. if (cpu_buf->fd < 0) {
  9948. err = -errno;
  9949. pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
  9950. cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
  9951. goto error;
  9952. }
  9953. cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
  9954. PROT_READ | PROT_WRITE, MAP_SHARED,
  9955. cpu_buf->fd, 0);
  9956. if (cpu_buf->base == MAP_FAILED) {
  9957. cpu_buf->base = NULL;
  9958. err = -errno;
  9959. pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
  9960. cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
  9961. goto error;
  9962. }
  9963. if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
  9964. err = -errno;
  9965. pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
  9966. cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
  9967. goto error;
  9968. }
  9969. return cpu_buf;
  9970. error:
  9971. perf_buffer__free_cpu_buf(pb, cpu_buf);
  9972. return (struct perf_cpu_buf *)ERR_PTR(err);
  9973. }
  9974. static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
  9975. struct perf_buffer_params *p);
  9976. struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
  9977. perf_buffer_sample_fn sample_cb,
  9978. perf_buffer_lost_fn lost_cb,
  9979. void *ctx,
  9980. const struct perf_buffer_opts *opts)
  9981. {
  9982. const size_t attr_sz = sizeof(struct perf_event_attr);
  9983. struct perf_buffer_params p = {};
  9984. struct perf_event_attr attr;
  9985. if (!OPTS_VALID(opts, perf_buffer_opts))
  9986. return libbpf_err_ptr(-EINVAL);
  9987. memset(&attr, 0, attr_sz);
  9988. attr.size = attr_sz;
  9989. attr.config = PERF_COUNT_SW_BPF_OUTPUT;
  9990. attr.type = PERF_TYPE_SOFTWARE;
  9991. attr.sample_type = PERF_SAMPLE_RAW;
  9992. attr.sample_period = 1;
  9993. attr.wakeup_events = 1;
  9994. p.attr = &attr;
  9995. p.sample_cb = sample_cb;
  9996. p.lost_cb = lost_cb;
  9997. p.ctx = ctx;
  9998. return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
  9999. }
  10000. struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
  10001. struct perf_event_attr *attr,
  10002. perf_buffer_event_fn event_cb, void *ctx,
  10003. const struct perf_buffer_raw_opts *opts)
  10004. {
  10005. struct perf_buffer_params p = {};
  10006. if (!attr)
  10007. return libbpf_err_ptr(-EINVAL);
  10008. if (!OPTS_VALID(opts, perf_buffer_raw_opts))
  10009. return libbpf_err_ptr(-EINVAL);
  10010. p.attr = attr;
  10011. p.event_cb = event_cb;
  10012. p.ctx = ctx;
  10013. p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
  10014. p.cpus = OPTS_GET(opts, cpus, NULL);
  10015. p.map_keys = OPTS_GET(opts, map_keys, NULL);
  10016. return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
  10017. }
  10018. static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
  10019. struct perf_buffer_params *p)
  10020. {
  10021. const char *online_cpus_file = "/sys/devices/system/cpu/online";
  10022. struct bpf_map_info map;
  10023. char msg[STRERR_BUFSIZE];
  10024. struct perf_buffer *pb;
  10025. bool *online = NULL;
  10026. __u32 map_info_len;
  10027. int err, i, j, n;
  10028. if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
  10029. pr_warn("page count should be power of two, but is %zu\n",
  10030. page_cnt);
  10031. return ERR_PTR(-EINVAL);
  10032. }
  10033. /* best-effort sanity checks */
  10034. memset(&map, 0, sizeof(map));
  10035. map_info_len = sizeof(map);
  10036. err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
  10037. if (err) {
  10038. err = -errno;
  10039. /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
  10040. * -EBADFD, -EFAULT, or -E2BIG on real error
  10041. */
  10042. if (err != -EINVAL) {
  10043. pr_warn("failed to get map info for map FD %d: %s\n",
  10044. map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
  10045. return ERR_PTR(err);
  10046. }
  10047. pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
  10048. map_fd);
  10049. } else {
  10050. if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
  10051. pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
  10052. map.name);
  10053. return ERR_PTR(-EINVAL);
  10054. }
  10055. }
  10056. pb = calloc(1, sizeof(*pb));
  10057. if (!pb)
  10058. return ERR_PTR(-ENOMEM);
  10059. pb->event_cb = p->event_cb;
  10060. pb->sample_cb = p->sample_cb;
  10061. pb->lost_cb = p->lost_cb;
  10062. pb->ctx = p->ctx;
  10063. pb->page_size = getpagesize();
  10064. pb->mmap_size = pb->page_size * page_cnt;
  10065. pb->map_fd = map_fd;
  10066. pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
  10067. if (pb->epoll_fd < 0) {
  10068. err = -errno;
  10069. pr_warn("failed to create epoll instance: %s\n",
  10070. libbpf_strerror_r(err, msg, sizeof(msg)));
  10071. goto error;
  10072. }
  10073. if (p->cpu_cnt > 0) {
  10074. pb->cpu_cnt = p->cpu_cnt;
  10075. } else {
  10076. pb->cpu_cnt = libbpf_num_possible_cpus();
  10077. if (pb->cpu_cnt < 0) {
  10078. err = pb->cpu_cnt;
  10079. goto error;
  10080. }
  10081. if (map.max_entries && map.max_entries < pb->cpu_cnt)
  10082. pb->cpu_cnt = map.max_entries;
  10083. }
  10084. pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
  10085. if (!pb->events) {
  10086. err = -ENOMEM;
  10087. pr_warn("failed to allocate events: out of memory\n");
  10088. goto error;
  10089. }
  10090. pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
  10091. if (!pb->cpu_bufs) {
  10092. err = -ENOMEM;
  10093. pr_warn("failed to allocate buffers: out of memory\n");
  10094. goto error;
  10095. }
  10096. err = parse_cpu_mask_file(online_cpus_file, &online, &n);
  10097. if (err) {
  10098. pr_warn("failed to get online CPU mask: %d\n", err);
  10099. goto error;
  10100. }
  10101. for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
  10102. struct perf_cpu_buf *cpu_buf;
  10103. int cpu, map_key;
  10104. cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
  10105. map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
  10106. /* in case user didn't explicitly requested particular CPUs to
  10107. * be attached to, skip offline/not present CPUs
  10108. */
  10109. if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
  10110. continue;
  10111. cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
  10112. if (IS_ERR(cpu_buf)) {
  10113. err = PTR_ERR(cpu_buf);
  10114. goto error;
  10115. }
  10116. pb->cpu_bufs[j] = cpu_buf;
  10117. err = bpf_map_update_elem(pb->map_fd, &map_key,
  10118. &cpu_buf->fd, 0);
  10119. if (err) {
  10120. err = -errno;
  10121. pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
  10122. cpu, map_key, cpu_buf->fd,
  10123. libbpf_strerror_r(err, msg, sizeof(msg)));
  10124. goto error;
  10125. }
  10126. pb->events[j].events = EPOLLIN;
  10127. pb->events[j].data.ptr = cpu_buf;
  10128. if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
  10129. &pb->events[j]) < 0) {
  10130. err = -errno;
  10131. pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
  10132. cpu, cpu_buf->fd,
  10133. libbpf_strerror_r(err, msg, sizeof(msg)));
  10134. goto error;
  10135. }
  10136. j++;
  10137. }
  10138. pb->cpu_cnt = j;
  10139. free(online);
  10140. return pb;
  10141. error:
  10142. free(online);
  10143. if (pb)
  10144. perf_buffer__free(pb);
  10145. return ERR_PTR(err);
  10146. }
  10147. struct perf_sample_raw {
  10148. struct perf_event_header header;
  10149. uint32_t size;
  10150. char data[];
  10151. };
  10152. struct perf_sample_lost {
  10153. struct perf_event_header header;
  10154. uint64_t id;
  10155. uint64_t lost;
  10156. uint64_t sample_id;
  10157. };
  10158. static enum bpf_perf_event_ret
  10159. perf_buffer__process_record(struct perf_event_header *e, void *ctx)
  10160. {
  10161. struct perf_cpu_buf *cpu_buf = ctx;
  10162. struct perf_buffer *pb = cpu_buf->pb;
  10163. void *data = e;
  10164. /* user wants full control over parsing perf event */
  10165. if (pb->event_cb)
  10166. return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
  10167. switch (e->type) {
  10168. case PERF_RECORD_SAMPLE: {
  10169. struct perf_sample_raw *s = data;
  10170. if (pb->sample_cb)
  10171. pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
  10172. break;
  10173. }
  10174. case PERF_RECORD_LOST: {
  10175. struct perf_sample_lost *s = data;
  10176. if (pb->lost_cb)
  10177. pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
  10178. break;
  10179. }
  10180. default:
  10181. pr_warn("unknown perf sample type %d\n", e->type);
  10182. return LIBBPF_PERF_EVENT_ERROR;
  10183. }
  10184. return LIBBPF_PERF_EVENT_CONT;
  10185. }
  10186. static int perf_buffer__process_records(struct perf_buffer *pb,
  10187. struct perf_cpu_buf *cpu_buf)
  10188. {
  10189. enum bpf_perf_event_ret ret;
  10190. ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
  10191. pb->page_size, &cpu_buf->buf,
  10192. &cpu_buf->buf_size,
  10193. perf_buffer__process_record, cpu_buf);
  10194. if (ret != LIBBPF_PERF_EVENT_CONT)
  10195. return ret;
  10196. return 0;
  10197. }
  10198. int perf_buffer__epoll_fd(const struct perf_buffer *pb)
  10199. {
  10200. return pb->epoll_fd;
  10201. }
  10202. int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
  10203. {
  10204. int i, cnt, err;
  10205. cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
  10206. if (cnt < 0)
  10207. return -errno;
  10208. for (i = 0; i < cnt; i++) {
  10209. struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
  10210. err = perf_buffer__process_records(pb, cpu_buf);
  10211. if (err) {
  10212. pr_warn("error while processing records: %d\n", err);
  10213. return libbpf_err(err);
  10214. }
  10215. }
  10216. return cnt;
  10217. }
  10218. /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
  10219. * manager.
  10220. */
  10221. size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
  10222. {
  10223. return pb->cpu_cnt;
  10224. }
  10225. /*
  10226. * Return perf_event FD of a ring buffer in *buf_idx* slot of
  10227. * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
  10228. * select()/poll()/epoll() Linux syscalls.
  10229. */
  10230. int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
  10231. {
  10232. struct perf_cpu_buf *cpu_buf;
  10233. if (buf_idx >= pb->cpu_cnt)
  10234. return libbpf_err(-EINVAL);
  10235. cpu_buf = pb->cpu_bufs[buf_idx];
  10236. if (!cpu_buf)
  10237. return libbpf_err(-ENOENT);
  10238. return cpu_buf->fd;
  10239. }
  10240. int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
  10241. {
  10242. struct perf_cpu_buf *cpu_buf;
  10243. if (buf_idx >= pb->cpu_cnt)
  10244. return libbpf_err(-EINVAL);
  10245. cpu_buf = pb->cpu_bufs[buf_idx];
  10246. if (!cpu_buf)
  10247. return libbpf_err(-ENOENT);
  10248. *buf = cpu_buf->base;
  10249. *buf_size = pb->mmap_size;
  10250. return 0;
  10251. }
  10252. /*
  10253. * Consume data from perf ring buffer corresponding to slot *buf_idx* in
  10254. * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
  10255. * consume, do nothing and return success.
  10256. * Returns:
  10257. * - 0 on success;
  10258. * - <0 on failure.
  10259. */
  10260. int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
  10261. {
  10262. struct perf_cpu_buf *cpu_buf;
  10263. if (buf_idx >= pb->cpu_cnt)
  10264. return libbpf_err(-EINVAL);
  10265. cpu_buf = pb->cpu_bufs[buf_idx];
  10266. if (!cpu_buf)
  10267. return libbpf_err(-ENOENT);
  10268. return perf_buffer__process_records(pb, cpu_buf);
  10269. }
  10270. int perf_buffer__consume(struct perf_buffer *pb)
  10271. {
  10272. int i, err;
  10273. for (i = 0; i < pb->cpu_cnt; i++) {
  10274. struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
  10275. if (!cpu_buf)
  10276. continue;
  10277. err = perf_buffer__process_records(pb, cpu_buf);
  10278. if (err) {
  10279. pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
  10280. return libbpf_err(err);
  10281. }
  10282. }
  10283. return 0;
  10284. }
  10285. int bpf_program__set_attach_target(struct bpf_program *prog,
  10286. int attach_prog_fd,
  10287. const char *attach_func_name)
  10288. {
  10289. int btf_obj_fd = 0, btf_id = 0, err;
  10290. if (!prog || attach_prog_fd < 0)
  10291. return libbpf_err(-EINVAL);
  10292. if (prog->obj->loaded)
  10293. return libbpf_err(-EINVAL);
  10294. if (attach_prog_fd && !attach_func_name) {
  10295. /* remember attach_prog_fd and let bpf_program__load() find
  10296. * BTF ID during the program load
  10297. */
  10298. prog->attach_prog_fd = attach_prog_fd;
  10299. return 0;
  10300. }
  10301. if (attach_prog_fd) {
  10302. btf_id = libbpf_find_prog_btf_id(attach_func_name,
  10303. attach_prog_fd);
  10304. if (btf_id < 0)
  10305. return libbpf_err(btf_id);
  10306. } else {
  10307. if (!attach_func_name)
  10308. return libbpf_err(-EINVAL);
  10309. /* load btf_vmlinux, if not yet */
  10310. err = bpf_object__load_vmlinux_btf(prog->obj, true);
  10311. if (err)
  10312. return libbpf_err(err);
  10313. err = find_kernel_btf_id(prog->obj, attach_func_name,
  10314. prog->expected_attach_type,
  10315. &btf_obj_fd, &btf_id);
  10316. if (err)
  10317. return libbpf_err(err);
  10318. }
  10319. prog->attach_btf_id = btf_id;
  10320. prog->attach_btf_obj_fd = btf_obj_fd;
  10321. prog->attach_prog_fd = attach_prog_fd;
  10322. return 0;
  10323. }
  10324. int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
  10325. {
  10326. int err = 0, n, len, start, end = -1;
  10327. bool *tmp;
  10328. *mask = NULL;
  10329. *mask_sz = 0;
  10330. /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
  10331. while (*s) {
  10332. if (*s == ',' || *s == '\n') {
  10333. s++;
  10334. continue;
  10335. }
  10336. n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
  10337. if (n <= 0 || n > 2) {
  10338. pr_warn("Failed to get CPU range %s: %d\n", s, n);
  10339. err = -EINVAL;
  10340. goto cleanup;
  10341. } else if (n == 1) {
  10342. end = start;
  10343. }
  10344. if (start < 0 || start > end) {
  10345. pr_warn("Invalid CPU range [%d,%d] in %s\n",
  10346. start, end, s);
  10347. err = -EINVAL;
  10348. goto cleanup;
  10349. }
  10350. tmp = realloc(*mask, end + 1);
  10351. if (!tmp) {
  10352. err = -ENOMEM;
  10353. goto cleanup;
  10354. }
  10355. *mask = tmp;
  10356. memset(tmp + *mask_sz, 0, start - *mask_sz);
  10357. memset(tmp + start, 1, end - start + 1);
  10358. *mask_sz = end + 1;
  10359. s += len;
  10360. }
  10361. if (!*mask_sz) {
  10362. pr_warn("Empty CPU range\n");
  10363. return -EINVAL;
  10364. }
  10365. return 0;
  10366. cleanup:
  10367. free(*mask);
  10368. *mask = NULL;
  10369. return err;
  10370. }
  10371. int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
  10372. {
  10373. int fd, err = 0, len;
  10374. char buf[128];
  10375. fd = open(fcpu, O_RDONLY | O_CLOEXEC);
  10376. if (fd < 0) {
  10377. err = -errno;
  10378. pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
  10379. return err;
  10380. }
  10381. len = read(fd, buf, sizeof(buf));
  10382. close(fd);
  10383. if (len <= 0) {
  10384. err = len ? -errno : -EINVAL;
  10385. pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
  10386. return err;
  10387. }
  10388. if (len >= sizeof(buf)) {
  10389. pr_warn("CPU mask is too big in file %s\n", fcpu);
  10390. return -E2BIG;
  10391. }
  10392. buf[len] = '\0';
  10393. return parse_cpu_mask_str(buf, mask, mask_sz);
  10394. }
  10395. int libbpf_num_possible_cpus(void)
  10396. {
  10397. static const char *fcpu = "/sys/devices/system/cpu/possible";
  10398. static int cpus;
  10399. int err, n, i, tmp_cpus;
  10400. bool *mask;
  10401. tmp_cpus = READ_ONCE(cpus);
  10402. if (tmp_cpus > 0)
  10403. return tmp_cpus;
  10404. err = parse_cpu_mask_file(fcpu, &mask, &n);
  10405. if (err)
  10406. return libbpf_err(err);
  10407. tmp_cpus = 0;
  10408. for (i = 0; i < n; i++) {
  10409. if (mask[i])
  10410. tmp_cpus++;
  10411. }
  10412. free(mask);
  10413. WRITE_ONCE(cpus, tmp_cpus);
  10414. return tmp_cpus;
  10415. }
  10416. static int populate_skeleton_maps(const struct bpf_object *obj,
  10417. struct bpf_map_skeleton *maps,
  10418. size_t map_cnt)
  10419. {
  10420. int i;
  10421. for (i = 0; i < map_cnt; i++) {
  10422. struct bpf_map **map = maps[i].map;
  10423. const char *name = maps[i].name;
  10424. void **mmaped = maps[i].mmaped;
  10425. *map = bpf_object__find_map_by_name(obj, name);
  10426. if (!*map) {
  10427. pr_warn("failed to find skeleton map '%s'\n", name);
  10428. return -ESRCH;
  10429. }
  10430. /* externs shouldn't be pre-setup from user code */
  10431. if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
  10432. *mmaped = (*map)->mmaped;
  10433. }
  10434. return 0;
  10435. }
  10436. static int populate_skeleton_progs(const struct bpf_object *obj,
  10437. struct bpf_prog_skeleton *progs,
  10438. size_t prog_cnt)
  10439. {
  10440. int i;
  10441. for (i = 0; i < prog_cnt; i++) {
  10442. struct bpf_program **prog = progs[i].prog;
  10443. const char *name = progs[i].name;
  10444. *prog = bpf_object__find_program_by_name(obj, name);
  10445. if (!*prog) {
  10446. pr_warn("failed to find skeleton program '%s'\n", name);
  10447. return -ESRCH;
  10448. }
  10449. }
  10450. return 0;
  10451. }
  10452. int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
  10453. const struct bpf_object_open_opts *opts)
  10454. {
  10455. DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
  10456. .object_name = s->name,
  10457. );
  10458. struct bpf_object *obj;
  10459. int err;
  10460. /* Attempt to preserve opts->object_name, unless overriden by user
  10461. * explicitly. Overwriting object name for skeletons is discouraged,
  10462. * as it breaks global data maps, because they contain object name
  10463. * prefix as their own map name prefix. When skeleton is generated,
  10464. * bpftool is making an assumption that this name will stay the same.
  10465. */
  10466. if (opts) {
  10467. memcpy(&skel_opts, opts, sizeof(*opts));
  10468. if (!opts->object_name)
  10469. skel_opts.object_name = s->name;
  10470. }
  10471. obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
  10472. err = libbpf_get_error(obj);
  10473. if (err) {
  10474. pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
  10475. s->name, err);
  10476. return libbpf_err(err);
  10477. }
  10478. *s->obj = obj;
  10479. err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
  10480. if (err) {
  10481. pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
  10482. return libbpf_err(err);
  10483. }
  10484. err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
  10485. if (err) {
  10486. pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
  10487. return libbpf_err(err);
  10488. }
  10489. return 0;
  10490. }
  10491. int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
  10492. {
  10493. int err, len, var_idx, i;
  10494. const char *var_name;
  10495. const struct bpf_map *map;
  10496. struct btf *btf;
  10497. __u32 map_type_id;
  10498. const struct btf_type *map_type, *var_type;
  10499. const struct bpf_var_skeleton *var_skel;
  10500. struct btf_var_secinfo *var;
  10501. if (!s->obj)
  10502. return libbpf_err(-EINVAL);
  10503. btf = bpf_object__btf(s->obj);
  10504. if (!btf) {
  10505. pr_warn("subskeletons require BTF at runtime (object %s)\n",
  10506. bpf_object__name(s->obj));
  10507. return libbpf_err(-errno);
  10508. }
  10509. err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
  10510. if (err) {
  10511. pr_warn("failed to populate subskeleton maps: %d\n", err);
  10512. return libbpf_err(err);
  10513. }
  10514. err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
  10515. if (err) {
  10516. pr_warn("failed to populate subskeleton maps: %d\n", err);
  10517. return libbpf_err(err);
  10518. }
  10519. for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
  10520. var_skel = &s->vars[var_idx];
  10521. map = *var_skel->map;
  10522. map_type_id = bpf_map__btf_value_type_id(map);
  10523. map_type = btf__type_by_id(btf, map_type_id);
  10524. if (!btf_is_datasec(map_type)) {
  10525. pr_warn("type for map '%1$s' is not a datasec: %2$s",
  10526. bpf_map__name(map),
  10527. __btf_kind_str(btf_kind(map_type)));
  10528. return libbpf_err(-EINVAL);
  10529. }
  10530. len = btf_vlen(map_type);
  10531. var = btf_var_secinfos(map_type);
  10532. for (i = 0; i < len; i++, var++) {
  10533. var_type = btf__type_by_id(btf, var->type);
  10534. var_name = btf__name_by_offset(btf, var_type->name_off);
  10535. if (strcmp(var_name, var_skel->name) == 0) {
  10536. *var_skel->addr = map->mmaped + var->offset;
  10537. break;
  10538. }
  10539. }
  10540. }
  10541. return 0;
  10542. }
  10543. void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
  10544. {
  10545. if (!s)
  10546. return;
  10547. free(s->maps);
  10548. free(s->progs);
  10549. free(s->vars);
  10550. free(s);
  10551. }
  10552. int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
  10553. {
  10554. int i, err;
  10555. err = bpf_object__load(*s->obj);
  10556. if (err) {
  10557. pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
  10558. return libbpf_err(err);
  10559. }
  10560. for (i = 0; i < s->map_cnt; i++) {
  10561. struct bpf_map *map = *s->maps[i].map;
  10562. size_t mmap_sz = bpf_map_mmap_sz(map);
  10563. int prot, map_fd = bpf_map__fd(map);
  10564. void **mmaped = s->maps[i].mmaped;
  10565. if (!mmaped)
  10566. continue;
  10567. if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
  10568. *mmaped = NULL;
  10569. continue;
  10570. }
  10571. if (map->def.map_flags & BPF_F_RDONLY_PROG)
  10572. prot = PROT_READ;
  10573. else
  10574. prot = PROT_READ | PROT_WRITE;
  10575. /* Remap anonymous mmap()-ed "map initialization image" as
  10576. * a BPF map-backed mmap()-ed memory, but preserving the same
  10577. * memory address. This will cause kernel to change process'
  10578. * page table to point to a different piece of kernel memory,
  10579. * but from userspace point of view memory address (and its
  10580. * contents, being identical at this point) will stay the
  10581. * same. This mapping will be released by bpf_object__close()
  10582. * as per normal clean up procedure, so we don't need to worry
  10583. * about it from skeleton's clean up perspective.
  10584. */
  10585. *mmaped = mmap(map->mmaped, mmap_sz, prot,
  10586. MAP_SHARED | MAP_FIXED, map_fd, 0);
  10587. if (*mmaped == MAP_FAILED) {
  10588. err = -errno;
  10589. *mmaped = NULL;
  10590. pr_warn("failed to re-mmap() map '%s': %d\n",
  10591. bpf_map__name(map), err);
  10592. return libbpf_err(err);
  10593. }
  10594. }
  10595. return 0;
  10596. }
  10597. int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
  10598. {
  10599. int i, err;
  10600. for (i = 0; i < s->prog_cnt; i++) {
  10601. struct bpf_program *prog = *s->progs[i].prog;
  10602. struct bpf_link **link = s->progs[i].link;
  10603. if (!prog->autoload || !prog->autoattach)
  10604. continue;
  10605. /* auto-attaching not supported for this program */
  10606. if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
  10607. continue;
  10608. /* if user already set the link manually, don't attempt auto-attach */
  10609. if (*link)
  10610. continue;
  10611. err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
  10612. if (err) {
  10613. pr_warn("prog '%s': failed to auto-attach: %d\n",
  10614. bpf_program__name(prog), err);
  10615. return libbpf_err(err);
  10616. }
  10617. /* It's possible that for some SEC() definitions auto-attach
  10618. * is supported in some cases (e.g., if definition completely
  10619. * specifies target information), but is not in other cases.
  10620. * SEC("uprobe") is one such case. If user specified target
  10621. * binary and function name, such BPF program can be
  10622. * auto-attached. But if not, it shouldn't trigger skeleton's
  10623. * attach to fail. It should just be skipped.
  10624. * attach_fn signals such case with returning 0 (no error) and
  10625. * setting link to NULL.
  10626. */
  10627. }
  10628. return 0;
  10629. }
  10630. void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
  10631. {
  10632. int i;
  10633. for (i = 0; i < s->prog_cnt; i++) {
  10634. struct bpf_link **link = s->progs[i].link;
  10635. bpf_link__destroy(*link);
  10636. *link = NULL;
  10637. }
  10638. }
  10639. void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
  10640. {
  10641. if (!s)
  10642. return;
  10643. if (s->progs)
  10644. bpf_object__detach_skeleton(s);
  10645. if (s->obj)
  10646. bpf_object__close(*s->obj);
  10647. free(s->maps);
  10648. free(s->progs);
  10649. free(s);
  10650. }