libbpf.c 376 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054
  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 <ast@kernel.org>
  6. * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
  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/bpf_perf_event.h>
  35. #include <linux/ring_buffer.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. #include "zip.h"
  55. #ifndef BPF_FS_MAGIC
  56. #define BPF_FS_MAGIC 0xcafe4a11
  57. #endif
  58. #define MAX_EVENT_NAME_LEN 64
  59. #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
  60. #define BPF_INSN_SZ (sizeof(struct bpf_insn))
  61. /* vsprintf() in __base_pr() uses nonliteral format string. It may break
  62. * compilation if user enables corresponding warning. Disable it explicitly.
  63. */
  64. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  65. #define __printf(a, b) __attribute__((format(printf, a, b)))
  66. static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
  67. static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
  68. static int map_set_def_max_entries(struct bpf_map *map);
  69. static const char * const attach_type_name[] = {
  70. [BPF_CGROUP_INET_INGRESS] = "cgroup_inet_ingress",
  71. [BPF_CGROUP_INET_EGRESS] = "cgroup_inet_egress",
  72. [BPF_CGROUP_INET_SOCK_CREATE] = "cgroup_inet_sock_create",
  73. [BPF_CGROUP_INET_SOCK_RELEASE] = "cgroup_inet_sock_release",
  74. [BPF_CGROUP_SOCK_OPS] = "cgroup_sock_ops",
  75. [BPF_CGROUP_DEVICE] = "cgroup_device",
  76. [BPF_CGROUP_INET4_BIND] = "cgroup_inet4_bind",
  77. [BPF_CGROUP_INET6_BIND] = "cgroup_inet6_bind",
  78. [BPF_CGROUP_INET4_CONNECT] = "cgroup_inet4_connect",
  79. [BPF_CGROUP_INET6_CONNECT] = "cgroup_inet6_connect",
  80. [BPF_CGROUP_UNIX_CONNECT] = "cgroup_unix_connect",
  81. [BPF_CGROUP_INET4_POST_BIND] = "cgroup_inet4_post_bind",
  82. [BPF_CGROUP_INET6_POST_BIND] = "cgroup_inet6_post_bind",
  83. [BPF_CGROUP_INET4_GETPEERNAME] = "cgroup_inet4_getpeername",
  84. [BPF_CGROUP_INET6_GETPEERNAME] = "cgroup_inet6_getpeername",
  85. [BPF_CGROUP_UNIX_GETPEERNAME] = "cgroup_unix_getpeername",
  86. [BPF_CGROUP_INET4_GETSOCKNAME] = "cgroup_inet4_getsockname",
  87. [BPF_CGROUP_INET6_GETSOCKNAME] = "cgroup_inet6_getsockname",
  88. [BPF_CGROUP_UNIX_GETSOCKNAME] = "cgroup_unix_getsockname",
  89. [BPF_CGROUP_UDP4_SENDMSG] = "cgroup_udp4_sendmsg",
  90. [BPF_CGROUP_UDP6_SENDMSG] = "cgroup_udp6_sendmsg",
  91. [BPF_CGROUP_UNIX_SENDMSG] = "cgroup_unix_sendmsg",
  92. [BPF_CGROUP_SYSCTL] = "cgroup_sysctl",
  93. [BPF_CGROUP_UDP4_RECVMSG] = "cgroup_udp4_recvmsg",
  94. [BPF_CGROUP_UDP6_RECVMSG] = "cgroup_udp6_recvmsg",
  95. [BPF_CGROUP_UNIX_RECVMSG] = "cgroup_unix_recvmsg",
  96. [BPF_CGROUP_GETSOCKOPT] = "cgroup_getsockopt",
  97. [BPF_CGROUP_SETSOCKOPT] = "cgroup_setsockopt",
  98. [BPF_SK_SKB_STREAM_PARSER] = "sk_skb_stream_parser",
  99. [BPF_SK_SKB_STREAM_VERDICT] = "sk_skb_stream_verdict",
  100. [BPF_SK_SKB_VERDICT] = "sk_skb_verdict",
  101. [BPF_SK_MSG_VERDICT] = "sk_msg_verdict",
  102. [BPF_LIRC_MODE2] = "lirc_mode2",
  103. [BPF_FLOW_DISSECTOR] = "flow_dissector",
  104. [BPF_TRACE_RAW_TP] = "trace_raw_tp",
  105. [BPF_TRACE_FENTRY] = "trace_fentry",
  106. [BPF_TRACE_FEXIT] = "trace_fexit",
  107. [BPF_MODIFY_RETURN] = "modify_return",
  108. [BPF_LSM_MAC] = "lsm_mac",
  109. [BPF_LSM_CGROUP] = "lsm_cgroup",
  110. [BPF_SK_LOOKUP] = "sk_lookup",
  111. [BPF_TRACE_ITER] = "trace_iter",
  112. [BPF_XDP_DEVMAP] = "xdp_devmap",
  113. [BPF_XDP_CPUMAP] = "xdp_cpumap",
  114. [BPF_XDP] = "xdp",
  115. [BPF_SK_REUSEPORT_SELECT] = "sk_reuseport_select",
  116. [BPF_SK_REUSEPORT_SELECT_OR_MIGRATE] = "sk_reuseport_select_or_migrate",
  117. [BPF_PERF_EVENT] = "perf_event",
  118. [BPF_TRACE_KPROBE_MULTI] = "trace_kprobe_multi",
  119. [BPF_STRUCT_OPS] = "struct_ops",
  120. [BPF_NETFILTER] = "netfilter",
  121. [BPF_TCX_INGRESS] = "tcx_ingress",
  122. [BPF_TCX_EGRESS] = "tcx_egress",
  123. [BPF_TRACE_UPROBE_MULTI] = "trace_uprobe_multi",
  124. [BPF_NETKIT_PRIMARY] = "netkit_primary",
  125. [BPF_NETKIT_PEER] = "netkit_peer",
  126. [BPF_TRACE_KPROBE_SESSION] = "trace_kprobe_session",
  127. };
  128. static const char * const link_type_name[] = {
  129. [BPF_LINK_TYPE_UNSPEC] = "unspec",
  130. [BPF_LINK_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
  131. [BPF_LINK_TYPE_TRACING] = "tracing",
  132. [BPF_LINK_TYPE_CGROUP] = "cgroup",
  133. [BPF_LINK_TYPE_ITER] = "iter",
  134. [BPF_LINK_TYPE_NETNS] = "netns",
  135. [BPF_LINK_TYPE_XDP] = "xdp",
  136. [BPF_LINK_TYPE_PERF_EVENT] = "perf_event",
  137. [BPF_LINK_TYPE_KPROBE_MULTI] = "kprobe_multi",
  138. [BPF_LINK_TYPE_STRUCT_OPS] = "struct_ops",
  139. [BPF_LINK_TYPE_NETFILTER] = "netfilter",
  140. [BPF_LINK_TYPE_TCX] = "tcx",
  141. [BPF_LINK_TYPE_UPROBE_MULTI] = "uprobe_multi",
  142. [BPF_LINK_TYPE_NETKIT] = "netkit",
  143. [BPF_LINK_TYPE_SOCKMAP] = "sockmap",
  144. };
  145. static const char * const map_type_name[] = {
  146. [BPF_MAP_TYPE_UNSPEC] = "unspec",
  147. [BPF_MAP_TYPE_HASH] = "hash",
  148. [BPF_MAP_TYPE_ARRAY] = "array",
  149. [BPF_MAP_TYPE_PROG_ARRAY] = "prog_array",
  150. [BPF_MAP_TYPE_PERF_EVENT_ARRAY] = "perf_event_array",
  151. [BPF_MAP_TYPE_PERCPU_HASH] = "percpu_hash",
  152. [BPF_MAP_TYPE_PERCPU_ARRAY] = "percpu_array",
  153. [BPF_MAP_TYPE_STACK_TRACE] = "stack_trace",
  154. [BPF_MAP_TYPE_CGROUP_ARRAY] = "cgroup_array",
  155. [BPF_MAP_TYPE_LRU_HASH] = "lru_hash",
  156. [BPF_MAP_TYPE_LRU_PERCPU_HASH] = "lru_percpu_hash",
  157. [BPF_MAP_TYPE_LPM_TRIE] = "lpm_trie",
  158. [BPF_MAP_TYPE_ARRAY_OF_MAPS] = "array_of_maps",
  159. [BPF_MAP_TYPE_HASH_OF_MAPS] = "hash_of_maps",
  160. [BPF_MAP_TYPE_DEVMAP] = "devmap",
  161. [BPF_MAP_TYPE_DEVMAP_HASH] = "devmap_hash",
  162. [BPF_MAP_TYPE_SOCKMAP] = "sockmap",
  163. [BPF_MAP_TYPE_CPUMAP] = "cpumap",
  164. [BPF_MAP_TYPE_XSKMAP] = "xskmap",
  165. [BPF_MAP_TYPE_SOCKHASH] = "sockhash",
  166. [BPF_MAP_TYPE_CGROUP_STORAGE] = "cgroup_storage",
  167. [BPF_MAP_TYPE_REUSEPORT_SOCKARRAY] = "reuseport_sockarray",
  168. [BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE] = "percpu_cgroup_storage",
  169. [BPF_MAP_TYPE_QUEUE] = "queue",
  170. [BPF_MAP_TYPE_STACK] = "stack",
  171. [BPF_MAP_TYPE_SK_STORAGE] = "sk_storage",
  172. [BPF_MAP_TYPE_STRUCT_OPS] = "struct_ops",
  173. [BPF_MAP_TYPE_RINGBUF] = "ringbuf",
  174. [BPF_MAP_TYPE_INODE_STORAGE] = "inode_storage",
  175. [BPF_MAP_TYPE_TASK_STORAGE] = "task_storage",
  176. [BPF_MAP_TYPE_BLOOM_FILTER] = "bloom_filter",
  177. [BPF_MAP_TYPE_USER_RINGBUF] = "user_ringbuf",
  178. [BPF_MAP_TYPE_CGRP_STORAGE] = "cgrp_storage",
  179. [BPF_MAP_TYPE_ARENA] = "arena",
  180. };
  181. static const char * const prog_type_name[] = {
  182. [BPF_PROG_TYPE_UNSPEC] = "unspec",
  183. [BPF_PROG_TYPE_SOCKET_FILTER] = "socket_filter",
  184. [BPF_PROG_TYPE_KPROBE] = "kprobe",
  185. [BPF_PROG_TYPE_SCHED_CLS] = "sched_cls",
  186. [BPF_PROG_TYPE_SCHED_ACT] = "sched_act",
  187. [BPF_PROG_TYPE_TRACEPOINT] = "tracepoint",
  188. [BPF_PROG_TYPE_XDP] = "xdp",
  189. [BPF_PROG_TYPE_PERF_EVENT] = "perf_event",
  190. [BPF_PROG_TYPE_CGROUP_SKB] = "cgroup_skb",
  191. [BPF_PROG_TYPE_CGROUP_SOCK] = "cgroup_sock",
  192. [BPF_PROG_TYPE_LWT_IN] = "lwt_in",
  193. [BPF_PROG_TYPE_LWT_OUT] = "lwt_out",
  194. [BPF_PROG_TYPE_LWT_XMIT] = "lwt_xmit",
  195. [BPF_PROG_TYPE_SOCK_OPS] = "sock_ops",
  196. [BPF_PROG_TYPE_SK_SKB] = "sk_skb",
  197. [BPF_PROG_TYPE_CGROUP_DEVICE] = "cgroup_device",
  198. [BPF_PROG_TYPE_SK_MSG] = "sk_msg",
  199. [BPF_PROG_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
  200. [BPF_PROG_TYPE_CGROUP_SOCK_ADDR] = "cgroup_sock_addr",
  201. [BPF_PROG_TYPE_LWT_SEG6LOCAL] = "lwt_seg6local",
  202. [BPF_PROG_TYPE_LIRC_MODE2] = "lirc_mode2",
  203. [BPF_PROG_TYPE_SK_REUSEPORT] = "sk_reuseport",
  204. [BPF_PROG_TYPE_FLOW_DISSECTOR] = "flow_dissector",
  205. [BPF_PROG_TYPE_CGROUP_SYSCTL] = "cgroup_sysctl",
  206. [BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE] = "raw_tracepoint_writable",
  207. [BPF_PROG_TYPE_CGROUP_SOCKOPT] = "cgroup_sockopt",
  208. [BPF_PROG_TYPE_TRACING] = "tracing",
  209. [BPF_PROG_TYPE_STRUCT_OPS] = "struct_ops",
  210. [BPF_PROG_TYPE_EXT] = "ext",
  211. [BPF_PROG_TYPE_LSM] = "lsm",
  212. [BPF_PROG_TYPE_SK_LOOKUP] = "sk_lookup",
  213. [BPF_PROG_TYPE_SYSCALL] = "syscall",
  214. [BPF_PROG_TYPE_NETFILTER] = "netfilter",
  215. };
  216. static int __base_pr(enum libbpf_print_level level, const char *format,
  217. va_list args)
  218. {
  219. const char *env_var = "LIBBPF_LOG_LEVEL";
  220. static enum libbpf_print_level min_level = LIBBPF_INFO;
  221. static bool initialized;
  222. if (!initialized) {
  223. char *verbosity;
  224. initialized = true;
  225. verbosity = getenv(env_var);
  226. if (verbosity) {
  227. if (strcasecmp(verbosity, "warn") == 0)
  228. min_level = LIBBPF_WARN;
  229. else if (strcasecmp(verbosity, "debug") == 0)
  230. min_level = LIBBPF_DEBUG;
  231. else if (strcasecmp(verbosity, "info") == 0)
  232. min_level = LIBBPF_INFO;
  233. else
  234. fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
  235. env_var, verbosity);
  236. }
  237. }
  238. /* if too verbose, skip logging */
  239. if (level > min_level)
  240. return 0;
  241. return vfprintf(stderr, format, args);
  242. }
  243. static libbpf_print_fn_t __libbpf_pr = __base_pr;
  244. libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
  245. {
  246. libbpf_print_fn_t old_print_fn;
  247. old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
  248. return old_print_fn;
  249. }
  250. __printf(2, 3)
  251. void libbpf_print(enum libbpf_print_level level, const char *format, ...)
  252. {
  253. va_list args;
  254. int old_errno;
  255. libbpf_print_fn_t print_fn;
  256. print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
  257. if (!print_fn)
  258. return;
  259. old_errno = errno;
  260. va_start(args, format);
  261. print_fn(level, format, args);
  262. va_end(args);
  263. errno = old_errno;
  264. }
  265. static void pr_perm_msg(int err)
  266. {
  267. struct rlimit limit;
  268. char buf[100];
  269. if (err != -EPERM || geteuid() != 0)
  270. return;
  271. err = getrlimit(RLIMIT_MEMLOCK, &limit);
  272. if (err)
  273. return;
  274. if (limit.rlim_cur == RLIM_INFINITY)
  275. return;
  276. if (limit.rlim_cur < 1024)
  277. snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
  278. else if (limit.rlim_cur < 1024*1024)
  279. snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
  280. else
  281. snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
  282. pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
  283. buf);
  284. }
  285. #define STRERR_BUFSIZE 128
  286. /* Copied from tools/perf/util/util.h */
  287. #ifndef zfree
  288. # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
  289. #endif
  290. #ifndef zclose
  291. # define zclose(fd) ({ \
  292. int ___err = 0; \
  293. if ((fd) >= 0) \
  294. ___err = close((fd)); \
  295. fd = -1; \
  296. ___err; })
  297. #endif
  298. static inline __u64 ptr_to_u64(const void *ptr)
  299. {
  300. return (__u64) (unsigned long) ptr;
  301. }
  302. int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
  303. {
  304. /* as of v1.0 libbpf_set_strict_mode() is a no-op */
  305. return 0;
  306. }
  307. __u32 libbpf_major_version(void)
  308. {
  309. return LIBBPF_MAJOR_VERSION;
  310. }
  311. __u32 libbpf_minor_version(void)
  312. {
  313. return LIBBPF_MINOR_VERSION;
  314. }
  315. const char *libbpf_version_string(void)
  316. {
  317. #define __S(X) #X
  318. #define _S(X) __S(X)
  319. return "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
  320. #undef _S
  321. #undef __S
  322. }
  323. enum reloc_type {
  324. RELO_LD64,
  325. RELO_CALL,
  326. RELO_DATA,
  327. RELO_EXTERN_LD64,
  328. RELO_EXTERN_CALL,
  329. RELO_SUBPROG_ADDR,
  330. RELO_CORE,
  331. };
  332. struct reloc_desc {
  333. enum reloc_type type;
  334. int insn_idx;
  335. union {
  336. const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
  337. struct {
  338. int map_idx;
  339. int sym_off;
  340. int ext_idx;
  341. };
  342. };
  343. };
  344. /* stored as sec_def->cookie for all libbpf-supported SEC()s */
  345. enum sec_def_flags {
  346. SEC_NONE = 0,
  347. /* expected_attach_type is optional, if kernel doesn't support that */
  348. SEC_EXP_ATTACH_OPT = 1,
  349. /* legacy, only used by libbpf_get_type_names() and
  350. * libbpf_attach_type_by_name(), not used by libbpf itself at all.
  351. * This used to be associated with cgroup (and few other) BPF programs
  352. * that were attachable through BPF_PROG_ATTACH command. Pretty
  353. * meaningless nowadays, though.
  354. */
  355. SEC_ATTACHABLE = 2,
  356. SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
  357. /* attachment target is specified through BTF ID in either kernel or
  358. * other BPF program's BTF object
  359. */
  360. SEC_ATTACH_BTF = 4,
  361. /* BPF program type allows sleeping/blocking in kernel */
  362. SEC_SLEEPABLE = 8,
  363. /* BPF program support non-linear XDP buffer */
  364. SEC_XDP_FRAGS = 16,
  365. /* Setup proper attach type for usdt probes. */
  366. SEC_USDT = 32,
  367. };
  368. struct bpf_sec_def {
  369. char *sec;
  370. enum bpf_prog_type prog_type;
  371. enum bpf_attach_type expected_attach_type;
  372. long cookie;
  373. int handler_id;
  374. libbpf_prog_setup_fn_t prog_setup_fn;
  375. libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
  376. libbpf_prog_attach_fn_t prog_attach_fn;
  377. };
  378. /*
  379. * bpf_prog should be a better name but it has been used in
  380. * linux/filter.h.
  381. */
  382. struct bpf_program {
  383. char *name;
  384. char *sec_name;
  385. size_t sec_idx;
  386. const struct bpf_sec_def *sec_def;
  387. /* this program's instruction offset (in number of instructions)
  388. * within its containing ELF section
  389. */
  390. size_t sec_insn_off;
  391. /* number of original instructions in ELF section belonging to this
  392. * program, not taking into account subprogram instructions possible
  393. * appended later during relocation
  394. */
  395. size_t sec_insn_cnt;
  396. /* Offset (in number of instructions) of the start of instruction
  397. * belonging to this BPF program within its containing main BPF
  398. * program. For the entry-point (main) BPF program, this is always
  399. * zero. For a sub-program, this gets reset before each of main BPF
  400. * programs are processed and relocated and is used to determined
  401. * whether sub-program was already appended to the main program, and
  402. * if yes, at which instruction offset.
  403. */
  404. size_t sub_insn_off;
  405. /* instructions that belong to BPF program; insns[0] is located at
  406. * sec_insn_off instruction within its ELF section in ELF file, so
  407. * when mapping ELF file instruction index to the local instruction,
  408. * one needs to subtract sec_insn_off; and vice versa.
  409. */
  410. struct bpf_insn *insns;
  411. /* actual number of instruction in this BPF program's image; for
  412. * entry-point BPF programs this includes the size of main program
  413. * itself plus all the used sub-programs, appended at the end
  414. */
  415. size_t insns_cnt;
  416. struct reloc_desc *reloc_desc;
  417. int nr_reloc;
  418. /* BPF verifier log settings */
  419. char *log_buf;
  420. size_t log_size;
  421. __u32 log_level;
  422. struct bpf_object *obj;
  423. int fd;
  424. bool autoload;
  425. bool autoattach;
  426. bool sym_global;
  427. bool mark_btf_static;
  428. enum bpf_prog_type type;
  429. enum bpf_attach_type expected_attach_type;
  430. int exception_cb_idx;
  431. int prog_ifindex;
  432. __u32 attach_btf_obj_fd;
  433. __u32 attach_btf_id;
  434. __u32 attach_prog_fd;
  435. void *func_info;
  436. __u32 func_info_rec_size;
  437. __u32 func_info_cnt;
  438. void *line_info;
  439. __u32 line_info_rec_size;
  440. __u32 line_info_cnt;
  441. __u32 prog_flags;
  442. };
  443. struct bpf_struct_ops {
  444. struct bpf_program **progs;
  445. __u32 *kern_func_off;
  446. /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
  447. void *data;
  448. /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
  449. * btf_vmlinux's format.
  450. * struct bpf_struct_ops_tcp_congestion_ops {
  451. * [... some other kernel fields ...]
  452. * struct tcp_congestion_ops data;
  453. * }
  454. * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
  455. * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
  456. * from "data".
  457. */
  458. void *kern_vdata;
  459. __u32 type_id;
  460. };
  461. #define DATA_SEC ".data"
  462. #define BSS_SEC ".bss"
  463. #define RODATA_SEC ".rodata"
  464. #define KCONFIG_SEC ".kconfig"
  465. #define KSYMS_SEC ".ksyms"
  466. #define STRUCT_OPS_SEC ".struct_ops"
  467. #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
  468. #define ARENA_SEC ".addr_space.1"
  469. enum libbpf_map_type {
  470. LIBBPF_MAP_UNSPEC,
  471. LIBBPF_MAP_DATA,
  472. LIBBPF_MAP_BSS,
  473. LIBBPF_MAP_RODATA,
  474. LIBBPF_MAP_KCONFIG,
  475. };
  476. struct bpf_map_def {
  477. unsigned int type;
  478. unsigned int key_size;
  479. unsigned int value_size;
  480. unsigned int max_entries;
  481. unsigned int map_flags;
  482. };
  483. struct bpf_map {
  484. struct bpf_object *obj;
  485. char *name;
  486. /* real_name is defined for special internal maps (.rodata*,
  487. * .data*, .bss, .kconfig) and preserves their original ELF section
  488. * name. This is important to be able to find corresponding BTF
  489. * DATASEC information.
  490. */
  491. char *real_name;
  492. int fd;
  493. int sec_idx;
  494. size_t sec_offset;
  495. int map_ifindex;
  496. int inner_map_fd;
  497. struct bpf_map_def def;
  498. __u32 numa_node;
  499. __u32 btf_var_idx;
  500. int mod_btf_fd;
  501. __u32 btf_key_type_id;
  502. __u32 btf_value_type_id;
  503. __u32 btf_vmlinux_value_type_id;
  504. enum libbpf_map_type libbpf_type;
  505. void *mmaped;
  506. struct bpf_struct_ops *st_ops;
  507. struct bpf_map *inner_map;
  508. void **init_slots;
  509. int init_slots_sz;
  510. char *pin_path;
  511. bool pinned;
  512. bool reused;
  513. bool autocreate;
  514. bool autoattach;
  515. __u64 map_extra;
  516. };
  517. enum extern_type {
  518. EXT_UNKNOWN,
  519. EXT_KCFG,
  520. EXT_KSYM,
  521. };
  522. enum kcfg_type {
  523. KCFG_UNKNOWN,
  524. KCFG_CHAR,
  525. KCFG_BOOL,
  526. KCFG_INT,
  527. KCFG_TRISTATE,
  528. KCFG_CHAR_ARR,
  529. };
  530. struct extern_desc {
  531. enum extern_type type;
  532. int sym_idx;
  533. int btf_id;
  534. int sec_btf_id;
  535. char *name;
  536. char *essent_name;
  537. bool is_set;
  538. bool is_weak;
  539. union {
  540. struct {
  541. enum kcfg_type type;
  542. int sz;
  543. int align;
  544. int data_off;
  545. bool is_signed;
  546. } kcfg;
  547. struct {
  548. unsigned long long addr;
  549. /* target btf_id of the corresponding kernel var. */
  550. int kernel_btf_obj_fd;
  551. int kernel_btf_id;
  552. /* local btf_id of the ksym extern's type. */
  553. __u32 type_id;
  554. /* BTF fd index to be patched in for insn->off, this is
  555. * 0 for vmlinux BTF, index in obj->fd_array for module
  556. * BTF
  557. */
  558. __s16 btf_fd_idx;
  559. } ksym;
  560. };
  561. };
  562. struct module_btf {
  563. struct btf *btf;
  564. char *name;
  565. __u32 id;
  566. int fd;
  567. int fd_array_idx;
  568. };
  569. enum sec_type {
  570. SEC_UNUSED = 0,
  571. SEC_RELO,
  572. SEC_BSS,
  573. SEC_DATA,
  574. SEC_RODATA,
  575. SEC_ST_OPS,
  576. };
  577. struct elf_sec_desc {
  578. enum sec_type sec_type;
  579. Elf64_Shdr *shdr;
  580. Elf_Data *data;
  581. };
  582. struct elf_state {
  583. int fd;
  584. const void *obj_buf;
  585. size_t obj_buf_sz;
  586. Elf *elf;
  587. Elf64_Ehdr *ehdr;
  588. Elf_Data *symbols;
  589. Elf_Data *arena_data;
  590. size_t shstrndx; /* section index for section name strings */
  591. size_t strtabidx;
  592. struct elf_sec_desc *secs;
  593. size_t sec_cnt;
  594. int btf_maps_shndx;
  595. __u32 btf_maps_sec_btf_id;
  596. int text_shndx;
  597. int symbols_shndx;
  598. bool has_st_ops;
  599. int arena_data_shndx;
  600. };
  601. struct usdt_manager;
  602. struct bpf_object {
  603. char name[BPF_OBJ_NAME_LEN];
  604. char license[64];
  605. __u32 kern_version;
  606. struct bpf_program *programs;
  607. size_t nr_programs;
  608. struct bpf_map *maps;
  609. size_t nr_maps;
  610. size_t maps_cap;
  611. char *kconfig;
  612. struct extern_desc *externs;
  613. int nr_extern;
  614. int kconfig_map_idx;
  615. bool loaded;
  616. bool has_subcalls;
  617. bool has_rodata;
  618. struct bpf_gen *gen_loader;
  619. /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
  620. struct elf_state efile;
  621. struct btf *btf;
  622. struct btf_ext *btf_ext;
  623. /* Parse and load BTF vmlinux if any of the programs in the object need
  624. * it at load time.
  625. */
  626. struct btf *btf_vmlinux;
  627. /* Path to the custom BTF to be used for BPF CO-RE relocations as an
  628. * override for vmlinux BTF.
  629. */
  630. char *btf_custom_path;
  631. /* vmlinux BTF override for CO-RE relocations */
  632. struct btf *btf_vmlinux_override;
  633. /* Lazily initialized kernel module BTFs */
  634. struct module_btf *btf_modules;
  635. bool btf_modules_loaded;
  636. size_t btf_module_cnt;
  637. size_t btf_module_cap;
  638. /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
  639. char *log_buf;
  640. size_t log_size;
  641. __u32 log_level;
  642. int *fd_array;
  643. size_t fd_array_cap;
  644. size_t fd_array_cnt;
  645. struct usdt_manager *usdt_man;
  646. int arena_map_idx;
  647. void *arena_data;
  648. size_t arena_data_sz;
  649. struct kern_feature_cache *feat_cache;
  650. char *token_path;
  651. int token_fd;
  652. char path[];
  653. };
  654. static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
  655. static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
  656. static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
  657. static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
  658. static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
  659. static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
  660. static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
  661. static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
  662. static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
  663. void bpf_program__unload(struct bpf_program *prog)
  664. {
  665. if (!prog)
  666. return;
  667. zclose(prog->fd);
  668. zfree(&prog->func_info);
  669. zfree(&prog->line_info);
  670. }
  671. static void bpf_program__exit(struct bpf_program *prog)
  672. {
  673. if (!prog)
  674. return;
  675. bpf_program__unload(prog);
  676. zfree(&prog->name);
  677. zfree(&prog->sec_name);
  678. zfree(&prog->insns);
  679. zfree(&prog->reloc_desc);
  680. prog->nr_reloc = 0;
  681. prog->insns_cnt = 0;
  682. prog->sec_idx = -1;
  683. }
  684. static bool insn_is_subprog_call(const struct bpf_insn *insn)
  685. {
  686. return BPF_CLASS(insn->code) == BPF_JMP &&
  687. BPF_OP(insn->code) == BPF_CALL &&
  688. BPF_SRC(insn->code) == BPF_K &&
  689. insn->src_reg == BPF_PSEUDO_CALL &&
  690. insn->dst_reg == 0 &&
  691. insn->off == 0;
  692. }
  693. static bool is_call_insn(const struct bpf_insn *insn)
  694. {
  695. return insn->code == (BPF_JMP | BPF_CALL);
  696. }
  697. static bool insn_is_pseudo_func(struct bpf_insn *insn)
  698. {
  699. return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
  700. }
  701. static int
  702. bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
  703. const char *name, size_t sec_idx, const char *sec_name,
  704. size_t sec_off, void *insn_data, size_t insn_data_sz)
  705. {
  706. if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
  707. pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
  708. sec_name, name, sec_off, insn_data_sz);
  709. return -EINVAL;
  710. }
  711. memset(prog, 0, sizeof(*prog));
  712. prog->obj = obj;
  713. prog->sec_idx = sec_idx;
  714. prog->sec_insn_off = sec_off / BPF_INSN_SZ;
  715. prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
  716. /* insns_cnt can later be increased by appending used subprograms */
  717. prog->insns_cnt = prog->sec_insn_cnt;
  718. prog->type = BPF_PROG_TYPE_UNSPEC;
  719. prog->fd = -1;
  720. prog->exception_cb_idx = -1;
  721. /* libbpf's convention for SEC("?abc...") is that it's just like
  722. * SEC("abc...") but the corresponding bpf_program starts out with
  723. * autoload set to false.
  724. */
  725. if (sec_name[0] == '?') {
  726. prog->autoload = false;
  727. /* from now on forget there was ? in section name */
  728. sec_name++;
  729. } else {
  730. prog->autoload = true;
  731. }
  732. prog->autoattach = true;
  733. /* inherit object's log_level */
  734. prog->log_level = obj->log_level;
  735. prog->sec_name = strdup(sec_name);
  736. if (!prog->sec_name)
  737. goto errout;
  738. prog->name = strdup(name);
  739. if (!prog->name)
  740. goto errout;
  741. prog->insns = malloc(insn_data_sz);
  742. if (!prog->insns)
  743. goto errout;
  744. memcpy(prog->insns, insn_data, insn_data_sz);
  745. return 0;
  746. errout:
  747. pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
  748. bpf_program__exit(prog);
  749. return -ENOMEM;
  750. }
  751. static int
  752. bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
  753. const char *sec_name, int sec_idx)
  754. {
  755. Elf_Data *symbols = obj->efile.symbols;
  756. struct bpf_program *prog, *progs;
  757. void *data = sec_data->d_buf;
  758. size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
  759. int nr_progs, err, i;
  760. const char *name;
  761. Elf64_Sym *sym;
  762. progs = obj->programs;
  763. nr_progs = obj->nr_programs;
  764. nr_syms = symbols->d_size / sizeof(Elf64_Sym);
  765. for (i = 0; i < nr_syms; i++) {
  766. sym = elf_sym_by_idx(obj, i);
  767. if (sym->st_shndx != sec_idx)
  768. continue;
  769. if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
  770. continue;
  771. prog_sz = sym->st_size;
  772. sec_off = sym->st_value;
  773. name = elf_sym_str(obj, sym->st_name);
  774. if (!name) {
  775. pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
  776. sec_name, sec_off);
  777. return -LIBBPF_ERRNO__FORMAT;
  778. }
  779. if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
  780. pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
  781. sec_name, sec_off);
  782. return -LIBBPF_ERRNO__FORMAT;
  783. }
  784. if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
  785. pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
  786. return -ENOTSUP;
  787. }
  788. pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
  789. sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
  790. progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
  791. if (!progs) {
  792. /*
  793. * In this case the original obj->programs
  794. * is still valid, so don't need special treat for
  795. * bpf_close_object().
  796. */
  797. pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
  798. sec_name, name);
  799. return -ENOMEM;
  800. }
  801. obj->programs = progs;
  802. prog = &progs[nr_progs];
  803. err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
  804. sec_off, data + sec_off, prog_sz);
  805. if (err)
  806. return err;
  807. if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
  808. prog->sym_global = true;
  809. /* if function is a global/weak symbol, but has restricted
  810. * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
  811. * as static to enable more permissive BPF verification mode
  812. * with more outside context available to BPF verifier
  813. */
  814. if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
  815. || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
  816. prog->mark_btf_static = true;
  817. nr_progs++;
  818. obj->nr_programs = nr_progs;
  819. }
  820. return 0;
  821. }
  822. static const struct btf_member *
  823. find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
  824. {
  825. struct btf_member *m;
  826. int i;
  827. for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
  828. if (btf_member_bit_offset(t, i) == bit_offset)
  829. return m;
  830. }
  831. return NULL;
  832. }
  833. static const struct btf_member *
  834. find_member_by_name(const struct btf *btf, const struct btf_type *t,
  835. const char *name)
  836. {
  837. struct btf_member *m;
  838. int i;
  839. for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
  840. if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
  841. return m;
  842. }
  843. return NULL;
  844. }
  845. static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
  846. __u16 kind, struct btf **res_btf,
  847. struct module_btf **res_mod_btf);
  848. #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
  849. static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
  850. const char *name, __u32 kind);
  851. static int
  852. find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
  853. struct module_btf **mod_btf,
  854. const struct btf_type **type, __u32 *type_id,
  855. const struct btf_type **vtype, __u32 *vtype_id,
  856. const struct btf_member **data_member)
  857. {
  858. const struct btf_type *kern_type, *kern_vtype;
  859. const struct btf_member *kern_data_member;
  860. struct btf *btf = NULL;
  861. __s32 kern_vtype_id, kern_type_id;
  862. char tname[192], stname[256];
  863. __u32 i;
  864. snprintf(tname, sizeof(tname), "%.*s",
  865. (int)bpf_core_essential_name_len(tname_raw), tname_raw);
  866. snprintf(stname, sizeof(stname), "%s%s", STRUCT_OPS_VALUE_PREFIX, tname);
  867. /* Look for the corresponding "map_value" type that will be used
  868. * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf
  869. * and the mod_btf.
  870. * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
  871. */
  872. kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf);
  873. if (kern_vtype_id < 0) {
  874. pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname);
  875. return kern_vtype_id;
  876. }
  877. kern_vtype = btf__type_by_id(btf, kern_vtype_id);
  878. kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
  879. if (kern_type_id < 0) {
  880. pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname);
  881. return kern_type_id;
  882. }
  883. kern_type = btf__type_by_id(btf, kern_type_id);
  884. /* Find "struct tcp_congestion_ops" from
  885. * struct bpf_struct_ops_tcp_congestion_ops {
  886. * [ ... ]
  887. * struct tcp_congestion_ops data;
  888. * }
  889. */
  890. kern_data_member = btf_members(kern_vtype);
  891. for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
  892. if (kern_data_member->type == kern_type_id)
  893. break;
  894. }
  895. if (i == btf_vlen(kern_vtype)) {
  896. pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
  897. tname, stname);
  898. return -EINVAL;
  899. }
  900. *type = kern_type;
  901. *type_id = kern_type_id;
  902. *vtype = kern_vtype;
  903. *vtype_id = kern_vtype_id;
  904. *data_member = kern_data_member;
  905. return 0;
  906. }
  907. static bool bpf_map__is_struct_ops(const struct bpf_map *map)
  908. {
  909. return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
  910. }
  911. static bool is_valid_st_ops_program(struct bpf_object *obj,
  912. const struct bpf_program *prog)
  913. {
  914. int i;
  915. for (i = 0; i < obj->nr_programs; i++) {
  916. if (&obj->programs[i] == prog)
  917. return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
  918. }
  919. return false;
  920. }
  921. /* For each struct_ops program P, referenced from some struct_ops map M,
  922. * enable P.autoload if there are Ms for which M.autocreate is true,
  923. * disable P.autoload if for all Ms M.autocreate is false.
  924. * Don't change P.autoload for programs that are not referenced from any maps.
  925. */
  926. static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
  927. {
  928. struct bpf_program *prog, *slot_prog;
  929. struct bpf_map *map;
  930. int i, j, k, vlen;
  931. for (i = 0; i < obj->nr_programs; ++i) {
  932. int should_load = false;
  933. int use_cnt = 0;
  934. prog = &obj->programs[i];
  935. if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
  936. continue;
  937. for (j = 0; j < obj->nr_maps; ++j) {
  938. const struct btf_type *type;
  939. map = &obj->maps[j];
  940. if (!bpf_map__is_struct_ops(map))
  941. continue;
  942. type = btf__type_by_id(obj->btf, map->st_ops->type_id);
  943. vlen = btf_vlen(type);
  944. for (k = 0; k < vlen; ++k) {
  945. slot_prog = map->st_ops->progs[k];
  946. if (prog != slot_prog)
  947. continue;
  948. use_cnt++;
  949. if (map->autocreate)
  950. should_load = true;
  951. }
  952. }
  953. if (use_cnt)
  954. prog->autoload = should_load;
  955. }
  956. return 0;
  957. }
  958. /* Init the map's fields that depend on kern_btf */
  959. static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
  960. {
  961. const struct btf_member *member, *kern_member, *kern_data_member;
  962. const struct btf_type *type, *kern_type, *kern_vtype;
  963. __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
  964. struct bpf_object *obj = map->obj;
  965. const struct btf *btf = obj->btf;
  966. struct bpf_struct_ops *st_ops;
  967. const struct btf *kern_btf;
  968. struct module_btf *mod_btf = NULL;
  969. void *data, *kern_data;
  970. const char *tname;
  971. int err;
  972. st_ops = map->st_ops;
  973. type = btf__type_by_id(btf, st_ops->type_id);
  974. tname = btf__name_by_offset(btf, type->name_off);
  975. err = find_struct_ops_kern_types(obj, tname, &mod_btf,
  976. &kern_type, &kern_type_id,
  977. &kern_vtype, &kern_vtype_id,
  978. &kern_data_member);
  979. if (err)
  980. return err;
  981. kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
  982. pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
  983. map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
  984. map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
  985. map->def.value_size = kern_vtype->size;
  986. map->btf_vmlinux_value_type_id = kern_vtype_id;
  987. st_ops->kern_vdata = calloc(1, kern_vtype->size);
  988. if (!st_ops->kern_vdata)
  989. return -ENOMEM;
  990. data = st_ops->data;
  991. kern_data_off = kern_data_member->offset / 8;
  992. kern_data = st_ops->kern_vdata + kern_data_off;
  993. member = btf_members(type);
  994. for (i = 0; i < btf_vlen(type); i++, member++) {
  995. const struct btf_type *mtype, *kern_mtype;
  996. __u32 mtype_id, kern_mtype_id;
  997. void *mdata, *kern_mdata;
  998. struct bpf_program *prog;
  999. __s64 msize, kern_msize;
  1000. __u32 moff, kern_moff;
  1001. __u32 kern_member_idx;
  1002. const char *mname;
  1003. mname = btf__name_by_offset(btf, member->name_off);
  1004. moff = member->offset / 8;
  1005. mdata = data + moff;
  1006. msize = btf__resolve_size(btf, member->type);
  1007. if (msize < 0) {
  1008. pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
  1009. map->name, mname);
  1010. return msize;
  1011. }
  1012. kern_member = find_member_by_name(kern_btf, kern_type, mname);
  1013. if (!kern_member) {
  1014. if (!libbpf_is_mem_zeroed(mdata, msize)) {
  1015. pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
  1016. map->name, mname);
  1017. return -ENOTSUP;
  1018. }
  1019. if (st_ops->progs[i]) {
  1020. /* If we had declaratively set struct_ops callback, we need to
  1021. * force its autoload to false, because it doesn't have
  1022. * a chance of succeeding from POV of the current struct_ops map.
  1023. * If this program is still referenced somewhere else, though,
  1024. * then bpf_object_adjust_struct_ops_autoload() will update its
  1025. * autoload accordingly.
  1026. */
  1027. st_ops->progs[i]->autoload = false;
  1028. st_ops->progs[i] = NULL;
  1029. }
  1030. /* Skip all-zero/NULL fields if they are not present in the kernel BTF */
  1031. pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
  1032. map->name, mname);
  1033. continue;
  1034. }
  1035. kern_member_idx = kern_member - btf_members(kern_type);
  1036. if (btf_member_bitfield_size(type, i) ||
  1037. btf_member_bitfield_size(kern_type, kern_member_idx)) {
  1038. pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
  1039. map->name, mname);
  1040. return -ENOTSUP;
  1041. }
  1042. kern_moff = kern_member->offset / 8;
  1043. kern_mdata = kern_data + kern_moff;
  1044. mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
  1045. kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
  1046. &kern_mtype_id);
  1047. if (BTF_INFO_KIND(mtype->info) !=
  1048. BTF_INFO_KIND(kern_mtype->info)) {
  1049. pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
  1050. map->name, mname, BTF_INFO_KIND(mtype->info),
  1051. BTF_INFO_KIND(kern_mtype->info));
  1052. return -ENOTSUP;
  1053. }
  1054. if (btf_is_ptr(mtype)) {
  1055. prog = *(void **)mdata;
  1056. /* just like for !kern_member case above, reset declaratively
  1057. * set (at compile time) program's autload to false,
  1058. * if user replaced it with another program or NULL
  1059. */
  1060. if (st_ops->progs[i] && st_ops->progs[i] != prog)
  1061. st_ops->progs[i]->autoload = false;
  1062. /* Update the value from the shadow type */
  1063. st_ops->progs[i] = prog;
  1064. if (!prog)
  1065. continue;
  1066. if (!is_valid_st_ops_program(obj, prog)) {
  1067. pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
  1068. map->name, mname);
  1069. return -ENOTSUP;
  1070. }
  1071. kern_mtype = skip_mods_and_typedefs(kern_btf,
  1072. kern_mtype->type,
  1073. &kern_mtype_id);
  1074. /* mtype->type must be a func_proto which was
  1075. * guaranteed in bpf_object__collect_st_ops_relos(),
  1076. * so only check kern_mtype for func_proto here.
  1077. */
  1078. if (!btf_is_func_proto(kern_mtype)) {
  1079. pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
  1080. map->name, mname);
  1081. return -ENOTSUP;
  1082. }
  1083. if (mod_btf)
  1084. prog->attach_btf_obj_fd = mod_btf->fd;
  1085. /* if we haven't yet processed this BPF program, record proper
  1086. * attach_btf_id and member_idx
  1087. */
  1088. if (!prog->attach_btf_id) {
  1089. prog->attach_btf_id = kern_type_id;
  1090. prog->expected_attach_type = kern_member_idx;
  1091. }
  1092. /* struct_ops BPF prog can be re-used between multiple
  1093. * .struct_ops & .struct_ops.link as long as it's the
  1094. * same struct_ops struct definition and the same
  1095. * function pointer field
  1096. */
  1097. if (prog->attach_btf_id != kern_type_id) {
  1098. pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: attach_btf_id %u != kern_type_id %u\n",
  1099. map->name, mname, prog->name, prog->sec_name, prog->type,
  1100. prog->attach_btf_id, kern_type_id);
  1101. return -EINVAL;
  1102. }
  1103. if (prog->expected_attach_type != kern_member_idx) {
  1104. pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: expected_attach_type %u != kern_member_idx %u\n",
  1105. map->name, mname, prog->name, prog->sec_name, prog->type,
  1106. prog->expected_attach_type, kern_member_idx);
  1107. return -EINVAL;
  1108. }
  1109. st_ops->kern_func_off[i] = kern_data_off + kern_moff;
  1110. pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
  1111. map->name, mname, prog->name, moff,
  1112. kern_moff);
  1113. continue;
  1114. }
  1115. kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
  1116. if (kern_msize < 0 || msize != kern_msize) {
  1117. pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
  1118. map->name, mname, (ssize_t)msize,
  1119. (ssize_t)kern_msize);
  1120. return -ENOTSUP;
  1121. }
  1122. pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
  1123. map->name, mname, (unsigned int)msize,
  1124. moff, kern_moff);
  1125. memcpy(kern_mdata, mdata, msize);
  1126. }
  1127. return 0;
  1128. }
  1129. static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
  1130. {
  1131. struct bpf_map *map;
  1132. size_t i;
  1133. int err;
  1134. for (i = 0; i < obj->nr_maps; i++) {
  1135. map = &obj->maps[i];
  1136. if (!bpf_map__is_struct_ops(map))
  1137. continue;
  1138. if (!map->autocreate)
  1139. continue;
  1140. err = bpf_map__init_kern_struct_ops(map);
  1141. if (err)
  1142. return err;
  1143. }
  1144. return 0;
  1145. }
  1146. static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
  1147. int shndx, Elf_Data *data)
  1148. {
  1149. const struct btf_type *type, *datasec;
  1150. const struct btf_var_secinfo *vsi;
  1151. struct bpf_struct_ops *st_ops;
  1152. const char *tname, *var_name;
  1153. __s32 type_id, datasec_id;
  1154. const struct btf *btf;
  1155. struct bpf_map *map;
  1156. __u32 i;
  1157. if (shndx == -1)
  1158. return 0;
  1159. btf = obj->btf;
  1160. datasec_id = btf__find_by_name_kind(btf, sec_name,
  1161. BTF_KIND_DATASEC);
  1162. if (datasec_id < 0) {
  1163. pr_warn("struct_ops init: DATASEC %s not found\n",
  1164. sec_name);
  1165. return -EINVAL;
  1166. }
  1167. datasec = btf__type_by_id(btf, datasec_id);
  1168. vsi = btf_var_secinfos(datasec);
  1169. for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
  1170. type = btf__type_by_id(obj->btf, vsi->type);
  1171. var_name = btf__name_by_offset(obj->btf, type->name_off);
  1172. type_id = btf__resolve_type(obj->btf, vsi->type);
  1173. if (type_id < 0) {
  1174. pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
  1175. vsi->type, sec_name);
  1176. return -EINVAL;
  1177. }
  1178. type = btf__type_by_id(obj->btf, type_id);
  1179. tname = btf__name_by_offset(obj->btf, type->name_off);
  1180. if (!tname[0]) {
  1181. pr_warn("struct_ops init: anonymous type is not supported\n");
  1182. return -ENOTSUP;
  1183. }
  1184. if (!btf_is_struct(type)) {
  1185. pr_warn("struct_ops init: %s is not a struct\n", tname);
  1186. return -EINVAL;
  1187. }
  1188. map = bpf_object__add_map(obj);
  1189. if (IS_ERR(map))
  1190. return PTR_ERR(map);
  1191. map->sec_idx = shndx;
  1192. map->sec_offset = vsi->offset;
  1193. map->name = strdup(var_name);
  1194. if (!map->name)
  1195. return -ENOMEM;
  1196. map->btf_value_type_id = type_id;
  1197. /* Follow same convention as for programs autoload:
  1198. * SEC("?.struct_ops") means map is not created by default.
  1199. */
  1200. if (sec_name[0] == '?') {
  1201. map->autocreate = false;
  1202. /* from now on forget there was ? in section name */
  1203. sec_name++;
  1204. }
  1205. map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
  1206. map->def.key_size = sizeof(int);
  1207. map->def.value_size = type->size;
  1208. map->def.max_entries = 1;
  1209. map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
  1210. map->autoattach = true;
  1211. map->st_ops = calloc(1, sizeof(*map->st_ops));
  1212. if (!map->st_ops)
  1213. return -ENOMEM;
  1214. st_ops = map->st_ops;
  1215. st_ops->data = malloc(type->size);
  1216. st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
  1217. st_ops->kern_func_off = malloc(btf_vlen(type) *
  1218. sizeof(*st_ops->kern_func_off));
  1219. if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
  1220. return -ENOMEM;
  1221. if (vsi->offset + type->size > data->d_size) {
  1222. pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
  1223. var_name, sec_name);
  1224. return -EINVAL;
  1225. }
  1226. memcpy(st_ops->data,
  1227. data->d_buf + vsi->offset,
  1228. type->size);
  1229. st_ops->type_id = type_id;
  1230. pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
  1231. tname, type_id, var_name, vsi->offset);
  1232. }
  1233. return 0;
  1234. }
  1235. static int bpf_object_init_struct_ops(struct bpf_object *obj)
  1236. {
  1237. const char *sec_name;
  1238. int sec_idx, err;
  1239. for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
  1240. struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
  1241. if (desc->sec_type != SEC_ST_OPS)
  1242. continue;
  1243. sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
  1244. if (!sec_name)
  1245. return -LIBBPF_ERRNO__FORMAT;
  1246. err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
  1247. if (err)
  1248. return err;
  1249. }
  1250. return 0;
  1251. }
  1252. static struct bpf_object *bpf_object__new(const char *path,
  1253. const void *obj_buf,
  1254. size_t obj_buf_sz,
  1255. const char *obj_name)
  1256. {
  1257. struct bpf_object *obj;
  1258. char *end;
  1259. obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
  1260. if (!obj) {
  1261. pr_warn("alloc memory failed for %s\n", path);
  1262. return ERR_PTR(-ENOMEM);
  1263. }
  1264. strcpy(obj->path, path);
  1265. if (obj_name) {
  1266. libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
  1267. } else {
  1268. /* Using basename() GNU version which doesn't modify arg. */
  1269. libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
  1270. end = strchr(obj->name, '.');
  1271. if (end)
  1272. *end = 0;
  1273. }
  1274. obj->efile.fd = -1;
  1275. /*
  1276. * Caller of this function should also call
  1277. * bpf_object__elf_finish() after data collection to return
  1278. * obj_buf to user. If not, we should duplicate the buffer to
  1279. * avoid user freeing them before elf finish.
  1280. */
  1281. obj->efile.obj_buf = obj_buf;
  1282. obj->efile.obj_buf_sz = obj_buf_sz;
  1283. obj->efile.btf_maps_shndx = -1;
  1284. obj->kconfig_map_idx = -1;
  1285. obj->arena_map_idx = -1;
  1286. obj->kern_version = get_kernel_version();
  1287. obj->loaded = false;
  1288. return obj;
  1289. }
  1290. static void bpf_object__elf_finish(struct bpf_object *obj)
  1291. {
  1292. if (!obj->efile.elf)
  1293. return;
  1294. elf_end(obj->efile.elf);
  1295. obj->efile.elf = NULL;
  1296. obj->efile.symbols = NULL;
  1297. obj->efile.arena_data = NULL;
  1298. zfree(&obj->efile.secs);
  1299. obj->efile.sec_cnt = 0;
  1300. zclose(obj->efile.fd);
  1301. obj->efile.obj_buf = NULL;
  1302. obj->efile.obj_buf_sz = 0;
  1303. }
  1304. static int bpf_object__elf_init(struct bpf_object *obj)
  1305. {
  1306. Elf64_Ehdr *ehdr;
  1307. int err = 0;
  1308. Elf *elf;
  1309. if (obj->efile.elf) {
  1310. pr_warn("elf: init internal error\n");
  1311. return -LIBBPF_ERRNO__LIBELF;
  1312. }
  1313. if (obj->efile.obj_buf_sz > 0) {
  1314. /* obj_buf should have been validated by bpf_object__open_mem(). */
  1315. elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
  1316. } else {
  1317. obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
  1318. if (obj->efile.fd < 0) {
  1319. char errmsg[STRERR_BUFSIZE], *cp;
  1320. err = -errno;
  1321. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  1322. pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
  1323. return err;
  1324. }
  1325. elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
  1326. }
  1327. if (!elf) {
  1328. pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
  1329. err = -LIBBPF_ERRNO__LIBELF;
  1330. goto errout;
  1331. }
  1332. obj->efile.elf = elf;
  1333. if (elf_kind(elf) != ELF_K_ELF) {
  1334. err = -LIBBPF_ERRNO__FORMAT;
  1335. pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
  1336. goto errout;
  1337. }
  1338. if (gelf_getclass(elf) != ELFCLASS64) {
  1339. err = -LIBBPF_ERRNO__FORMAT;
  1340. pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
  1341. goto errout;
  1342. }
  1343. obj->efile.ehdr = ehdr = elf64_getehdr(elf);
  1344. if (!obj->efile.ehdr) {
  1345. pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
  1346. err = -LIBBPF_ERRNO__FORMAT;
  1347. goto errout;
  1348. }
  1349. if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
  1350. pr_warn("elf: failed to get section names section index for %s: %s\n",
  1351. obj->path, elf_errmsg(-1));
  1352. err = -LIBBPF_ERRNO__FORMAT;
  1353. goto errout;
  1354. }
  1355. /* ELF is corrupted/truncated, avoid calling elf_strptr. */
  1356. if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
  1357. pr_warn("elf: failed to get section names strings from %s: %s\n",
  1358. obj->path, elf_errmsg(-1));
  1359. err = -LIBBPF_ERRNO__FORMAT;
  1360. goto errout;
  1361. }
  1362. /* Old LLVM set e_machine to EM_NONE */
  1363. if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
  1364. pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
  1365. err = -LIBBPF_ERRNO__FORMAT;
  1366. goto errout;
  1367. }
  1368. return 0;
  1369. errout:
  1370. bpf_object__elf_finish(obj);
  1371. return err;
  1372. }
  1373. static int bpf_object__check_endianness(struct bpf_object *obj)
  1374. {
  1375. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  1376. if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
  1377. return 0;
  1378. #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  1379. if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
  1380. return 0;
  1381. #else
  1382. # error "Unrecognized __BYTE_ORDER__"
  1383. #endif
  1384. pr_warn("elf: endianness mismatch in %s.\n", obj->path);
  1385. return -LIBBPF_ERRNO__ENDIAN;
  1386. }
  1387. static int
  1388. bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
  1389. {
  1390. if (!data) {
  1391. pr_warn("invalid license section in %s\n", obj->path);
  1392. return -LIBBPF_ERRNO__FORMAT;
  1393. }
  1394. /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
  1395. * go over allowed ELF data section buffer
  1396. */
  1397. libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
  1398. pr_debug("license of %s is %s\n", obj->path, obj->license);
  1399. return 0;
  1400. }
  1401. static int
  1402. bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
  1403. {
  1404. __u32 kver;
  1405. if (!data || size != sizeof(kver)) {
  1406. pr_warn("invalid kver section in %s\n", obj->path);
  1407. return -LIBBPF_ERRNO__FORMAT;
  1408. }
  1409. memcpy(&kver, data, sizeof(kver));
  1410. obj->kern_version = kver;
  1411. pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
  1412. return 0;
  1413. }
  1414. static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
  1415. {
  1416. if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
  1417. type == BPF_MAP_TYPE_HASH_OF_MAPS)
  1418. return true;
  1419. return false;
  1420. }
  1421. static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
  1422. {
  1423. Elf_Data *data;
  1424. Elf_Scn *scn;
  1425. if (!name)
  1426. return -EINVAL;
  1427. scn = elf_sec_by_name(obj, name);
  1428. data = elf_sec_data(obj, scn);
  1429. if (data) {
  1430. *size = data->d_size;
  1431. return 0; /* found it */
  1432. }
  1433. return -ENOENT;
  1434. }
  1435. static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
  1436. {
  1437. Elf_Data *symbols = obj->efile.symbols;
  1438. const char *sname;
  1439. size_t si;
  1440. for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
  1441. Elf64_Sym *sym = elf_sym_by_idx(obj, si);
  1442. if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
  1443. continue;
  1444. if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
  1445. ELF64_ST_BIND(sym->st_info) != STB_WEAK)
  1446. continue;
  1447. sname = elf_sym_str(obj, sym->st_name);
  1448. if (!sname) {
  1449. pr_warn("failed to get sym name string for var %s\n", name);
  1450. return ERR_PTR(-EIO);
  1451. }
  1452. if (strcmp(name, sname) == 0)
  1453. return sym;
  1454. }
  1455. return ERR_PTR(-ENOENT);
  1456. }
  1457. /* Some versions of Android don't provide memfd_create() in their libc
  1458. * implementation, so avoid complications and just go straight to Linux
  1459. * syscall.
  1460. */
  1461. static int sys_memfd_create(const char *name, unsigned flags)
  1462. {
  1463. return syscall(__NR_memfd_create, name, flags);
  1464. }
  1465. #ifndef MFD_CLOEXEC
  1466. #define MFD_CLOEXEC 0x0001U
  1467. #endif
  1468. static int create_placeholder_fd(void)
  1469. {
  1470. int fd;
  1471. fd = ensure_good_fd(sys_memfd_create("libbpf-placeholder-fd", MFD_CLOEXEC));
  1472. if (fd < 0)
  1473. return -errno;
  1474. return fd;
  1475. }
  1476. static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
  1477. {
  1478. struct bpf_map *map;
  1479. int err;
  1480. err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
  1481. sizeof(*obj->maps), obj->nr_maps + 1);
  1482. if (err)
  1483. return ERR_PTR(err);
  1484. map = &obj->maps[obj->nr_maps++];
  1485. map->obj = obj;
  1486. /* Preallocate map FD without actually creating BPF map just yet.
  1487. * These map FD "placeholders" will be reused later without changing
  1488. * FD value when map is actually created in the kernel.
  1489. *
  1490. * This is useful to be able to perform BPF program relocations
  1491. * without having to create BPF maps before that step. This allows us
  1492. * to finalize and load BTF very late in BPF object's loading phase,
  1493. * right before BPF maps have to be created and BPF programs have to
  1494. * be loaded. By having these map FD placeholders we can perform all
  1495. * the sanitizations, relocations, and any other adjustments before we
  1496. * start creating actual BPF kernel objects (BTF, maps, progs).
  1497. */
  1498. map->fd = create_placeholder_fd();
  1499. if (map->fd < 0)
  1500. return ERR_PTR(map->fd);
  1501. map->inner_map_fd = -1;
  1502. map->autocreate = true;
  1503. return map;
  1504. }
  1505. static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
  1506. {
  1507. const long page_sz = sysconf(_SC_PAGE_SIZE);
  1508. size_t map_sz;
  1509. map_sz = (size_t)roundup(value_sz, 8) * max_entries;
  1510. map_sz = roundup(map_sz, page_sz);
  1511. return map_sz;
  1512. }
  1513. static size_t bpf_map_mmap_sz(const struct bpf_map *map)
  1514. {
  1515. const long page_sz = sysconf(_SC_PAGE_SIZE);
  1516. switch (map->def.type) {
  1517. case BPF_MAP_TYPE_ARRAY:
  1518. return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
  1519. case BPF_MAP_TYPE_ARENA:
  1520. return page_sz * map->def.max_entries;
  1521. default:
  1522. return 0; /* not supported */
  1523. }
  1524. }
  1525. static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
  1526. {
  1527. void *mmaped;
  1528. if (!map->mmaped)
  1529. return -EINVAL;
  1530. if (old_sz == new_sz)
  1531. return 0;
  1532. mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
  1533. if (mmaped == MAP_FAILED)
  1534. return -errno;
  1535. memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
  1536. munmap(map->mmaped, old_sz);
  1537. map->mmaped = mmaped;
  1538. return 0;
  1539. }
  1540. static char *internal_map_name(struct bpf_object *obj, const char *real_name)
  1541. {
  1542. char map_name[BPF_OBJ_NAME_LEN], *p;
  1543. int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
  1544. /* This is one of the more confusing parts of libbpf for various
  1545. * reasons, some of which are historical. The original idea for naming
  1546. * internal names was to include as much of BPF object name prefix as
  1547. * possible, so that it can be distinguished from similar internal
  1548. * maps of a different BPF object.
  1549. * As an example, let's say we have bpf_object named 'my_object_name'
  1550. * and internal map corresponding to '.rodata' ELF section. The final
  1551. * map name advertised to user and to the kernel will be
  1552. * 'my_objec.rodata', taking first 8 characters of object name and
  1553. * entire 7 characters of '.rodata'.
  1554. * Somewhat confusingly, if internal map ELF section name is shorter
  1555. * than 7 characters, e.g., '.bss', we still reserve 7 characters
  1556. * for the suffix, even though we only have 4 actual characters, and
  1557. * resulting map will be called 'my_objec.bss', not even using all 15
  1558. * characters allowed by the kernel. Oh well, at least the truncated
  1559. * object name is somewhat consistent in this case. But if the map
  1560. * name is '.kconfig', we'll still have entirety of '.kconfig' added
  1561. * (8 chars) and thus will be left with only first 7 characters of the
  1562. * object name ('my_obje'). Happy guessing, user, that the final map
  1563. * name will be "my_obje.kconfig".
  1564. * Now, with libbpf starting to support arbitrarily named .rodata.*
  1565. * and .data.* data sections, it's possible that ELF section name is
  1566. * longer than allowed 15 chars, so we now need to be careful to take
  1567. * only up to 15 first characters of ELF name, taking no BPF object
  1568. * name characters at all. So '.rodata.abracadabra' will result in
  1569. * '.rodata.abracad' kernel and user-visible name.
  1570. * We need to keep this convoluted logic intact for .data, .bss and
  1571. * .rodata maps, but for new custom .data.custom and .rodata.custom
  1572. * maps we use their ELF names as is, not prepending bpf_object name
  1573. * in front. We still need to truncate them to 15 characters for the
  1574. * kernel. Full name can be recovered for such maps by using DATASEC
  1575. * BTF type associated with such map's value type, though.
  1576. */
  1577. if (sfx_len >= BPF_OBJ_NAME_LEN)
  1578. sfx_len = BPF_OBJ_NAME_LEN - 1;
  1579. /* if there are two or more dots in map name, it's a custom dot map */
  1580. if (strchr(real_name + 1, '.') != NULL)
  1581. pfx_len = 0;
  1582. else
  1583. pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
  1584. snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
  1585. sfx_len, real_name);
  1586. /* sanities map name to characters allowed by kernel */
  1587. for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
  1588. if (!isalnum(*p) && *p != '_' && *p != '.')
  1589. *p = '_';
  1590. return strdup(map_name);
  1591. }
  1592. static int
  1593. map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
  1594. /* Internal BPF map is mmap()'able only if at least one of corresponding
  1595. * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
  1596. * variable and it's not marked as __hidden (which turns it into, effectively,
  1597. * a STATIC variable).
  1598. */
  1599. static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
  1600. {
  1601. const struct btf_type *t, *vt;
  1602. struct btf_var_secinfo *vsi;
  1603. int i, n;
  1604. if (!map->btf_value_type_id)
  1605. return false;
  1606. t = btf__type_by_id(obj->btf, map->btf_value_type_id);
  1607. if (!btf_is_datasec(t))
  1608. return false;
  1609. vsi = btf_var_secinfos(t);
  1610. for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
  1611. vt = btf__type_by_id(obj->btf, vsi->type);
  1612. if (!btf_is_var(vt))
  1613. continue;
  1614. if (btf_var(vt)->linkage != BTF_VAR_STATIC)
  1615. return true;
  1616. }
  1617. return false;
  1618. }
  1619. static int
  1620. bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
  1621. const char *real_name, int sec_idx, void *data, size_t data_sz)
  1622. {
  1623. struct bpf_map_def *def;
  1624. struct bpf_map *map;
  1625. size_t mmap_sz;
  1626. int err;
  1627. map = bpf_object__add_map(obj);
  1628. if (IS_ERR(map))
  1629. return PTR_ERR(map);
  1630. map->libbpf_type = type;
  1631. map->sec_idx = sec_idx;
  1632. map->sec_offset = 0;
  1633. map->real_name = strdup(real_name);
  1634. map->name = internal_map_name(obj, real_name);
  1635. if (!map->real_name || !map->name) {
  1636. zfree(&map->real_name);
  1637. zfree(&map->name);
  1638. return -ENOMEM;
  1639. }
  1640. def = &map->def;
  1641. def->type = BPF_MAP_TYPE_ARRAY;
  1642. def->key_size = sizeof(int);
  1643. def->value_size = data_sz;
  1644. def->max_entries = 1;
  1645. def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
  1646. ? BPF_F_RDONLY_PROG : 0;
  1647. /* failures are fine because of maps like .rodata.str1.1 */
  1648. (void) map_fill_btf_type_info(obj, map);
  1649. if (map_is_mmapable(obj, map))
  1650. def->map_flags |= BPF_F_MMAPABLE;
  1651. pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
  1652. map->name, map->sec_idx, map->sec_offset, def->map_flags);
  1653. mmap_sz = bpf_map_mmap_sz(map);
  1654. map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
  1655. MAP_SHARED | MAP_ANONYMOUS, -1, 0);
  1656. if (map->mmaped == MAP_FAILED) {
  1657. err = -errno;
  1658. map->mmaped = NULL;
  1659. pr_warn("failed to alloc map '%s' content buffer: %d\n",
  1660. map->name, err);
  1661. zfree(&map->real_name);
  1662. zfree(&map->name);
  1663. return err;
  1664. }
  1665. if (data)
  1666. memcpy(map->mmaped, data, data_sz);
  1667. pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
  1668. return 0;
  1669. }
  1670. static int bpf_object__init_global_data_maps(struct bpf_object *obj)
  1671. {
  1672. struct elf_sec_desc *sec_desc;
  1673. const char *sec_name;
  1674. int err = 0, sec_idx;
  1675. /*
  1676. * Populate obj->maps with libbpf internal maps.
  1677. */
  1678. for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
  1679. sec_desc = &obj->efile.secs[sec_idx];
  1680. /* Skip recognized sections with size 0. */
  1681. if (!sec_desc->data || sec_desc->data->d_size == 0)
  1682. continue;
  1683. switch (sec_desc->sec_type) {
  1684. case SEC_DATA:
  1685. sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
  1686. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
  1687. sec_name, sec_idx,
  1688. sec_desc->data->d_buf,
  1689. sec_desc->data->d_size);
  1690. break;
  1691. case SEC_RODATA:
  1692. obj->has_rodata = true;
  1693. sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
  1694. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
  1695. sec_name, sec_idx,
  1696. sec_desc->data->d_buf,
  1697. sec_desc->data->d_size);
  1698. break;
  1699. case SEC_BSS:
  1700. sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
  1701. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
  1702. sec_name, sec_idx,
  1703. NULL,
  1704. sec_desc->data->d_size);
  1705. break;
  1706. default:
  1707. /* skip */
  1708. break;
  1709. }
  1710. if (err)
  1711. return err;
  1712. }
  1713. return 0;
  1714. }
  1715. static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
  1716. const void *name)
  1717. {
  1718. int i;
  1719. for (i = 0; i < obj->nr_extern; i++) {
  1720. if (strcmp(obj->externs[i].name, name) == 0)
  1721. return &obj->externs[i];
  1722. }
  1723. return NULL;
  1724. }
  1725. static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
  1726. const void *name, int len)
  1727. {
  1728. const char *ext_name;
  1729. int i;
  1730. for (i = 0; i < obj->nr_extern; i++) {
  1731. ext_name = obj->externs[i].name;
  1732. if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
  1733. return &obj->externs[i];
  1734. }
  1735. return NULL;
  1736. }
  1737. static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
  1738. char value)
  1739. {
  1740. switch (ext->kcfg.type) {
  1741. case KCFG_BOOL:
  1742. if (value == 'm') {
  1743. pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
  1744. ext->name, value);
  1745. return -EINVAL;
  1746. }
  1747. *(bool *)ext_val = value == 'y' ? true : false;
  1748. break;
  1749. case KCFG_TRISTATE:
  1750. if (value == 'y')
  1751. *(enum libbpf_tristate *)ext_val = TRI_YES;
  1752. else if (value == 'm')
  1753. *(enum libbpf_tristate *)ext_val = TRI_MODULE;
  1754. else /* value == 'n' */
  1755. *(enum libbpf_tristate *)ext_val = TRI_NO;
  1756. break;
  1757. case KCFG_CHAR:
  1758. *(char *)ext_val = value;
  1759. break;
  1760. case KCFG_UNKNOWN:
  1761. case KCFG_INT:
  1762. case KCFG_CHAR_ARR:
  1763. default:
  1764. pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
  1765. ext->name, value);
  1766. return -EINVAL;
  1767. }
  1768. ext->is_set = true;
  1769. return 0;
  1770. }
  1771. static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
  1772. const char *value)
  1773. {
  1774. size_t len;
  1775. if (ext->kcfg.type != KCFG_CHAR_ARR) {
  1776. pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
  1777. ext->name, value);
  1778. return -EINVAL;
  1779. }
  1780. len = strlen(value);
  1781. if (len < 2 || value[len - 1] != '"') {
  1782. pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
  1783. ext->name, value);
  1784. return -EINVAL;
  1785. }
  1786. /* strip quotes */
  1787. len -= 2;
  1788. if (len >= ext->kcfg.sz) {
  1789. pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
  1790. ext->name, value, len, ext->kcfg.sz - 1);
  1791. len = ext->kcfg.sz - 1;
  1792. }
  1793. memcpy(ext_val, value + 1, len);
  1794. ext_val[len] = '\0';
  1795. ext->is_set = true;
  1796. return 0;
  1797. }
  1798. static int parse_u64(const char *value, __u64 *res)
  1799. {
  1800. char *value_end;
  1801. int err;
  1802. errno = 0;
  1803. *res = strtoull(value, &value_end, 0);
  1804. if (errno) {
  1805. err = -errno;
  1806. pr_warn("failed to parse '%s' as integer: %d\n", value, err);
  1807. return err;
  1808. }
  1809. if (*value_end) {
  1810. pr_warn("failed to parse '%s' as integer completely\n", value);
  1811. return -EINVAL;
  1812. }
  1813. return 0;
  1814. }
  1815. static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
  1816. {
  1817. int bit_sz = ext->kcfg.sz * 8;
  1818. if (ext->kcfg.sz == 8)
  1819. return true;
  1820. /* Validate that value stored in u64 fits in integer of `ext->sz`
  1821. * bytes size without any loss of information. If the target integer
  1822. * is signed, we rely on the following limits of integer type of
  1823. * Y bits and subsequent transformation:
  1824. *
  1825. * -2^(Y-1) <= X <= 2^(Y-1) - 1
  1826. * 0 <= X + 2^(Y-1) <= 2^Y - 1
  1827. * 0 <= X + 2^(Y-1) < 2^Y
  1828. *
  1829. * For unsigned target integer, check that all the (64 - Y) bits are
  1830. * zero.
  1831. */
  1832. if (ext->kcfg.is_signed)
  1833. return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
  1834. else
  1835. return (v >> bit_sz) == 0;
  1836. }
  1837. static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
  1838. __u64 value)
  1839. {
  1840. if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
  1841. ext->kcfg.type != KCFG_BOOL) {
  1842. pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
  1843. ext->name, (unsigned long long)value);
  1844. return -EINVAL;
  1845. }
  1846. if (ext->kcfg.type == KCFG_BOOL && value > 1) {
  1847. pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
  1848. ext->name, (unsigned long long)value);
  1849. return -EINVAL;
  1850. }
  1851. if (!is_kcfg_value_in_range(ext, value)) {
  1852. pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
  1853. ext->name, (unsigned long long)value, ext->kcfg.sz);
  1854. return -ERANGE;
  1855. }
  1856. switch (ext->kcfg.sz) {
  1857. case 1:
  1858. *(__u8 *)ext_val = value;
  1859. break;
  1860. case 2:
  1861. *(__u16 *)ext_val = value;
  1862. break;
  1863. case 4:
  1864. *(__u32 *)ext_val = value;
  1865. break;
  1866. case 8:
  1867. *(__u64 *)ext_val = value;
  1868. break;
  1869. default:
  1870. return -EINVAL;
  1871. }
  1872. ext->is_set = true;
  1873. return 0;
  1874. }
  1875. static int bpf_object__process_kconfig_line(struct bpf_object *obj,
  1876. char *buf, void *data)
  1877. {
  1878. struct extern_desc *ext;
  1879. char *sep, *value;
  1880. int len, err = 0;
  1881. void *ext_val;
  1882. __u64 num;
  1883. if (!str_has_pfx(buf, "CONFIG_"))
  1884. return 0;
  1885. sep = strchr(buf, '=');
  1886. if (!sep) {
  1887. pr_warn("failed to parse '%s': no separator\n", buf);
  1888. return -EINVAL;
  1889. }
  1890. /* Trim ending '\n' */
  1891. len = strlen(buf);
  1892. if (buf[len - 1] == '\n')
  1893. buf[len - 1] = '\0';
  1894. /* Split on '=' and ensure that a value is present. */
  1895. *sep = '\0';
  1896. if (!sep[1]) {
  1897. *sep = '=';
  1898. pr_warn("failed to parse '%s': no value\n", buf);
  1899. return -EINVAL;
  1900. }
  1901. ext = find_extern_by_name(obj, buf);
  1902. if (!ext || ext->is_set)
  1903. return 0;
  1904. ext_val = data + ext->kcfg.data_off;
  1905. value = sep + 1;
  1906. switch (*value) {
  1907. case 'y': case 'n': case 'm':
  1908. err = set_kcfg_value_tri(ext, ext_val, *value);
  1909. break;
  1910. case '"':
  1911. err = set_kcfg_value_str(ext, ext_val, value);
  1912. break;
  1913. default:
  1914. /* assume integer */
  1915. err = parse_u64(value, &num);
  1916. if (err) {
  1917. pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
  1918. return err;
  1919. }
  1920. if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
  1921. pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
  1922. return -EINVAL;
  1923. }
  1924. err = set_kcfg_value_num(ext, ext_val, num);
  1925. break;
  1926. }
  1927. if (err)
  1928. return err;
  1929. pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
  1930. return 0;
  1931. }
  1932. static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
  1933. {
  1934. char buf[PATH_MAX];
  1935. struct utsname uts;
  1936. int len, err = 0;
  1937. gzFile file;
  1938. uname(&uts);
  1939. len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
  1940. if (len < 0)
  1941. return -EINVAL;
  1942. else if (len >= PATH_MAX)
  1943. return -ENAMETOOLONG;
  1944. /* gzopen also accepts uncompressed files. */
  1945. file = gzopen(buf, "re");
  1946. if (!file)
  1947. file = gzopen("/proc/config.gz", "re");
  1948. if (!file) {
  1949. pr_warn("failed to open system Kconfig\n");
  1950. return -ENOENT;
  1951. }
  1952. while (gzgets(file, buf, sizeof(buf))) {
  1953. err = bpf_object__process_kconfig_line(obj, buf, data);
  1954. if (err) {
  1955. pr_warn("error parsing system Kconfig line '%s': %d\n",
  1956. buf, err);
  1957. goto out;
  1958. }
  1959. }
  1960. out:
  1961. gzclose(file);
  1962. return err;
  1963. }
  1964. static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
  1965. const char *config, void *data)
  1966. {
  1967. char buf[PATH_MAX];
  1968. int err = 0;
  1969. FILE *file;
  1970. file = fmemopen((void *)config, strlen(config), "r");
  1971. if (!file) {
  1972. err = -errno;
  1973. pr_warn("failed to open in-memory Kconfig: %d\n", err);
  1974. return err;
  1975. }
  1976. while (fgets(buf, sizeof(buf), file)) {
  1977. err = bpf_object__process_kconfig_line(obj, buf, data);
  1978. if (err) {
  1979. pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
  1980. buf, err);
  1981. break;
  1982. }
  1983. }
  1984. fclose(file);
  1985. return err;
  1986. }
  1987. static int bpf_object__init_kconfig_map(struct bpf_object *obj)
  1988. {
  1989. struct extern_desc *last_ext = NULL, *ext;
  1990. size_t map_sz;
  1991. int i, err;
  1992. for (i = 0; i < obj->nr_extern; i++) {
  1993. ext = &obj->externs[i];
  1994. if (ext->type == EXT_KCFG)
  1995. last_ext = ext;
  1996. }
  1997. if (!last_ext)
  1998. return 0;
  1999. map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
  2000. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
  2001. ".kconfig", obj->efile.symbols_shndx,
  2002. NULL, map_sz);
  2003. if (err)
  2004. return err;
  2005. obj->kconfig_map_idx = obj->nr_maps - 1;
  2006. return 0;
  2007. }
  2008. const struct btf_type *
  2009. skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
  2010. {
  2011. const struct btf_type *t = btf__type_by_id(btf, id);
  2012. if (res_id)
  2013. *res_id = id;
  2014. while (btf_is_mod(t) || btf_is_typedef(t)) {
  2015. if (res_id)
  2016. *res_id = t->type;
  2017. t = btf__type_by_id(btf, t->type);
  2018. }
  2019. return t;
  2020. }
  2021. static const struct btf_type *
  2022. resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
  2023. {
  2024. const struct btf_type *t;
  2025. t = skip_mods_and_typedefs(btf, id, NULL);
  2026. if (!btf_is_ptr(t))
  2027. return NULL;
  2028. t = skip_mods_and_typedefs(btf, t->type, res_id);
  2029. return btf_is_func_proto(t) ? t : NULL;
  2030. }
  2031. static const char *__btf_kind_str(__u16 kind)
  2032. {
  2033. switch (kind) {
  2034. case BTF_KIND_UNKN: return "void";
  2035. case BTF_KIND_INT: return "int";
  2036. case BTF_KIND_PTR: return "ptr";
  2037. case BTF_KIND_ARRAY: return "array";
  2038. case BTF_KIND_STRUCT: return "struct";
  2039. case BTF_KIND_UNION: return "union";
  2040. case BTF_KIND_ENUM: return "enum";
  2041. case BTF_KIND_FWD: return "fwd";
  2042. case BTF_KIND_TYPEDEF: return "typedef";
  2043. case BTF_KIND_VOLATILE: return "volatile";
  2044. case BTF_KIND_CONST: return "const";
  2045. case BTF_KIND_RESTRICT: return "restrict";
  2046. case BTF_KIND_FUNC: return "func";
  2047. case BTF_KIND_FUNC_PROTO: return "func_proto";
  2048. case BTF_KIND_VAR: return "var";
  2049. case BTF_KIND_DATASEC: return "datasec";
  2050. case BTF_KIND_FLOAT: return "float";
  2051. case BTF_KIND_DECL_TAG: return "decl_tag";
  2052. case BTF_KIND_TYPE_TAG: return "type_tag";
  2053. case BTF_KIND_ENUM64: return "enum64";
  2054. default: return "unknown";
  2055. }
  2056. }
  2057. const char *btf_kind_str(const struct btf_type *t)
  2058. {
  2059. return __btf_kind_str(btf_kind(t));
  2060. }
  2061. /*
  2062. * Fetch integer attribute of BTF map definition. Such attributes are
  2063. * represented using a pointer to an array, in which dimensionality of array
  2064. * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
  2065. * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
  2066. * type definition, while using only sizeof(void *) space in ELF data section.
  2067. */
  2068. static bool get_map_field_int(const char *map_name, const struct btf *btf,
  2069. const struct btf_member *m, __u32 *res)
  2070. {
  2071. const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
  2072. const char *name = btf__name_by_offset(btf, m->name_off);
  2073. const struct btf_array *arr_info;
  2074. const struct btf_type *arr_t;
  2075. if (!btf_is_ptr(t)) {
  2076. pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
  2077. map_name, name, btf_kind_str(t));
  2078. return false;
  2079. }
  2080. arr_t = btf__type_by_id(btf, t->type);
  2081. if (!arr_t) {
  2082. pr_warn("map '%s': attr '%s': type [%u] not found.\n",
  2083. map_name, name, t->type);
  2084. return false;
  2085. }
  2086. if (!btf_is_array(arr_t)) {
  2087. pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
  2088. map_name, name, btf_kind_str(arr_t));
  2089. return false;
  2090. }
  2091. arr_info = btf_array(arr_t);
  2092. *res = arr_info->nelems;
  2093. return true;
  2094. }
  2095. static bool get_map_field_long(const char *map_name, const struct btf *btf,
  2096. const struct btf_member *m, __u64 *res)
  2097. {
  2098. const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
  2099. const char *name = btf__name_by_offset(btf, m->name_off);
  2100. if (btf_is_ptr(t)) {
  2101. __u32 res32;
  2102. bool ret;
  2103. ret = get_map_field_int(map_name, btf, m, &res32);
  2104. if (ret)
  2105. *res = (__u64)res32;
  2106. return ret;
  2107. }
  2108. if (!btf_is_enum(t) && !btf_is_enum64(t)) {
  2109. pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
  2110. map_name, name, btf_kind_str(t));
  2111. return false;
  2112. }
  2113. if (btf_vlen(t) != 1) {
  2114. pr_warn("map '%s': attr '%s': invalid __ulong\n",
  2115. map_name, name);
  2116. return false;
  2117. }
  2118. if (btf_is_enum(t)) {
  2119. const struct btf_enum *e = btf_enum(t);
  2120. *res = e->val;
  2121. } else {
  2122. const struct btf_enum64 *e = btf_enum64(t);
  2123. *res = btf_enum64_value(e);
  2124. }
  2125. return true;
  2126. }
  2127. static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
  2128. {
  2129. int len;
  2130. len = snprintf(buf, buf_sz, "%s/%s", path, name);
  2131. if (len < 0)
  2132. return -EINVAL;
  2133. if (len >= buf_sz)
  2134. return -ENAMETOOLONG;
  2135. return 0;
  2136. }
  2137. static int build_map_pin_path(struct bpf_map *map, const char *path)
  2138. {
  2139. char buf[PATH_MAX];
  2140. int err;
  2141. if (!path)
  2142. path = BPF_FS_DEFAULT_PATH;
  2143. err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
  2144. if (err)
  2145. return err;
  2146. return bpf_map__set_pin_path(map, buf);
  2147. }
  2148. /* should match definition in bpf_helpers.h */
  2149. enum libbpf_pin_type {
  2150. LIBBPF_PIN_NONE,
  2151. /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
  2152. LIBBPF_PIN_BY_NAME,
  2153. };
  2154. int parse_btf_map_def(const char *map_name, struct btf *btf,
  2155. const struct btf_type *def_t, bool strict,
  2156. struct btf_map_def *map_def, struct btf_map_def *inner_def)
  2157. {
  2158. const struct btf_type *t;
  2159. const struct btf_member *m;
  2160. bool is_inner = inner_def == NULL;
  2161. int vlen, i;
  2162. vlen = btf_vlen(def_t);
  2163. m = btf_members(def_t);
  2164. for (i = 0; i < vlen; i++, m++) {
  2165. const char *name = btf__name_by_offset(btf, m->name_off);
  2166. if (!name) {
  2167. pr_warn("map '%s': invalid field #%d.\n", map_name, i);
  2168. return -EINVAL;
  2169. }
  2170. if (strcmp(name, "type") == 0) {
  2171. if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
  2172. return -EINVAL;
  2173. map_def->parts |= MAP_DEF_MAP_TYPE;
  2174. } else if (strcmp(name, "max_entries") == 0) {
  2175. if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
  2176. return -EINVAL;
  2177. map_def->parts |= MAP_DEF_MAX_ENTRIES;
  2178. } else if (strcmp(name, "map_flags") == 0) {
  2179. if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
  2180. return -EINVAL;
  2181. map_def->parts |= MAP_DEF_MAP_FLAGS;
  2182. } else if (strcmp(name, "numa_node") == 0) {
  2183. if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
  2184. return -EINVAL;
  2185. map_def->parts |= MAP_DEF_NUMA_NODE;
  2186. } else if (strcmp(name, "key_size") == 0) {
  2187. __u32 sz;
  2188. if (!get_map_field_int(map_name, btf, m, &sz))
  2189. return -EINVAL;
  2190. if (map_def->key_size && map_def->key_size != sz) {
  2191. pr_warn("map '%s': conflicting key size %u != %u.\n",
  2192. map_name, map_def->key_size, sz);
  2193. return -EINVAL;
  2194. }
  2195. map_def->key_size = sz;
  2196. map_def->parts |= MAP_DEF_KEY_SIZE;
  2197. } else if (strcmp(name, "key") == 0) {
  2198. __s64 sz;
  2199. t = btf__type_by_id(btf, m->type);
  2200. if (!t) {
  2201. pr_warn("map '%s': key type [%d] not found.\n",
  2202. map_name, m->type);
  2203. return -EINVAL;
  2204. }
  2205. if (!btf_is_ptr(t)) {
  2206. pr_warn("map '%s': key spec is not PTR: %s.\n",
  2207. map_name, btf_kind_str(t));
  2208. return -EINVAL;
  2209. }
  2210. sz = btf__resolve_size(btf, t->type);
  2211. if (sz < 0) {
  2212. pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
  2213. map_name, t->type, (ssize_t)sz);
  2214. return sz;
  2215. }
  2216. if (map_def->key_size && map_def->key_size != sz) {
  2217. pr_warn("map '%s': conflicting key size %u != %zd.\n",
  2218. map_name, map_def->key_size, (ssize_t)sz);
  2219. return -EINVAL;
  2220. }
  2221. map_def->key_size = sz;
  2222. map_def->key_type_id = t->type;
  2223. map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
  2224. } else if (strcmp(name, "value_size") == 0) {
  2225. __u32 sz;
  2226. if (!get_map_field_int(map_name, btf, m, &sz))
  2227. return -EINVAL;
  2228. if (map_def->value_size && map_def->value_size != sz) {
  2229. pr_warn("map '%s': conflicting value size %u != %u.\n",
  2230. map_name, map_def->value_size, sz);
  2231. return -EINVAL;
  2232. }
  2233. map_def->value_size = sz;
  2234. map_def->parts |= MAP_DEF_VALUE_SIZE;
  2235. } else if (strcmp(name, "value") == 0) {
  2236. __s64 sz;
  2237. t = btf__type_by_id(btf, m->type);
  2238. if (!t) {
  2239. pr_warn("map '%s': value type [%d] not found.\n",
  2240. map_name, m->type);
  2241. return -EINVAL;
  2242. }
  2243. if (!btf_is_ptr(t)) {
  2244. pr_warn("map '%s': value spec is not PTR: %s.\n",
  2245. map_name, btf_kind_str(t));
  2246. return -EINVAL;
  2247. }
  2248. sz = btf__resolve_size(btf, t->type);
  2249. if (sz < 0) {
  2250. pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
  2251. map_name, t->type, (ssize_t)sz);
  2252. return sz;
  2253. }
  2254. if (map_def->value_size && map_def->value_size != sz) {
  2255. pr_warn("map '%s': conflicting value size %u != %zd.\n",
  2256. map_name, map_def->value_size, (ssize_t)sz);
  2257. return -EINVAL;
  2258. }
  2259. map_def->value_size = sz;
  2260. map_def->value_type_id = t->type;
  2261. map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
  2262. }
  2263. else if (strcmp(name, "values") == 0) {
  2264. bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
  2265. bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
  2266. const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
  2267. char inner_map_name[128];
  2268. int err;
  2269. if (is_inner) {
  2270. pr_warn("map '%s': multi-level inner maps not supported.\n",
  2271. map_name);
  2272. return -ENOTSUP;
  2273. }
  2274. if (i != vlen - 1) {
  2275. pr_warn("map '%s': '%s' member should be last.\n",
  2276. map_name, name);
  2277. return -EINVAL;
  2278. }
  2279. if (!is_map_in_map && !is_prog_array) {
  2280. pr_warn("map '%s': should be map-in-map or prog-array.\n",
  2281. map_name);
  2282. return -ENOTSUP;
  2283. }
  2284. if (map_def->value_size && map_def->value_size != 4) {
  2285. pr_warn("map '%s': conflicting value size %u != 4.\n",
  2286. map_name, map_def->value_size);
  2287. return -EINVAL;
  2288. }
  2289. map_def->value_size = 4;
  2290. t = btf__type_by_id(btf, m->type);
  2291. if (!t) {
  2292. pr_warn("map '%s': %s type [%d] not found.\n",
  2293. map_name, desc, m->type);
  2294. return -EINVAL;
  2295. }
  2296. if (!btf_is_array(t) || btf_array(t)->nelems) {
  2297. pr_warn("map '%s': %s spec is not a zero-sized array.\n",
  2298. map_name, desc);
  2299. return -EINVAL;
  2300. }
  2301. t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
  2302. if (!btf_is_ptr(t)) {
  2303. pr_warn("map '%s': %s def is of unexpected kind %s.\n",
  2304. map_name, desc, btf_kind_str(t));
  2305. return -EINVAL;
  2306. }
  2307. t = skip_mods_and_typedefs(btf, t->type, NULL);
  2308. if (is_prog_array) {
  2309. if (!btf_is_func_proto(t)) {
  2310. pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
  2311. map_name, btf_kind_str(t));
  2312. return -EINVAL;
  2313. }
  2314. continue;
  2315. }
  2316. if (!btf_is_struct(t)) {
  2317. pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
  2318. map_name, btf_kind_str(t));
  2319. return -EINVAL;
  2320. }
  2321. snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
  2322. err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
  2323. if (err)
  2324. return err;
  2325. map_def->parts |= MAP_DEF_INNER_MAP;
  2326. } else if (strcmp(name, "pinning") == 0) {
  2327. __u32 val;
  2328. if (is_inner) {
  2329. pr_warn("map '%s': inner def can't be pinned.\n", map_name);
  2330. return -EINVAL;
  2331. }
  2332. if (!get_map_field_int(map_name, btf, m, &val))
  2333. return -EINVAL;
  2334. if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
  2335. pr_warn("map '%s': invalid pinning value %u.\n",
  2336. map_name, val);
  2337. return -EINVAL;
  2338. }
  2339. map_def->pinning = val;
  2340. map_def->parts |= MAP_DEF_PINNING;
  2341. } else if (strcmp(name, "map_extra") == 0) {
  2342. __u64 map_extra;
  2343. if (!get_map_field_long(map_name, btf, m, &map_extra))
  2344. return -EINVAL;
  2345. map_def->map_extra = map_extra;
  2346. map_def->parts |= MAP_DEF_MAP_EXTRA;
  2347. } else {
  2348. if (strict) {
  2349. pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
  2350. return -ENOTSUP;
  2351. }
  2352. pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
  2353. }
  2354. }
  2355. if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
  2356. pr_warn("map '%s': map type isn't specified.\n", map_name);
  2357. return -EINVAL;
  2358. }
  2359. return 0;
  2360. }
  2361. static size_t adjust_ringbuf_sz(size_t sz)
  2362. {
  2363. __u32 page_sz = sysconf(_SC_PAGE_SIZE);
  2364. __u32 mul;
  2365. /* if user forgot to set any size, make sure they see error */
  2366. if (sz == 0)
  2367. return 0;
  2368. /* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
  2369. * a power-of-2 multiple of kernel's page size. If user diligently
  2370. * satisified these conditions, pass the size through.
  2371. */
  2372. if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
  2373. return sz;
  2374. /* Otherwise find closest (page_sz * power_of_2) product bigger than
  2375. * user-set size to satisfy both user size request and kernel
  2376. * requirements and substitute correct max_entries for map creation.
  2377. */
  2378. for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
  2379. if (mul * page_sz > sz)
  2380. return mul * page_sz;
  2381. }
  2382. /* if it's impossible to satisfy the conditions (i.e., user size is
  2383. * very close to UINT_MAX but is not a power-of-2 multiple of
  2384. * page_size) then just return original size and let kernel reject it
  2385. */
  2386. return sz;
  2387. }
  2388. static bool map_is_ringbuf(const struct bpf_map *map)
  2389. {
  2390. return map->def.type == BPF_MAP_TYPE_RINGBUF ||
  2391. map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
  2392. }
  2393. static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
  2394. {
  2395. map->def.type = def->map_type;
  2396. map->def.key_size = def->key_size;
  2397. map->def.value_size = def->value_size;
  2398. map->def.max_entries = def->max_entries;
  2399. map->def.map_flags = def->map_flags;
  2400. map->map_extra = def->map_extra;
  2401. map->numa_node = def->numa_node;
  2402. map->btf_key_type_id = def->key_type_id;
  2403. map->btf_value_type_id = def->value_type_id;
  2404. /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
  2405. if (map_is_ringbuf(map))
  2406. map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
  2407. if (def->parts & MAP_DEF_MAP_TYPE)
  2408. pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
  2409. if (def->parts & MAP_DEF_KEY_TYPE)
  2410. pr_debug("map '%s': found key [%u], sz = %u.\n",
  2411. map->name, def->key_type_id, def->key_size);
  2412. else if (def->parts & MAP_DEF_KEY_SIZE)
  2413. pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
  2414. if (def->parts & MAP_DEF_VALUE_TYPE)
  2415. pr_debug("map '%s': found value [%u], sz = %u.\n",
  2416. map->name, def->value_type_id, def->value_size);
  2417. else if (def->parts & MAP_DEF_VALUE_SIZE)
  2418. pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
  2419. if (def->parts & MAP_DEF_MAX_ENTRIES)
  2420. pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
  2421. if (def->parts & MAP_DEF_MAP_FLAGS)
  2422. pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
  2423. if (def->parts & MAP_DEF_MAP_EXTRA)
  2424. pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
  2425. (unsigned long long)def->map_extra);
  2426. if (def->parts & MAP_DEF_PINNING)
  2427. pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
  2428. if (def->parts & MAP_DEF_NUMA_NODE)
  2429. pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
  2430. if (def->parts & MAP_DEF_INNER_MAP)
  2431. pr_debug("map '%s': found inner map definition.\n", map->name);
  2432. }
  2433. static const char *btf_var_linkage_str(__u32 linkage)
  2434. {
  2435. switch (linkage) {
  2436. case BTF_VAR_STATIC: return "static";
  2437. case BTF_VAR_GLOBAL_ALLOCATED: return "global";
  2438. case BTF_VAR_GLOBAL_EXTERN: return "extern";
  2439. default: return "unknown";
  2440. }
  2441. }
  2442. static int bpf_object__init_user_btf_map(struct bpf_object *obj,
  2443. const struct btf_type *sec,
  2444. int var_idx, int sec_idx,
  2445. const Elf_Data *data, bool strict,
  2446. const char *pin_root_path)
  2447. {
  2448. struct btf_map_def map_def = {}, inner_def = {};
  2449. const struct btf_type *var, *def;
  2450. const struct btf_var_secinfo *vi;
  2451. const struct btf_var *var_extra;
  2452. const char *map_name;
  2453. struct bpf_map *map;
  2454. int err;
  2455. vi = btf_var_secinfos(sec) + var_idx;
  2456. var = btf__type_by_id(obj->btf, vi->type);
  2457. var_extra = btf_var(var);
  2458. map_name = btf__name_by_offset(obj->btf, var->name_off);
  2459. if (map_name == NULL || map_name[0] == '\0') {
  2460. pr_warn("map #%d: empty name.\n", var_idx);
  2461. return -EINVAL;
  2462. }
  2463. if ((__u64)vi->offset + vi->size > data->d_size) {
  2464. pr_warn("map '%s' BTF data is corrupted.\n", map_name);
  2465. return -EINVAL;
  2466. }
  2467. if (!btf_is_var(var)) {
  2468. pr_warn("map '%s': unexpected var kind %s.\n",
  2469. map_name, btf_kind_str(var));
  2470. return -EINVAL;
  2471. }
  2472. if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
  2473. pr_warn("map '%s': unsupported map linkage %s.\n",
  2474. map_name, btf_var_linkage_str(var_extra->linkage));
  2475. return -EOPNOTSUPP;
  2476. }
  2477. def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
  2478. if (!btf_is_struct(def)) {
  2479. pr_warn("map '%s': unexpected def kind %s.\n",
  2480. map_name, btf_kind_str(var));
  2481. return -EINVAL;
  2482. }
  2483. if (def->size > vi->size) {
  2484. pr_warn("map '%s': invalid def size.\n", map_name);
  2485. return -EINVAL;
  2486. }
  2487. map = bpf_object__add_map(obj);
  2488. if (IS_ERR(map))
  2489. return PTR_ERR(map);
  2490. map->name = strdup(map_name);
  2491. if (!map->name) {
  2492. pr_warn("map '%s': failed to alloc map name.\n", map_name);
  2493. return -ENOMEM;
  2494. }
  2495. map->libbpf_type = LIBBPF_MAP_UNSPEC;
  2496. map->def.type = BPF_MAP_TYPE_UNSPEC;
  2497. map->sec_idx = sec_idx;
  2498. map->sec_offset = vi->offset;
  2499. map->btf_var_idx = var_idx;
  2500. pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
  2501. map_name, map->sec_idx, map->sec_offset);
  2502. err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
  2503. if (err)
  2504. return err;
  2505. fill_map_from_def(map, &map_def);
  2506. if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
  2507. err = build_map_pin_path(map, pin_root_path);
  2508. if (err) {
  2509. pr_warn("map '%s': couldn't build pin path.\n", map->name);
  2510. return err;
  2511. }
  2512. }
  2513. if (map_def.parts & MAP_DEF_INNER_MAP) {
  2514. map->inner_map = calloc(1, sizeof(*map->inner_map));
  2515. if (!map->inner_map)
  2516. return -ENOMEM;
  2517. map->inner_map->fd = create_placeholder_fd();
  2518. if (map->inner_map->fd < 0)
  2519. return map->inner_map->fd;
  2520. map->inner_map->sec_idx = sec_idx;
  2521. map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
  2522. if (!map->inner_map->name)
  2523. return -ENOMEM;
  2524. sprintf(map->inner_map->name, "%s.inner", map_name);
  2525. fill_map_from_def(map->inner_map, &inner_def);
  2526. }
  2527. err = map_fill_btf_type_info(obj, map);
  2528. if (err)
  2529. return err;
  2530. return 0;
  2531. }
  2532. static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
  2533. const char *sec_name, int sec_idx,
  2534. void *data, size_t data_sz)
  2535. {
  2536. const long page_sz = sysconf(_SC_PAGE_SIZE);
  2537. size_t mmap_sz;
  2538. mmap_sz = bpf_map_mmap_sz(map);
  2539. if (roundup(data_sz, page_sz) > mmap_sz) {
  2540. pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
  2541. sec_name, mmap_sz, data_sz);
  2542. return -E2BIG;
  2543. }
  2544. obj->arena_data = malloc(data_sz);
  2545. if (!obj->arena_data)
  2546. return -ENOMEM;
  2547. memcpy(obj->arena_data, data, data_sz);
  2548. obj->arena_data_sz = data_sz;
  2549. /* make bpf_map__init_value() work for ARENA maps */
  2550. map->mmaped = obj->arena_data;
  2551. return 0;
  2552. }
  2553. static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
  2554. const char *pin_root_path)
  2555. {
  2556. const struct btf_type *sec = NULL;
  2557. int nr_types, i, vlen, err;
  2558. const struct btf_type *t;
  2559. const char *name;
  2560. Elf_Data *data;
  2561. Elf_Scn *scn;
  2562. if (obj->efile.btf_maps_shndx < 0)
  2563. return 0;
  2564. scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
  2565. data = elf_sec_data(obj, scn);
  2566. if (!scn || !data) {
  2567. pr_warn("elf: failed to get %s map definitions for %s\n",
  2568. MAPS_ELF_SEC, obj->path);
  2569. return -EINVAL;
  2570. }
  2571. nr_types = btf__type_cnt(obj->btf);
  2572. for (i = 1; i < nr_types; i++) {
  2573. t = btf__type_by_id(obj->btf, i);
  2574. if (!btf_is_datasec(t))
  2575. continue;
  2576. name = btf__name_by_offset(obj->btf, t->name_off);
  2577. if (strcmp(name, MAPS_ELF_SEC) == 0) {
  2578. sec = t;
  2579. obj->efile.btf_maps_sec_btf_id = i;
  2580. break;
  2581. }
  2582. }
  2583. if (!sec) {
  2584. pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
  2585. return -ENOENT;
  2586. }
  2587. vlen = btf_vlen(sec);
  2588. for (i = 0; i < vlen; i++) {
  2589. err = bpf_object__init_user_btf_map(obj, sec, i,
  2590. obj->efile.btf_maps_shndx,
  2591. data, strict,
  2592. pin_root_path);
  2593. if (err)
  2594. return err;
  2595. }
  2596. for (i = 0; i < obj->nr_maps; i++) {
  2597. struct bpf_map *map = &obj->maps[i];
  2598. if (map->def.type != BPF_MAP_TYPE_ARENA)
  2599. continue;
  2600. if (obj->arena_map_idx >= 0) {
  2601. pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
  2602. map->name, obj->maps[obj->arena_map_idx].name);
  2603. return -EINVAL;
  2604. }
  2605. obj->arena_map_idx = i;
  2606. if (obj->efile.arena_data) {
  2607. err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
  2608. obj->efile.arena_data->d_buf,
  2609. obj->efile.arena_data->d_size);
  2610. if (err)
  2611. return err;
  2612. }
  2613. }
  2614. if (obj->efile.arena_data && obj->arena_map_idx < 0) {
  2615. pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
  2616. ARENA_SEC);
  2617. return -ENOENT;
  2618. }
  2619. return 0;
  2620. }
  2621. static int bpf_object__init_maps(struct bpf_object *obj,
  2622. const struct bpf_object_open_opts *opts)
  2623. {
  2624. const char *pin_root_path;
  2625. bool strict;
  2626. int err = 0;
  2627. strict = !OPTS_GET(opts, relaxed_maps, false);
  2628. pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
  2629. err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
  2630. err = err ?: bpf_object__init_global_data_maps(obj);
  2631. err = err ?: bpf_object__init_kconfig_map(obj);
  2632. err = err ?: bpf_object_init_struct_ops(obj);
  2633. return err;
  2634. }
  2635. static bool section_have_execinstr(struct bpf_object *obj, int idx)
  2636. {
  2637. Elf64_Shdr *sh;
  2638. sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
  2639. if (!sh)
  2640. return false;
  2641. return sh->sh_flags & SHF_EXECINSTR;
  2642. }
  2643. static bool starts_with_qmark(const char *s)
  2644. {
  2645. return s && s[0] == '?';
  2646. }
  2647. static bool btf_needs_sanitization(struct bpf_object *obj)
  2648. {
  2649. bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
  2650. bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
  2651. bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
  2652. bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
  2653. bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
  2654. bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
  2655. bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
  2656. bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
  2657. return !has_func || !has_datasec || !has_func_global || !has_float ||
  2658. !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
  2659. }
  2660. static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
  2661. {
  2662. bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
  2663. bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
  2664. bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
  2665. bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
  2666. bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
  2667. bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
  2668. bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
  2669. bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
  2670. int enum64_placeholder_id = 0;
  2671. struct btf_type *t;
  2672. int i, j, vlen;
  2673. for (i = 1; i < btf__type_cnt(btf); i++) {
  2674. t = (struct btf_type *)btf__type_by_id(btf, i);
  2675. if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
  2676. /* replace VAR/DECL_TAG with INT */
  2677. t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
  2678. /*
  2679. * using size = 1 is the safest choice, 4 will be too
  2680. * big and cause kernel BTF validation failure if
  2681. * original variable took less than 4 bytes
  2682. */
  2683. t->size = 1;
  2684. *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
  2685. } else if (!has_datasec && btf_is_datasec(t)) {
  2686. /* replace DATASEC with STRUCT */
  2687. const struct btf_var_secinfo *v = btf_var_secinfos(t);
  2688. struct btf_member *m = btf_members(t);
  2689. struct btf_type *vt;
  2690. char *name;
  2691. name = (char *)btf__name_by_offset(btf, t->name_off);
  2692. while (*name) {
  2693. if (*name == '.' || *name == '?')
  2694. *name = '_';
  2695. name++;
  2696. }
  2697. vlen = btf_vlen(t);
  2698. t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
  2699. for (j = 0; j < vlen; j++, v++, m++) {
  2700. /* order of field assignments is important */
  2701. m->offset = v->offset * 8;
  2702. m->type = v->type;
  2703. /* preserve variable name as member name */
  2704. vt = (void *)btf__type_by_id(btf, v->type);
  2705. m->name_off = vt->name_off;
  2706. }
  2707. } else if (!has_qmark_datasec && btf_is_datasec(t) &&
  2708. starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
  2709. /* replace '?' prefix with '_' for DATASEC names */
  2710. char *name;
  2711. name = (char *)btf__name_by_offset(btf, t->name_off);
  2712. if (name[0] == '?')
  2713. name[0] = '_';
  2714. } else if (!has_func && btf_is_func_proto(t)) {
  2715. /* replace FUNC_PROTO with ENUM */
  2716. vlen = btf_vlen(t);
  2717. t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
  2718. t->size = sizeof(__u32); /* kernel enforced */
  2719. } else if (!has_func && btf_is_func(t)) {
  2720. /* replace FUNC with TYPEDEF */
  2721. t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
  2722. } else if (!has_func_global && btf_is_func(t)) {
  2723. /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
  2724. t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
  2725. } else if (!has_float && btf_is_float(t)) {
  2726. /* replace FLOAT with an equally-sized empty STRUCT;
  2727. * since C compilers do not accept e.g. "float" as a
  2728. * valid struct name, make it anonymous
  2729. */
  2730. t->name_off = 0;
  2731. t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
  2732. } else if (!has_type_tag && btf_is_type_tag(t)) {
  2733. /* replace TYPE_TAG with a CONST */
  2734. t->name_off = 0;
  2735. t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
  2736. } else if (!has_enum64 && btf_is_enum(t)) {
  2737. /* clear the kflag */
  2738. t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
  2739. } else if (!has_enum64 && btf_is_enum64(t)) {
  2740. /* replace ENUM64 with a union */
  2741. struct btf_member *m;
  2742. if (enum64_placeholder_id == 0) {
  2743. enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
  2744. if (enum64_placeholder_id < 0)
  2745. return enum64_placeholder_id;
  2746. t = (struct btf_type *)btf__type_by_id(btf, i);
  2747. }
  2748. m = btf_members(t);
  2749. vlen = btf_vlen(t);
  2750. t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
  2751. for (j = 0; j < vlen; j++, m++) {
  2752. m->type = enum64_placeholder_id;
  2753. m->offset = 0;
  2754. }
  2755. }
  2756. }
  2757. return 0;
  2758. }
  2759. static bool libbpf_needs_btf(const struct bpf_object *obj)
  2760. {
  2761. return obj->efile.btf_maps_shndx >= 0 ||
  2762. obj->efile.has_st_ops ||
  2763. obj->nr_extern > 0;
  2764. }
  2765. static bool kernel_needs_btf(const struct bpf_object *obj)
  2766. {
  2767. return obj->efile.has_st_ops;
  2768. }
  2769. static int bpf_object__init_btf(struct bpf_object *obj,
  2770. Elf_Data *btf_data,
  2771. Elf_Data *btf_ext_data)
  2772. {
  2773. int err = -ENOENT;
  2774. if (btf_data) {
  2775. obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
  2776. err = libbpf_get_error(obj->btf);
  2777. if (err) {
  2778. obj->btf = NULL;
  2779. pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
  2780. goto out;
  2781. }
  2782. /* enforce 8-byte pointers for BPF-targeted BTFs */
  2783. btf__set_pointer_size(obj->btf, 8);
  2784. }
  2785. if (btf_ext_data) {
  2786. struct btf_ext_info *ext_segs[3];
  2787. int seg_num, sec_num;
  2788. if (!obj->btf) {
  2789. pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
  2790. BTF_EXT_ELF_SEC, BTF_ELF_SEC);
  2791. goto out;
  2792. }
  2793. obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
  2794. err = libbpf_get_error(obj->btf_ext);
  2795. if (err) {
  2796. pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
  2797. BTF_EXT_ELF_SEC, err);
  2798. obj->btf_ext = NULL;
  2799. goto out;
  2800. }
  2801. /* setup .BTF.ext to ELF section mapping */
  2802. ext_segs[0] = &obj->btf_ext->func_info;
  2803. ext_segs[1] = &obj->btf_ext->line_info;
  2804. ext_segs[2] = &obj->btf_ext->core_relo_info;
  2805. for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
  2806. struct btf_ext_info *seg = ext_segs[seg_num];
  2807. const struct btf_ext_info_sec *sec;
  2808. const char *sec_name;
  2809. Elf_Scn *scn;
  2810. if (seg->sec_cnt == 0)
  2811. continue;
  2812. seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
  2813. if (!seg->sec_idxs) {
  2814. err = -ENOMEM;
  2815. goto out;
  2816. }
  2817. sec_num = 0;
  2818. for_each_btf_ext_sec(seg, sec) {
  2819. /* preventively increment index to avoid doing
  2820. * this before every continue below
  2821. */
  2822. sec_num++;
  2823. sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
  2824. if (str_is_empty(sec_name))
  2825. continue;
  2826. scn = elf_sec_by_name(obj, sec_name);
  2827. if (!scn)
  2828. continue;
  2829. seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
  2830. }
  2831. }
  2832. }
  2833. out:
  2834. if (err && libbpf_needs_btf(obj)) {
  2835. pr_warn("BTF is required, but is missing or corrupted.\n");
  2836. return err;
  2837. }
  2838. return 0;
  2839. }
  2840. static int compare_vsi_off(const void *_a, const void *_b)
  2841. {
  2842. const struct btf_var_secinfo *a = _a;
  2843. const struct btf_var_secinfo *b = _b;
  2844. return a->offset - b->offset;
  2845. }
  2846. static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
  2847. struct btf_type *t)
  2848. {
  2849. __u32 size = 0, i, vars = btf_vlen(t);
  2850. const char *sec_name = btf__name_by_offset(btf, t->name_off);
  2851. struct btf_var_secinfo *vsi;
  2852. bool fixup_offsets = false;
  2853. int err;
  2854. if (!sec_name) {
  2855. pr_debug("No name found in string section for DATASEC kind.\n");
  2856. return -ENOENT;
  2857. }
  2858. /* Extern-backing datasecs (.ksyms, .kconfig) have their size and
  2859. * variable offsets set at the previous step. Further, not every
  2860. * extern BTF VAR has corresponding ELF symbol preserved, so we skip
  2861. * all fixups altogether for such sections and go straight to sorting
  2862. * VARs within their DATASEC.
  2863. */
  2864. if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
  2865. goto sort_vars;
  2866. /* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
  2867. * fix this up. But BPF static linker already fixes this up and fills
  2868. * all the sizes and offsets during static linking. So this step has
  2869. * to be optional. But the STV_HIDDEN handling is non-optional for any
  2870. * non-extern DATASEC, so the variable fixup loop below handles both
  2871. * functions at the same time, paying the cost of BTF VAR <-> ELF
  2872. * symbol matching just once.
  2873. */
  2874. if (t->size == 0) {
  2875. err = find_elf_sec_sz(obj, sec_name, &size);
  2876. if (err || !size) {
  2877. pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
  2878. sec_name, size, err);
  2879. return -ENOENT;
  2880. }
  2881. t->size = size;
  2882. fixup_offsets = true;
  2883. }
  2884. for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
  2885. const struct btf_type *t_var;
  2886. struct btf_var *var;
  2887. const char *var_name;
  2888. Elf64_Sym *sym;
  2889. t_var = btf__type_by_id(btf, vsi->type);
  2890. if (!t_var || !btf_is_var(t_var)) {
  2891. pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
  2892. return -EINVAL;
  2893. }
  2894. var = btf_var(t_var);
  2895. if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
  2896. continue;
  2897. var_name = btf__name_by_offset(btf, t_var->name_off);
  2898. if (!var_name) {
  2899. pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
  2900. sec_name, i);
  2901. return -ENOENT;
  2902. }
  2903. sym = find_elf_var_sym(obj, var_name);
  2904. if (IS_ERR(sym)) {
  2905. pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
  2906. sec_name, var_name);
  2907. return -ENOENT;
  2908. }
  2909. if (fixup_offsets)
  2910. vsi->offset = sym->st_value;
  2911. /* if variable is a global/weak symbol, but has restricted
  2912. * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
  2913. * as static. This follows similar logic for functions (BPF
  2914. * subprogs) and influences libbpf's further decisions about
  2915. * whether to make global data BPF array maps as
  2916. * BPF_F_MMAPABLE.
  2917. */
  2918. if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
  2919. || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
  2920. var->linkage = BTF_VAR_STATIC;
  2921. }
  2922. sort_vars:
  2923. qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
  2924. return 0;
  2925. }
  2926. static int bpf_object_fixup_btf(struct bpf_object *obj)
  2927. {
  2928. int i, n, err = 0;
  2929. if (!obj->btf)
  2930. return 0;
  2931. n = btf__type_cnt(obj->btf);
  2932. for (i = 1; i < n; i++) {
  2933. struct btf_type *t = btf_type_by_id(obj->btf, i);
  2934. /* Loader needs to fix up some of the things compiler
  2935. * couldn't get its hands on while emitting BTF. This
  2936. * is section size and global variable offset. We use
  2937. * the info from the ELF itself for this purpose.
  2938. */
  2939. if (btf_is_datasec(t)) {
  2940. err = btf_fixup_datasec(obj, obj->btf, t);
  2941. if (err)
  2942. return err;
  2943. }
  2944. }
  2945. return 0;
  2946. }
  2947. static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
  2948. {
  2949. if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
  2950. prog->type == BPF_PROG_TYPE_LSM)
  2951. return true;
  2952. /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
  2953. * also need vmlinux BTF
  2954. */
  2955. if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
  2956. return true;
  2957. return false;
  2958. }
  2959. static bool map_needs_vmlinux_btf(struct bpf_map *map)
  2960. {
  2961. return bpf_map__is_struct_ops(map);
  2962. }
  2963. static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
  2964. {
  2965. struct bpf_program *prog;
  2966. struct bpf_map *map;
  2967. int i;
  2968. /* CO-RE relocations need kernel BTF, only when btf_custom_path
  2969. * is not specified
  2970. */
  2971. if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
  2972. return true;
  2973. /* Support for typed ksyms needs kernel BTF */
  2974. for (i = 0; i < obj->nr_extern; i++) {
  2975. const struct extern_desc *ext;
  2976. ext = &obj->externs[i];
  2977. if (ext->type == EXT_KSYM && ext->ksym.type_id)
  2978. return true;
  2979. }
  2980. bpf_object__for_each_program(prog, obj) {
  2981. if (!prog->autoload)
  2982. continue;
  2983. if (prog_needs_vmlinux_btf(prog))
  2984. return true;
  2985. }
  2986. bpf_object__for_each_map(map, obj) {
  2987. if (map_needs_vmlinux_btf(map))
  2988. return true;
  2989. }
  2990. return false;
  2991. }
  2992. static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
  2993. {
  2994. int err;
  2995. /* btf_vmlinux could be loaded earlier */
  2996. if (obj->btf_vmlinux || obj->gen_loader)
  2997. return 0;
  2998. if (!force && !obj_needs_vmlinux_btf(obj))
  2999. return 0;
  3000. obj->btf_vmlinux = btf__load_vmlinux_btf();
  3001. err = libbpf_get_error(obj->btf_vmlinux);
  3002. if (err) {
  3003. pr_warn("Error loading vmlinux BTF: %d\n", err);
  3004. obj->btf_vmlinux = NULL;
  3005. return err;
  3006. }
  3007. return 0;
  3008. }
  3009. static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
  3010. {
  3011. struct btf *kern_btf = obj->btf;
  3012. bool btf_mandatory, sanitize;
  3013. int i, err = 0;
  3014. if (!obj->btf)
  3015. return 0;
  3016. if (!kernel_supports(obj, FEAT_BTF)) {
  3017. if (kernel_needs_btf(obj)) {
  3018. err = -EOPNOTSUPP;
  3019. goto report;
  3020. }
  3021. pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
  3022. return 0;
  3023. }
  3024. /* Even though some subprogs are global/weak, user might prefer more
  3025. * permissive BPF verification process that BPF verifier performs for
  3026. * static functions, taking into account more context from the caller
  3027. * functions. In such case, they need to mark such subprogs with
  3028. * __attribute__((visibility("hidden"))) and libbpf will adjust
  3029. * corresponding FUNC BTF type to be marked as static and trigger more
  3030. * involved BPF verification process.
  3031. */
  3032. for (i = 0; i < obj->nr_programs; i++) {
  3033. struct bpf_program *prog = &obj->programs[i];
  3034. struct btf_type *t;
  3035. const char *name;
  3036. int j, n;
  3037. if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
  3038. continue;
  3039. n = btf__type_cnt(obj->btf);
  3040. for (j = 1; j < n; j++) {
  3041. t = btf_type_by_id(obj->btf, j);
  3042. if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
  3043. continue;
  3044. name = btf__str_by_offset(obj->btf, t->name_off);
  3045. if (strcmp(name, prog->name) != 0)
  3046. continue;
  3047. t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
  3048. break;
  3049. }
  3050. }
  3051. sanitize = btf_needs_sanitization(obj);
  3052. if (sanitize) {
  3053. const void *raw_data;
  3054. __u32 sz;
  3055. /* clone BTF to sanitize a copy and leave the original intact */
  3056. raw_data = btf__raw_data(obj->btf, &sz);
  3057. kern_btf = btf__new(raw_data, sz);
  3058. err = libbpf_get_error(kern_btf);
  3059. if (err)
  3060. return err;
  3061. /* enforce 8-byte pointers for BPF-targeted BTFs */
  3062. btf__set_pointer_size(obj->btf, 8);
  3063. err = bpf_object__sanitize_btf(obj, kern_btf);
  3064. if (err)
  3065. return err;
  3066. }
  3067. if (obj->gen_loader) {
  3068. __u32 raw_size = 0;
  3069. const void *raw_data = btf__raw_data(kern_btf, &raw_size);
  3070. if (!raw_data)
  3071. return -ENOMEM;
  3072. bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
  3073. /* Pretend to have valid FD to pass various fd >= 0 checks.
  3074. * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
  3075. */
  3076. btf__set_fd(kern_btf, 0);
  3077. } else {
  3078. /* currently BPF_BTF_LOAD only supports log_level 1 */
  3079. err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
  3080. obj->log_level ? 1 : 0, obj->token_fd);
  3081. }
  3082. if (sanitize) {
  3083. if (!err) {
  3084. /* move fd to libbpf's BTF */
  3085. btf__set_fd(obj->btf, btf__fd(kern_btf));
  3086. btf__set_fd(kern_btf, -1);
  3087. }
  3088. btf__free(kern_btf);
  3089. }
  3090. report:
  3091. if (err) {
  3092. btf_mandatory = kernel_needs_btf(obj);
  3093. pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
  3094. btf_mandatory ? "BTF is mandatory, can't proceed."
  3095. : "BTF is optional, ignoring.");
  3096. if (!btf_mandatory)
  3097. err = 0;
  3098. }
  3099. return err;
  3100. }
  3101. static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
  3102. {
  3103. const char *name;
  3104. name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
  3105. if (!name) {
  3106. pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
  3107. off, obj->path, elf_errmsg(-1));
  3108. return NULL;
  3109. }
  3110. return name;
  3111. }
  3112. static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
  3113. {
  3114. const char *name;
  3115. name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
  3116. if (!name) {
  3117. pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
  3118. off, obj->path, elf_errmsg(-1));
  3119. return NULL;
  3120. }
  3121. return name;
  3122. }
  3123. static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
  3124. {
  3125. Elf_Scn *scn;
  3126. scn = elf_getscn(obj->efile.elf, idx);
  3127. if (!scn) {
  3128. pr_warn("elf: failed to get section(%zu) from %s: %s\n",
  3129. idx, obj->path, elf_errmsg(-1));
  3130. return NULL;
  3131. }
  3132. return scn;
  3133. }
  3134. static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
  3135. {
  3136. Elf_Scn *scn = NULL;
  3137. Elf *elf = obj->efile.elf;
  3138. const char *sec_name;
  3139. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  3140. sec_name = elf_sec_name(obj, scn);
  3141. if (!sec_name)
  3142. return NULL;
  3143. if (strcmp(sec_name, name) != 0)
  3144. continue;
  3145. return scn;
  3146. }
  3147. return NULL;
  3148. }
  3149. static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
  3150. {
  3151. Elf64_Shdr *shdr;
  3152. if (!scn)
  3153. return NULL;
  3154. shdr = elf64_getshdr(scn);
  3155. if (!shdr) {
  3156. pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
  3157. elf_ndxscn(scn), obj->path, elf_errmsg(-1));
  3158. return NULL;
  3159. }
  3160. return shdr;
  3161. }
  3162. static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
  3163. {
  3164. const char *name;
  3165. Elf64_Shdr *sh;
  3166. if (!scn)
  3167. return NULL;
  3168. sh = elf_sec_hdr(obj, scn);
  3169. if (!sh)
  3170. return NULL;
  3171. name = elf_sec_str(obj, sh->sh_name);
  3172. if (!name) {
  3173. pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
  3174. elf_ndxscn(scn), obj->path, elf_errmsg(-1));
  3175. return NULL;
  3176. }
  3177. return name;
  3178. }
  3179. static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
  3180. {
  3181. Elf_Data *data;
  3182. if (!scn)
  3183. return NULL;
  3184. data = elf_getdata(scn, 0);
  3185. if (!data) {
  3186. pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
  3187. elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
  3188. obj->path, elf_errmsg(-1));
  3189. return NULL;
  3190. }
  3191. return data;
  3192. }
  3193. static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
  3194. {
  3195. if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
  3196. return NULL;
  3197. return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
  3198. }
  3199. static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
  3200. {
  3201. if (idx >= data->d_size / sizeof(Elf64_Rel))
  3202. return NULL;
  3203. return (Elf64_Rel *)data->d_buf + idx;
  3204. }
  3205. static bool is_sec_name_dwarf(const char *name)
  3206. {
  3207. /* approximation, but the actual list is too long */
  3208. return str_has_pfx(name, ".debug_");
  3209. }
  3210. static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
  3211. {
  3212. /* no special handling of .strtab */
  3213. if (hdr->sh_type == SHT_STRTAB)
  3214. return true;
  3215. /* ignore .llvm_addrsig section as well */
  3216. if (hdr->sh_type == SHT_LLVM_ADDRSIG)
  3217. return true;
  3218. /* no subprograms will lead to an empty .text section, ignore it */
  3219. if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
  3220. strcmp(name, ".text") == 0)
  3221. return true;
  3222. /* DWARF sections */
  3223. if (is_sec_name_dwarf(name))
  3224. return true;
  3225. if (str_has_pfx(name, ".rel")) {
  3226. name += sizeof(".rel") - 1;
  3227. /* DWARF section relocations */
  3228. if (is_sec_name_dwarf(name))
  3229. return true;
  3230. /* .BTF and .BTF.ext don't need relocations */
  3231. if (strcmp(name, BTF_ELF_SEC) == 0 ||
  3232. strcmp(name, BTF_EXT_ELF_SEC) == 0)
  3233. return true;
  3234. }
  3235. return false;
  3236. }
  3237. static int cmp_progs(const void *_a, const void *_b)
  3238. {
  3239. const struct bpf_program *a = _a;
  3240. const struct bpf_program *b = _b;
  3241. if (a->sec_idx != b->sec_idx)
  3242. return a->sec_idx < b->sec_idx ? -1 : 1;
  3243. /* sec_insn_off can't be the same within the section */
  3244. return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
  3245. }
  3246. static int bpf_object__elf_collect(struct bpf_object *obj)
  3247. {
  3248. struct elf_sec_desc *sec_desc;
  3249. Elf *elf = obj->efile.elf;
  3250. Elf_Data *btf_ext_data = NULL;
  3251. Elf_Data *btf_data = NULL;
  3252. int idx = 0, err = 0;
  3253. const char *name;
  3254. Elf_Data *data;
  3255. Elf_Scn *scn;
  3256. Elf64_Shdr *sh;
  3257. /* ELF section indices are 0-based, but sec #0 is special "invalid"
  3258. * section. Since section count retrieved by elf_getshdrnum() does
  3259. * include sec #0, it is already the necessary size of an array to keep
  3260. * all the sections.
  3261. */
  3262. if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
  3263. pr_warn("elf: failed to get the number of sections for %s: %s\n",
  3264. obj->path, elf_errmsg(-1));
  3265. return -LIBBPF_ERRNO__FORMAT;
  3266. }
  3267. obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
  3268. if (!obj->efile.secs)
  3269. return -ENOMEM;
  3270. /* a bunch of ELF parsing functionality depends on processing symbols,
  3271. * so do the first pass and find the symbol table
  3272. */
  3273. scn = NULL;
  3274. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  3275. sh = elf_sec_hdr(obj, scn);
  3276. if (!sh)
  3277. return -LIBBPF_ERRNO__FORMAT;
  3278. if (sh->sh_type == SHT_SYMTAB) {
  3279. if (obj->efile.symbols) {
  3280. pr_warn("elf: multiple symbol tables in %s\n", obj->path);
  3281. return -LIBBPF_ERRNO__FORMAT;
  3282. }
  3283. data = elf_sec_data(obj, scn);
  3284. if (!data)
  3285. return -LIBBPF_ERRNO__FORMAT;
  3286. idx = elf_ndxscn(scn);
  3287. obj->efile.symbols = data;
  3288. obj->efile.symbols_shndx = idx;
  3289. obj->efile.strtabidx = sh->sh_link;
  3290. }
  3291. }
  3292. if (!obj->efile.symbols) {
  3293. pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
  3294. obj->path);
  3295. return -ENOENT;
  3296. }
  3297. scn = NULL;
  3298. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  3299. idx = elf_ndxscn(scn);
  3300. sec_desc = &obj->efile.secs[idx];
  3301. sh = elf_sec_hdr(obj, scn);
  3302. if (!sh)
  3303. return -LIBBPF_ERRNO__FORMAT;
  3304. name = elf_sec_str(obj, sh->sh_name);
  3305. if (!name)
  3306. return -LIBBPF_ERRNO__FORMAT;
  3307. if (ignore_elf_section(sh, name))
  3308. continue;
  3309. data = elf_sec_data(obj, scn);
  3310. if (!data)
  3311. return -LIBBPF_ERRNO__FORMAT;
  3312. pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
  3313. idx, name, (unsigned long)data->d_size,
  3314. (int)sh->sh_link, (unsigned long)sh->sh_flags,
  3315. (int)sh->sh_type);
  3316. if (strcmp(name, "license") == 0) {
  3317. err = bpf_object__init_license(obj, data->d_buf, data->d_size);
  3318. if (err)
  3319. return err;
  3320. } else if (strcmp(name, "version") == 0) {
  3321. err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
  3322. if (err)
  3323. return err;
  3324. } else if (strcmp(name, "maps") == 0) {
  3325. pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
  3326. return -ENOTSUP;
  3327. } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
  3328. obj->efile.btf_maps_shndx = idx;
  3329. } else if (strcmp(name, BTF_ELF_SEC) == 0) {
  3330. if (sh->sh_type != SHT_PROGBITS)
  3331. return -LIBBPF_ERRNO__FORMAT;
  3332. btf_data = data;
  3333. } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
  3334. if (sh->sh_type != SHT_PROGBITS)
  3335. return -LIBBPF_ERRNO__FORMAT;
  3336. btf_ext_data = data;
  3337. } else if (sh->sh_type == SHT_SYMTAB) {
  3338. /* already processed during the first pass above */
  3339. } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
  3340. if (sh->sh_flags & SHF_EXECINSTR) {
  3341. if (strcmp(name, ".text") == 0)
  3342. obj->efile.text_shndx = idx;
  3343. err = bpf_object__add_programs(obj, data, name, idx);
  3344. if (err)
  3345. return err;
  3346. } else if (strcmp(name, DATA_SEC) == 0 ||
  3347. str_has_pfx(name, DATA_SEC ".")) {
  3348. sec_desc->sec_type = SEC_DATA;
  3349. sec_desc->shdr = sh;
  3350. sec_desc->data = data;
  3351. } else if (strcmp(name, RODATA_SEC) == 0 ||
  3352. str_has_pfx(name, RODATA_SEC ".")) {
  3353. sec_desc->sec_type = SEC_RODATA;
  3354. sec_desc->shdr = sh;
  3355. sec_desc->data = data;
  3356. } else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
  3357. strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
  3358. strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
  3359. strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
  3360. sec_desc->sec_type = SEC_ST_OPS;
  3361. sec_desc->shdr = sh;
  3362. sec_desc->data = data;
  3363. obj->efile.has_st_ops = true;
  3364. } else if (strcmp(name, ARENA_SEC) == 0) {
  3365. obj->efile.arena_data = data;
  3366. obj->efile.arena_data_shndx = idx;
  3367. } else {
  3368. pr_info("elf: skipping unrecognized data section(%d) %s\n",
  3369. idx, name);
  3370. }
  3371. } else if (sh->sh_type == SHT_REL) {
  3372. int targ_sec_idx = sh->sh_info; /* points to other section */
  3373. if (sh->sh_entsize != sizeof(Elf64_Rel) ||
  3374. targ_sec_idx >= obj->efile.sec_cnt)
  3375. return -LIBBPF_ERRNO__FORMAT;
  3376. /* Only do relo for section with exec instructions */
  3377. if (!section_have_execinstr(obj, targ_sec_idx) &&
  3378. strcmp(name, ".rel" STRUCT_OPS_SEC) &&
  3379. strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
  3380. strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
  3381. strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
  3382. strcmp(name, ".rel" MAPS_ELF_SEC)) {
  3383. pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
  3384. idx, name, targ_sec_idx,
  3385. elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
  3386. continue;
  3387. }
  3388. sec_desc->sec_type = SEC_RELO;
  3389. sec_desc->shdr = sh;
  3390. sec_desc->data = data;
  3391. } else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
  3392. str_has_pfx(name, BSS_SEC "."))) {
  3393. sec_desc->sec_type = SEC_BSS;
  3394. sec_desc->shdr = sh;
  3395. sec_desc->data = data;
  3396. } else {
  3397. pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
  3398. (size_t)sh->sh_size);
  3399. }
  3400. }
  3401. if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
  3402. pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
  3403. return -LIBBPF_ERRNO__FORMAT;
  3404. }
  3405. /* sort BPF programs by section name and in-section instruction offset
  3406. * for faster search
  3407. */
  3408. if (obj->nr_programs)
  3409. qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
  3410. return bpf_object__init_btf(obj, btf_data, btf_ext_data);
  3411. }
  3412. static bool sym_is_extern(const Elf64_Sym *sym)
  3413. {
  3414. int bind = ELF64_ST_BIND(sym->st_info);
  3415. /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
  3416. return sym->st_shndx == SHN_UNDEF &&
  3417. (bind == STB_GLOBAL || bind == STB_WEAK) &&
  3418. ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
  3419. }
  3420. static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
  3421. {
  3422. int bind = ELF64_ST_BIND(sym->st_info);
  3423. int type = ELF64_ST_TYPE(sym->st_info);
  3424. /* in .text section */
  3425. if (sym->st_shndx != text_shndx)
  3426. return false;
  3427. /* local function */
  3428. if (bind == STB_LOCAL && type == STT_SECTION)
  3429. return true;
  3430. /* global function */
  3431. return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
  3432. }
  3433. static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
  3434. {
  3435. const struct btf_type *t;
  3436. const char *tname;
  3437. int i, n;
  3438. if (!btf)
  3439. return -ESRCH;
  3440. n = btf__type_cnt(btf);
  3441. for (i = 1; i < n; i++) {
  3442. t = btf__type_by_id(btf, i);
  3443. if (!btf_is_var(t) && !btf_is_func(t))
  3444. continue;
  3445. tname = btf__name_by_offset(btf, t->name_off);
  3446. if (strcmp(tname, ext_name))
  3447. continue;
  3448. if (btf_is_var(t) &&
  3449. btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
  3450. return -EINVAL;
  3451. if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
  3452. return -EINVAL;
  3453. return i;
  3454. }
  3455. return -ENOENT;
  3456. }
  3457. static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
  3458. const struct btf_var_secinfo *vs;
  3459. const struct btf_type *t;
  3460. int i, j, n;
  3461. if (!btf)
  3462. return -ESRCH;
  3463. n = btf__type_cnt(btf);
  3464. for (i = 1; i < n; i++) {
  3465. t = btf__type_by_id(btf, i);
  3466. if (!btf_is_datasec(t))
  3467. continue;
  3468. vs = btf_var_secinfos(t);
  3469. for (j = 0; j < btf_vlen(t); j++, vs++) {
  3470. if (vs->type == ext_btf_id)
  3471. return i;
  3472. }
  3473. }
  3474. return -ENOENT;
  3475. }
  3476. static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
  3477. bool *is_signed)
  3478. {
  3479. const struct btf_type *t;
  3480. const char *name;
  3481. t = skip_mods_and_typedefs(btf, id, NULL);
  3482. name = btf__name_by_offset(btf, t->name_off);
  3483. if (is_signed)
  3484. *is_signed = false;
  3485. switch (btf_kind(t)) {
  3486. case BTF_KIND_INT: {
  3487. int enc = btf_int_encoding(t);
  3488. if (enc & BTF_INT_BOOL)
  3489. return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
  3490. if (is_signed)
  3491. *is_signed = enc & BTF_INT_SIGNED;
  3492. if (t->size == 1)
  3493. return KCFG_CHAR;
  3494. if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
  3495. return KCFG_UNKNOWN;
  3496. return KCFG_INT;
  3497. }
  3498. case BTF_KIND_ENUM:
  3499. if (t->size != 4)
  3500. return KCFG_UNKNOWN;
  3501. if (strcmp(name, "libbpf_tristate"))
  3502. return KCFG_UNKNOWN;
  3503. return KCFG_TRISTATE;
  3504. case BTF_KIND_ENUM64:
  3505. if (strcmp(name, "libbpf_tristate"))
  3506. return KCFG_UNKNOWN;
  3507. return KCFG_TRISTATE;
  3508. case BTF_KIND_ARRAY:
  3509. if (btf_array(t)->nelems == 0)
  3510. return KCFG_UNKNOWN;
  3511. if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
  3512. return KCFG_UNKNOWN;
  3513. return KCFG_CHAR_ARR;
  3514. default:
  3515. return KCFG_UNKNOWN;
  3516. }
  3517. }
  3518. static int cmp_externs(const void *_a, const void *_b)
  3519. {
  3520. const struct extern_desc *a = _a;
  3521. const struct extern_desc *b = _b;
  3522. if (a->type != b->type)
  3523. return a->type < b->type ? -1 : 1;
  3524. if (a->type == EXT_KCFG) {
  3525. /* descending order by alignment requirements */
  3526. if (a->kcfg.align != b->kcfg.align)
  3527. return a->kcfg.align > b->kcfg.align ? -1 : 1;
  3528. /* ascending order by size, within same alignment class */
  3529. if (a->kcfg.sz != b->kcfg.sz)
  3530. return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
  3531. }
  3532. /* resolve ties by name */
  3533. return strcmp(a->name, b->name);
  3534. }
  3535. static int find_int_btf_id(const struct btf *btf)
  3536. {
  3537. const struct btf_type *t;
  3538. int i, n;
  3539. n = btf__type_cnt(btf);
  3540. for (i = 1; i < n; i++) {
  3541. t = btf__type_by_id(btf, i);
  3542. if (btf_is_int(t) && btf_int_bits(t) == 32)
  3543. return i;
  3544. }
  3545. return 0;
  3546. }
  3547. static int add_dummy_ksym_var(struct btf *btf)
  3548. {
  3549. int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
  3550. const struct btf_var_secinfo *vs;
  3551. const struct btf_type *sec;
  3552. if (!btf)
  3553. return 0;
  3554. sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
  3555. BTF_KIND_DATASEC);
  3556. if (sec_btf_id < 0)
  3557. return 0;
  3558. sec = btf__type_by_id(btf, sec_btf_id);
  3559. vs = btf_var_secinfos(sec);
  3560. for (i = 0; i < btf_vlen(sec); i++, vs++) {
  3561. const struct btf_type *vt;
  3562. vt = btf__type_by_id(btf, vs->type);
  3563. if (btf_is_func(vt))
  3564. break;
  3565. }
  3566. /* No func in ksyms sec. No need to add dummy var. */
  3567. if (i == btf_vlen(sec))
  3568. return 0;
  3569. int_btf_id = find_int_btf_id(btf);
  3570. dummy_var_btf_id = btf__add_var(btf,
  3571. "dummy_ksym",
  3572. BTF_VAR_GLOBAL_ALLOCATED,
  3573. int_btf_id);
  3574. if (dummy_var_btf_id < 0)
  3575. pr_warn("cannot create a dummy_ksym var\n");
  3576. return dummy_var_btf_id;
  3577. }
  3578. static int bpf_object__collect_externs(struct bpf_object *obj)
  3579. {
  3580. struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
  3581. const struct btf_type *t;
  3582. struct extern_desc *ext;
  3583. int i, n, off, dummy_var_btf_id;
  3584. const char *ext_name, *sec_name;
  3585. size_t ext_essent_len;
  3586. Elf_Scn *scn;
  3587. Elf64_Shdr *sh;
  3588. if (!obj->efile.symbols)
  3589. return 0;
  3590. scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
  3591. sh = elf_sec_hdr(obj, scn);
  3592. if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
  3593. return -LIBBPF_ERRNO__FORMAT;
  3594. dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
  3595. if (dummy_var_btf_id < 0)
  3596. return dummy_var_btf_id;
  3597. n = sh->sh_size / sh->sh_entsize;
  3598. pr_debug("looking for externs among %d symbols...\n", n);
  3599. for (i = 0; i < n; i++) {
  3600. Elf64_Sym *sym = elf_sym_by_idx(obj, i);
  3601. if (!sym)
  3602. return -LIBBPF_ERRNO__FORMAT;
  3603. if (!sym_is_extern(sym))
  3604. continue;
  3605. ext_name = elf_sym_str(obj, sym->st_name);
  3606. if (!ext_name || !ext_name[0])
  3607. continue;
  3608. ext = obj->externs;
  3609. ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
  3610. if (!ext)
  3611. return -ENOMEM;
  3612. obj->externs = ext;
  3613. ext = &ext[obj->nr_extern];
  3614. memset(ext, 0, sizeof(*ext));
  3615. obj->nr_extern++;
  3616. ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
  3617. if (ext->btf_id <= 0) {
  3618. pr_warn("failed to find BTF for extern '%s': %d\n",
  3619. ext_name, ext->btf_id);
  3620. return ext->btf_id;
  3621. }
  3622. t = btf__type_by_id(obj->btf, ext->btf_id);
  3623. ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
  3624. if (!ext->name)
  3625. return -ENOMEM;
  3626. ext->sym_idx = i;
  3627. ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
  3628. ext_essent_len = bpf_core_essential_name_len(ext->name);
  3629. ext->essent_name = NULL;
  3630. if (ext_essent_len != strlen(ext->name)) {
  3631. ext->essent_name = strndup(ext->name, ext_essent_len);
  3632. if (!ext->essent_name)
  3633. return -ENOMEM;
  3634. }
  3635. ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
  3636. if (ext->sec_btf_id <= 0) {
  3637. pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
  3638. ext_name, ext->btf_id, ext->sec_btf_id);
  3639. return ext->sec_btf_id;
  3640. }
  3641. sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
  3642. sec_name = btf__name_by_offset(obj->btf, sec->name_off);
  3643. if (strcmp(sec_name, KCONFIG_SEC) == 0) {
  3644. if (btf_is_func(t)) {
  3645. pr_warn("extern function %s is unsupported under %s section\n",
  3646. ext->name, KCONFIG_SEC);
  3647. return -ENOTSUP;
  3648. }
  3649. kcfg_sec = sec;
  3650. ext->type = EXT_KCFG;
  3651. ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
  3652. if (ext->kcfg.sz <= 0) {
  3653. pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
  3654. ext_name, ext->kcfg.sz);
  3655. return ext->kcfg.sz;
  3656. }
  3657. ext->kcfg.align = btf__align_of(obj->btf, t->type);
  3658. if (ext->kcfg.align <= 0) {
  3659. pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
  3660. ext_name, ext->kcfg.align);
  3661. return -EINVAL;
  3662. }
  3663. ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
  3664. &ext->kcfg.is_signed);
  3665. if (ext->kcfg.type == KCFG_UNKNOWN) {
  3666. pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
  3667. return -ENOTSUP;
  3668. }
  3669. } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
  3670. ksym_sec = sec;
  3671. ext->type = EXT_KSYM;
  3672. skip_mods_and_typedefs(obj->btf, t->type,
  3673. &ext->ksym.type_id);
  3674. } else {
  3675. pr_warn("unrecognized extern section '%s'\n", sec_name);
  3676. return -ENOTSUP;
  3677. }
  3678. }
  3679. pr_debug("collected %d externs total\n", obj->nr_extern);
  3680. if (!obj->nr_extern)
  3681. return 0;
  3682. /* sort externs by type, for kcfg ones also by (align, size, name) */
  3683. qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
  3684. /* for .ksyms section, we need to turn all externs into allocated
  3685. * variables in BTF to pass kernel verification; we do this by
  3686. * pretending that each extern is a 8-byte variable
  3687. */
  3688. if (ksym_sec) {
  3689. /* find existing 4-byte integer type in BTF to use for fake
  3690. * extern variables in DATASEC
  3691. */
  3692. int int_btf_id = find_int_btf_id(obj->btf);
  3693. /* For extern function, a dummy_var added earlier
  3694. * will be used to replace the vs->type and
  3695. * its name string will be used to refill
  3696. * the missing param's name.
  3697. */
  3698. const struct btf_type *dummy_var;
  3699. dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
  3700. for (i = 0; i < obj->nr_extern; i++) {
  3701. ext = &obj->externs[i];
  3702. if (ext->type != EXT_KSYM)
  3703. continue;
  3704. pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
  3705. i, ext->sym_idx, ext->name);
  3706. }
  3707. sec = ksym_sec;
  3708. n = btf_vlen(sec);
  3709. for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
  3710. struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
  3711. struct btf_type *vt;
  3712. vt = (void *)btf__type_by_id(obj->btf, vs->type);
  3713. ext_name = btf__name_by_offset(obj->btf, vt->name_off);
  3714. ext = find_extern_by_name(obj, ext_name);
  3715. if (!ext) {
  3716. pr_warn("failed to find extern definition for BTF %s '%s'\n",
  3717. btf_kind_str(vt), ext_name);
  3718. return -ESRCH;
  3719. }
  3720. if (btf_is_func(vt)) {
  3721. const struct btf_type *func_proto;
  3722. struct btf_param *param;
  3723. int j;
  3724. func_proto = btf__type_by_id(obj->btf,
  3725. vt->type);
  3726. param = btf_params(func_proto);
  3727. /* Reuse the dummy_var string if the
  3728. * func proto does not have param name.
  3729. */
  3730. for (j = 0; j < btf_vlen(func_proto); j++)
  3731. if (param[j].type && !param[j].name_off)
  3732. param[j].name_off =
  3733. dummy_var->name_off;
  3734. vs->type = dummy_var_btf_id;
  3735. vt->info &= ~0xffff;
  3736. vt->info |= BTF_FUNC_GLOBAL;
  3737. } else {
  3738. btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
  3739. vt->type = int_btf_id;
  3740. }
  3741. vs->offset = off;
  3742. vs->size = sizeof(int);
  3743. }
  3744. sec->size = off;
  3745. }
  3746. if (kcfg_sec) {
  3747. sec = kcfg_sec;
  3748. /* for kcfg externs calculate their offsets within a .kconfig map */
  3749. off = 0;
  3750. for (i = 0; i < obj->nr_extern; i++) {
  3751. ext = &obj->externs[i];
  3752. if (ext->type != EXT_KCFG)
  3753. continue;
  3754. ext->kcfg.data_off = roundup(off, ext->kcfg.align);
  3755. off = ext->kcfg.data_off + ext->kcfg.sz;
  3756. pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
  3757. i, ext->sym_idx, ext->kcfg.data_off, ext->name);
  3758. }
  3759. sec->size = off;
  3760. n = btf_vlen(sec);
  3761. for (i = 0; i < n; i++) {
  3762. struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
  3763. t = btf__type_by_id(obj->btf, vs->type);
  3764. ext_name = btf__name_by_offset(obj->btf, t->name_off);
  3765. ext = find_extern_by_name(obj, ext_name);
  3766. if (!ext) {
  3767. pr_warn("failed to find extern definition for BTF var '%s'\n",
  3768. ext_name);
  3769. return -ESRCH;
  3770. }
  3771. btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
  3772. vs->offset = ext->kcfg.data_off;
  3773. }
  3774. }
  3775. return 0;
  3776. }
  3777. static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
  3778. {
  3779. return prog->sec_idx == obj->efile.text_shndx;
  3780. }
  3781. struct bpf_program *
  3782. bpf_object__find_program_by_name(const struct bpf_object *obj,
  3783. const char *name)
  3784. {
  3785. struct bpf_program *prog;
  3786. bpf_object__for_each_program(prog, obj) {
  3787. if (prog_is_subprog(obj, prog))
  3788. continue;
  3789. if (!strcmp(prog->name, name))
  3790. return prog;
  3791. }
  3792. return errno = ENOENT, NULL;
  3793. }
  3794. static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
  3795. int shndx)
  3796. {
  3797. switch (obj->efile.secs[shndx].sec_type) {
  3798. case SEC_BSS:
  3799. case SEC_DATA:
  3800. case SEC_RODATA:
  3801. return true;
  3802. default:
  3803. return false;
  3804. }
  3805. }
  3806. static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
  3807. int shndx)
  3808. {
  3809. return shndx == obj->efile.btf_maps_shndx;
  3810. }
  3811. static enum libbpf_map_type
  3812. bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
  3813. {
  3814. if (shndx == obj->efile.symbols_shndx)
  3815. return LIBBPF_MAP_KCONFIG;
  3816. switch (obj->efile.secs[shndx].sec_type) {
  3817. case SEC_BSS:
  3818. return LIBBPF_MAP_BSS;
  3819. case SEC_DATA:
  3820. return LIBBPF_MAP_DATA;
  3821. case SEC_RODATA:
  3822. return LIBBPF_MAP_RODATA;
  3823. default:
  3824. return LIBBPF_MAP_UNSPEC;
  3825. }
  3826. }
  3827. static int bpf_program__record_reloc(struct bpf_program *prog,
  3828. struct reloc_desc *reloc_desc,
  3829. __u32 insn_idx, const char *sym_name,
  3830. const Elf64_Sym *sym, const Elf64_Rel *rel)
  3831. {
  3832. struct bpf_insn *insn = &prog->insns[insn_idx];
  3833. size_t map_idx, nr_maps = prog->obj->nr_maps;
  3834. struct bpf_object *obj = prog->obj;
  3835. __u32 shdr_idx = sym->st_shndx;
  3836. enum libbpf_map_type type;
  3837. const char *sym_sec_name;
  3838. struct bpf_map *map;
  3839. if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
  3840. pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
  3841. prog->name, sym_name, insn_idx, insn->code);
  3842. return -LIBBPF_ERRNO__RELOC;
  3843. }
  3844. if (sym_is_extern(sym)) {
  3845. int sym_idx = ELF64_R_SYM(rel->r_info);
  3846. int i, n = obj->nr_extern;
  3847. struct extern_desc *ext;
  3848. for (i = 0; i < n; i++) {
  3849. ext = &obj->externs[i];
  3850. if (ext->sym_idx == sym_idx)
  3851. break;
  3852. }
  3853. if (i >= n) {
  3854. pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
  3855. prog->name, sym_name, sym_idx);
  3856. return -LIBBPF_ERRNO__RELOC;
  3857. }
  3858. pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
  3859. prog->name, i, ext->name, ext->sym_idx, insn_idx);
  3860. if (insn->code == (BPF_JMP | BPF_CALL))
  3861. reloc_desc->type = RELO_EXTERN_CALL;
  3862. else
  3863. reloc_desc->type = RELO_EXTERN_LD64;
  3864. reloc_desc->insn_idx = insn_idx;
  3865. reloc_desc->ext_idx = i;
  3866. return 0;
  3867. }
  3868. /* sub-program call relocation */
  3869. if (is_call_insn(insn)) {
  3870. if (insn->src_reg != BPF_PSEUDO_CALL) {
  3871. pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
  3872. return -LIBBPF_ERRNO__RELOC;
  3873. }
  3874. /* text_shndx can be 0, if no default "main" program exists */
  3875. if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
  3876. sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
  3877. pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
  3878. prog->name, sym_name, sym_sec_name);
  3879. return -LIBBPF_ERRNO__RELOC;
  3880. }
  3881. if (sym->st_value % BPF_INSN_SZ) {
  3882. pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
  3883. prog->name, sym_name, (size_t)sym->st_value);
  3884. return -LIBBPF_ERRNO__RELOC;
  3885. }
  3886. reloc_desc->type = RELO_CALL;
  3887. reloc_desc->insn_idx = insn_idx;
  3888. reloc_desc->sym_off = sym->st_value;
  3889. return 0;
  3890. }
  3891. if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
  3892. pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
  3893. prog->name, sym_name, shdr_idx);
  3894. return -LIBBPF_ERRNO__RELOC;
  3895. }
  3896. /* loading subprog addresses */
  3897. if (sym_is_subprog(sym, obj->efile.text_shndx)) {
  3898. /* global_func: sym->st_value = offset in the section, insn->imm = 0.
  3899. * local_func: sym->st_value = 0, insn->imm = offset in the section.
  3900. */
  3901. if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
  3902. pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
  3903. prog->name, sym_name, (size_t)sym->st_value, insn->imm);
  3904. return -LIBBPF_ERRNO__RELOC;
  3905. }
  3906. reloc_desc->type = RELO_SUBPROG_ADDR;
  3907. reloc_desc->insn_idx = insn_idx;
  3908. reloc_desc->sym_off = sym->st_value;
  3909. return 0;
  3910. }
  3911. type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
  3912. sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
  3913. /* arena data relocation */
  3914. if (shdr_idx == obj->efile.arena_data_shndx) {
  3915. if (obj->arena_map_idx < 0) {
  3916. pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
  3917. prog->name, insn_idx);
  3918. return -LIBBPF_ERRNO__RELOC;
  3919. }
  3920. reloc_desc->type = RELO_DATA;
  3921. reloc_desc->insn_idx = insn_idx;
  3922. reloc_desc->map_idx = obj->arena_map_idx;
  3923. reloc_desc->sym_off = sym->st_value;
  3924. map = &obj->maps[obj->arena_map_idx];
  3925. pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
  3926. prog->name, obj->arena_map_idx, map->name, map->sec_idx,
  3927. map->sec_offset, insn_idx);
  3928. return 0;
  3929. }
  3930. /* generic map reference relocation */
  3931. if (type == LIBBPF_MAP_UNSPEC) {
  3932. if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
  3933. pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
  3934. prog->name, sym_name, sym_sec_name);
  3935. return -LIBBPF_ERRNO__RELOC;
  3936. }
  3937. for (map_idx = 0; map_idx < nr_maps; map_idx++) {
  3938. map = &obj->maps[map_idx];
  3939. if (map->libbpf_type != type ||
  3940. map->sec_idx != sym->st_shndx ||
  3941. map->sec_offset != sym->st_value)
  3942. continue;
  3943. pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
  3944. prog->name, map_idx, map->name, map->sec_idx,
  3945. map->sec_offset, insn_idx);
  3946. break;
  3947. }
  3948. if (map_idx >= nr_maps) {
  3949. pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
  3950. prog->name, sym_sec_name, (size_t)sym->st_value);
  3951. return -LIBBPF_ERRNO__RELOC;
  3952. }
  3953. reloc_desc->type = RELO_LD64;
  3954. reloc_desc->insn_idx = insn_idx;
  3955. reloc_desc->map_idx = map_idx;
  3956. reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
  3957. return 0;
  3958. }
  3959. /* global data map relocation */
  3960. if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
  3961. pr_warn("prog '%s': bad data relo against section '%s'\n",
  3962. prog->name, sym_sec_name);
  3963. return -LIBBPF_ERRNO__RELOC;
  3964. }
  3965. for (map_idx = 0; map_idx < nr_maps; map_idx++) {
  3966. map = &obj->maps[map_idx];
  3967. if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
  3968. continue;
  3969. pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
  3970. prog->name, map_idx, map->name, map->sec_idx,
  3971. map->sec_offset, insn_idx);
  3972. break;
  3973. }
  3974. if (map_idx >= nr_maps) {
  3975. pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
  3976. prog->name, sym_sec_name);
  3977. return -LIBBPF_ERRNO__RELOC;
  3978. }
  3979. reloc_desc->type = RELO_DATA;
  3980. reloc_desc->insn_idx = insn_idx;
  3981. reloc_desc->map_idx = map_idx;
  3982. reloc_desc->sym_off = sym->st_value;
  3983. return 0;
  3984. }
  3985. static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
  3986. {
  3987. return insn_idx >= prog->sec_insn_off &&
  3988. insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
  3989. }
  3990. static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
  3991. size_t sec_idx, size_t insn_idx)
  3992. {
  3993. int l = 0, r = obj->nr_programs - 1, m;
  3994. struct bpf_program *prog;
  3995. if (!obj->nr_programs)
  3996. return NULL;
  3997. while (l < r) {
  3998. m = l + (r - l + 1) / 2;
  3999. prog = &obj->programs[m];
  4000. if (prog->sec_idx < sec_idx ||
  4001. (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
  4002. l = m;
  4003. else
  4004. r = m - 1;
  4005. }
  4006. /* matching program could be at index l, but it still might be the
  4007. * wrong one, so we need to double check conditions for the last time
  4008. */
  4009. prog = &obj->programs[l];
  4010. if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
  4011. return prog;
  4012. return NULL;
  4013. }
  4014. static int
  4015. bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
  4016. {
  4017. const char *relo_sec_name, *sec_name;
  4018. size_t sec_idx = shdr->sh_info, sym_idx;
  4019. struct bpf_program *prog;
  4020. struct reloc_desc *relos;
  4021. int err, i, nrels;
  4022. const char *sym_name;
  4023. __u32 insn_idx;
  4024. Elf_Scn *scn;
  4025. Elf_Data *scn_data;
  4026. Elf64_Sym *sym;
  4027. Elf64_Rel *rel;
  4028. if (sec_idx >= obj->efile.sec_cnt)
  4029. return -EINVAL;
  4030. scn = elf_sec_by_idx(obj, sec_idx);
  4031. scn_data = elf_sec_data(obj, scn);
  4032. if (!scn_data)
  4033. return -LIBBPF_ERRNO__FORMAT;
  4034. relo_sec_name = elf_sec_str(obj, shdr->sh_name);
  4035. sec_name = elf_sec_name(obj, scn);
  4036. if (!relo_sec_name || !sec_name)
  4037. return -EINVAL;
  4038. pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
  4039. relo_sec_name, sec_idx, sec_name);
  4040. nrels = shdr->sh_size / shdr->sh_entsize;
  4041. for (i = 0; i < nrels; i++) {
  4042. rel = elf_rel_by_idx(data, i);
  4043. if (!rel) {
  4044. pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
  4045. return -LIBBPF_ERRNO__FORMAT;
  4046. }
  4047. sym_idx = ELF64_R_SYM(rel->r_info);
  4048. sym = elf_sym_by_idx(obj, sym_idx);
  4049. if (!sym) {
  4050. pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
  4051. relo_sec_name, sym_idx, i);
  4052. return -LIBBPF_ERRNO__FORMAT;
  4053. }
  4054. if (sym->st_shndx >= obj->efile.sec_cnt) {
  4055. pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
  4056. relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
  4057. return -LIBBPF_ERRNO__FORMAT;
  4058. }
  4059. if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
  4060. pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
  4061. relo_sec_name, (size_t)rel->r_offset, i);
  4062. return -LIBBPF_ERRNO__FORMAT;
  4063. }
  4064. insn_idx = rel->r_offset / BPF_INSN_SZ;
  4065. /* relocations against static functions are recorded as
  4066. * relocations against the section that contains a function;
  4067. * in such case, symbol will be STT_SECTION and sym.st_name
  4068. * will point to empty string (0), so fetch section name
  4069. * instead
  4070. */
  4071. if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
  4072. sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
  4073. else
  4074. sym_name = elf_sym_str(obj, sym->st_name);
  4075. sym_name = sym_name ?: "<?";
  4076. pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
  4077. relo_sec_name, i, insn_idx, sym_name);
  4078. prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
  4079. if (!prog) {
  4080. pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
  4081. relo_sec_name, i, sec_name, insn_idx);
  4082. continue;
  4083. }
  4084. relos = libbpf_reallocarray(prog->reloc_desc,
  4085. prog->nr_reloc + 1, sizeof(*relos));
  4086. if (!relos)
  4087. return -ENOMEM;
  4088. prog->reloc_desc = relos;
  4089. /* adjust insn_idx to local BPF program frame of reference */
  4090. insn_idx -= prog->sec_insn_off;
  4091. err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
  4092. insn_idx, sym_name, sym, rel);
  4093. if (err)
  4094. return err;
  4095. prog->nr_reloc++;
  4096. }
  4097. return 0;
  4098. }
  4099. static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
  4100. {
  4101. int id;
  4102. if (!obj->btf)
  4103. return -ENOENT;
  4104. /* if it's BTF-defined map, we don't need to search for type IDs.
  4105. * For struct_ops map, it does not need btf_key_type_id and
  4106. * btf_value_type_id.
  4107. */
  4108. if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
  4109. return 0;
  4110. /*
  4111. * LLVM annotates global data differently in BTF, that is,
  4112. * only as '.data', '.bss' or '.rodata'.
  4113. */
  4114. if (!bpf_map__is_internal(map))
  4115. return -ENOENT;
  4116. id = btf__find_by_name(obj->btf, map->real_name);
  4117. if (id < 0)
  4118. return id;
  4119. map->btf_key_type_id = 0;
  4120. map->btf_value_type_id = id;
  4121. return 0;
  4122. }
  4123. static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
  4124. {
  4125. char file[PATH_MAX], buff[4096];
  4126. FILE *fp;
  4127. __u32 val;
  4128. int err;
  4129. snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
  4130. memset(info, 0, sizeof(*info));
  4131. fp = fopen(file, "re");
  4132. if (!fp) {
  4133. err = -errno;
  4134. pr_warn("failed to open %s: %d. No procfs support?\n", file,
  4135. err);
  4136. return err;
  4137. }
  4138. while (fgets(buff, sizeof(buff), fp)) {
  4139. if (sscanf(buff, "map_type:\t%u", &val) == 1)
  4140. info->type = val;
  4141. else if (sscanf(buff, "key_size:\t%u", &val) == 1)
  4142. info->key_size = val;
  4143. else if (sscanf(buff, "value_size:\t%u", &val) == 1)
  4144. info->value_size = val;
  4145. else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
  4146. info->max_entries = val;
  4147. else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
  4148. info->map_flags = val;
  4149. }
  4150. fclose(fp);
  4151. return 0;
  4152. }
  4153. bool bpf_map__autocreate(const struct bpf_map *map)
  4154. {
  4155. return map->autocreate;
  4156. }
  4157. int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
  4158. {
  4159. if (map->obj->loaded)
  4160. return libbpf_err(-EBUSY);
  4161. map->autocreate = autocreate;
  4162. return 0;
  4163. }
  4164. int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
  4165. {
  4166. if (!bpf_map__is_struct_ops(map))
  4167. return libbpf_err(-EINVAL);
  4168. map->autoattach = autoattach;
  4169. return 0;
  4170. }
  4171. bool bpf_map__autoattach(const struct bpf_map *map)
  4172. {
  4173. return map->autoattach;
  4174. }
  4175. int bpf_map__reuse_fd(struct bpf_map *map, int fd)
  4176. {
  4177. struct bpf_map_info info;
  4178. __u32 len = sizeof(info), name_len;
  4179. int new_fd, err;
  4180. char *new_name;
  4181. memset(&info, 0, len);
  4182. err = bpf_map_get_info_by_fd(fd, &info, &len);
  4183. if (err && errno == EINVAL)
  4184. err = bpf_get_map_info_from_fdinfo(fd, &info);
  4185. if (err)
  4186. return libbpf_err(err);
  4187. name_len = strlen(info.name);
  4188. if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
  4189. new_name = strdup(map->name);
  4190. else
  4191. new_name = strdup(info.name);
  4192. if (!new_name)
  4193. return libbpf_err(-errno);
  4194. /*
  4195. * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
  4196. * This is similar to what we do in ensure_good_fd(), but without
  4197. * closing original FD.
  4198. */
  4199. new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
  4200. if (new_fd < 0) {
  4201. err = -errno;
  4202. goto err_free_new_name;
  4203. }
  4204. err = reuse_fd(map->fd, new_fd);
  4205. if (err)
  4206. goto err_free_new_name;
  4207. free(map->name);
  4208. map->name = new_name;
  4209. map->def.type = info.type;
  4210. map->def.key_size = info.key_size;
  4211. map->def.value_size = info.value_size;
  4212. map->def.max_entries = info.max_entries;
  4213. map->def.map_flags = info.map_flags;
  4214. map->btf_key_type_id = info.btf_key_type_id;
  4215. map->btf_value_type_id = info.btf_value_type_id;
  4216. map->reused = true;
  4217. map->map_extra = info.map_extra;
  4218. return 0;
  4219. err_free_new_name:
  4220. free(new_name);
  4221. return libbpf_err(err);
  4222. }
  4223. __u32 bpf_map__max_entries(const struct bpf_map *map)
  4224. {
  4225. return map->def.max_entries;
  4226. }
  4227. struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
  4228. {
  4229. if (!bpf_map_type__is_map_in_map(map->def.type))
  4230. return errno = EINVAL, NULL;
  4231. return map->inner_map;
  4232. }
  4233. int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
  4234. {
  4235. if (map->obj->loaded)
  4236. return libbpf_err(-EBUSY);
  4237. map->def.max_entries = max_entries;
  4238. /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
  4239. if (map_is_ringbuf(map))
  4240. map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
  4241. return 0;
  4242. }
  4243. static int bpf_object_prepare_token(struct bpf_object *obj)
  4244. {
  4245. const char *bpffs_path;
  4246. int bpffs_fd = -1, token_fd, err;
  4247. bool mandatory;
  4248. enum libbpf_print_level level;
  4249. /* token is explicitly prevented */
  4250. if (obj->token_path && obj->token_path[0] == '\0') {
  4251. pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
  4252. return 0;
  4253. }
  4254. mandatory = obj->token_path != NULL;
  4255. level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
  4256. bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
  4257. bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
  4258. if (bpffs_fd < 0) {
  4259. err = -errno;
  4260. __pr(level, "object '%s': failed (%d) to open BPF FS mount at '%s'%s\n",
  4261. obj->name, err, bpffs_path,
  4262. mandatory ? "" : ", skipping optional step...");
  4263. return mandatory ? err : 0;
  4264. }
  4265. token_fd = bpf_token_create(bpffs_fd, 0);
  4266. close(bpffs_fd);
  4267. if (token_fd < 0) {
  4268. if (!mandatory && token_fd == -ENOENT) {
  4269. pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
  4270. obj->name, bpffs_path);
  4271. return 0;
  4272. }
  4273. __pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
  4274. obj->name, token_fd, bpffs_path,
  4275. mandatory ? "" : ", skipping optional step...");
  4276. return mandatory ? token_fd : 0;
  4277. }
  4278. obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
  4279. if (!obj->feat_cache) {
  4280. close(token_fd);
  4281. return -ENOMEM;
  4282. }
  4283. obj->token_fd = token_fd;
  4284. obj->feat_cache->token_fd = token_fd;
  4285. return 0;
  4286. }
  4287. static int
  4288. bpf_object__probe_loading(struct bpf_object *obj)
  4289. {
  4290. char *cp, errmsg[STRERR_BUFSIZE];
  4291. struct bpf_insn insns[] = {
  4292. BPF_MOV64_IMM(BPF_REG_0, 0),
  4293. BPF_EXIT_INSN(),
  4294. };
  4295. int ret, insn_cnt = ARRAY_SIZE(insns);
  4296. LIBBPF_OPTS(bpf_prog_load_opts, opts,
  4297. .token_fd = obj->token_fd,
  4298. .prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
  4299. );
  4300. if (obj->gen_loader)
  4301. return 0;
  4302. ret = bump_rlimit_memlock();
  4303. if (ret)
  4304. pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
  4305. /* make sure basic loading works */
  4306. ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
  4307. if (ret < 0)
  4308. ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
  4309. if (ret < 0) {
  4310. ret = errno;
  4311. cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
  4312. pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
  4313. "program. Make sure your kernel supports BPF "
  4314. "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
  4315. "set to big enough value.\n", __func__, cp, ret);
  4316. return -ret;
  4317. }
  4318. close(ret);
  4319. return 0;
  4320. }
  4321. bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
  4322. {
  4323. if (obj->gen_loader)
  4324. /* To generate loader program assume the latest kernel
  4325. * to avoid doing extra prog_load, map_create syscalls.
  4326. */
  4327. return true;
  4328. if (obj->token_fd)
  4329. return feat_supported(obj->feat_cache, feat_id);
  4330. return feat_supported(NULL, feat_id);
  4331. }
  4332. static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
  4333. {
  4334. struct bpf_map_info map_info;
  4335. char msg[STRERR_BUFSIZE];
  4336. __u32 map_info_len = sizeof(map_info);
  4337. int err;
  4338. memset(&map_info, 0, map_info_len);
  4339. err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
  4340. if (err && errno == EINVAL)
  4341. err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
  4342. if (err) {
  4343. pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
  4344. libbpf_strerror_r(errno, msg, sizeof(msg)));
  4345. return false;
  4346. }
  4347. /*
  4348. * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
  4349. * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
  4350. * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
  4351. * bpf_get_map_info_by_fd() when checking for compatibility with an
  4352. * existing DEVMAP.
  4353. */
  4354. if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
  4355. map_info.map_flags &= ~BPF_F_RDONLY_PROG;
  4356. return (map_info.type == map->def.type &&
  4357. map_info.key_size == map->def.key_size &&
  4358. map_info.value_size == map->def.value_size &&
  4359. map_info.max_entries == map->def.max_entries &&
  4360. map_info.map_flags == map->def.map_flags &&
  4361. map_info.map_extra == map->map_extra);
  4362. }
  4363. static int
  4364. bpf_object__reuse_map(struct bpf_map *map)
  4365. {
  4366. char *cp, errmsg[STRERR_BUFSIZE];
  4367. int err, pin_fd;
  4368. pin_fd = bpf_obj_get(map->pin_path);
  4369. if (pin_fd < 0) {
  4370. err = -errno;
  4371. if (err == -ENOENT) {
  4372. pr_debug("found no pinned map to reuse at '%s'\n",
  4373. map->pin_path);
  4374. return 0;
  4375. }
  4376. cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
  4377. pr_warn("couldn't retrieve pinned map '%s': %s\n",
  4378. map->pin_path, cp);
  4379. return err;
  4380. }
  4381. if (!map_is_reuse_compat(map, pin_fd)) {
  4382. pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
  4383. map->pin_path);
  4384. close(pin_fd);
  4385. return -EINVAL;
  4386. }
  4387. err = bpf_map__reuse_fd(map, pin_fd);
  4388. close(pin_fd);
  4389. if (err)
  4390. return err;
  4391. map->pinned = true;
  4392. pr_debug("reused pinned map at '%s'\n", map->pin_path);
  4393. return 0;
  4394. }
  4395. static int
  4396. bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
  4397. {
  4398. enum libbpf_map_type map_type = map->libbpf_type;
  4399. char *cp, errmsg[STRERR_BUFSIZE];
  4400. int err, zero = 0;
  4401. size_t mmap_sz;
  4402. if (obj->gen_loader) {
  4403. bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
  4404. map->mmaped, map->def.value_size);
  4405. if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
  4406. bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
  4407. return 0;
  4408. }
  4409. err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
  4410. if (err) {
  4411. err = -errno;
  4412. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  4413. pr_warn("map '%s': failed to set initial contents: %s\n",
  4414. bpf_map__name(map), cp);
  4415. return err;
  4416. }
  4417. /* Freeze .rodata and .kconfig map as read-only from syscall side. */
  4418. if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
  4419. err = bpf_map_freeze(map->fd);
  4420. if (err) {
  4421. err = -errno;
  4422. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  4423. pr_warn("map '%s': failed to freeze as read-only: %s\n",
  4424. bpf_map__name(map), cp);
  4425. return err;
  4426. }
  4427. }
  4428. /* Remap anonymous mmap()-ed "map initialization image" as
  4429. * a BPF map-backed mmap()-ed memory, but preserving the same
  4430. * memory address. This will cause kernel to change process'
  4431. * page table to point to a different piece of kernel memory,
  4432. * but from userspace point of view memory address (and its
  4433. * contents, being identical at this point) will stay the
  4434. * same. This mapping will be released by bpf_object__close()
  4435. * as per normal clean up procedure.
  4436. */
  4437. mmap_sz = bpf_map_mmap_sz(map);
  4438. if (map->def.map_flags & BPF_F_MMAPABLE) {
  4439. void *mmaped;
  4440. int prot;
  4441. if (map->def.map_flags & BPF_F_RDONLY_PROG)
  4442. prot = PROT_READ;
  4443. else
  4444. prot = PROT_READ | PROT_WRITE;
  4445. mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
  4446. if (mmaped == MAP_FAILED) {
  4447. err = -errno;
  4448. pr_warn("map '%s': failed to re-mmap() contents: %d\n",
  4449. bpf_map__name(map), err);
  4450. return err;
  4451. }
  4452. map->mmaped = mmaped;
  4453. } else if (map->mmaped) {
  4454. munmap(map->mmaped, mmap_sz);
  4455. map->mmaped = NULL;
  4456. }
  4457. return 0;
  4458. }
  4459. static void bpf_map__destroy(struct bpf_map *map);
  4460. static bool map_is_created(const struct bpf_map *map)
  4461. {
  4462. return map->obj->loaded || map->reused;
  4463. }
  4464. static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
  4465. {
  4466. LIBBPF_OPTS(bpf_map_create_opts, create_attr);
  4467. struct bpf_map_def *def = &map->def;
  4468. const char *map_name = NULL;
  4469. int err = 0, map_fd;
  4470. if (kernel_supports(obj, FEAT_PROG_NAME))
  4471. map_name = map->name;
  4472. create_attr.map_ifindex = map->map_ifindex;
  4473. create_attr.map_flags = def->map_flags;
  4474. create_attr.numa_node = map->numa_node;
  4475. create_attr.map_extra = map->map_extra;
  4476. create_attr.token_fd = obj->token_fd;
  4477. if (obj->token_fd)
  4478. create_attr.map_flags |= BPF_F_TOKEN_FD;
  4479. if (bpf_map__is_struct_ops(map)) {
  4480. create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
  4481. if (map->mod_btf_fd >= 0) {
  4482. create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
  4483. create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
  4484. }
  4485. }
  4486. if (obj->btf && btf__fd(obj->btf) >= 0) {
  4487. create_attr.btf_fd = btf__fd(obj->btf);
  4488. create_attr.btf_key_type_id = map->btf_key_type_id;
  4489. create_attr.btf_value_type_id = map->btf_value_type_id;
  4490. }
  4491. if (bpf_map_type__is_map_in_map(def->type)) {
  4492. if (map->inner_map) {
  4493. err = map_set_def_max_entries(map->inner_map);
  4494. if (err)
  4495. return err;
  4496. err = bpf_object__create_map(obj, map->inner_map, true);
  4497. if (err) {
  4498. pr_warn("map '%s': failed to create inner map: %d\n",
  4499. map->name, err);
  4500. return err;
  4501. }
  4502. map->inner_map_fd = map->inner_map->fd;
  4503. }
  4504. if (map->inner_map_fd >= 0)
  4505. create_attr.inner_map_fd = map->inner_map_fd;
  4506. }
  4507. switch (def->type) {
  4508. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  4509. case BPF_MAP_TYPE_CGROUP_ARRAY:
  4510. case BPF_MAP_TYPE_STACK_TRACE:
  4511. case BPF_MAP_TYPE_ARRAY_OF_MAPS:
  4512. case BPF_MAP_TYPE_HASH_OF_MAPS:
  4513. case BPF_MAP_TYPE_DEVMAP:
  4514. case BPF_MAP_TYPE_DEVMAP_HASH:
  4515. case BPF_MAP_TYPE_CPUMAP:
  4516. case BPF_MAP_TYPE_XSKMAP:
  4517. case BPF_MAP_TYPE_SOCKMAP:
  4518. case BPF_MAP_TYPE_SOCKHASH:
  4519. case BPF_MAP_TYPE_QUEUE:
  4520. case BPF_MAP_TYPE_STACK:
  4521. case BPF_MAP_TYPE_ARENA:
  4522. create_attr.btf_fd = 0;
  4523. create_attr.btf_key_type_id = 0;
  4524. create_attr.btf_value_type_id = 0;
  4525. map->btf_key_type_id = 0;
  4526. map->btf_value_type_id = 0;
  4527. break;
  4528. case BPF_MAP_TYPE_STRUCT_OPS:
  4529. create_attr.btf_value_type_id = 0;
  4530. break;
  4531. default:
  4532. break;
  4533. }
  4534. if (obj->gen_loader) {
  4535. bpf_gen__map_create(obj->gen_loader, def->type, map_name,
  4536. def->key_size, def->value_size, def->max_entries,
  4537. &create_attr, is_inner ? -1 : map - obj->maps);
  4538. /* We keep pretenting we have valid FD to pass various fd >= 0
  4539. * checks by just keeping original placeholder FDs in place.
  4540. * See bpf_object__add_map() comment.
  4541. * This placeholder fd will not be used with any syscall and
  4542. * will be reset to -1 eventually.
  4543. */
  4544. map_fd = map->fd;
  4545. } else {
  4546. map_fd = bpf_map_create(def->type, map_name,
  4547. def->key_size, def->value_size,
  4548. def->max_entries, &create_attr);
  4549. }
  4550. if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
  4551. char *cp, errmsg[STRERR_BUFSIZE];
  4552. err = -errno;
  4553. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  4554. pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
  4555. map->name, cp, err);
  4556. create_attr.btf_fd = 0;
  4557. create_attr.btf_key_type_id = 0;
  4558. create_attr.btf_value_type_id = 0;
  4559. map->btf_key_type_id = 0;
  4560. map->btf_value_type_id = 0;
  4561. map_fd = bpf_map_create(def->type, map_name,
  4562. def->key_size, def->value_size,
  4563. def->max_entries, &create_attr);
  4564. }
  4565. if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
  4566. if (obj->gen_loader)
  4567. map->inner_map->fd = -1;
  4568. bpf_map__destroy(map->inner_map);
  4569. zfree(&map->inner_map);
  4570. }
  4571. if (map_fd < 0)
  4572. return map_fd;
  4573. /* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
  4574. if (map->fd == map_fd)
  4575. return 0;
  4576. /* Keep placeholder FD value but now point it to the BPF map object.
  4577. * This way everything that relied on this map's FD (e.g., relocated
  4578. * ldimm64 instructions) will stay valid and won't need adjustments.
  4579. * map->fd stays valid but now point to what map_fd points to.
  4580. */
  4581. return reuse_fd(map->fd, map_fd);
  4582. }
  4583. static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
  4584. {
  4585. const struct bpf_map *targ_map;
  4586. unsigned int i;
  4587. int fd, err = 0;
  4588. for (i = 0; i < map->init_slots_sz; i++) {
  4589. if (!map->init_slots[i])
  4590. continue;
  4591. targ_map = map->init_slots[i];
  4592. fd = targ_map->fd;
  4593. if (obj->gen_loader) {
  4594. bpf_gen__populate_outer_map(obj->gen_loader,
  4595. map - obj->maps, i,
  4596. targ_map - obj->maps);
  4597. } else {
  4598. err = bpf_map_update_elem(map->fd, &i, &fd, 0);
  4599. }
  4600. if (err) {
  4601. err = -errno;
  4602. pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
  4603. map->name, i, targ_map->name, fd, err);
  4604. return err;
  4605. }
  4606. pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
  4607. map->name, i, targ_map->name, fd);
  4608. }
  4609. zfree(&map->init_slots);
  4610. map->init_slots_sz = 0;
  4611. return 0;
  4612. }
  4613. static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
  4614. {
  4615. const struct bpf_program *targ_prog;
  4616. unsigned int i;
  4617. int fd, err;
  4618. if (obj->gen_loader)
  4619. return -ENOTSUP;
  4620. for (i = 0; i < map->init_slots_sz; i++) {
  4621. if (!map->init_slots[i])
  4622. continue;
  4623. targ_prog = map->init_slots[i];
  4624. fd = bpf_program__fd(targ_prog);
  4625. err = bpf_map_update_elem(map->fd, &i, &fd, 0);
  4626. if (err) {
  4627. err = -errno;
  4628. pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
  4629. map->name, i, targ_prog->name, fd, err);
  4630. return err;
  4631. }
  4632. pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
  4633. map->name, i, targ_prog->name, fd);
  4634. }
  4635. zfree(&map->init_slots);
  4636. map->init_slots_sz = 0;
  4637. return 0;
  4638. }
  4639. static int bpf_object_init_prog_arrays(struct bpf_object *obj)
  4640. {
  4641. struct bpf_map *map;
  4642. int i, err;
  4643. for (i = 0; i < obj->nr_maps; i++) {
  4644. map = &obj->maps[i];
  4645. if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
  4646. continue;
  4647. err = init_prog_array_slots(obj, map);
  4648. if (err < 0)
  4649. return err;
  4650. }
  4651. return 0;
  4652. }
  4653. static int map_set_def_max_entries(struct bpf_map *map)
  4654. {
  4655. if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
  4656. int nr_cpus;
  4657. nr_cpus = libbpf_num_possible_cpus();
  4658. if (nr_cpus < 0) {
  4659. pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
  4660. map->name, nr_cpus);
  4661. return nr_cpus;
  4662. }
  4663. pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
  4664. map->def.max_entries = nr_cpus;
  4665. }
  4666. return 0;
  4667. }
  4668. static int
  4669. bpf_object__create_maps(struct bpf_object *obj)
  4670. {
  4671. struct bpf_map *map;
  4672. char *cp, errmsg[STRERR_BUFSIZE];
  4673. unsigned int i, j;
  4674. int err;
  4675. bool retried;
  4676. for (i = 0; i < obj->nr_maps; i++) {
  4677. map = &obj->maps[i];
  4678. /* To support old kernels, we skip creating global data maps
  4679. * (.rodata, .data, .kconfig, etc); later on, during program
  4680. * loading, if we detect that at least one of the to-be-loaded
  4681. * programs is referencing any global data map, we'll error
  4682. * out with program name and relocation index logged.
  4683. * This approach allows to accommodate Clang emitting
  4684. * unnecessary .rodata.str1.1 sections for string literals,
  4685. * but also it allows to have CO-RE applications that use
  4686. * global variables in some of BPF programs, but not others.
  4687. * If those global variable-using programs are not loaded at
  4688. * runtime due to bpf_program__set_autoload(prog, false),
  4689. * bpf_object loading will succeed just fine even on old
  4690. * kernels.
  4691. */
  4692. if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
  4693. map->autocreate = false;
  4694. if (!map->autocreate) {
  4695. pr_debug("map '%s': skipped auto-creating...\n", map->name);
  4696. continue;
  4697. }
  4698. err = map_set_def_max_entries(map);
  4699. if (err)
  4700. goto err_out;
  4701. retried = false;
  4702. retry:
  4703. if (map->pin_path) {
  4704. err = bpf_object__reuse_map(map);
  4705. if (err) {
  4706. pr_warn("map '%s': error reusing pinned map\n",
  4707. map->name);
  4708. goto err_out;
  4709. }
  4710. if (retried && map->fd < 0) {
  4711. pr_warn("map '%s': cannot find pinned map\n",
  4712. map->name);
  4713. err = -ENOENT;
  4714. goto err_out;
  4715. }
  4716. }
  4717. if (map->reused) {
  4718. pr_debug("map '%s': skipping creation (preset fd=%d)\n",
  4719. map->name, map->fd);
  4720. } else {
  4721. err = bpf_object__create_map(obj, map, false);
  4722. if (err)
  4723. goto err_out;
  4724. pr_debug("map '%s': created successfully, fd=%d\n",
  4725. map->name, map->fd);
  4726. if (bpf_map__is_internal(map)) {
  4727. err = bpf_object__populate_internal_map(obj, map);
  4728. if (err < 0)
  4729. goto err_out;
  4730. } else if (map->def.type == BPF_MAP_TYPE_ARENA) {
  4731. map->mmaped = mmap((void *)(long)map->map_extra,
  4732. bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
  4733. map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
  4734. map->fd, 0);
  4735. if (map->mmaped == MAP_FAILED) {
  4736. err = -errno;
  4737. map->mmaped = NULL;
  4738. pr_warn("map '%s': failed to mmap arena: %d\n",
  4739. map->name, err);
  4740. return err;
  4741. }
  4742. if (obj->arena_data) {
  4743. memcpy(map->mmaped, obj->arena_data, obj->arena_data_sz);
  4744. zfree(&obj->arena_data);
  4745. }
  4746. }
  4747. if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
  4748. err = init_map_in_map_slots(obj, map);
  4749. if (err < 0)
  4750. goto err_out;
  4751. }
  4752. }
  4753. if (map->pin_path && !map->pinned) {
  4754. err = bpf_map__pin(map, NULL);
  4755. if (err) {
  4756. if (!retried && err == -EEXIST) {
  4757. retried = true;
  4758. goto retry;
  4759. }
  4760. pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
  4761. map->name, map->pin_path, err);
  4762. goto err_out;
  4763. }
  4764. }
  4765. }
  4766. return 0;
  4767. err_out:
  4768. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  4769. pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
  4770. pr_perm_msg(err);
  4771. for (j = 0; j < i; j++)
  4772. zclose(obj->maps[j].fd);
  4773. return err;
  4774. }
  4775. static bool bpf_core_is_flavor_sep(const char *s)
  4776. {
  4777. /* check X___Y name pattern, where X and Y are not underscores */
  4778. return s[0] != '_' && /* X */
  4779. s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
  4780. s[4] != '_'; /* Y */
  4781. }
  4782. /* Given 'some_struct_name___with_flavor' return the length of a name prefix
  4783. * before last triple underscore. Struct name part after last triple
  4784. * underscore is ignored by BPF CO-RE relocation during relocation matching.
  4785. */
  4786. size_t bpf_core_essential_name_len(const char *name)
  4787. {
  4788. size_t n = strlen(name);
  4789. int i;
  4790. for (i = n - 5; i >= 0; i--) {
  4791. if (bpf_core_is_flavor_sep(name + i))
  4792. return i + 1;
  4793. }
  4794. return n;
  4795. }
  4796. void bpf_core_free_cands(struct bpf_core_cand_list *cands)
  4797. {
  4798. if (!cands)
  4799. return;
  4800. free(cands->cands);
  4801. free(cands);
  4802. }
  4803. int bpf_core_add_cands(struct bpf_core_cand *local_cand,
  4804. size_t local_essent_len,
  4805. const struct btf *targ_btf,
  4806. const char *targ_btf_name,
  4807. int targ_start_id,
  4808. struct bpf_core_cand_list *cands)
  4809. {
  4810. struct bpf_core_cand *new_cands, *cand;
  4811. const struct btf_type *t, *local_t;
  4812. const char *targ_name, *local_name;
  4813. size_t targ_essent_len;
  4814. int n, i;
  4815. local_t = btf__type_by_id(local_cand->btf, local_cand->id);
  4816. local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
  4817. n = btf__type_cnt(targ_btf);
  4818. for (i = targ_start_id; i < n; i++) {
  4819. t = btf__type_by_id(targ_btf, i);
  4820. if (!btf_kind_core_compat(t, local_t))
  4821. continue;
  4822. targ_name = btf__name_by_offset(targ_btf, t->name_off);
  4823. if (str_is_empty(targ_name))
  4824. continue;
  4825. targ_essent_len = bpf_core_essential_name_len(targ_name);
  4826. if (targ_essent_len != local_essent_len)
  4827. continue;
  4828. if (strncmp(local_name, targ_name, local_essent_len) != 0)
  4829. continue;
  4830. pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
  4831. local_cand->id, btf_kind_str(local_t),
  4832. local_name, i, btf_kind_str(t), targ_name,
  4833. targ_btf_name);
  4834. new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
  4835. sizeof(*cands->cands));
  4836. if (!new_cands)
  4837. return -ENOMEM;
  4838. cand = &new_cands[cands->len];
  4839. cand->btf = targ_btf;
  4840. cand->id = i;
  4841. cands->cands = new_cands;
  4842. cands->len++;
  4843. }
  4844. return 0;
  4845. }
  4846. static int load_module_btfs(struct bpf_object *obj)
  4847. {
  4848. struct bpf_btf_info info;
  4849. struct module_btf *mod_btf;
  4850. struct btf *btf;
  4851. char name[64];
  4852. __u32 id = 0, len;
  4853. int err, fd;
  4854. if (obj->btf_modules_loaded)
  4855. return 0;
  4856. if (obj->gen_loader)
  4857. return 0;
  4858. /* don't do this again, even if we find no module BTFs */
  4859. obj->btf_modules_loaded = true;
  4860. /* kernel too old to support module BTFs */
  4861. if (!kernel_supports(obj, FEAT_MODULE_BTF))
  4862. return 0;
  4863. while (true) {
  4864. err = bpf_btf_get_next_id(id, &id);
  4865. if (err && errno == ENOENT)
  4866. return 0;
  4867. if (err && errno == EPERM) {
  4868. pr_debug("skipping module BTFs loading, missing privileges\n");
  4869. return 0;
  4870. }
  4871. if (err) {
  4872. err = -errno;
  4873. pr_warn("failed to iterate BTF objects: %d\n", err);
  4874. return err;
  4875. }
  4876. fd = bpf_btf_get_fd_by_id(id);
  4877. if (fd < 0) {
  4878. if (errno == ENOENT)
  4879. continue; /* expected race: BTF was unloaded */
  4880. err = -errno;
  4881. pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
  4882. return err;
  4883. }
  4884. len = sizeof(info);
  4885. memset(&info, 0, sizeof(info));
  4886. info.name = ptr_to_u64(name);
  4887. info.name_len = sizeof(name);
  4888. err = bpf_btf_get_info_by_fd(fd, &info, &len);
  4889. if (err) {
  4890. err = -errno;
  4891. pr_warn("failed to get BTF object #%d info: %d\n", id, err);
  4892. goto err_out;
  4893. }
  4894. /* ignore non-module BTFs */
  4895. if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
  4896. close(fd);
  4897. continue;
  4898. }
  4899. btf = btf_get_from_fd(fd, obj->btf_vmlinux);
  4900. err = libbpf_get_error(btf);
  4901. if (err) {
  4902. pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
  4903. name, id, err);
  4904. goto err_out;
  4905. }
  4906. err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
  4907. sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
  4908. if (err)
  4909. goto err_out;
  4910. mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
  4911. mod_btf->btf = btf;
  4912. mod_btf->id = id;
  4913. mod_btf->fd = fd;
  4914. mod_btf->name = strdup(name);
  4915. if (!mod_btf->name) {
  4916. err = -ENOMEM;
  4917. goto err_out;
  4918. }
  4919. continue;
  4920. err_out:
  4921. close(fd);
  4922. return err;
  4923. }
  4924. return 0;
  4925. }
  4926. static struct bpf_core_cand_list *
  4927. bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
  4928. {
  4929. struct bpf_core_cand local_cand = {};
  4930. struct bpf_core_cand_list *cands;
  4931. const struct btf *main_btf;
  4932. const struct btf_type *local_t;
  4933. const char *local_name;
  4934. size_t local_essent_len;
  4935. int err, i;
  4936. local_cand.btf = local_btf;
  4937. local_cand.id = local_type_id;
  4938. local_t = btf__type_by_id(local_btf, local_type_id);
  4939. if (!local_t)
  4940. return ERR_PTR(-EINVAL);
  4941. local_name = btf__name_by_offset(local_btf, local_t->name_off);
  4942. if (str_is_empty(local_name))
  4943. return ERR_PTR(-EINVAL);
  4944. local_essent_len = bpf_core_essential_name_len(local_name);
  4945. cands = calloc(1, sizeof(*cands));
  4946. if (!cands)
  4947. return ERR_PTR(-ENOMEM);
  4948. /* Attempt to find target candidates in vmlinux BTF first */
  4949. main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
  4950. err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
  4951. if (err)
  4952. goto err_out;
  4953. /* if vmlinux BTF has any candidate, don't got for module BTFs */
  4954. if (cands->len)
  4955. return cands;
  4956. /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
  4957. if (obj->btf_vmlinux_override)
  4958. return cands;
  4959. /* now look through module BTFs, trying to still find candidates */
  4960. err = load_module_btfs(obj);
  4961. if (err)
  4962. goto err_out;
  4963. for (i = 0; i < obj->btf_module_cnt; i++) {
  4964. err = bpf_core_add_cands(&local_cand, local_essent_len,
  4965. obj->btf_modules[i].btf,
  4966. obj->btf_modules[i].name,
  4967. btf__type_cnt(obj->btf_vmlinux),
  4968. cands);
  4969. if (err)
  4970. goto err_out;
  4971. }
  4972. return cands;
  4973. err_out:
  4974. bpf_core_free_cands(cands);
  4975. return ERR_PTR(err);
  4976. }
  4977. /* Check local and target types for compatibility. This check is used for
  4978. * type-based CO-RE relocations and follow slightly different rules than
  4979. * field-based relocations. This function assumes that root types were already
  4980. * checked for name match. Beyond that initial root-level name check, names
  4981. * are completely ignored. Compatibility rules are as follows:
  4982. * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
  4983. * kind should match for local and target types (i.e., STRUCT is not
  4984. * compatible with UNION);
  4985. * - for ENUMs, the size is ignored;
  4986. * - for INT, size and signedness are ignored;
  4987. * - for ARRAY, dimensionality is ignored, element types are checked for
  4988. * compatibility recursively;
  4989. * - CONST/VOLATILE/RESTRICT modifiers are ignored;
  4990. * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
  4991. * - FUNC_PROTOs are compatible if they have compatible signature: same
  4992. * number of input args and compatible return and argument types.
  4993. * These rules are not set in stone and probably will be adjusted as we get
  4994. * more experience with using BPF CO-RE relocations.
  4995. */
  4996. int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
  4997. const struct btf *targ_btf, __u32 targ_id)
  4998. {
  4999. return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
  5000. }
  5001. int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
  5002. const struct btf *targ_btf, __u32 targ_id)
  5003. {
  5004. return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
  5005. }
  5006. static size_t bpf_core_hash_fn(const long key, void *ctx)
  5007. {
  5008. return key;
  5009. }
  5010. static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
  5011. {
  5012. return k1 == k2;
  5013. }
  5014. static int record_relo_core(struct bpf_program *prog,
  5015. const struct bpf_core_relo *core_relo, int insn_idx)
  5016. {
  5017. struct reloc_desc *relos, *relo;
  5018. relos = libbpf_reallocarray(prog->reloc_desc,
  5019. prog->nr_reloc + 1, sizeof(*relos));
  5020. if (!relos)
  5021. return -ENOMEM;
  5022. relo = &relos[prog->nr_reloc];
  5023. relo->type = RELO_CORE;
  5024. relo->insn_idx = insn_idx;
  5025. relo->core_relo = core_relo;
  5026. prog->reloc_desc = relos;
  5027. prog->nr_reloc++;
  5028. return 0;
  5029. }
  5030. static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
  5031. {
  5032. struct reloc_desc *relo;
  5033. int i;
  5034. for (i = 0; i < prog->nr_reloc; i++) {
  5035. relo = &prog->reloc_desc[i];
  5036. if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
  5037. continue;
  5038. return relo->core_relo;
  5039. }
  5040. return NULL;
  5041. }
  5042. static int bpf_core_resolve_relo(struct bpf_program *prog,
  5043. const struct bpf_core_relo *relo,
  5044. int relo_idx,
  5045. const struct btf *local_btf,
  5046. struct hashmap *cand_cache,
  5047. struct bpf_core_relo_res *targ_res)
  5048. {
  5049. struct bpf_core_spec specs_scratch[3] = {};
  5050. struct bpf_core_cand_list *cands = NULL;
  5051. const char *prog_name = prog->name;
  5052. const struct btf_type *local_type;
  5053. const char *local_name;
  5054. __u32 local_id = relo->type_id;
  5055. int err;
  5056. local_type = btf__type_by_id(local_btf, local_id);
  5057. if (!local_type)
  5058. return -EINVAL;
  5059. local_name = btf__name_by_offset(local_btf, local_type->name_off);
  5060. if (!local_name)
  5061. return -EINVAL;
  5062. if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
  5063. !hashmap__find(cand_cache, local_id, &cands)) {
  5064. cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
  5065. if (IS_ERR(cands)) {
  5066. pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
  5067. prog_name, relo_idx, local_id, btf_kind_str(local_type),
  5068. local_name, PTR_ERR(cands));
  5069. return PTR_ERR(cands);
  5070. }
  5071. err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
  5072. if (err) {
  5073. bpf_core_free_cands(cands);
  5074. return err;
  5075. }
  5076. }
  5077. return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
  5078. targ_res);
  5079. }
  5080. static int
  5081. bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
  5082. {
  5083. const struct btf_ext_info_sec *sec;
  5084. struct bpf_core_relo_res targ_res;
  5085. const struct bpf_core_relo *rec;
  5086. const struct btf_ext_info *seg;
  5087. struct hashmap_entry *entry;
  5088. struct hashmap *cand_cache = NULL;
  5089. struct bpf_program *prog;
  5090. struct bpf_insn *insn;
  5091. const char *sec_name;
  5092. int i, err = 0, insn_idx, sec_idx, sec_num;
  5093. if (obj->btf_ext->core_relo_info.len == 0)
  5094. return 0;
  5095. if (targ_btf_path) {
  5096. obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
  5097. err = libbpf_get_error(obj->btf_vmlinux_override);
  5098. if (err) {
  5099. pr_warn("failed to parse target BTF: %d\n", err);
  5100. return err;
  5101. }
  5102. }
  5103. cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
  5104. if (IS_ERR(cand_cache)) {
  5105. err = PTR_ERR(cand_cache);
  5106. goto out;
  5107. }
  5108. seg = &obj->btf_ext->core_relo_info;
  5109. sec_num = 0;
  5110. for_each_btf_ext_sec(seg, sec) {
  5111. sec_idx = seg->sec_idxs[sec_num];
  5112. sec_num++;
  5113. sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
  5114. if (str_is_empty(sec_name)) {
  5115. err = -EINVAL;
  5116. goto out;
  5117. }
  5118. pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
  5119. for_each_btf_ext_rec(seg, sec, i, rec) {
  5120. if (rec->insn_off % BPF_INSN_SZ)
  5121. return -EINVAL;
  5122. insn_idx = rec->insn_off / BPF_INSN_SZ;
  5123. prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
  5124. if (!prog) {
  5125. /* When __weak subprog is "overridden" by another instance
  5126. * of the subprog from a different object file, linker still
  5127. * appends all the .BTF.ext info that used to belong to that
  5128. * eliminated subprogram.
  5129. * This is similar to what x86-64 linker does for relocations.
  5130. * So just ignore such relocations just like we ignore
  5131. * subprog instructions when discovering subprograms.
  5132. */
  5133. pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
  5134. sec_name, i, insn_idx);
  5135. continue;
  5136. }
  5137. /* no need to apply CO-RE relocation if the program is
  5138. * not going to be loaded
  5139. */
  5140. if (!prog->autoload)
  5141. continue;
  5142. /* adjust insn_idx from section frame of reference to the local
  5143. * program's frame of reference; (sub-)program code is not yet
  5144. * relocated, so it's enough to just subtract in-section offset
  5145. */
  5146. insn_idx = insn_idx - prog->sec_insn_off;
  5147. if (insn_idx >= prog->insns_cnt)
  5148. return -EINVAL;
  5149. insn = &prog->insns[insn_idx];
  5150. err = record_relo_core(prog, rec, insn_idx);
  5151. if (err) {
  5152. pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
  5153. prog->name, i, err);
  5154. goto out;
  5155. }
  5156. if (prog->obj->gen_loader)
  5157. continue;
  5158. err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
  5159. if (err) {
  5160. pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
  5161. prog->name, i, err);
  5162. goto out;
  5163. }
  5164. err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
  5165. if (err) {
  5166. pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
  5167. prog->name, i, insn_idx, err);
  5168. goto out;
  5169. }
  5170. }
  5171. }
  5172. out:
  5173. /* obj->btf_vmlinux and module BTFs are freed after object load */
  5174. btf__free(obj->btf_vmlinux_override);
  5175. obj->btf_vmlinux_override = NULL;
  5176. if (!IS_ERR_OR_NULL(cand_cache)) {
  5177. hashmap__for_each_entry(cand_cache, entry, i) {
  5178. bpf_core_free_cands(entry->pvalue);
  5179. }
  5180. hashmap__free(cand_cache);
  5181. }
  5182. return err;
  5183. }
  5184. /* base map load ldimm64 special constant, used also for log fixup logic */
  5185. #define POISON_LDIMM64_MAP_BASE 2001000000
  5186. #define POISON_LDIMM64_MAP_PFX "200100"
  5187. static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
  5188. int insn_idx, struct bpf_insn *insn,
  5189. int map_idx, const struct bpf_map *map)
  5190. {
  5191. int i;
  5192. pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
  5193. prog->name, relo_idx, insn_idx, map_idx, map->name);
  5194. /* we turn single ldimm64 into two identical invalid calls */
  5195. for (i = 0; i < 2; i++) {
  5196. insn->code = BPF_JMP | BPF_CALL;
  5197. insn->dst_reg = 0;
  5198. insn->src_reg = 0;
  5199. insn->off = 0;
  5200. /* if this instruction is reachable (not a dead code),
  5201. * verifier will complain with something like:
  5202. * invalid func unknown#2001000123
  5203. * where lower 123 is map index into obj->maps[] array
  5204. */
  5205. insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
  5206. insn++;
  5207. }
  5208. }
  5209. /* unresolved kfunc call special constant, used also for log fixup logic */
  5210. #define POISON_CALL_KFUNC_BASE 2002000000
  5211. #define POISON_CALL_KFUNC_PFX "2002"
  5212. static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
  5213. int insn_idx, struct bpf_insn *insn,
  5214. int ext_idx, const struct extern_desc *ext)
  5215. {
  5216. pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
  5217. prog->name, relo_idx, insn_idx, ext->name);
  5218. /* we turn kfunc call into invalid helper call with identifiable constant */
  5219. insn->code = BPF_JMP | BPF_CALL;
  5220. insn->dst_reg = 0;
  5221. insn->src_reg = 0;
  5222. insn->off = 0;
  5223. /* if this instruction is reachable (not a dead code),
  5224. * verifier will complain with something like:
  5225. * invalid func unknown#2001000123
  5226. * where lower 123 is extern index into obj->externs[] array
  5227. */
  5228. insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
  5229. }
  5230. /* Relocate data references within program code:
  5231. * - map references;
  5232. * - global variable references;
  5233. * - extern references.
  5234. */
  5235. static int
  5236. bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
  5237. {
  5238. int i;
  5239. for (i = 0; i < prog->nr_reloc; i++) {
  5240. struct reloc_desc *relo = &prog->reloc_desc[i];
  5241. struct bpf_insn *insn = &prog->insns[relo->insn_idx];
  5242. const struct bpf_map *map;
  5243. struct extern_desc *ext;
  5244. switch (relo->type) {
  5245. case RELO_LD64:
  5246. map = &obj->maps[relo->map_idx];
  5247. if (obj->gen_loader) {
  5248. insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
  5249. insn[0].imm = relo->map_idx;
  5250. } else if (map->autocreate) {
  5251. insn[0].src_reg = BPF_PSEUDO_MAP_FD;
  5252. insn[0].imm = map->fd;
  5253. } else {
  5254. poison_map_ldimm64(prog, i, relo->insn_idx, insn,
  5255. relo->map_idx, map);
  5256. }
  5257. break;
  5258. case RELO_DATA:
  5259. map = &obj->maps[relo->map_idx];
  5260. insn[1].imm = insn[0].imm + relo->sym_off;
  5261. if (obj->gen_loader) {
  5262. insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
  5263. insn[0].imm = relo->map_idx;
  5264. } else if (map->autocreate) {
  5265. insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
  5266. insn[0].imm = map->fd;
  5267. } else {
  5268. poison_map_ldimm64(prog, i, relo->insn_idx, insn,
  5269. relo->map_idx, map);
  5270. }
  5271. break;
  5272. case RELO_EXTERN_LD64:
  5273. ext = &obj->externs[relo->ext_idx];
  5274. if (ext->type == EXT_KCFG) {
  5275. if (obj->gen_loader) {
  5276. insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
  5277. insn[0].imm = obj->kconfig_map_idx;
  5278. } else {
  5279. insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
  5280. insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
  5281. }
  5282. insn[1].imm = ext->kcfg.data_off;
  5283. } else /* EXT_KSYM */ {
  5284. if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
  5285. insn[0].src_reg = BPF_PSEUDO_BTF_ID;
  5286. insn[0].imm = ext->ksym.kernel_btf_id;
  5287. insn[1].imm = ext->ksym.kernel_btf_obj_fd;
  5288. } else { /* typeless ksyms or unresolved typed ksyms */
  5289. insn[0].imm = (__u32)ext->ksym.addr;
  5290. insn[1].imm = ext->ksym.addr >> 32;
  5291. }
  5292. }
  5293. break;
  5294. case RELO_EXTERN_CALL:
  5295. ext = &obj->externs[relo->ext_idx];
  5296. insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
  5297. if (ext->is_set) {
  5298. insn[0].imm = ext->ksym.kernel_btf_id;
  5299. insn[0].off = ext->ksym.btf_fd_idx;
  5300. } else { /* unresolved weak kfunc call */
  5301. poison_kfunc_call(prog, i, relo->insn_idx, insn,
  5302. relo->ext_idx, ext);
  5303. }
  5304. break;
  5305. case RELO_SUBPROG_ADDR:
  5306. if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
  5307. pr_warn("prog '%s': relo #%d: bad insn\n",
  5308. prog->name, i);
  5309. return -EINVAL;
  5310. }
  5311. /* handled already */
  5312. break;
  5313. case RELO_CALL:
  5314. /* handled already */
  5315. break;
  5316. case RELO_CORE:
  5317. /* will be handled by bpf_program_record_relos() */
  5318. break;
  5319. default:
  5320. pr_warn("prog '%s': relo #%d: bad relo type %d\n",
  5321. prog->name, i, relo->type);
  5322. return -EINVAL;
  5323. }
  5324. }
  5325. return 0;
  5326. }
  5327. static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
  5328. const struct bpf_program *prog,
  5329. const struct btf_ext_info *ext_info,
  5330. void **prog_info, __u32 *prog_rec_cnt,
  5331. __u32 *prog_rec_sz)
  5332. {
  5333. void *copy_start = NULL, *copy_end = NULL;
  5334. void *rec, *rec_end, *new_prog_info;
  5335. const struct btf_ext_info_sec *sec;
  5336. size_t old_sz, new_sz;
  5337. int i, sec_num, sec_idx, off_adj;
  5338. sec_num = 0;
  5339. for_each_btf_ext_sec(ext_info, sec) {
  5340. sec_idx = ext_info->sec_idxs[sec_num];
  5341. sec_num++;
  5342. if (prog->sec_idx != sec_idx)
  5343. continue;
  5344. for_each_btf_ext_rec(ext_info, sec, i, rec) {
  5345. __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
  5346. if (insn_off < prog->sec_insn_off)
  5347. continue;
  5348. if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
  5349. break;
  5350. if (!copy_start)
  5351. copy_start = rec;
  5352. copy_end = rec + ext_info->rec_size;
  5353. }
  5354. if (!copy_start)
  5355. return -ENOENT;
  5356. /* append func/line info of a given (sub-)program to the main
  5357. * program func/line info
  5358. */
  5359. old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
  5360. new_sz = old_sz + (copy_end - copy_start);
  5361. new_prog_info = realloc(*prog_info, new_sz);
  5362. if (!new_prog_info)
  5363. return -ENOMEM;
  5364. *prog_info = new_prog_info;
  5365. *prog_rec_cnt = new_sz / ext_info->rec_size;
  5366. memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
  5367. /* Kernel instruction offsets are in units of 8-byte
  5368. * instructions, while .BTF.ext instruction offsets generated
  5369. * by Clang are in units of bytes. So convert Clang offsets
  5370. * into kernel offsets and adjust offset according to program
  5371. * relocated position.
  5372. */
  5373. off_adj = prog->sub_insn_off - prog->sec_insn_off;
  5374. rec = new_prog_info + old_sz;
  5375. rec_end = new_prog_info + new_sz;
  5376. for (; rec < rec_end; rec += ext_info->rec_size) {
  5377. __u32 *insn_off = rec;
  5378. *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
  5379. }
  5380. *prog_rec_sz = ext_info->rec_size;
  5381. return 0;
  5382. }
  5383. return -ENOENT;
  5384. }
  5385. static int
  5386. reloc_prog_func_and_line_info(const struct bpf_object *obj,
  5387. struct bpf_program *main_prog,
  5388. const struct bpf_program *prog)
  5389. {
  5390. int err;
  5391. /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
  5392. * support func/line info
  5393. */
  5394. if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
  5395. return 0;
  5396. /* only attempt func info relocation if main program's func_info
  5397. * relocation was successful
  5398. */
  5399. if (main_prog != prog && !main_prog->func_info)
  5400. goto line_info;
  5401. err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
  5402. &main_prog->func_info,
  5403. &main_prog->func_info_cnt,
  5404. &main_prog->func_info_rec_size);
  5405. if (err) {
  5406. if (err != -ENOENT) {
  5407. pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
  5408. prog->name, err);
  5409. return err;
  5410. }
  5411. if (main_prog->func_info) {
  5412. /*
  5413. * Some info has already been found but has problem
  5414. * in the last btf_ext reloc. Must have to error out.
  5415. */
  5416. pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
  5417. return err;
  5418. }
  5419. /* Have problem loading the very first info. Ignore the rest. */
  5420. pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
  5421. prog->name);
  5422. }
  5423. line_info:
  5424. /* don't relocate line info if main program's relocation failed */
  5425. if (main_prog != prog && !main_prog->line_info)
  5426. return 0;
  5427. err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
  5428. &main_prog->line_info,
  5429. &main_prog->line_info_cnt,
  5430. &main_prog->line_info_rec_size);
  5431. if (err) {
  5432. if (err != -ENOENT) {
  5433. pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
  5434. prog->name, err);
  5435. return err;
  5436. }
  5437. if (main_prog->line_info) {
  5438. /*
  5439. * Some info has already been found but has problem
  5440. * in the last btf_ext reloc. Must have to error out.
  5441. */
  5442. pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
  5443. return err;
  5444. }
  5445. /* Have problem loading the very first info. Ignore the rest. */
  5446. pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
  5447. prog->name);
  5448. }
  5449. return 0;
  5450. }
  5451. static int cmp_relo_by_insn_idx(const void *key, const void *elem)
  5452. {
  5453. size_t insn_idx = *(const size_t *)key;
  5454. const struct reloc_desc *relo = elem;
  5455. if (insn_idx == relo->insn_idx)
  5456. return 0;
  5457. return insn_idx < relo->insn_idx ? -1 : 1;
  5458. }
  5459. static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
  5460. {
  5461. if (!prog->nr_reloc)
  5462. return NULL;
  5463. return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
  5464. sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
  5465. }
  5466. static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
  5467. {
  5468. int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
  5469. struct reloc_desc *relos;
  5470. int i;
  5471. if (main_prog == subprog)
  5472. return 0;
  5473. relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
  5474. /* if new count is zero, reallocarray can return a valid NULL result;
  5475. * in this case the previous pointer will be freed, so we *have to*
  5476. * reassign old pointer to the new value (even if it's NULL)
  5477. */
  5478. if (!relos && new_cnt)
  5479. return -ENOMEM;
  5480. if (subprog->nr_reloc)
  5481. memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
  5482. sizeof(*relos) * subprog->nr_reloc);
  5483. for (i = main_prog->nr_reloc; i < new_cnt; i++)
  5484. relos[i].insn_idx += subprog->sub_insn_off;
  5485. /* After insn_idx adjustment the 'relos' array is still sorted
  5486. * by insn_idx and doesn't break bsearch.
  5487. */
  5488. main_prog->reloc_desc = relos;
  5489. main_prog->nr_reloc = new_cnt;
  5490. return 0;
  5491. }
  5492. static int
  5493. bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
  5494. struct bpf_program *subprog)
  5495. {
  5496. struct bpf_insn *insns;
  5497. size_t new_cnt;
  5498. int err;
  5499. subprog->sub_insn_off = main_prog->insns_cnt;
  5500. new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
  5501. insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
  5502. if (!insns) {
  5503. pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
  5504. return -ENOMEM;
  5505. }
  5506. main_prog->insns = insns;
  5507. main_prog->insns_cnt = new_cnt;
  5508. memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
  5509. subprog->insns_cnt * sizeof(*insns));
  5510. pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
  5511. main_prog->name, subprog->insns_cnt, subprog->name);
  5512. /* The subprog insns are now appended. Append its relos too. */
  5513. err = append_subprog_relos(main_prog, subprog);
  5514. if (err)
  5515. return err;
  5516. return 0;
  5517. }
  5518. static int
  5519. bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
  5520. struct bpf_program *prog)
  5521. {
  5522. size_t sub_insn_idx, insn_idx;
  5523. struct bpf_program *subprog;
  5524. struct reloc_desc *relo;
  5525. struct bpf_insn *insn;
  5526. int err;
  5527. err = reloc_prog_func_and_line_info(obj, main_prog, prog);
  5528. if (err)
  5529. return err;
  5530. for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
  5531. insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
  5532. if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
  5533. continue;
  5534. relo = find_prog_insn_relo(prog, insn_idx);
  5535. if (relo && relo->type == RELO_EXTERN_CALL)
  5536. /* kfunc relocations will be handled later
  5537. * in bpf_object__relocate_data()
  5538. */
  5539. continue;
  5540. if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
  5541. pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
  5542. prog->name, insn_idx, relo->type);
  5543. return -LIBBPF_ERRNO__RELOC;
  5544. }
  5545. if (relo) {
  5546. /* sub-program instruction index is a combination of
  5547. * an offset of a symbol pointed to by relocation and
  5548. * call instruction's imm field; for global functions,
  5549. * call always has imm = -1, but for static functions
  5550. * relocation is against STT_SECTION and insn->imm
  5551. * points to a start of a static function
  5552. *
  5553. * for subprog addr relocation, the relo->sym_off + insn->imm is
  5554. * the byte offset in the corresponding section.
  5555. */
  5556. if (relo->type == RELO_CALL)
  5557. sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
  5558. else
  5559. sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
  5560. } else if (insn_is_pseudo_func(insn)) {
  5561. /*
  5562. * RELO_SUBPROG_ADDR relo is always emitted even if both
  5563. * functions are in the same section, so it shouldn't reach here.
  5564. */
  5565. pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
  5566. prog->name, insn_idx);
  5567. return -LIBBPF_ERRNO__RELOC;
  5568. } else {
  5569. /* if subprogram call is to a static function within
  5570. * the same ELF section, there won't be any relocation
  5571. * emitted, but it also means there is no additional
  5572. * offset necessary, insns->imm is relative to
  5573. * instruction's original position within the section
  5574. */
  5575. sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
  5576. }
  5577. /* we enforce that sub-programs should be in .text section */
  5578. subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
  5579. if (!subprog) {
  5580. pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
  5581. prog->name);
  5582. return -LIBBPF_ERRNO__RELOC;
  5583. }
  5584. /* if it's the first call instruction calling into this
  5585. * subprogram (meaning this subprog hasn't been processed
  5586. * yet) within the context of current main program:
  5587. * - append it at the end of main program's instructions blog;
  5588. * - process is recursively, while current program is put on hold;
  5589. * - if that subprogram calls some other not yet processes
  5590. * subprogram, same thing will happen recursively until
  5591. * there are no more unprocesses subprograms left to append
  5592. * and relocate.
  5593. */
  5594. if (subprog->sub_insn_off == 0) {
  5595. err = bpf_object__append_subprog_code(obj, main_prog, subprog);
  5596. if (err)
  5597. return err;
  5598. err = bpf_object__reloc_code(obj, main_prog, subprog);
  5599. if (err)
  5600. return err;
  5601. }
  5602. /* main_prog->insns memory could have been re-allocated, so
  5603. * calculate pointer again
  5604. */
  5605. insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
  5606. /* calculate correct instruction position within current main
  5607. * prog; each main prog can have a different set of
  5608. * subprograms appended (potentially in different order as
  5609. * well), so position of any subprog can be different for
  5610. * different main programs
  5611. */
  5612. insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
  5613. pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
  5614. prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
  5615. }
  5616. return 0;
  5617. }
  5618. /*
  5619. * Relocate sub-program calls.
  5620. *
  5621. * Algorithm operates as follows. Each entry-point BPF program (referred to as
  5622. * main prog) is processed separately. For each subprog (non-entry functions,
  5623. * that can be called from either entry progs or other subprogs) gets their
  5624. * sub_insn_off reset to zero. This serves as indicator that this subprogram
  5625. * hasn't been yet appended and relocated within current main prog. Once its
  5626. * relocated, sub_insn_off will point at the position within current main prog
  5627. * where given subprog was appended. This will further be used to relocate all
  5628. * the call instructions jumping into this subprog.
  5629. *
  5630. * We start with main program and process all call instructions. If the call
  5631. * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
  5632. * is zero), subprog instructions are appended at the end of main program's
  5633. * instruction array. Then main program is "put on hold" while we recursively
  5634. * process newly appended subprogram. If that subprogram calls into another
  5635. * subprogram that hasn't been appended, new subprogram is appended again to
  5636. * the *main* prog's instructions (subprog's instructions are always left
  5637. * untouched, as they need to be in unmodified state for subsequent main progs
  5638. * and subprog instructions are always sent only as part of a main prog) and
  5639. * the process continues recursively. Once all the subprogs called from a main
  5640. * prog or any of its subprogs are appended (and relocated), all their
  5641. * positions within finalized instructions array are known, so it's easy to
  5642. * rewrite call instructions with correct relative offsets, corresponding to
  5643. * desired target subprog.
  5644. *
  5645. * Its important to realize that some subprogs might not be called from some
  5646. * main prog and any of its called/used subprogs. Those will keep their
  5647. * subprog->sub_insn_off as zero at all times and won't be appended to current
  5648. * main prog and won't be relocated within the context of current main prog.
  5649. * They might still be used from other main progs later.
  5650. *
  5651. * Visually this process can be shown as below. Suppose we have two main
  5652. * programs mainA and mainB and BPF object contains three subprogs: subA,
  5653. * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
  5654. * subC both call subB:
  5655. *
  5656. * +--------+ +-------+
  5657. * | v v |
  5658. * +--+---+ +--+-+-+ +---+--+
  5659. * | subA | | subB | | subC |
  5660. * +--+---+ +------+ +---+--+
  5661. * ^ ^
  5662. * | |
  5663. * +---+-------+ +------+----+
  5664. * | mainA | | mainB |
  5665. * +-----------+ +-----------+
  5666. *
  5667. * We'll start relocating mainA, will find subA, append it and start
  5668. * processing sub A recursively:
  5669. *
  5670. * +-----------+------+
  5671. * | mainA | subA |
  5672. * +-----------+------+
  5673. *
  5674. * At this point we notice that subB is used from subA, so we append it and
  5675. * relocate (there are no further subcalls from subB):
  5676. *
  5677. * +-----------+------+------+
  5678. * | mainA | subA | subB |
  5679. * +-----------+------+------+
  5680. *
  5681. * At this point, we relocate subA calls, then go one level up and finish with
  5682. * relocatin mainA calls. mainA is done.
  5683. *
  5684. * For mainB process is similar but results in different order. We start with
  5685. * mainB and skip subA and subB, as mainB never calls them (at least
  5686. * directly), but we see subC is needed, so we append and start processing it:
  5687. *
  5688. * +-----------+------+
  5689. * | mainB | subC |
  5690. * +-----------+------+
  5691. * Now we see subC needs subB, so we go back to it, append and relocate it:
  5692. *
  5693. * +-----------+------+------+
  5694. * | mainB | subC | subB |
  5695. * +-----------+------+------+
  5696. *
  5697. * At this point we unwind recursion, relocate calls in subC, then in mainB.
  5698. */
  5699. static int
  5700. bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
  5701. {
  5702. struct bpf_program *subprog;
  5703. int i, err;
  5704. /* mark all subprogs as not relocated (yet) within the context of
  5705. * current main program
  5706. */
  5707. for (i = 0; i < obj->nr_programs; i++) {
  5708. subprog = &obj->programs[i];
  5709. if (!prog_is_subprog(obj, subprog))
  5710. continue;
  5711. subprog->sub_insn_off = 0;
  5712. }
  5713. err = bpf_object__reloc_code(obj, prog, prog);
  5714. if (err)
  5715. return err;
  5716. return 0;
  5717. }
  5718. static void
  5719. bpf_object__free_relocs(struct bpf_object *obj)
  5720. {
  5721. struct bpf_program *prog;
  5722. int i;
  5723. /* free up relocation descriptors */
  5724. for (i = 0; i < obj->nr_programs; i++) {
  5725. prog = &obj->programs[i];
  5726. zfree(&prog->reloc_desc);
  5727. prog->nr_reloc = 0;
  5728. }
  5729. }
  5730. static int cmp_relocs(const void *_a, const void *_b)
  5731. {
  5732. const struct reloc_desc *a = _a;
  5733. const struct reloc_desc *b = _b;
  5734. if (a->insn_idx != b->insn_idx)
  5735. return a->insn_idx < b->insn_idx ? -1 : 1;
  5736. /* no two relocations should have the same insn_idx, but ... */
  5737. if (a->type != b->type)
  5738. return a->type < b->type ? -1 : 1;
  5739. return 0;
  5740. }
  5741. static void bpf_object__sort_relos(struct bpf_object *obj)
  5742. {
  5743. int i;
  5744. for (i = 0; i < obj->nr_programs; i++) {
  5745. struct bpf_program *p = &obj->programs[i];
  5746. if (!p->nr_reloc)
  5747. continue;
  5748. qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
  5749. }
  5750. }
  5751. static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
  5752. {
  5753. const char *str = "exception_callback:";
  5754. size_t pfx_len = strlen(str);
  5755. int i, j, n;
  5756. if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
  5757. return 0;
  5758. n = btf__type_cnt(obj->btf);
  5759. for (i = 1; i < n; i++) {
  5760. const char *name;
  5761. struct btf_type *t;
  5762. t = btf_type_by_id(obj->btf, i);
  5763. if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
  5764. continue;
  5765. name = btf__str_by_offset(obj->btf, t->name_off);
  5766. if (strncmp(name, str, pfx_len) != 0)
  5767. continue;
  5768. t = btf_type_by_id(obj->btf, t->type);
  5769. if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
  5770. pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
  5771. prog->name);
  5772. return -EINVAL;
  5773. }
  5774. if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
  5775. continue;
  5776. /* Multiple callbacks are specified for the same prog,
  5777. * the verifier will eventually return an error for this
  5778. * case, hence simply skip appending a subprog.
  5779. */
  5780. if (prog->exception_cb_idx >= 0) {
  5781. prog->exception_cb_idx = -1;
  5782. break;
  5783. }
  5784. name += pfx_len;
  5785. if (str_is_empty(name)) {
  5786. pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
  5787. prog->name);
  5788. return -EINVAL;
  5789. }
  5790. for (j = 0; j < obj->nr_programs; j++) {
  5791. struct bpf_program *subprog = &obj->programs[j];
  5792. if (!prog_is_subprog(obj, subprog))
  5793. continue;
  5794. if (strcmp(name, subprog->name) != 0)
  5795. continue;
  5796. /* Enforce non-hidden, as from verifier point of
  5797. * view it expects global functions, whereas the
  5798. * mark_btf_static fixes up linkage as static.
  5799. */
  5800. if (!subprog->sym_global || subprog->mark_btf_static) {
  5801. pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
  5802. prog->name, subprog->name);
  5803. return -EINVAL;
  5804. }
  5805. /* Let's see if we already saw a static exception callback with the same name */
  5806. if (prog->exception_cb_idx >= 0) {
  5807. pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
  5808. prog->name, subprog->name);
  5809. return -EINVAL;
  5810. }
  5811. prog->exception_cb_idx = j;
  5812. break;
  5813. }
  5814. if (prog->exception_cb_idx >= 0)
  5815. continue;
  5816. pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
  5817. return -ENOENT;
  5818. }
  5819. return 0;
  5820. }
  5821. static struct {
  5822. enum bpf_prog_type prog_type;
  5823. const char *ctx_name;
  5824. } global_ctx_map[] = {
  5825. { BPF_PROG_TYPE_CGROUP_DEVICE, "bpf_cgroup_dev_ctx" },
  5826. { BPF_PROG_TYPE_CGROUP_SKB, "__sk_buff" },
  5827. { BPF_PROG_TYPE_CGROUP_SOCK, "bpf_sock" },
  5828. { BPF_PROG_TYPE_CGROUP_SOCK_ADDR, "bpf_sock_addr" },
  5829. { BPF_PROG_TYPE_CGROUP_SOCKOPT, "bpf_sockopt" },
  5830. { BPF_PROG_TYPE_CGROUP_SYSCTL, "bpf_sysctl" },
  5831. { BPF_PROG_TYPE_FLOW_DISSECTOR, "__sk_buff" },
  5832. { BPF_PROG_TYPE_KPROBE, "bpf_user_pt_regs_t" },
  5833. { BPF_PROG_TYPE_LWT_IN, "__sk_buff" },
  5834. { BPF_PROG_TYPE_LWT_OUT, "__sk_buff" },
  5835. { BPF_PROG_TYPE_LWT_SEG6LOCAL, "__sk_buff" },
  5836. { BPF_PROG_TYPE_LWT_XMIT, "__sk_buff" },
  5837. { BPF_PROG_TYPE_NETFILTER, "bpf_nf_ctx" },
  5838. { BPF_PROG_TYPE_PERF_EVENT, "bpf_perf_event_data" },
  5839. { BPF_PROG_TYPE_RAW_TRACEPOINT, "bpf_raw_tracepoint_args" },
  5840. { BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
  5841. { BPF_PROG_TYPE_SCHED_ACT, "__sk_buff" },
  5842. { BPF_PROG_TYPE_SCHED_CLS, "__sk_buff" },
  5843. { BPF_PROG_TYPE_SK_LOOKUP, "bpf_sk_lookup" },
  5844. { BPF_PROG_TYPE_SK_MSG, "sk_msg_md" },
  5845. { BPF_PROG_TYPE_SK_REUSEPORT, "sk_reuseport_md" },
  5846. { BPF_PROG_TYPE_SK_SKB, "__sk_buff" },
  5847. { BPF_PROG_TYPE_SOCK_OPS, "bpf_sock_ops" },
  5848. { BPF_PROG_TYPE_SOCKET_FILTER, "__sk_buff" },
  5849. { BPF_PROG_TYPE_XDP, "xdp_md" },
  5850. /* all other program types don't have "named" context structs */
  5851. };
  5852. /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
  5853. * for below __builtin_types_compatible_p() checks;
  5854. * with this approach we don't need any extra arch-specific #ifdef guards
  5855. */
  5856. struct pt_regs;
  5857. struct user_pt_regs;
  5858. struct user_regs_struct;
  5859. static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
  5860. const char *subprog_name, int arg_idx,
  5861. int arg_type_id, const char *ctx_name)
  5862. {
  5863. const struct btf_type *t;
  5864. const char *tname;
  5865. /* check if existing parameter already matches verifier expectations */
  5866. t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
  5867. if (!btf_is_ptr(t))
  5868. goto out_warn;
  5869. /* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
  5870. * and perf_event programs, so check this case early on and forget
  5871. * about it for subsequent checks
  5872. */
  5873. while (btf_is_mod(t))
  5874. t = btf__type_by_id(btf, t->type);
  5875. if (btf_is_typedef(t) &&
  5876. (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
  5877. tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
  5878. if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
  5879. return false; /* canonical type for kprobe/perf_event */
  5880. }
  5881. /* now we can ignore typedefs moving forward */
  5882. t = skip_mods_and_typedefs(btf, t->type, NULL);
  5883. /* if it's `void *`, definitely fix up BTF info */
  5884. if (btf_is_void(t))
  5885. return true;
  5886. /* if it's already proper canonical type, no need to fix up */
  5887. tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
  5888. if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
  5889. return false;
  5890. /* special cases */
  5891. switch (prog->type) {
  5892. case BPF_PROG_TYPE_KPROBE:
  5893. /* `struct pt_regs *` is expected, but we need to fix up */
  5894. if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
  5895. return true;
  5896. break;
  5897. case BPF_PROG_TYPE_PERF_EVENT:
  5898. if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
  5899. btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
  5900. return true;
  5901. if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
  5902. btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
  5903. return true;
  5904. if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
  5905. btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
  5906. return true;
  5907. break;
  5908. case BPF_PROG_TYPE_RAW_TRACEPOINT:
  5909. case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
  5910. /* allow u64* as ctx */
  5911. if (btf_is_int(t) && t->size == 8)
  5912. return true;
  5913. break;
  5914. default:
  5915. break;
  5916. }
  5917. out_warn:
  5918. pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
  5919. prog->name, subprog_name, arg_idx, ctx_name);
  5920. return false;
  5921. }
  5922. static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
  5923. {
  5924. int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
  5925. int i, err, arg_cnt, fn_name_off, linkage;
  5926. struct btf_type *fn_t, *fn_proto_t, *t;
  5927. struct btf_param *p;
  5928. /* caller already validated FUNC -> FUNC_PROTO validity */
  5929. fn_t = btf_type_by_id(btf, orig_fn_id);
  5930. fn_proto_t = btf_type_by_id(btf, fn_t->type);
  5931. /* Note that each btf__add_xxx() operation invalidates
  5932. * all btf_type and string pointers, so we need to be
  5933. * very careful when cloning BTF types. BTF type
  5934. * pointers have to be always refetched. And to avoid
  5935. * problems with invalidated string pointers, we
  5936. * add empty strings initially, then just fix up
  5937. * name_off offsets in place. Offsets are stable for
  5938. * existing strings, so that works out.
  5939. */
  5940. fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
  5941. linkage = btf_func_linkage(fn_t);
  5942. orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
  5943. ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
  5944. arg_cnt = btf_vlen(fn_proto_t);
  5945. /* clone FUNC_PROTO and its params */
  5946. fn_proto_id = btf__add_func_proto(btf, ret_type_id);
  5947. if (fn_proto_id < 0)
  5948. return -EINVAL;
  5949. for (i = 0; i < arg_cnt; i++) {
  5950. int name_off;
  5951. /* copy original parameter data */
  5952. t = btf_type_by_id(btf, orig_proto_id);
  5953. p = &btf_params(t)[i];
  5954. name_off = p->name_off;
  5955. err = btf__add_func_param(btf, "", p->type);
  5956. if (err)
  5957. return err;
  5958. fn_proto_t = btf_type_by_id(btf, fn_proto_id);
  5959. p = &btf_params(fn_proto_t)[i];
  5960. p->name_off = name_off; /* use remembered str offset */
  5961. }
  5962. /* clone FUNC now, btf__add_func() enforces non-empty name, so use
  5963. * entry program's name as a placeholder, which we replace immediately
  5964. * with original name_off
  5965. */
  5966. fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
  5967. if (fn_id < 0)
  5968. return -EINVAL;
  5969. fn_t = btf_type_by_id(btf, fn_id);
  5970. fn_t->name_off = fn_name_off; /* reuse original string */
  5971. return fn_id;
  5972. }
  5973. /* Check if main program or global subprog's function prototype has `arg:ctx`
  5974. * argument tags, and, if necessary, substitute correct type to match what BPF
  5975. * verifier would expect, taking into account specific program type. This
  5976. * allows to support __arg_ctx tag transparently on old kernels that don't yet
  5977. * have a native support for it in the verifier, making user's life much
  5978. * easier.
  5979. */
  5980. static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
  5981. {
  5982. const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
  5983. struct bpf_func_info_min *func_rec;
  5984. struct btf_type *fn_t, *fn_proto_t;
  5985. struct btf *btf = obj->btf;
  5986. const struct btf_type *t;
  5987. struct btf_param *p;
  5988. int ptr_id = 0, struct_id, tag_id, orig_fn_id;
  5989. int i, n, arg_idx, arg_cnt, err, rec_idx;
  5990. int *orig_ids;
  5991. /* no .BTF.ext, no problem */
  5992. if (!obj->btf_ext || !prog->func_info)
  5993. return 0;
  5994. /* don't do any fix ups if kernel natively supports __arg_ctx */
  5995. if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
  5996. return 0;
  5997. /* some BPF program types just don't have named context structs, so
  5998. * this fallback mechanism doesn't work for them
  5999. */
  6000. for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
  6001. if (global_ctx_map[i].prog_type != prog->type)
  6002. continue;
  6003. ctx_name = global_ctx_map[i].ctx_name;
  6004. break;
  6005. }
  6006. if (!ctx_name)
  6007. return 0;
  6008. /* remember original func BTF IDs to detect if we already cloned them */
  6009. orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
  6010. if (!orig_ids)
  6011. return -ENOMEM;
  6012. for (i = 0; i < prog->func_info_cnt; i++) {
  6013. func_rec = prog->func_info + prog->func_info_rec_size * i;
  6014. orig_ids[i] = func_rec->type_id;
  6015. }
  6016. /* go through each DECL_TAG with "arg:ctx" and see if it points to one
  6017. * of our subprogs; if yes and subprog is global and needs adjustment,
  6018. * clone and adjust FUNC -> FUNC_PROTO combo
  6019. */
  6020. for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
  6021. /* only DECL_TAG with "arg:ctx" value are interesting */
  6022. t = btf__type_by_id(btf, i);
  6023. if (!btf_is_decl_tag(t))
  6024. continue;
  6025. if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
  6026. continue;
  6027. /* only global funcs need adjustment, if at all */
  6028. orig_fn_id = t->type;
  6029. fn_t = btf_type_by_id(btf, orig_fn_id);
  6030. if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
  6031. continue;
  6032. /* sanity check FUNC -> FUNC_PROTO chain, just in case */
  6033. fn_proto_t = btf_type_by_id(btf, fn_t->type);
  6034. if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
  6035. continue;
  6036. /* find corresponding func_info record */
  6037. func_rec = NULL;
  6038. for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
  6039. if (orig_ids[rec_idx] == t->type) {
  6040. func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
  6041. break;
  6042. }
  6043. }
  6044. /* current main program doesn't call into this subprog */
  6045. if (!func_rec)
  6046. continue;
  6047. /* some more sanity checking of DECL_TAG */
  6048. arg_cnt = btf_vlen(fn_proto_t);
  6049. arg_idx = btf_decl_tag(t)->component_idx;
  6050. if (arg_idx < 0 || arg_idx >= arg_cnt)
  6051. continue;
  6052. /* check if we should fix up argument type */
  6053. p = &btf_params(fn_proto_t)[arg_idx];
  6054. fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
  6055. if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
  6056. continue;
  6057. /* clone fn/fn_proto, unless we already did it for another arg */
  6058. if (func_rec->type_id == orig_fn_id) {
  6059. int fn_id;
  6060. fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
  6061. if (fn_id < 0) {
  6062. err = fn_id;
  6063. goto err_out;
  6064. }
  6065. /* point func_info record to a cloned FUNC type */
  6066. func_rec->type_id = fn_id;
  6067. }
  6068. /* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
  6069. * we do it just once per main BPF program, as all global
  6070. * funcs share the same program type, so need only PTR ->
  6071. * STRUCT type chain
  6072. */
  6073. if (ptr_id == 0) {
  6074. struct_id = btf__add_struct(btf, ctx_name, 0);
  6075. ptr_id = btf__add_ptr(btf, struct_id);
  6076. if (ptr_id < 0 || struct_id < 0) {
  6077. err = -EINVAL;
  6078. goto err_out;
  6079. }
  6080. }
  6081. /* for completeness, clone DECL_TAG and point it to cloned param */
  6082. tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
  6083. if (tag_id < 0) {
  6084. err = -EINVAL;
  6085. goto err_out;
  6086. }
  6087. /* all the BTF manipulations invalidated pointers, refetch them */
  6088. fn_t = btf_type_by_id(btf, func_rec->type_id);
  6089. fn_proto_t = btf_type_by_id(btf, fn_t->type);
  6090. /* fix up type ID pointed to by param */
  6091. p = &btf_params(fn_proto_t)[arg_idx];
  6092. p->type = ptr_id;
  6093. }
  6094. free(orig_ids);
  6095. return 0;
  6096. err_out:
  6097. free(orig_ids);
  6098. return err;
  6099. }
  6100. static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
  6101. {
  6102. struct bpf_program *prog;
  6103. size_t i, j;
  6104. int err;
  6105. if (obj->btf_ext) {
  6106. err = bpf_object__relocate_core(obj, targ_btf_path);
  6107. if (err) {
  6108. pr_warn("failed to perform CO-RE relocations: %d\n",
  6109. err);
  6110. return err;
  6111. }
  6112. bpf_object__sort_relos(obj);
  6113. }
  6114. /* Before relocating calls pre-process relocations and mark
  6115. * few ld_imm64 instructions that points to subprogs.
  6116. * Otherwise bpf_object__reloc_code() later would have to consider
  6117. * all ld_imm64 insns as relocation candidates. That would
  6118. * reduce relocation speed, since amount of find_prog_insn_relo()
  6119. * would increase and most of them will fail to find a relo.
  6120. */
  6121. for (i = 0; i < obj->nr_programs; i++) {
  6122. prog = &obj->programs[i];
  6123. for (j = 0; j < prog->nr_reloc; j++) {
  6124. struct reloc_desc *relo = &prog->reloc_desc[j];
  6125. struct bpf_insn *insn = &prog->insns[relo->insn_idx];
  6126. /* mark the insn, so it's recognized by insn_is_pseudo_func() */
  6127. if (relo->type == RELO_SUBPROG_ADDR)
  6128. insn[0].src_reg = BPF_PSEUDO_FUNC;
  6129. }
  6130. }
  6131. /* relocate subprogram calls and append used subprograms to main
  6132. * programs; each copy of subprogram code needs to be relocated
  6133. * differently for each main program, because its code location might
  6134. * have changed.
  6135. * Append subprog relos to main programs to allow data relos to be
  6136. * processed after text is completely relocated.
  6137. */
  6138. for (i = 0; i < obj->nr_programs; i++) {
  6139. prog = &obj->programs[i];
  6140. /* sub-program's sub-calls are relocated within the context of
  6141. * its main program only
  6142. */
  6143. if (prog_is_subprog(obj, prog))
  6144. continue;
  6145. if (!prog->autoload)
  6146. continue;
  6147. err = bpf_object__relocate_calls(obj, prog);
  6148. if (err) {
  6149. pr_warn("prog '%s': failed to relocate calls: %d\n",
  6150. prog->name, err);
  6151. return err;
  6152. }
  6153. err = bpf_prog_assign_exc_cb(obj, prog);
  6154. if (err)
  6155. return err;
  6156. /* Now, also append exception callback if it has not been done already. */
  6157. if (prog->exception_cb_idx >= 0) {
  6158. struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
  6159. /* Calling exception callback directly is disallowed, which the
  6160. * verifier will reject later. In case it was processed already,
  6161. * we can skip this step, otherwise for all other valid cases we
  6162. * have to append exception callback now.
  6163. */
  6164. if (subprog->sub_insn_off == 0) {
  6165. err = bpf_object__append_subprog_code(obj, prog, subprog);
  6166. if (err)
  6167. return err;
  6168. err = bpf_object__reloc_code(obj, prog, subprog);
  6169. if (err)
  6170. return err;
  6171. }
  6172. }
  6173. }
  6174. for (i = 0; i < obj->nr_programs; i++) {
  6175. prog = &obj->programs[i];
  6176. if (prog_is_subprog(obj, prog))
  6177. continue;
  6178. if (!prog->autoload)
  6179. continue;
  6180. /* Process data relos for main programs */
  6181. err = bpf_object__relocate_data(obj, prog);
  6182. if (err) {
  6183. pr_warn("prog '%s': failed to relocate data references: %d\n",
  6184. prog->name, err);
  6185. return err;
  6186. }
  6187. /* Fix up .BTF.ext information, if necessary */
  6188. err = bpf_program_fixup_func_info(obj, prog);
  6189. if (err) {
  6190. pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %d\n",
  6191. prog->name, err);
  6192. return err;
  6193. }
  6194. }
  6195. return 0;
  6196. }
  6197. static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
  6198. Elf64_Shdr *shdr, Elf_Data *data);
  6199. static int bpf_object__collect_map_relos(struct bpf_object *obj,
  6200. Elf64_Shdr *shdr, Elf_Data *data)
  6201. {
  6202. const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
  6203. int i, j, nrels, new_sz;
  6204. const struct btf_var_secinfo *vi = NULL;
  6205. const struct btf_type *sec, *var, *def;
  6206. struct bpf_map *map = NULL, *targ_map = NULL;
  6207. struct bpf_program *targ_prog = NULL;
  6208. bool is_prog_array, is_map_in_map;
  6209. const struct btf_member *member;
  6210. const char *name, *mname, *type;
  6211. unsigned int moff;
  6212. Elf64_Sym *sym;
  6213. Elf64_Rel *rel;
  6214. void *tmp;
  6215. if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
  6216. return -EINVAL;
  6217. sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
  6218. if (!sec)
  6219. return -EINVAL;
  6220. nrels = shdr->sh_size / shdr->sh_entsize;
  6221. for (i = 0; i < nrels; i++) {
  6222. rel = elf_rel_by_idx(data, i);
  6223. if (!rel) {
  6224. pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
  6225. return -LIBBPF_ERRNO__FORMAT;
  6226. }
  6227. sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
  6228. if (!sym) {
  6229. pr_warn(".maps relo #%d: symbol %zx not found\n",
  6230. i, (size_t)ELF64_R_SYM(rel->r_info));
  6231. return -LIBBPF_ERRNO__FORMAT;
  6232. }
  6233. name = elf_sym_str(obj, sym->st_name) ?: "<?>";
  6234. pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
  6235. i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
  6236. (size_t)rel->r_offset, sym->st_name, name);
  6237. for (j = 0; j < obj->nr_maps; j++) {
  6238. map = &obj->maps[j];
  6239. if (map->sec_idx != obj->efile.btf_maps_shndx)
  6240. continue;
  6241. vi = btf_var_secinfos(sec) + map->btf_var_idx;
  6242. if (vi->offset <= rel->r_offset &&
  6243. rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
  6244. break;
  6245. }
  6246. if (j == obj->nr_maps) {
  6247. pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
  6248. i, name, (size_t)rel->r_offset);
  6249. return -EINVAL;
  6250. }
  6251. is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
  6252. is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
  6253. type = is_map_in_map ? "map" : "prog";
  6254. if (is_map_in_map) {
  6255. if (sym->st_shndx != obj->efile.btf_maps_shndx) {
  6256. pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
  6257. i, name);
  6258. return -LIBBPF_ERRNO__RELOC;
  6259. }
  6260. if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
  6261. map->def.key_size != sizeof(int)) {
  6262. pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
  6263. i, map->name, sizeof(int));
  6264. return -EINVAL;
  6265. }
  6266. targ_map = bpf_object__find_map_by_name(obj, name);
  6267. if (!targ_map) {
  6268. pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
  6269. i, name);
  6270. return -ESRCH;
  6271. }
  6272. } else if (is_prog_array) {
  6273. targ_prog = bpf_object__find_program_by_name(obj, name);
  6274. if (!targ_prog) {
  6275. pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
  6276. i, name);
  6277. return -ESRCH;
  6278. }
  6279. if (targ_prog->sec_idx != sym->st_shndx ||
  6280. targ_prog->sec_insn_off * 8 != sym->st_value ||
  6281. prog_is_subprog(obj, targ_prog)) {
  6282. pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
  6283. i, name);
  6284. return -LIBBPF_ERRNO__RELOC;
  6285. }
  6286. } else {
  6287. return -EINVAL;
  6288. }
  6289. var = btf__type_by_id(obj->btf, vi->type);
  6290. def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
  6291. if (btf_vlen(def) == 0)
  6292. return -EINVAL;
  6293. member = btf_members(def) + btf_vlen(def) - 1;
  6294. mname = btf__name_by_offset(obj->btf, member->name_off);
  6295. if (strcmp(mname, "values"))
  6296. return -EINVAL;
  6297. moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
  6298. if (rel->r_offset - vi->offset < moff)
  6299. return -EINVAL;
  6300. moff = rel->r_offset - vi->offset - moff;
  6301. /* here we use BPF pointer size, which is always 64 bit, as we
  6302. * are parsing ELF that was built for BPF target
  6303. */
  6304. if (moff % bpf_ptr_sz)
  6305. return -EINVAL;
  6306. moff /= bpf_ptr_sz;
  6307. if (moff >= map->init_slots_sz) {
  6308. new_sz = moff + 1;
  6309. tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
  6310. if (!tmp)
  6311. return -ENOMEM;
  6312. map->init_slots = tmp;
  6313. memset(map->init_slots + map->init_slots_sz, 0,
  6314. (new_sz - map->init_slots_sz) * host_ptr_sz);
  6315. map->init_slots_sz = new_sz;
  6316. }
  6317. map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
  6318. pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
  6319. i, map->name, moff, type, name);
  6320. }
  6321. return 0;
  6322. }
  6323. static int bpf_object__collect_relos(struct bpf_object *obj)
  6324. {
  6325. int i, err;
  6326. for (i = 0; i < obj->efile.sec_cnt; i++) {
  6327. struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
  6328. Elf64_Shdr *shdr;
  6329. Elf_Data *data;
  6330. int idx;
  6331. if (sec_desc->sec_type != SEC_RELO)
  6332. continue;
  6333. shdr = sec_desc->shdr;
  6334. data = sec_desc->data;
  6335. idx = shdr->sh_info;
  6336. if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
  6337. pr_warn("internal error at %d\n", __LINE__);
  6338. return -LIBBPF_ERRNO__INTERNAL;
  6339. }
  6340. if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
  6341. err = bpf_object__collect_st_ops_relos(obj, shdr, data);
  6342. else if (idx == obj->efile.btf_maps_shndx)
  6343. err = bpf_object__collect_map_relos(obj, shdr, data);
  6344. else
  6345. err = bpf_object__collect_prog_relos(obj, shdr, data);
  6346. if (err)
  6347. return err;
  6348. }
  6349. bpf_object__sort_relos(obj);
  6350. return 0;
  6351. }
  6352. static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
  6353. {
  6354. if (BPF_CLASS(insn->code) == BPF_JMP &&
  6355. BPF_OP(insn->code) == BPF_CALL &&
  6356. BPF_SRC(insn->code) == BPF_K &&
  6357. insn->src_reg == 0 &&
  6358. insn->dst_reg == 0) {
  6359. *func_id = insn->imm;
  6360. return true;
  6361. }
  6362. return false;
  6363. }
  6364. static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
  6365. {
  6366. struct bpf_insn *insn = prog->insns;
  6367. enum bpf_func_id func_id;
  6368. int i;
  6369. if (obj->gen_loader)
  6370. return 0;
  6371. for (i = 0; i < prog->insns_cnt; i++, insn++) {
  6372. if (!insn_is_helper_call(insn, &func_id))
  6373. continue;
  6374. /* on kernels that don't yet support
  6375. * bpf_probe_read_{kernel,user}[_str] helpers, fall back
  6376. * to bpf_probe_read() which works well for old kernels
  6377. */
  6378. switch (func_id) {
  6379. case BPF_FUNC_probe_read_kernel:
  6380. case BPF_FUNC_probe_read_user:
  6381. if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
  6382. insn->imm = BPF_FUNC_probe_read;
  6383. break;
  6384. case BPF_FUNC_probe_read_kernel_str:
  6385. case BPF_FUNC_probe_read_user_str:
  6386. if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
  6387. insn->imm = BPF_FUNC_probe_read_str;
  6388. break;
  6389. default:
  6390. break;
  6391. }
  6392. }
  6393. return 0;
  6394. }
  6395. static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
  6396. int *btf_obj_fd, int *btf_type_id);
  6397. /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
  6398. static int libbpf_prepare_prog_load(struct bpf_program *prog,
  6399. struct bpf_prog_load_opts *opts, long cookie)
  6400. {
  6401. enum sec_def_flags def = cookie;
  6402. /* old kernels might not support specifying expected_attach_type */
  6403. if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
  6404. opts->expected_attach_type = 0;
  6405. if (def & SEC_SLEEPABLE)
  6406. opts->prog_flags |= BPF_F_SLEEPABLE;
  6407. if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
  6408. opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
  6409. /* special check for usdt to use uprobe_multi link */
  6410. if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
  6411. /* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
  6412. * in prog, and expected_attach_type we set in kernel is from opts, so we
  6413. * update both.
  6414. */
  6415. prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
  6416. opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
  6417. }
  6418. if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
  6419. int btf_obj_fd = 0, btf_type_id = 0, err;
  6420. const char *attach_name;
  6421. attach_name = strchr(prog->sec_name, '/');
  6422. if (!attach_name) {
  6423. /* if BPF program is annotated with just SEC("fentry")
  6424. * (or similar) without declaratively specifying
  6425. * target, then it is expected that target will be
  6426. * specified with bpf_program__set_attach_target() at
  6427. * runtime before BPF object load step. If not, then
  6428. * there is nothing to load into the kernel as BPF
  6429. * verifier won't be able to validate BPF program
  6430. * correctness anyways.
  6431. */
  6432. pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
  6433. prog->name);
  6434. return -EINVAL;
  6435. }
  6436. attach_name++; /* skip over / */
  6437. err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
  6438. if (err)
  6439. return err;
  6440. /* cache resolved BTF FD and BTF type ID in the prog */
  6441. prog->attach_btf_obj_fd = btf_obj_fd;
  6442. prog->attach_btf_id = btf_type_id;
  6443. /* but by now libbpf common logic is not utilizing
  6444. * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
  6445. * this callback is called after opts were populated by
  6446. * libbpf, so this callback has to update opts explicitly here
  6447. */
  6448. opts->attach_btf_obj_fd = btf_obj_fd;
  6449. opts->attach_btf_id = btf_type_id;
  6450. }
  6451. return 0;
  6452. }
  6453. static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
  6454. static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
  6455. struct bpf_insn *insns, int insns_cnt,
  6456. const char *license, __u32 kern_version, int *prog_fd)
  6457. {
  6458. LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
  6459. const char *prog_name = NULL;
  6460. char *cp, errmsg[STRERR_BUFSIZE];
  6461. size_t log_buf_size = 0;
  6462. char *log_buf = NULL, *tmp;
  6463. bool own_log_buf = true;
  6464. __u32 log_level = prog->log_level;
  6465. int ret, err;
  6466. /* Be more helpful by rejecting programs that can't be validated early
  6467. * with more meaningful and actionable error message.
  6468. */
  6469. switch (prog->type) {
  6470. case BPF_PROG_TYPE_UNSPEC:
  6471. /*
  6472. * The program type must be set. Most likely we couldn't find a proper
  6473. * section definition at load time, and thus we didn't infer the type.
  6474. */
  6475. pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
  6476. prog->name, prog->sec_name);
  6477. return -EINVAL;
  6478. case BPF_PROG_TYPE_STRUCT_OPS:
  6479. if (prog->attach_btf_id == 0) {
  6480. pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
  6481. prog->name);
  6482. return -EINVAL;
  6483. }
  6484. break;
  6485. default:
  6486. break;
  6487. }
  6488. if (!insns || !insns_cnt)
  6489. return -EINVAL;
  6490. if (kernel_supports(obj, FEAT_PROG_NAME))
  6491. prog_name = prog->name;
  6492. load_attr.attach_prog_fd = prog->attach_prog_fd;
  6493. load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
  6494. load_attr.attach_btf_id = prog->attach_btf_id;
  6495. load_attr.kern_version = kern_version;
  6496. load_attr.prog_ifindex = prog->prog_ifindex;
  6497. load_attr.expected_attach_type = prog->expected_attach_type;
  6498. /* specify func_info/line_info only if kernel supports them */
  6499. if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
  6500. load_attr.prog_btf_fd = btf__fd(obj->btf);
  6501. load_attr.func_info = prog->func_info;
  6502. load_attr.func_info_rec_size = prog->func_info_rec_size;
  6503. load_attr.func_info_cnt = prog->func_info_cnt;
  6504. load_attr.line_info = prog->line_info;
  6505. load_attr.line_info_rec_size = prog->line_info_rec_size;
  6506. load_attr.line_info_cnt = prog->line_info_cnt;
  6507. }
  6508. load_attr.log_level = log_level;
  6509. load_attr.prog_flags = prog->prog_flags;
  6510. load_attr.fd_array = obj->fd_array;
  6511. load_attr.token_fd = obj->token_fd;
  6512. if (obj->token_fd)
  6513. load_attr.prog_flags |= BPF_F_TOKEN_FD;
  6514. /* adjust load_attr if sec_def provides custom preload callback */
  6515. if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
  6516. err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
  6517. if (err < 0) {
  6518. pr_warn("prog '%s': failed to prepare load attributes: %d\n",
  6519. prog->name, err);
  6520. return err;
  6521. }
  6522. insns = prog->insns;
  6523. insns_cnt = prog->insns_cnt;
  6524. }
  6525. if (obj->gen_loader) {
  6526. bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
  6527. license, insns, insns_cnt, &load_attr,
  6528. prog - obj->programs);
  6529. *prog_fd = -1;
  6530. return 0;
  6531. }
  6532. retry_load:
  6533. /* if log_level is zero, we don't request logs initially even if
  6534. * custom log_buf is specified; if the program load fails, then we'll
  6535. * bump log_level to 1 and use either custom log_buf or we'll allocate
  6536. * our own and retry the load to get details on what failed
  6537. */
  6538. if (log_level) {
  6539. if (prog->log_buf) {
  6540. log_buf = prog->log_buf;
  6541. log_buf_size = prog->log_size;
  6542. own_log_buf = false;
  6543. } else if (obj->log_buf) {
  6544. log_buf = obj->log_buf;
  6545. log_buf_size = obj->log_size;
  6546. own_log_buf = false;
  6547. } else {
  6548. log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
  6549. tmp = realloc(log_buf, log_buf_size);
  6550. if (!tmp) {
  6551. ret = -ENOMEM;
  6552. goto out;
  6553. }
  6554. log_buf = tmp;
  6555. log_buf[0] = '\0';
  6556. own_log_buf = true;
  6557. }
  6558. }
  6559. load_attr.log_buf = log_buf;
  6560. load_attr.log_size = log_buf_size;
  6561. load_attr.log_level = log_level;
  6562. ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
  6563. if (ret >= 0) {
  6564. if (log_level && own_log_buf) {
  6565. pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
  6566. prog->name, log_buf);
  6567. }
  6568. if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
  6569. struct bpf_map *map;
  6570. int i;
  6571. for (i = 0; i < obj->nr_maps; i++) {
  6572. map = &prog->obj->maps[i];
  6573. if (map->libbpf_type != LIBBPF_MAP_RODATA)
  6574. continue;
  6575. if (bpf_prog_bind_map(ret, map->fd, NULL)) {
  6576. cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
  6577. pr_warn("prog '%s': failed to bind map '%s': %s\n",
  6578. prog->name, map->real_name, cp);
  6579. /* Don't fail hard if can't bind rodata. */
  6580. }
  6581. }
  6582. }
  6583. *prog_fd = ret;
  6584. ret = 0;
  6585. goto out;
  6586. }
  6587. if (log_level == 0) {
  6588. log_level = 1;
  6589. goto retry_load;
  6590. }
  6591. /* On ENOSPC, increase log buffer size and retry, unless custom
  6592. * log_buf is specified.
  6593. * Be careful to not overflow u32, though. Kernel's log buf size limit
  6594. * isn't part of UAPI so it can always be bumped to full 4GB. So don't
  6595. * multiply by 2 unless we are sure we'll fit within 32 bits.
  6596. * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
  6597. */
  6598. if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
  6599. goto retry_load;
  6600. ret = -errno;
  6601. /* post-process verifier log to improve error descriptions */
  6602. fixup_verifier_log(prog, log_buf, log_buf_size);
  6603. cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
  6604. pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
  6605. pr_perm_msg(ret);
  6606. if (own_log_buf && log_buf && log_buf[0] != '\0') {
  6607. pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
  6608. prog->name, log_buf);
  6609. }
  6610. out:
  6611. if (own_log_buf)
  6612. free(log_buf);
  6613. return ret;
  6614. }
  6615. static char *find_prev_line(char *buf, char *cur)
  6616. {
  6617. char *p;
  6618. if (cur == buf) /* end of a log buf */
  6619. return NULL;
  6620. p = cur - 1;
  6621. while (p - 1 >= buf && *(p - 1) != '\n')
  6622. p--;
  6623. return p;
  6624. }
  6625. static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
  6626. char *orig, size_t orig_sz, const char *patch)
  6627. {
  6628. /* size of the remaining log content to the right from the to-be-replaced part */
  6629. size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
  6630. size_t patch_sz = strlen(patch);
  6631. if (patch_sz != orig_sz) {
  6632. /* If patch line(s) are longer than original piece of verifier log,
  6633. * shift log contents by (patch_sz - orig_sz) bytes to the right
  6634. * starting from after to-be-replaced part of the log.
  6635. *
  6636. * If patch line(s) are shorter than original piece of verifier log,
  6637. * shift log contents by (orig_sz - patch_sz) bytes to the left
  6638. * starting from after to-be-replaced part of the log
  6639. *
  6640. * We need to be careful about not overflowing available
  6641. * buf_sz capacity. If that's the case, we'll truncate the end
  6642. * of the original log, as necessary.
  6643. */
  6644. if (patch_sz > orig_sz) {
  6645. if (orig + patch_sz >= buf + buf_sz) {
  6646. /* patch is big enough to cover remaining space completely */
  6647. patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
  6648. rem_sz = 0;
  6649. } else if (patch_sz - orig_sz > buf_sz - log_sz) {
  6650. /* patch causes part of remaining log to be truncated */
  6651. rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
  6652. }
  6653. }
  6654. /* shift remaining log to the right by calculated amount */
  6655. memmove(orig + patch_sz, orig + orig_sz, rem_sz);
  6656. }
  6657. memcpy(orig, patch, patch_sz);
  6658. }
  6659. static void fixup_log_failed_core_relo(struct bpf_program *prog,
  6660. char *buf, size_t buf_sz, size_t log_sz,
  6661. char *line1, char *line2, char *line3)
  6662. {
  6663. /* Expected log for failed and not properly guarded CO-RE relocation:
  6664. * line1 -> 123: (85) call unknown#195896080
  6665. * line2 -> invalid func unknown#195896080
  6666. * line3 -> <anything else or end of buffer>
  6667. *
  6668. * "123" is the index of the instruction that was poisoned. We extract
  6669. * instruction index to find corresponding CO-RE relocation and
  6670. * replace this part of the log with more relevant information about
  6671. * failed CO-RE relocation.
  6672. */
  6673. const struct bpf_core_relo *relo;
  6674. struct bpf_core_spec spec;
  6675. char patch[512], spec_buf[256];
  6676. int insn_idx, err, spec_len;
  6677. if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
  6678. return;
  6679. relo = find_relo_core(prog, insn_idx);
  6680. if (!relo)
  6681. return;
  6682. err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
  6683. if (err)
  6684. return;
  6685. spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
  6686. snprintf(patch, sizeof(patch),
  6687. "%d: <invalid CO-RE relocation>\n"
  6688. "failed to resolve CO-RE relocation %s%s\n",
  6689. insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
  6690. patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
  6691. }
  6692. static void fixup_log_missing_map_load(struct bpf_program *prog,
  6693. char *buf, size_t buf_sz, size_t log_sz,
  6694. char *line1, char *line2, char *line3)
  6695. {
  6696. /* Expected log for failed and not properly guarded map reference:
  6697. * line1 -> 123: (85) call unknown#2001000345
  6698. * line2 -> invalid func unknown#2001000345
  6699. * line3 -> <anything else or end of buffer>
  6700. *
  6701. * "123" is the index of the instruction that was poisoned.
  6702. * "345" in "2001000345" is a map index in obj->maps to fetch map name.
  6703. */
  6704. struct bpf_object *obj = prog->obj;
  6705. const struct bpf_map *map;
  6706. int insn_idx, map_idx;
  6707. char patch[128];
  6708. if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
  6709. return;
  6710. map_idx -= POISON_LDIMM64_MAP_BASE;
  6711. if (map_idx < 0 || map_idx >= obj->nr_maps)
  6712. return;
  6713. map = &obj->maps[map_idx];
  6714. snprintf(patch, sizeof(patch),
  6715. "%d: <invalid BPF map reference>\n"
  6716. "BPF map '%s' is referenced but wasn't created\n",
  6717. insn_idx, map->name);
  6718. patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
  6719. }
  6720. static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
  6721. char *buf, size_t buf_sz, size_t log_sz,
  6722. char *line1, char *line2, char *line3)
  6723. {
  6724. /* Expected log for failed and not properly guarded kfunc call:
  6725. * line1 -> 123: (85) call unknown#2002000345
  6726. * line2 -> invalid func unknown#2002000345
  6727. * line3 -> <anything else or end of buffer>
  6728. *
  6729. * "123" is the index of the instruction that was poisoned.
  6730. * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
  6731. */
  6732. struct bpf_object *obj = prog->obj;
  6733. const struct extern_desc *ext;
  6734. int insn_idx, ext_idx;
  6735. char patch[128];
  6736. if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
  6737. return;
  6738. ext_idx -= POISON_CALL_KFUNC_BASE;
  6739. if (ext_idx < 0 || ext_idx >= obj->nr_extern)
  6740. return;
  6741. ext = &obj->externs[ext_idx];
  6742. snprintf(patch, sizeof(patch),
  6743. "%d: <invalid kfunc call>\n"
  6744. "kfunc '%s' is referenced but wasn't resolved\n",
  6745. insn_idx, ext->name);
  6746. patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
  6747. }
  6748. static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
  6749. {
  6750. /* look for familiar error patterns in last N lines of the log */
  6751. const size_t max_last_line_cnt = 10;
  6752. char *prev_line, *cur_line, *next_line;
  6753. size_t log_sz;
  6754. int i;
  6755. if (!buf)
  6756. return;
  6757. log_sz = strlen(buf) + 1;
  6758. next_line = buf + log_sz - 1;
  6759. for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
  6760. cur_line = find_prev_line(buf, next_line);
  6761. if (!cur_line)
  6762. return;
  6763. if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
  6764. prev_line = find_prev_line(buf, cur_line);
  6765. if (!prev_line)
  6766. continue;
  6767. /* failed CO-RE relocation case */
  6768. fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
  6769. prev_line, cur_line, next_line);
  6770. return;
  6771. } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
  6772. prev_line = find_prev_line(buf, cur_line);
  6773. if (!prev_line)
  6774. continue;
  6775. /* reference to uncreated BPF map */
  6776. fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
  6777. prev_line, cur_line, next_line);
  6778. return;
  6779. } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
  6780. prev_line = find_prev_line(buf, cur_line);
  6781. if (!prev_line)
  6782. continue;
  6783. /* reference to unresolved kfunc */
  6784. fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
  6785. prev_line, cur_line, next_line);
  6786. return;
  6787. }
  6788. }
  6789. }
  6790. static int bpf_program_record_relos(struct bpf_program *prog)
  6791. {
  6792. struct bpf_object *obj = prog->obj;
  6793. int i;
  6794. for (i = 0; i < prog->nr_reloc; i++) {
  6795. struct reloc_desc *relo = &prog->reloc_desc[i];
  6796. struct extern_desc *ext = &obj->externs[relo->ext_idx];
  6797. int kind;
  6798. switch (relo->type) {
  6799. case RELO_EXTERN_LD64:
  6800. if (ext->type != EXT_KSYM)
  6801. continue;
  6802. kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
  6803. BTF_KIND_VAR : BTF_KIND_FUNC;
  6804. bpf_gen__record_extern(obj->gen_loader, ext->name,
  6805. ext->is_weak, !ext->ksym.type_id,
  6806. true, kind, relo->insn_idx);
  6807. break;
  6808. case RELO_EXTERN_CALL:
  6809. bpf_gen__record_extern(obj->gen_loader, ext->name,
  6810. ext->is_weak, false, false, BTF_KIND_FUNC,
  6811. relo->insn_idx);
  6812. break;
  6813. case RELO_CORE: {
  6814. struct bpf_core_relo cr = {
  6815. .insn_off = relo->insn_idx * 8,
  6816. .type_id = relo->core_relo->type_id,
  6817. .access_str_off = relo->core_relo->access_str_off,
  6818. .kind = relo->core_relo->kind,
  6819. };
  6820. bpf_gen__record_relo_core(obj->gen_loader, &cr);
  6821. break;
  6822. }
  6823. default:
  6824. continue;
  6825. }
  6826. }
  6827. return 0;
  6828. }
  6829. static int
  6830. bpf_object__load_progs(struct bpf_object *obj, int log_level)
  6831. {
  6832. struct bpf_program *prog;
  6833. size_t i;
  6834. int err;
  6835. for (i = 0; i < obj->nr_programs; i++) {
  6836. prog = &obj->programs[i];
  6837. err = bpf_object__sanitize_prog(obj, prog);
  6838. if (err)
  6839. return err;
  6840. }
  6841. for (i = 0; i < obj->nr_programs; i++) {
  6842. prog = &obj->programs[i];
  6843. if (prog_is_subprog(obj, prog))
  6844. continue;
  6845. if (!prog->autoload) {
  6846. pr_debug("prog '%s': skipped loading\n", prog->name);
  6847. continue;
  6848. }
  6849. prog->log_level |= log_level;
  6850. if (obj->gen_loader)
  6851. bpf_program_record_relos(prog);
  6852. err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
  6853. obj->license, obj->kern_version, &prog->fd);
  6854. if (err) {
  6855. pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
  6856. return err;
  6857. }
  6858. }
  6859. bpf_object__free_relocs(obj);
  6860. return 0;
  6861. }
  6862. static const struct bpf_sec_def *find_sec_def(const char *sec_name);
  6863. static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
  6864. {
  6865. struct bpf_program *prog;
  6866. int err;
  6867. bpf_object__for_each_program(prog, obj) {
  6868. prog->sec_def = find_sec_def(prog->sec_name);
  6869. if (!prog->sec_def) {
  6870. /* couldn't guess, but user might manually specify */
  6871. pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
  6872. prog->name, prog->sec_name);
  6873. continue;
  6874. }
  6875. prog->type = prog->sec_def->prog_type;
  6876. prog->expected_attach_type = prog->sec_def->expected_attach_type;
  6877. /* sec_def can have custom callback which should be called
  6878. * after bpf_program is initialized to adjust its properties
  6879. */
  6880. if (prog->sec_def->prog_setup_fn) {
  6881. err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
  6882. if (err < 0) {
  6883. pr_warn("prog '%s': failed to initialize: %d\n",
  6884. prog->name, err);
  6885. return err;
  6886. }
  6887. }
  6888. }
  6889. return 0;
  6890. }
  6891. static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
  6892. const char *obj_name,
  6893. const struct bpf_object_open_opts *opts)
  6894. {
  6895. const char *kconfig, *btf_tmp_path, *token_path;
  6896. struct bpf_object *obj;
  6897. int err;
  6898. char *log_buf;
  6899. size_t log_size;
  6900. __u32 log_level;
  6901. if (obj_buf && !obj_name)
  6902. return ERR_PTR(-EINVAL);
  6903. if (elf_version(EV_CURRENT) == EV_NONE) {
  6904. pr_warn("failed to init libelf for %s\n",
  6905. path ? : "(mem buf)");
  6906. return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
  6907. }
  6908. if (!OPTS_VALID(opts, bpf_object_open_opts))
  6909. return ERR_PTR(-EINVAL);
  6910. obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
  6911. if (obj_buf) {
  6912. path = obj_name;
  6913. pr_debug("loading object '%s' from buffer\n", obj_name);
  6914. } else {
  6915. pr_debug("loading object from %s\n", path);
  6916. }
  6917. log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
  6918. log_size = OPTS_GET(opts, kernel_log_size, 0);
  6919. log_level = OPTS_GET(opts, kernel_log_level, 0);
  6920. if (log_size > UINT_MAX)
  6921. return ERR_PTR(-EINVAL);
  6922. if (log_size && !log_buf)
  6923. return ERR_PTR(-EINVAL);
  6924. token_path = OPTS_GET(opts, bpf_token_path, NULL);
  6925. /* if user didn't specify bpf_token_path explicitly, check if
  6926. * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
  6927. * option
  6928. */
  6929. if (!token_path)
  6930. token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
  6931. if (token_path && strlen(token_path) >= PATH_MAX)
  6932. return ERR_PTR(-ENAMETOOLONG);
  6933. obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
  6934. if (IS_ERR(obj))
  6935. return obj;
  6936. obj->log_buf = log_buf;
  6937. obj->log_size = log_size;
  6938. obj->log_level = log_level;
  6939. if (token_path) {
  6940. obj->token_path = strdup(token_path);
  6941. if (!obj->token_path) {
  6942. err = -ENOMEM;
  6943. goto out;
  6944. }
  6945. }
  6946. btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
  6947. if (btf_tmp_path) {
  6948. if (strlen(btf_tmp_path) >= PATH_MAX) {
  6949. err = -ENAMETOOLONG;
  6950. goto out;
  6951. }
  6952. obj->btf_custom_path = strdup(btf_tmp_path);
  6953. if (!obj->btf_custom_path) {
  6954. err = -ENOMEM;
  6955. goto out;
  6956. }
  6957. }
  6958. kconfig = OPTS_GET(opts, kconfig, NULL);
  6959. if (kconfig) {
  6960. obj->kconfig = strdup(kconfig);
  6961. if (!obj->kconfig) {
  6962. err = -ENOMEM;
  6963. goto out;
  6964. }
  6965. }
  6966. err = bpf_object__elf_init(obj);
  6967. err = err ? : bpf_object__check_endianness(obj);
  6968. err = err ? : bpf_object__elf_collect(obj);
  6969. err = err ? : bpf_object__collect_externs(obj);
  6970. err = err ? : bpf_object_fixup_btf(obj);
  6971. err = err ? : bpf_object__init_maps(obj, opts);
  6972. err = err ? : bpf_object_init_progs(obj, opts);
  6973. err = err ? : bpf_object__collect_relos(obj);
  6974. if (err)
  6975. goto out;
  6976. bpf_object__elf_finish(obj);
  6977. return obj;
  6978. out:
  6979. bpf_object__close(obj);
  6980. return ERR_PTR(err);
  6981. }
  6982. struct bpf_object *
  6983. bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
  6984. {
  6985. if (!path)
  6986. return libbpf_err_ptr(-EINVAL);
  6987. return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
  6988. }
  6989. struct bpf_object *bpf_object__open(const char *path)
  6990. {
  6991. return bpf_object__open_file(path, NULL);
  6992. }
  6993. struct bpf_object *
  6994. bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
  6995. const struct bpf_object_open_opts *opts)
  6996. {
  6997. char tmp_name[64];
  6998. if (!obj_buf || obj_buf_sz == 0)
  6999. return libbpf_err_ptr(-EINVAL);
  7000. /* create a (quite useless) default "name" for this memory buffer object */
  7001. snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
  7002. return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
  7003. }
  7004. static int bpf_object_unload(struct bpf_object *obj)
  7005. {
  7006. size_t i;
  7007. if (!obj)
  7008. return libbpf_err(-EINVAL);
  7009. for (i = 0; i < obj->nr_maps; i++) {
  7010. zclose(obj->maps[i].fd);
  7011. if (obj->maps[i].st_ops)
  7012. zfree(&obj->maps[i].st_ops->kern_vdata);
  7013. }
  7014. for (i = 0; i < obj->nr_programs; i++)
  7015. bpf_program__unload(&obj->programs[i]);
  7016. return 0;
  7017. }
  7018. static int bpf_object__sanitize_maps(struct bpf_object *obj)
  7019. {
  7020. struct bpf_map *m;
  7021. bpf_object__for_each_map(m, obj) {
  7022. if (!bpf_map__is_internal(m))
  7023. continue;
  7024. if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
  7025. m->def.map_flags &= ~BPF_F_MMAPABLE;
  7026. }
  7027. return 0;
  7028. }
  7029. typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
  7030. const char *sym_name, void *ctx);
  7031. static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
  7032. {
  7033. char sym_type, sym_name[500];
  7034. unsigned long long sym_addr;
  7035. int ret, err = 0;
  7036. FILE *f;
  7037. f = fopen("/proc/kallsyms", "re");
  7038. if (!f) {
  7039. err = -errno;
  7040. pr_warn("failed to open /proc/kallsyms: %d\n", err);
  7041. return err;
  7042. }
  7043. while (true) {
  7044. ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
  7045. &sym_addr, &sym_type, sym_name);
  7046. if (ret == EOF && feof(f))
  7047. break;
  7048. if (ret != 3) {
  7049. pr_warn("failed to read kallsyms entry: %d\n", ret);
  7050. err = -EINVAL;
  7051. break;
  7052. }
  7053. err = cb(sym_addr, sym_type, sym_name, ctx);
  7054. if (err)
  7055. break;
  7056. }
  7057. fclose(f);
  7058. return err;
  7059. }
  7060. static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
  7061. const char *sym_name, void *ctx)
  7062. {
  7063. struct bpf_object *obj = ctx;
  7064. const struct btf_type *t;
  7065. struct extern_desc *ext;
  7066. char *res;
  7067. res = strstr(sym_name, ".llvm.");
  7068. if (sym_type == 'd' && res)
  7069. ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
  7070. else
  7071. ext = find_extern_by_name(obj, sym_name);
  7072. if (!ext || ext->type != EXT_KSYM)
  7073. return 0;
  7074. t = btf__type_by_id(obj->btf, ext->btf_id);
  7075. if (!btf_is_var(t))
  7076. return 0;
  7077. if (ext->is_set && ext->ksym.addr != sym_addr) {
  7078. pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
  7079. sym_name, ext->ksym.addr, sym_addr);
  7080. return -EINVAL;
  7081. }
  7082. if (!ext->is_set) {
  7083. ext->is_set = true;
  7084. ext->ksym.addr = sym_addr;
  7085. pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
  7086. }
  7087. return 0;
  7088. }
  7089. static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
  7090. {
  7091. return libbpf_kallsyms_parse(kallsyms_cb, obj);
  7092. }
  7093. static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
  7094. __u16 kind, struct btf **res_btf,
  7095. struct module_btf **res_mod_btf)
  7096. {
  7097. struct module_btf *mod_btf;
  7098. struct btf *btf;
  7099. int i, id, err;
  7100. btf = obj->btf_vmlinux;
  7101. mod_btf = NULL;
  7102. id = btf__find_by_name_kind(btf, ksym_name, kind);
  7103. if (id == -ENOENT) {
  7104. err = load_module_btfs(obj);
  7105. if (err)
  7106. return err;
  7107. for (i = 0; i < obj->btf_module_cnt; i++) {
  7108. /* we assume module_btf's BTF FD is always >0 */
  7109. mod_btf = &obj->btf_modules[i];
  7110. btf = mod_btf->btf;
  7111. id = btf__find_by_name_kind_own(btf, ksym_name, kind);
  7112. if (id != -ENOENT)
  7113. break;
  7114. }
  7115. }
  7116. if (id <= 0)
  7117. return -ESRCH;
  7118. *res_btf = btf;
  7119. *res_mod_btf = mod_btf;
  7120. return id;
  7121. }
  7122. static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
  7123. struct extern_desc *ext)
  7124. {
  7125. const struct btf_type *targ_var, *targ_type;
  7126. __u32 targ_type_id, local_type_id;
  7127. struct module_btf *mod_btf = NULL;
  7128. const char *targ_var_name;
  7129. struct btf *btf = NULL;
  7130. int id, err;
  7131. id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
  7132. if (id < 0) {
  7133. if (id == -ESRCH && ext->is_weak)
  7134. return 0;
  7135. pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
  7136. ext->name);
  7137. return id;
  7138. }
  7139. /* find local type_id */
  7140. local_type_id = ext->ksym.type_id;
  7141. /* find target type_id */
  7142. targ_var = btf__type_by_id(btf, id);
  7143. targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
  7144. targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
  7145. err = bpf_core_types_are_compat(obj->btf, local_type_id,
  7146. btf, targ_type_id);
  7147. if (err <= 0) {
  7148. const struct btf_type *local_type;
  7149. const char *targ_name, *local_name;
  7150. local_type = btf__type_by_id(obj->btf, local_type_id);
  7151. local_name = btf__name_by_offset(obj->btf, local_type->name_off);
  7152. targ_name = btf__name_by_offset(btf, targ_type->name_off);
  7153. pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
  7154. ext->name, local_type_id,
  7155. btf_kind_str(local_type), local_name, targ_type_id,
  7156. btf_kind_str(targ_type), targ_name);
  7157. return -EINVAL;
  7158. }
  7159. ext->is_set = true;
  7160. ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
  7161. ext->ksym.kernel_btf_id = id;
  7162. pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
  7163. ext->name, id, btf_kind_str(targ_var), targ_var_name);
  7164. return 0;
  7165. }
  7166. static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
  7167. struct extern_desc *ext)
  7168. {
  7169. int local_func_proto_id, kfunc_proto_id, kfunc_id;
  7170. struct module_btf *mod_btf = NULL;
  7171. const struct btf_type *kern_func;
  7172. struct btf *kern_btf = NULL;
  7173. int ret;
  7174. local_func_proto_id = ext->ksym.type_id;
  7175. kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
  7176. &mod_btf);
  7177. if (kfunc_id < 0) {
  7178. if (kfunc_id == -ESRCH && ext->is_weak)
  7179. return 0;
  7180. pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
  7181. ext->name);
  7182. return kfunc_id;
  7183. }
  7184. kern_func = btf__type_by_id(kern_btf, kfunc_id);
  7185. kfunc_proto_id = kern_func->type;
  7186. ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
  7187. kern_btf, kfunc_proto_id);
  7188. if (ret <= 0) {
  7189. if (ext->is_weak)
  7190. return 0;
  7191. pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
  7192. ext->name, local_func_proto_id,
  7193. mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
  7194. return -EINVAL;
  7195. }
  7196. /* set index for module BTF fd in fd_array, if unset */
  7197. if (mod_btf && !mod_btf->fd_array_idx) {
  7198. /* insn->off is s16 */
  7199. if (obj->fd_array_cnt == INT16_MAX) {
  7200. pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
  7201. ext->name, mod_btf->fd_array_idx);
  7202. return -E2BIG;
  7203. }
  7204. /* Cannot use index 0 for module BTF fd */
  7205. if (!obj->fd_array_cnt)
  7206. obj->fd_array_cnt = 1;
  7207. ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
  7208. obj->fd_array_cnt + 1);
  7209. if (ret)
  7210. return ret;
  7211. mod_btf->fd_array_idx = obj->fd_array_cnt;
  7212. /* we assume module BTF FD is always >0 */
  7213. obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
  7214. }
  7215. ext->is_set = true;
  7216. ext->ksym.kernel_btf_id = kfunc_id;
  7217. ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
  7218. /* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
  7219. * populates FD into ld_imm64 insn when it's used to point to kfunc.
  7220. * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
  7221. * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
  7222. */
  7223. ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
  7224. pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
  7225. ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
  7226. return 0;
  7227. }
  7228. static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
  7229. {
  7230. const struct btf_type *t;
  7231. struct extern_desc *ext;
  7232. int i, err;
  7233. for (i = 0; i < obj->nr_extern; i++) {
  7234. ext = &obj->externs[i];
  7235. if (ext->type != EXT_KSYM || !ext->ksym.type_id)
  7236. continue;
  7237. if (obj->gen_loader) {
  7238. ext->is_set = true;
  7239. ext->ksym.kernel_btf_obj_fd = 0;
  7240. ext->ksym.kernel_btf_id = 0;
  7241. continue;
  7242. }
  7243. t = btf__type_by_id(obj->btf, ext->btf_id);
  7244. if (btf_is_var(t))
  7245. err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
  7246. else
  7247. err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
  7248. if (err)
  7249. return err;
  7250. }
  7251. return 0;
  7252. }
  7253. static int bpf_object__resolve_externs(struct bpf_object *obj,
  7254. const char *extra_kconfig)
  7255. {
  7256. bool need_config = false, need_kallsyms = false;
  7257. bool need_vmlinux_btf = false;
  7258. struct extern_desc *ext;
  7259. void *kcfg_data = NULL;
  7260. int err, i;
  7261. if (obj->nr_extern == 0)
  7262. return 0;
  7263. if (obj->kconfig_map_idx >= 0)
  7264. kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
  7265. for (i = 0; i < obj->nr_extern; i++) {
  7266. ext = &obj->externs[i];
  7267. if (ext->type == EXT_KSYM) {
  7268. if (ext->ksym.type_id)
  7269. need_vmlinux_btf = true;
  7270. else
  7271. need_kallsyms = true;
  7272. continue;
  7273. } else if (ext->type == EXT_KCFG) {
  7274. void *ext_ptr = kcfg_data + ext->kcfg.data_off;
  7275. __u64 value = 0;
  7276. /* Kconfig externs need actual /proc/config.gz */
  7277. if (str_has_pfx(ext->name, "CONFIG_")) {
  7278. need_config = true;
  7279. continue;
  7280. }
  7281. /* Virtual kcfg externs are customly handled by libbpf */
  7282. if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
  7283. value = get_kernel_version();
  7284. if (!value) {
  7285. pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
  7286. return -EINVAL;
  7287. }
  7288. } else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
  7289. value = kernel_supports(obj, FEAT_BPF_COOKIE);
  7290. } else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
  7291. value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
  7292. } else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
  7293. /* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
  7294. * __kconfig externs, where LINUX_ ones are virtual and filled out
  7295. * customly by libbpf (their values don't come from Kconfig).
  7296. * If LINUX_xxx variable is not recognized by libbpf, but is marked
  7297. * __weak, it defaults to zero value, just like for CONFIG_xxx
  7298. * externs.
  7299. */
  7300. pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
  7301. return -EINVAL;
  7302. }
  7303. err = set_kcfg_value_num(ext, ext_ptr, value);
  7304. if (err)
  7305. return err;
  7306. pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
  7307. ext->name, (long long)value);
  7308. } else {
  7309. pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
  7310. return -EINVAL;
  7311. }
  7312. }
  7313. if (need_config && extra_kconfig) {
  7314. err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
  7315. if (err)
  7316. return -EINVAL;
  7317. need_config = false;
  7318. for (i = 0; i < obj->nr_extern; i++) {
  7319. ext = &obj->externs[i];
  7320. if (ext->type == EXT_KCFG && !ext->is_set) {
  7321. need_config = true;
  7322. break;
  7323. }
  7324. }
  7325. }
  7326. if (need_config) {
  7327. err = bpf_object__read_kconfig_file(obj, kcfg_data);
  7328. if (err)
  7329. return -EINVAL;
  7330. }
  7331. if (need_kallsyms) {
  7332. err = bpf_object__read_kallsyms_file(obj);
  7333. if (err)
  7334. return -EINVAL;
  7335. }
  7336. if (need_vmlinux_btf) {
  7337. err = bpf_object__resolve_ksyms_btf_id(obj);
  7338. if (err)
  7339. return -EINVAL;
  7340. }
  7341. for (i = 0; i < obj->nr_extern; i++) {
  7342. ext = &obj->externs[i];
  7343. if (!ext->is_set && !ext->is_weak) {
  7344. pr_warn("extern '%s' (strong): not resolved\n", ext->name);
  7345. return -ESRCH;
  7346. } else if (!ext->is_set) {
  7347. pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
  7348. ext->name);
  7349. }
  7350. }
  7351. return 0;
  7352. }
  7353. static void bpf_map_prepare_vdata(const struct bpf_map *map)
  7354. {
  7355. const struct btf_type *type;
  7356. struct bpf_struct_ops *st_ops;
  7357. __u32 i;
  7358. st_ops = map->st_ops;
  7359. type = btf__type_by_id(map->obj->btf, st_ops->type_id);
  7360. for (i = 0; i < btf_vlen(type); i++) {
  7361. struct bpf_program *prog = st_ops->progs[i];
  7362. void *kern_data;
  7363. int prog_fd;
  7364. if (!prog)
  7365. continue;
  7366. prog_fd = bpf_program__fd(prog);
  7367. kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
  7368. *(unsigned long *)kern_data = prog_fd;
  7369. }
  7370. }
  7371. static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
  7372. {
  7373. struct bpf_map *map;
  7374. int i;
  7375. for (i = 0; i < obj->nr_maps; i++) {
  7376. map = &obj->maps[i];
  7377. if (!bpf_map__is_struct_ops(map))
  7378. continue;
  7379. if (!map->autocreate)
  7380. continue;
  7381. bpf_map_prepare_vdata(map);
  7382. }
  7383. return 0;
  7384. }
  7385. static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
  7386. {
  7387. int err, i;
  7388. if (!obj)
  7389. return libbpf_err(-EINVAL);
  7390. if (obj->loaded) {
  7391. pr_warn("object '%s': load can't be attempted twice\n", obj->name);
  7392. return libbpf_err(-EINVAL);
  7393. }
  7394. if (obj->gen_loader)
  7395. bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
  7396. err = bpf_object_prepare_token(obj);
  7397. err = err ? : bpf_object__probe_loading(obj);
  7398. err = err ? : bpf_object__load_vmlinux_btf(obj, false);
  7399. err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
  7400. err = err ? : bpf_object__sanitize_maps(obj);
  7401. err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
  7402. err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
  7403. err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
  7404. err = err ? : bpf_object__sanitize_and_load_btf(obj);
  7405. err = err ? : bpf_object__create_maps(obj);
  7406. err = err ? : bpf_object__load_progs(obj, extra_log_level);
  7407. err = err ? : bpf_object_init_prog_arrays(obj);
  7408. err = err ? : bpf_object_prepare_struct_ops(obj);
  7409. if (obj->gen_loader) {
  7410. /* reset FDs */
  7411. if (obj->btf)
  7412. btf__set_fd(obj->btf, -1);
  7413. if (!err)
  7414. err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
  7415. }
  7416. /* clean up fd_array */
  7417. zfree(&obj->fd_array);
  7418. /* clean up module BTFs */
  7419. for (i = 0; i < obj->btf_module_cnt; i++) {
  7420. close(obj->btf_modules[i].fd);
  7421. btf__free(obj->btf_modules[i].btf);
  7422. free(obj->btf_modules[i].name);
  7423. }
  7424. free(obj->btf_modules);
  7425. /* clean up vmlinux BTF */
  7426. btf__free(obj->btf_vmlinux);
  7427. obj->btf_vmlinux = NULL;
  7428. obj->loaded = true; /* doesn't matter if successfully or not */
  7429. if (err)
  7430. goto out;
  7431. return 0;
  7432. out:
  7433. /* unpin any maps that were auto-pinned during load */
  7434. for (i = 0; i < obj->nr_maps; i++)
  7435. if (obj->maps[i].pinned && !obj->maps[i].reused)
  7436. bpf_map__unpin(&obj->maps[i], NULL);
  7437. bpf_object_unload(obj);
  7438. pr_warn("failed to load object '%s'\n", obj->path);
  7439. return libbpf_err(err);
  7440. }
  7441. int bpf_object__load(struct bpf_object *obj)
  7442. {
  7443. return bpf_object_load(obj, 0, NULL);
  7444. }
  7445. static int make_parent_dir(const char *path)
  7446. {
  7447. char *cp, errmsg[STRERR_BUFSIZE];
  7448. char *dname, *dir;
  7449. int err = 0;
  7450. dname = strdup(path);
  7451. if (dname == NULL)
  7452. return -ENOMEM;
  7453. dir = dirname(dname);
  7454. if (mkdir(dir, 0700) && errno != EEXIST)
  7455. err = -errno;
  7456. free(dname);
  7457. if (err) {
  7458. cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
  7459. pr_warn("failed to mkdir %s: %s\n", path, cp);
  7460. }
  7461. return err;
  7462. }
  7463. static int check_path(const char *path)
  7464. {
  7465. char *cp, errmsg[STRERR_BUFSIZE];
  7466. struct statfs st_fs;
  7467. char *dname, *dir;
  7468. int err = 0;
  7469. if (path == NULL)
  7470. return -EINVAL;
  7471. dname = strdup(path);
  7472. if (dname == NULL)
  7473. return -ENOMEM;
  7474. dir = dirname(dname);
  7475. if (statfs(dir, &st_fs)) {
  7476. cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
  7477. pr_warn("failed to statfs %s: %s\n", dir, cp);
  7478. err = -errno;
  7479. }
  7480. free(dname);
  7481. if (!err && st_fs.f_type != BPF_FS_MAGIC) {
  7482. pr_warn("specified path %s is not on BPF FS\n", path);
  7483. err = -EINVAL;
  7484. }
  7485. return err;
  7486. }
  7487. int bpf_program__pin(struct bpf_program *prog, const char *path)
  7488. {
  7489. char *cp, errmsg[STRERR_BUFSIZE];
  7490. int err;
  7491. if (prog->fd < 0) {
  7492. pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
  7493. return libbpf_err(-EINVAL);
  7494. }
  7495. err = make_parent_dir(path);
  7496. if (err)
  7497. return libbpf_err(err);
  7498. err = check_path(path);
  7499. if (err)
  7500. return libbpf_err(err);
  7501. if (bpf_obj_pin(prog->fd, path)) {
  7502. err = -errno;
  7503. cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
  7504. pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
  7505. return libbpf_err(err);
  7506. }
  7507. pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
  7508. return 0;
  7509. }
  7510. int bpf_program__unpin(struct bpf_program *prog, const char *path)
  7511. {
  7512. int err;
  7513. if (prog->fd < 0) {
  7514. pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
  7515. return libbpf_err(-EINVAL);
  7516. }
  7517. err = check_path(path);
  7518. if (err)
  7519. return libbpf_err(err);
  7520. err = unlink(path);
  7521. if (err)
  7522. return libbpf_err(-errno);
  7523. pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
  7524. return 0;
  7525. }
  7526. int bpf_map__pin(struct bpf_map *map, const char *path)
  7527. {
  7528. char *cp, errmsg[STRERR_BUFSIZE];
  7529. int err;
  7530. if (map == NULL) {
  7531. pr_warn("invalid map pointer\n");
  7532. return libbpf_err(-EINVAL);
  7533. }
  7534. if (map->fd < 0) {
  7535. pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
  7536. return libbpf_err(-EINVAL);
  7537. }
  7538. if (map->pin_path) {
  7539. if (path && strcmp(path, map->pin_path)) {
  7540. pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
  7541. bpf_map__name(map), map->pin_path, path);
  7542. return libbpf_err(-EINVAL);
  7543. } else if (map->pinned) {
  7544. pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
  7545. bpf_map__name(map), map->pin_path);
  7546. return 0;
  7547. }
  7548. } else {
  7549. if (!path) {
  7550. pr_warn("missing a path to pin map '%s' at\n",
  7551. bpf_map__name(map));
  7552. return libbpf_err(-EINVAL);
  7553. } else if (map->pinned) {
  7554. pr_warn("map '%s' already pinned\n", bpf_map__name(map));
  7555. return libbpf_err(-EEXIST);
  7556. }
  7557. map->pin_path = strdup(path);
  7558. if (!map->pin_path) {
  7559. err = -errno;
  7560. goto out_err;
  7561. }
  7562. }
  7563. err = make_parent_dir(map->pin_path);
  7564. if (err)
  7565. return libbpf_err(err);
  7566. err = check_path(map->pin_path);
  7567. if (err)
  7568. return libbpf_err(err);
  7569. if (bpf_obj_pin(map->fd, map->pin_path)) {
  7570. err = -errno;
  7571. goto out_err;
  7572. }
  7573. map->pinned = true;
  7574. pr_debug("pinned map '%s'\n", map->pin_path);
  7575. return 0;
  7576. out_err:
  7577. cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
  7578. pr_warn("failed to pin map: %s\n", cp);
  7579. return libbpf_err(err);
  7580. }
  7581. int bpf_map__unpin(struct bpf_map *map, const char *path)
  7582. {
  7583. int err;
  7584. if (map == NULL) {
  7585. pr_warn("invalid map pointer\n");
  7586. return libbpf_err(-EINVAL);
  7587. }
  7588. if (map->pin_path) {
  7589. if (path && strcmp(path, map->pin_path)) {
  7590. pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
  7591. bpf_map__name(map), map->pin_path, path);
  7592. return libbpf_err(-EINVAL);
  7593. }
  7594. path = map->pin_path;
  7595. } else if (!path) {
  7596. pr_warn("no path to unpin map '%s' from\n",
  7597. bpf_map__name(map));
  7598. return libbpf_err(-EINVAL);
  7599. }
  7600. err = check_path(path);
  7601. if (err)
  7602. return libbpf_err(err);
  7603. err = unlink(path);
  7604. if (err != 0)
  7605. return libbpf_err(-errno);
  7606. map->pinned = false;
  7607. pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
  7608. return 0;
  7609. }
  7610. int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
  7611. {
  7612. char *new = NULL;
  7613. if (path) {
  7614. new = strdup(path);
  7615. if (!new)
  7616. return libbpf_err(-errno);
  7617. }
  7618. free(map->pin_path);
  7619. map->pin_path = new;
  7620. return 0;
  7621. }
  7622. __alias(bpf_map__pin_path)
  7623. const char *bpf_map__get_pin_path(const struct bpf_map *map);
  7624. const char *bpf_map__pin_path(const struct bpf_map *map)
  7625. {
  7626. return map->pin_path;
  7627. }
  7628. bool bpf_map__is_pinned(const struct bpf_map *map)
  7629. {
  7630. return map->pinned;
  7631. }
  7632. static void sanitize_pin_path(char *s)
  7633. {
  7634. /* bpffs disallows periods in path names */
  7635. while (*s) {
  7636. if (*s == '.')
  7637. *s = '_';
  7638. s++;
  7639. }
  7640. }
  7641. int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
  7642. {
  7643. struct bpf_map *map;
  7644. int err;
  7645. if (!obj)
  7646. return libbpf_err(-ENOENT);
  7647. if (!obj->loaded) {
  7648. pr_warn("object not yet loaded; load it first\n");
  7649. return libbpf_err(-ENOENT);
  7650. }
  7651. bpf_object__for_each_map(map, obj) {
  7652. char *pin_path = NULL;
  7653. char buf[PATH_MAX];
  7654. if (!map->autocreate)
  7655. continue;
  7656. if (path) {
  7657. err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
  7658. if (err)
  7659. goto err_unpin_maps;
  7660. sanitize_pin_path(buf);
  7661. pin_path = buf;
  7662. } else if (!map->pin_path) {
  7663. continue;
  7664. }
  7665. err = bpf_map__pin(map, pin_path);
  7666. if (err)
  7667. goto err_unpin_maps;
  7668. }
  7669. return 0;
  7670. err_unpin_maps:
  7671. while ((map = bpf_object__prev_map(obj, map))) {
  7672. if (!map->pin_path)
  7673. continue;
  7674. bpf_map__unpin(map, NULL);
  7675. }
  7676. return libbpf_err(err);
  7677. }
  7678. int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
  7679. {
  7680. struct bpf_map *map;
  7681. int err;
  7682. if (!obj)
  7683. return libbpf_err(-ENOENT);
  7684. bpf_object__for_each_map(map, obj) {
  7685. char *pin_path = NULL;
  7686. char buf[PATH_MAX];
  7687. if (path) {
  7688. err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
  7689. if (err)
  7690. return libbpf_err(err);
  7691. sanitize_pin_path(buf);
  7692. pin_path = buf;
  7693. } else if (!map->pin_path) {
  7694. continue;
  7695. }
  7696. err = bpf_map__unpin(map, pin_path);
  7697. if (err)
  7698. return libbpf_err(err);
  7699. }
  7700. return 0;
  7701. }
  7702. int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
  7703. {
  7704. struct bpf_program *prog;
  7705. char buf[PATH_MAX];
  7706. int err;
  7707. if (!obj)
  7708. return libbpf_err(-ENOENT);
  7709. if (!obj->loaded) {
  7710. pr_warn("object not yet loaded; load it first\n");
  7711. return libbpf_err(-ENOENT);
  7712. }
  7713. bpf_object__for_each_program(prog, obj) {
  7714. err = pathname_concat(buf, sizeof(buf), path, prog->name);
  7715. if (err)
  7716. goto err_unpin_programs;
  7717. err = bpf_program__pin(prog, buf);
  7718. if (err)
  7719. goto err_unpin_programs;
  7720. }
  7721. return 0;
  7722. err_unpin_programs:
  7723. while ((prog = bpf_object__prev_program(obj, prog))) {
  7724. if (pathname_concat(buf, sizeof(buf), path, prog->name))
  7725. continue;
  7726. bpf_program__unpin(prog, buf);
  7727. }
  7728. return libbpf_err(err);
  7729. }
  7730. int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
  7731. {
  7732. struct bpf_program *prog;
  7733. int err;
  7734. if (!obj)
  7735. return libbpf_err(-ENOENT);
  7736. bpf_object__for_each_program(prog, obj) {
  7737. char buf[PATH_MAX];
  7738. err = pathname_concat(buf, sizeof(buf), path, prog->name);
  7739. if (err)
  7740. return libbpf_err(err);
  7741. err = bpf_program__unpin(prog, buf);
  7742. if (err)
  7743. return libbpf_err(err);
  7744. }
  7745. return 0;
  7746. }
  7747. int bpf_object__pin(struct bpf_object *obj, const char *path)
  7748. {
  7749. int err;
  7750. err = bpf_object__pin_maps(obj, path);
  7751. if (err)
  7752. return libbpf_err(err);
  7753. err = bpf_object__pin_programs(obj, path);
  7754. if (err) {
  7755. bpf_object__unpin_maps(obj, path);
  7756. return libbpf_err(err);
  7757. }
  7758. return 0;
  7759. }
  7760. int bpf_object__unpin(struct bpf_object *obj, const char *path)
  7761. {
  7762. int err;
  7763. err = bpf_object__unpin_programs(obj, path);
  7764. if (err)
  7765. return libbpf_err(err);
  7766. err = bpf_object__unpin_maps(obj, path);
  7767. if (err)
  7768. return libbpf_err(err);
  7769. return 0;
  7770. }
  7771. static void bpf_map__destroy(struct bpf_map *map)
  7772. {
  7773. if (map->inner_map) {
  7774. bpf_map__destroy(map->inner_map);
  7775. zfree(&map->inner_map);
  7776. }
  7777. zfree(&map->init_slots);
  7778. map->init_slots_sz = 0;
  7779. if (map->mmaped && map->mmaped != map->obj->arena_data)
  7780. munmap(map->mmaped, bpf_map_mmap_sz(map));
  7781. map->mmaped = NULL;
  7782. if (map->st_ops) {
  7783. zfree(&map->st_ops->data);
  7784. zfree(&map->st_ops->progs);
  7785. zfree(&map->st_ops->kern_func_off);
  7786. zfree(&map->st_ops);
  7787. }
  7788. zfree(&map->name);
  7789. zfree(&map->real_name);
  7790. zfree(&map->pin_path);
  7791. if (map->fd >= 0)
  7792. zclose(map->fd);
  7793. }
  7794. void bpf_object__close(struct bpf_object *obj)
  7795. {
  7796. size_t i;
  7797. if (IS_ERR_OR_NULL(obj))
  7798. return;
  7799. usdt_manager_free(obj->usdt_man);
  7800. obj->usdt_man = NULL;
  7801. bpf_gen__free(obj->gen_loader);
  7802. bpf_object__elf_finish(obj);
  7803. bpf_object_unload(obj);
  7804. btf__free(obj->btf);
  7805. btf__free(obj->btf_vmlinux);
  7806. btf_ext__free(obj->btf_ext);
  7807. for (i = 0; i < obj->nr_maps; i++)
  7808. bpf_map__destroy(&obj->maps[i]);
  7809. zfree(&obj->btf_custom_path);
  7810. zfree(&obj->kconfig);
  7811. for (i = 0; i < obj->nr_extern; i++) {
  7812. zfree(&obj->externs[i].name);
  7813. zfree(&obj->externs[i].essent_name);
  7814. }
  7815. zfree(&obj->externs);
  7816. obj->nr_extern = 0;
  7817. zfree(&obj->maps);
  7818. obj->nr_maps = 0;
  7819. if (obj->programs && obj->nr_programs) {
  7820. for (i = 0; i < obj->nr_programs; i++)
  7821. bpf_program__exit(&obj->programs[i]);
  7822. }
  7823. zfree(&obj->programs);
  7824. zfree(&obj->feat_cache);
  7825. zfree(&obj->token_path);
  7826. if (obj->token_fd > 0)
  7827. close(obj->token_fd);
  7828. zfree(&obj->arena_data);
  7829. free(obj);
  7830. }
  7831. const char *bpf_object__name(const struct bpf_object *obj)
  7832. {
  7833. return obj ? obj->name : libbpf_err_ptr(-EINVAL);
  7834. }
  7835. unsigned int bpf_object__kversion(const struct bpf_object *obj)
  7836. {
  7837. return obj ? obj->kern_version : 0;
  7838. }
  7839. int bpf_object__token_fd(const struct bpf_object *obj)
  7840. {
  7841. return obj->token_fd ?: -1;
  7842. }
  7843. struct btf *bpf_object__btf(const struct bpf_object *obj)
  7844. {
  7845. return obj ? obj->btf : NULL;
  7846. }
  7847. int bpf_object__btf_fd(const struct bpf_object *obj)
  7848. {
  7849. return obj->btf ? btf__fd(obj->btf) : -1;
  7850. }
  7851. int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
  7852. {
  7853. if (obj->loaded)
  7854. return libbpf_err(-EINVAL);
  7855. obj->kern_version = kern_version;
  7856. return 0;
  7857. }
  7858. int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
  7859. {
  7860. struct bpf_gen *gen;
  7861. if (!opts)
  7862. return -EFAULT;
  7863. if (!OPTS_VALID(opts, gen_loader_opts))
  7864. return -EINVAL;
  7865. gen = calloc(sizeof(*gen), 1);
  7866. if (!gen)
  7867. return -ENOMEM;
  7868. gen->opts = opts;
  7869. obj->gen_loader = gen;
  7870. return 0;
  7871. }
  7872. static struct bpf_program *
  7873. __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
  7874. bool forward)
  7875. {
  7876. size_t nr_programs = obj->nr_programs;
  7877. ssize_t idx;
  7878. if (!nr_programs)
  7879. return NULL;
  7880. if (!p)
  7881. /* Iter from the beginning */
  7882. return forward ? &obj->programs[0] :
  7883. &obj->programs[nr_programs - 1];
  7884. if (p->obj != obj) {
  7885. pr_warn("error: program handler doesn't match object\n");
  7886. return errno = EINVAL, NULL;
  7887. }
  7888. idx = (p - obj->programs) + (forward ? 1 : -1);
  7889. if (idx >= obj->nr_programs || idx < 0)
  7890. return NULL;
  7891. return &obj->programs[idx];
  7892. }
  7893. struct bpf_program *
  7894. bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
  7895. {
  7896. struct bpf_program *prog = prev;
  7897. do {
  7898. prog = __bpf_program__iter(prog, obj, true);
  7899. } while (prog && prog_is_subprog(obj, prog));
  7900. return prog;
  7901. }
  7902. struct bpf_program *
  7903. bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
  7904. {
  7905. struct bpf_program *prog = next;
  7906. do {
  7907. prog = __bpf_program__iter(prog, obj, false);
  7908. } while (prog && prog_is_subprog(obj, prog));
  7909. return prog;
  7910. }
  7911. void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
  7912. {
  7913. prog->prog_ifindex = ifindex;
  7914. }
  7915. const char *bpf_program__name(const struct bpf_program *prog)
  7916. {
  7917. return prog->name;
  7918. }
  7919. const char *bpf_program__section_name(const struct bpf_program *prog)
  7920. {
  7921. return prog->sec_name;
  7922. }
  7923. bool bpf_program__autoload(const struct bpf_program *prog)
  7924. {
  7925. return prog->autoload;
  7926. }
  7927. int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
  7928. {
  7929. if (prog->obj->loaded)
  7930. return libbpf_err(-EINVAL);
  7931. prog->autoload = autoload;
  7932. return 0;
  7933. }
  7934. bool bpf_program__autoattach(const struct bpf_program *prog)
  7935. {
  7936. return prog->autoattach;
  7937. }
  7938. void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
  7939. {
  7940. prog->autoattach = autoattach;
  7941. }
  7942. const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
  7943. {
  7944. return prog->insns;
  7945. }
  7946. size_t bpf_program__insn_cnt(const struct bpf_program *prog)
  7947. {
  7948. return prog->insns_cnt;
  7949. }
  7950. int bpf_program__set_insns(struct bpf_program *prog,
  7951. struct bpf_insn *new_insns, size_t new_insn_cnt)
  7952. {
  7953. struct bpf_insn *insns;
  7954. if (prog->obj->loaded)
  7955. return -EBUSY;
  7956. insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
  7957. /* NULL is a valid return from reallocarray if the new count is zero */
  7958. if (!insns && new_insn_cnt) {
  7959. pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
  7960. return -ENOMEM;
  7961. }
  7962. memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
  7963. prog->insns = insns;
  7964. prog->insns_cnt = new_insn_cnt;
  7965. return 0;
  7966. }
  7967. int bpf_program__fd(const struct bpf_program *prog)
  7968. {
  7969. if (!prog)
  7970. return libbpf_err(-EINVAL);
  7971. if (prog->fd < 0)
  7972. return libbpf_err(-ENOENT);
  7973. return prog->fd;
  7974. }
  7975. __alias(bpf_program__type)
  7976. enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
  7977. enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
  7978. {
  7979. return prog->type;
  7980. }
  7981. static size_t custom_sec_def_cnt;
  7982. static struct bpf_sec_def *custom_sec_defs;
  7983. static struct bpf_sec_def custom_fallback_def;
  7984. static bool has_custom_fallback_def;
  7985. static int last_custom_sec_def_handler_id;
  7986. int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
  7987. {
  7988. if (prog->obj->loaded)
  7989. return libbpf_err(-EBUSY);
  7990. /* if type is not changed, do nothing */
  7991. if (prog->type == type)
  7992. return 0;
  7993. prog->type = type;
  7994. /* If a program type was changed, we need to reset associated SEC()
  7995. * handler, as it will be invalid now. The only exception is a generic
  7996. * fallback handler, which by definition is program type-agnostic and
  7997. * is a catch-all custom handler, optionally set by the application,
  7998. * so should be able to handle any type of BPF program.
  7999. */
  8000. if (prog->sec_def != &custom_fallback_def)
  8001. prog->sec_def = NULL;
  8002. return 0;
  8003. }
  8004. __alias(bpf_program__expected_attach_type)
  8005. enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
  8006. enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
  8007. {
  8008. return prog->expected_attach_type;
  8009. }
  8010. int bpf_program__set_expected_attach_type(struct bpf_program *prog,
  8011. enum bpf_attach_type type)
  8012. {
  8013. if (prog->obj->loaded)
  8014. return libbpf_err(-EBUSY);
  8015. prog->expected_attach_type = type;
  8016. return 0;
  8017. }
  8018. __u32 bpf_program__flags(const struct bpf_program *prog)
  8019. {
  8020. return prog->prog_flags;
  8021. }
  8022. int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
  8023. {
  8024. if (prog->obj->loaded)
  8025. return libbpf_err(-EBUSY);
  8026. prog->prog_flags = flags;
  8027. return 0;
  8028. }
  8029. __u32 bpf_program__log_level(const struct bpf_program *prog)
  8030. {
  8031. return prog->log_level;
  8032. }
  8033. int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
  8034. {
  8035. if (prog->obj->loaded)
  8036. return libbpf_err(-EBUSY);
  8037. prog->log_level = log_level;
  8038. return 0;
  8039. }
  8040. const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
  8041. {
  8042. *log_size = prog->log_size;
  8043. return prog->log_buf;
  8044. }
  8045. int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
  8046. {
  8047. if (log_size && !log_buf)
  8048. return -EINVAL;
  8049. if (prog->log_size > UINT_MAX)
  8050. return -EINVAL;
  8051. if (prog->obj->loaded)
  8052. return -EBUSY;
  8053. prog->log_buf = log_buf;
  8054. prog->log_size = log_size;
  8055. return 0;
  8056. }
  8057. #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
  8058. .sec = (char *)sec_pfx, \
  8059. .prog_type = BPF_PROG_TYPE_##ptype, \
  8060. .expected_attach_type = atype, \
  8061. .cookie = (long)(flags), \
  8062. .prog_prepare_load_fn = libbpf_prepare_prog_load, \
  8063. __VA_ARGS__ \
  8064. }
  8065. static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8066. static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8067. static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8068. static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8069. static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8070. static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8071. static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8072. static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8073. static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8074. static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8075. static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8076. static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8077. static const struct bpf_sec_def section_defs[] = {
  8078. SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE),
  8079. SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
  8080. SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
  8081. SEC_DEF("kprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
  8082. SEC_DEF("uprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
  8083. SEC_DEF("uprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
  8084. SEC_DEF("kretprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
  8085. SEC_DEF("uretprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
  8086. SEC_DEF("uretprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
  8087. SEC_DEF("kprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
  8088. SEC_DEF("kretprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
  8089. SEC_DEF("kprobe.session+", KPROBE, BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
  8090. SEC_DEF("uprobe.multi+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
  8091. SEC_DEF("uretprobe.multi+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
  8092. SEC_DEF("uprobe.multi.s+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
  8093. SEC_DEF("uretprobe.multi.s+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
  8094. SEC_DEF("ksyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
  8095. SEC_DEF("kretsyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
  8096. SEC_DEF("usdt+", KPROBE, 0, SEC_USDT, attach_usdt),
  8097. SEC_DEF("usdt.s+", KPROBE, 0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
  8098. SEC_DEF("tc/ingress", SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
  8099. SEC_DEF("tc/egress", SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE), /* alias for tcx */
  8100. SEC_DEF("tcx/ingress", SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
  8101. SEC_DEF("tcx/egress", SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
  8102. SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
  8103. SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
  8104. SEC_DEF("action", SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
  8105. SEC_DEF("netkit/primary", SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
  8106. SEC_DEF("netkit/peer", SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
  8107. SEC_DEF("tracepoint+", TRACEPOINT, 0, SEC_NONE, attach_tp),
  8108. SEC_DEF("tp+", TRACEPOINT, 0, SEC_NONE, attach_tp),
  8109. SEC_DEF("raw_tracepoint+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
  8110. SEC_DEF("raw_tp+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
  8111. SEC_DEF("raw_tracepoint.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
  8112. SEC_DEF("raw_tp.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
  8113. SEC_DEF("tp_btf+", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
  8114. SEC_DEF("fentry+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
  8115. SEC_DEF("fmod_ret+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
  8116. SEC_DEF("fexit+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
  8117. SEC_DEF("fentry.s+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
  8118. SEC_DEF("fmod_ret.s+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
  8119. SEC_DEF("fexit.s+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
  8120. SEC_DEF("freplace+", EXT, 0, SEC_ATTACH_BTF, attach_trace),
  8121. SEC_DEF("lsm+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
  8122. SEC_DEF("lsm.s+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
  8123. SEC_DEF("lsm_cgroup+", LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
  8124. SEC_DEF("iter+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
  8125. SEC_DEF("iter.s+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
  8126. SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
  8127. SEC_DEF("xdp.frags/devmap", XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
  8128. SEC_DEF("xdp/devmap", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
  8129. SEC_DEF("xdp.frags/cpumap", XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
  8130. SEC_DEF("xdp/cpumap", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
  8131. SEC_DEF("xdp.frags", XDP, BPF_XDP, SEC_XDP_FRAGS),
  8132. SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
  8133. SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE),
  8134. SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE),
  8135. SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE),
  8136. SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE),
  8137. SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE),
  8138. SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
  8139. SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
  8140. SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
  8141. SEC_DEF("sk_skb/verdict", SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
  8142. SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE),
  8143. SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
  8144. SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
  8145. SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
  8146. SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
  8147. SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
  8148. SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE),
  8149. SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
  8150. SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
  8151. SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
  8152. SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
  8153. SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
  8154. SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
  8155. SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
  8156. SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
  8157. SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
  8158. SEC_DEF("cgroup/connect_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
  8159. SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
  8160. SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
  8161. SEC_DEF("cgroup/sendmsg_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
  8162. SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
  8163. SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
  8164. SEC_DEF("cgroup/recvmsg_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
  8165. SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
  8166. SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
  8167. SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
  8168. SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
  8169. SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
  8170. SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
  8171. SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
  8172. SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
  8173. SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
  8174. SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
  8175. SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
  8176. SEC_DEF("struct_ops.s+", STRUCT_OPS, 0, SEC_SLEEPABLE),
  8177. SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
  8178. SEC_DEF("netfilter", NETFILTER, BPF_NETFILTER, SEC_NONE),
  8179. };
  8180. int libbpf_register_prog_handler(const char *sec,
  8181. enum bpf_prog_type prog_type,
  8182. enum bpf_attach_type exp_attach_type,
  8183. const struct libbpf_prog_handler_opts *opts)
  8184. {
  8185. struct bpf_sec_def *sec_def;
  8186. if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
  8187. return libbpf_err(-EINVAL);
  8188. if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
  8189. return libbpf_err(-E2BIG);
  8190. if (sec) {
  8191. sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
  8192. sizeof(*sec_def));
  8193. if (!sec_def)
  8194. return libbpf_err(-ENOMEM);
  8195. custom_sec_defs = sec_def;
  8196. sec_def = &custom_sec_defs[custom_sec_def_cnt];
  8197. } else {
  8198. if (has_custom_fallback_def)
  8199. return libbpf_err(-EBUSY);
  8200. sec_def = &custom_fallback_def;
  8201. }
  8202. sec_def->sec = sec ? strdup(sec) : NULL;
  8203. if (sec && !sec_def->sec)
  8204. return libbpf_err(-ENOMEM);
  8205. sec_def->prog_type = prog_type;
  8206. sec_def->expected_attach_type = exp_attach_type;
  8207. sec_def->cookie = OPTS_GET(opts, cookie, 0);
  8208. sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
  8209. sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
  8210. sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
  8211. sec_def->handler_id = ++last_custom_sec_def_handler_id;
  8212. if (sec)
  8213. custom_sec_def_cnt++;
  8214. else
  8215. has_custom_fallback_def = true;
  8216. return sec_def->handler_id;
  8217. }
  8218. int libbpf_unregister_prog_handler(int handler_id)
  8219. {
  8220. struct bpf_sec_def *sec_defs;
  8221. int i;
  8222. if (handler_id <= 0)
  8223. return libbpf_err(-EINVAL);
  8224. if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
  8225. memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
  8226. has_custom_fallback_def = false;
  8227. return 0;
  8228. }
  8229. for (i = 0; i < custom_sec_def_cnt; i++) {
  8230. if (custom_sec_defs[i].handler_id == handler_id)
  8231. break;
  8232. }
  8233. if (i == custom_sec_def_cnt)
  8234. return libbpf_err(-ENOENT);
  8235. free(custom_sec_defs[i].sec);
  8236. for (i = i + 1; i < custom_sec_def_cnt; i++)
  8237. custom_sec_defs[i - 1] = custom_sec_defs[i];
  8238. custom_sec_def_cnt--;
  8239. /* try to shrink the array, but it's ok if we couldn't */
  8240. sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
  8241. /* if new count is zero, reallocarray can return a valid NULL result;
  8242. * in this case the previous pointer will be freed, so we *have to*
  8243. * reassign old pointer to the new value (even if it's NULL)
  8244. */
  8245. if (sec_defs || custom_sec_def_cnt == 0)
  8246. custom_sec_defs = sec_defs;
  8247. return 0;
  8248. }
  8249. static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
  8250. {
  8251. size_t len = strlen(sec_def->sec);
  8252. /* "type/" always has to have proper SEC("type/extras") form */
  8253. if (sec_def->sec[len - 1] == '/') {
  8254. if (str_has_pfx(sec_name, sec_def->sec))
  8255. return true;
  8256. return false;
  8257. }
  8258. /* "type+" means it can be either exact SEC("type") or
  8259. * well-formed SEC("type/extras") with proper '/' separator
  8260. */
  8261. if (sec_def->sec[len - 1] == '+') {
  8262. len--;
  8263. /* not even a prefix */
  8264. if (strncmp(sec_name, sec_def->sec, len) != 0)
  8265. return false;
  8266. /* exact match or has '/' separator */
  8267. if (sec_name[len] == '\0' || sec_name[len] == '/')
  8268. return true;
  8269. return false;
  8270. }
  8271. return strcmp(sec_name, sec_def->sec) == 0;
  8272. }
  8273. static const struct bpf_sec_def *find_sec_def(const char *sec_name)
  8274. {
  8275. const struct bpf_sec_def *sec_def;
  8276. int i, n;
  8277. n = custom_sec_def_cnt;
  8278. for (i = 0; i < n; i++) {
  8279. sec_def = &custom_sec_defs[i];
  8280. if (sec_def_matches(sec_def, sec_name))
  8281. return sec_def;
  8282. }
  8283. n = ARRAY_SIZE(section_defs);
  8284. for (i = 0; i < n; i++) {
  8285. sec_def = &section_defs[i];
  8286. if (sec_def_matches(sec_def, sec_name))
  8287. return sec_def;
  8288. }
  8289. if (has_custom_fallback_def)
  8290. return &custom_fallback_def;
  8291. return NULL;
  8292. }
  8293. #define MAX_TYPE_NAME_SIZE 32
  8294. static char *libbpf_get_type_names(bool attach_type)
  8295. {
  8296. int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
  8297. char *buf;
  8298. buf = malloc(len);
  8299. if (!buf)
  8300. return NULL;
  8301. buf[0] = '\0';
  8302. /* Forge string buf with all available names */
  8303. for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
  8304. const struct bpf_sec_def *sec_def = &section_defs[i];
  8305. if (attach_type) {
  8306. if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
  8307. continue;
  8308. if (!(sec_def->cookie & SEC_ATTACHABLE))
  8309. continue;
  8310. }
  8311. if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
  8312. free(buf);
  8313. return NULL;
  8314. }
  8315. strcat(buf, " ");
  8316. strcat(buf, section_defs[i].sec);
  8317. }
  8318. return buf;
  8319. }
  8320. int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
  8321. enum bpf_attach_type *expected_attach_type)
  8322. {
  8323. const struct bpf_sec_def *sec_def;
  8324. char *type_names;
  8325. if (!name)
  8326. return libbpf_err(-EINVAL);
  8327. sec_def = find_sec_def(name);
  8328. if (sec_def) {
  8329. *prog_type = sec_def->prog_type;
  8330. *expected_attach_type = sec_def->expected_attach_type;
  8331. return 0;
  8332. }
  8333. pr_debug("failed to guess program type from ELF section '%s'\n", name);
  8334. type_names = libbpf_get_type_names(false);
  8335. if (type_names != NULL) {
  8336. pr_debug("supported section(type) names are:%s\n", type_names);
  8337. free(type_names);
  8338. }
  8339. return libbpf_err(-ESRCH);
  8340. }
  8341. const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
  8342. {
  8343. if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
  8344. return NULL;
  8345. return attach_type_name[t];
  8346. }
  8347. const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
  8348. {
  8349. if (t < 0 || t >= ARRAY_SIZE(link_type_name))
  8350. return NULL;
  8351. return link_type_name[t];
  8352. }
  8353. const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
  8354. {
  8355. if (t < 0 || t >= ARRAY_SIZE(map_type_name))
  8356. return NULL;
  8357. return map_type_name[t];
  8358. }
  8359. const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
  8360. {
  8361. if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
  8362. return NULL;
  8363. return prog_type_name[t];
  8364. }
  8365. static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
  8366. int sec_idx,
  8367. size_t offset)
  8368. {
  8369. struct bpf_map *map;
  8370. size_t i;
  8371. for (i = 0; i < obj->nr_maps; i++) {
  8372. map = &obj->maps[i];
  8373. if (!bpf_map__is_struct_ops(map))
  8374. continue;
  8375. if (map->sec_idx == sec_idx &&
  8376. map->sec_offset <= offset &&
  8377. offset - map->sec_offset < map->def.value_size)
  8378. return map;
  8379. }
  8380. return NULL;
  8381. }
  8382. /* Collect the reloc from ELF, populate the st_ops->progs[], and update
  8383. * st_ops->data for shadow type.
  8384. */
  8385. static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
  8386. Elf64_Shdr *shdr, Elf_Data *data)
  8387. {
  8388. const struct btf_type *type;
  8389. const struct btf_member *member;
  8390. struct bpf_struct_ops *st_ops;
  8391. struct bpf_program *prog;
  8392. unsigned int shdr_idx;
  8393. const struct btf *btf;
  8394. struct bpf_map *map;
  8395. unsigned int moff, insn_idx;
  8396. const char *name;
  8397. __u32 member_idx;
  8398. Elf64_Sym *sym;
  8399. Elf64_Rel *rel;
  8400. int i, nrels;
  8401. btf = obj->btf;
  8402. nrels = shdr->sh_size / shdr->sh_entsize;
  8403. for (i = 0; i < nrels; i++) {
  8404. rel = elf_rel_by_idx(data, i);
  8405. if (!rel) {
  8406. pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
  8407. return -LIBBPF_ERRNO__FORMAT;
  8408. }
  8409. sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
  8410. if (!sym) {
  8411. pr_warn("struct_ops reloc: symbol %zx not found\n",
  8412. (size_t)ELF64_R_SYM(rel->r_info));
  8413. return -LIBBPF_ERRNO__FORMAT;
  8414. }
  8415. name = elf_sym_str(obj, sym->st_name) ?: "<?>";
  8416. map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
  8417. if (!map) {
  8418. pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
  8419. (size_t)rel->r_offset);
  8420. return -EINVAL;
  8421. }
  8422. moff = rel->r_offset - map->sec_offset;
  8423. shdr_idx = sym->st_shndx;
  8424. st_ops = map->st_ops;
  8425. 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",
  8426. map->name,
  8427. (long long)(rel->r_info >> 32),
  8428. (long long)sym->st_value,
  8429. shdr_idx, (size_t)rel->r_offset,
  8430. map->sec_offset, sym->st_name, name);
  8431. if (shdr_idx >= SHN_LORESERVE) {
  8432. pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
  8433. map->name, (size_t)rel->r_offset, shdr_idx);
  8434. return -LIBBPF_ERRNO__RELOC;
  8435. }
  8436. if (sym->st_value % BPF_INSN_SZ) {
  8437. pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
  8438. map->name, (unsigned long long)sym->st_value);
  8439. return -LIBBPF_ERRNO__FORMAT;
  8440. }
  8441. insn_idx = sym->st_value / BPF_INSN_SZ;
  8442. type = btf__type_by_id(btf, st_ops->type_id);
  8443. member = find_member_by_offset(type, moff * 8);
  8444. if (!member) {
  8445. pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
  8446. map->name, moff);
  8447. return -EINVAL;
  8448. }
  8449. member_idx = member - btf_members(type);
  8450. name = btf__name_by_offset(btf, member->name_off);
  8451. if (!resolve_func_ptr(btf, member->type, NULL)) {
  8452. pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
  8453. map->name, name);
  8454. return -EINVAL;
  8455. }
  8456. prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
  8457. if (!prog) {
  8458. pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
  8459. map->name, shdr_idx, name);
  8460. return -EINVAL;
  8461. }
  8462. /* prevent the use of BPF prog with invalid type */
  8463. if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
  8464. pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
  8465. map->name, prog->name);
  8466. return -EINVAL;
  8467. }
  8468. st_ops->progs[member_idx] = prog;
  8469. /* st_ops->data will be exposed to users, being returned by
  8470. * bpf_map__initial_value() as a pointer to the shadow
  8471. * type. All function pointers in the original struct type
  8472. * should be converted to a pointer to struct bpf_program
  8473. * in the shadow type.
  8474. */
  8475. *((struct bpf_program **)(st_ops->data + moff)) = prog;
  8476. }
  8477. return 0;
  8478. }
  8479. #define BTF_TRACE_PREFIX "btf_trace_"
  8480. #define BTF_LSM_PREFIX "bpf_lsm_"
  8481. #define BTF_ITER_PREFIX "bpf_iter_"
  8482. #define BTF_MAX_NAME_SIZE 128
  8483. void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
  8484. const char **prefix, int *kind)
  8485. {
  8486. switch (attach_type) {
  8487. case BPF_TRACE_RAW_TP:
  8488. *prefix = BTF_TRACE_PREFIX;
  8489. *kind = BTF_KIND_TYPEDEF;
  8490. break;
  8491. case BPF_LSM_MAC:
  8492. case BPF_LSM_CGROUP:
  8493. *prefix = BTF_LSM_PREFIX;
  8494. *kind = BTF_KIND_FUNC;
  8495. break;
  8496. case BPF_TRACE_ITER:
  8497. *prefix = BTF_ITER_PREFIX;
  8498. *kind = BTF_KIND_FUNC;
  8499. break;
  8500. default:
  8501. *prefix = "";
  8502. *kind = BTF_KIND_FUNC;
  8503. }
  8504. }
  8505. static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
  8506. const char *name, __u32 kind)
  8507. {
  8508. char btf_type_name[BTF_MAX_NAME_SIZE];
  8509. int ret;
  8510. ret = snprintf(btf_type_name, sizeof(btf_type_name),
  8511. "%s%s", prefix, name);
  8512. /* snprintf returns the number of characters written excluding the
  8513. * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
  8514. * indicates truncation.
  8515. */
  8516. if (ret < 0 || ret >= sizeof(btf_type_name))
  8517. return -ENAMETOOLONG;
  8518. return btf__find_by_name_kind(btf, btf_type_name, kind);
  8519. }
  8520. static inline int find_attach_btf_id(struct btf *btf, const char *name,
  8521. enum bpf_attach_type attach_type)
  8522. {
  8523. const char *prefix;
  8524. int kind;
  8525. btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
  8526. return find_btf_by_prefix_kind(btf, prefix, name, kind);
  8527. }
  8528. int libbpf_find_vmlinux_btf_id(const char *name,
  8529. enum bpf_attach_type attach_type)
  8530. {
  8531. struct btf *btf;
  8532. int err;
  8533. btf = btf__load_vmlinux_btf();
  8534. err = libbpf_get_error(btf);
  8535. if (err) {
  8536. pr_warn("vmlinux BTF is not found\n");
  8537. return libbpf_err(err);
  8538. }
  8539. err = find_attach_btf_id(btf, name, attach_type);
  8540. if (err <= 0)
  8541. pr_warn("%s is not found in vmlinux BTF\n", name);
  8542. btf__free(btf);
  8543. return libbpf_err(err);
  8544. }
  8545. static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
  8546. {
  8547. struct bpf_prog_info info;
  8548. __u32 info_len = sizeof(info);
  8549. struct btf *btf;
  8550. int err;
  8551. memset(&info, 0, info_len);
  8552. err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
  8553. if (err) {
  8554. pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
  8555. attach_prog_fd, err);
  8556. return err;
  8557. }
  8558. err = -EINVAL;
  8559. if (!info.btf_id) {
  8560. pr_warn("The target program doesn't have BTF\n");
  8561. goto out;
  8562. }
  8563. btf = btf__load_from_kernel_by_id(info.btf_id);
  8564. err = libbpf_get_error(btf);
  8565. if (err) {
  8566. pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
  8567. goto out;
  8568. }
  8569. err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
  8570. btf__free(btf);
  8571. if (err <= 0) {
  8572. pr_warn("%s is not found in prog's BTF\n", name);
  8573. goto out;
  8574. }
  8575. out:
  8576. return err;
  8577. }
  8578. static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
  8579. enum bpf_attach_type attach_type,
  8580. int *btf_obj_fd, int *btf_type_id)
  8581. {
  8582. int ret, i, mod_len;
  8583. const char *fn_name, *mod_name = NULL;
  8584. fn_name = strchr(attach_name, ':');
  8585. if (fn_name) {
  8586. mod_name = attach_name;
  8587. mod_len = fn_name - mod_name;
  8588. fn_name++;
  8589. }
  8590. if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
  8591. ret = find_attach_btf_id(obj->btf_vmlinux,
  8592. mod_name ? fn_name : attach_name,
  8593. attach_type);
  8594. if (ret > 0) {
  8595. *btf_obj_fd = 0; /* vmlinux BTF */
  8596. *btf_type_id = ret;
  8597. return 0;
  8598. }
  8599. if (ret != -ENOENT)
  8600. return ret;
  8601. }
  8602. ret = load_module_btfs(obj);
  8603. if (ret)
  8604. return ret;
  8605. for (i = 0; i < obj->btf_module_cnt; i++) {
  8606. const struct module_btf *mod = &obj->btf_modules[i];
  8607. if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
  8608. continue;
  8609. ret = find_attach_btf_id(mod->btf,
  8610. mod_name ? fn_name : attach_name,
  8611. attach_type);
  8612. if (ret > 0) {
  8613. *btf_obj_fd = mod->fd;
  8614. *btf_type_id = ret;
  8615. return 0;
  8616. }
  8617. if (ret == -ENOENT)
  8618. continue;
  8619. return ret;
  8620. }
  8621. return -ESRCH;
  8622. }
  8623. static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
  8624. int *btf_obj_fd, int *btf_type_id)
  8625. {
  8626. enum bpf_attach_type attach_type = prog->expected_attach_type;
  8627. __u32 attach_prog_fd = prog->attach_prog_fd;
  8628. int err = 0;
  8629. /* BPF program's BTF ID */
  8630. if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
  8631. if (!attach_prog_fd) {
  8632. pr_warn("prog '%s': attach program FD is not set\n", prog->name);
  8633. return -EINVAL;
  8634. }
  8635. err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
  8636. if (err < 0) {
  8637. pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
  8638. prog->name, attach_prog_fd, attach_name, err);
  8639. return err;
  8640. }
  8641. *btf_obj_fd = 0;
  8642. *btf_type_id = err;
  8643. return 0;
  8644. }
  8645. /* kernel/module BTF ID */
  8646. if (prog->obj->gen_loader) {
  8647. bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
  8648. *btf_obj_fd = 0;
  8649. *btf_type_id = 1;
  8650. } else {
  8651. err = find_kernel_btf_id(prog->obj, attach_name,
  8652. attach_type, btf_obj_fd,
  8653. btf_type_id);
  8654. }
  8655. if (err) {
  8656. pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
  8657. prog->name, attach_name, err);
  8658. return err;
  8659. }
  8660. return 0;
  8661. }
  8662. int libbpf_attach_type_by_name(const char *name,
  8663. enum bpf_attach_type *attach_type)
  8664. {
  8665. char *type_names;
  8666. const struct bpf_sec_def *sec_def;
  8667. if (!name)
  8668. return libbpf_err(-EINVAL);
  8669. sec_def = find_sec_def(name);
  8670. if (!sec_def) {
  8671. pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
  8672. type_names = libbpf_get_type_names(true);
  8673. if (type_names != NULL) {
  8674. pr_debug("attachable section(type) names are:%s\n", type_names);
  8675. free(type_names);
  8676. }
  8677. return libbpf_err(-EINVAL);
  8678. }
  8679. if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
  8680. return libbpf_err(-EINVAL);
  8681. if (!(sec_def->cookie & SEC_ATTACHABLE))
  8682. return libbpf_err(-EINVAL);
  8683. *attach_type = sec_def->expected_attach_type;
  8684. return 0;
  8685. }
  8686. int bpf_map__fd(const struct bpf_map *map)
  8687. {
  8688. if (!map)
  8689. return libbpf_err(-EINVAL);
  8690. if (!map_is_created(map))
  8691. return -1;
  8692. return map->fd;
  8693. }
  8694. static bool map_uses_real_name(const struct bpf_map *map)
  8695. {
  8696. /* Since libbpf started to support custom .data.* and .rodata.* maps,
  8697. * their user-visible name differs from kernel-visible name. Users see
  8698. * such map's corresponding ELF section name as a map name.
  8699. * This check distinguishes .data/.rodata from .data.* and .rodata.*
  8700. * maps to know which name has to be returned to the user.
  8701. */
  8702. if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
  8703. return true;
  8704. if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
  8705. return true;
  8706. return false;
  8707. }
  8708. const char *bpf_map__name(const struct bpf_map *map)
  8709. {
  8710. if (!map)
  8711. return NULL;
  8712. if (map_uses_real_name(map))
  8713. return map->real_name;
  8714. return map->name;
  8715. }
  8716. enum bpf_map_type bpf_map__type(const struct bpf_map *map)
  8717. {
  8718. return map->def.type;
  8719. }
  8720. int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
  8721. {
  8722. if (map_is_created(map))
  8723. return libbpf_err(-EBUSY);
  8724. map->def.type = type;
  8725. return 0;
  8726. }
  8727. __u32 bpf_map__map_flags(const struct bpf_map *map)
  8728. {
  8729. return map->def.map_flags;
  8730. }
  8731. int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
  8732. {
  8733. if (map_is_created(map))
  8734. return libbpf_err(-EBUSY);
  8735. map->def.map_flags = flags;
  8736. return 0;
  8737. }
  8738. __u64 bpf_map__map_extra(const struct bpf_map *map)
  8739. {
  8740. return map->map_extra;
  8741. }
  8742. int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
  8743. {
  8744. if (map_is_created(map))
  8745. return libbpf_err(-EBUSY);
  8746. map->map_extra = map_extra;
  8747. return 0;
  8748. }
  8749. __u32 bpf_map__numa_node(const struct bpf_map *map)
  8750. {
  8751. return map->numa_node;
  8752. }
  8753. int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
  8754. {
  8755. if (map_is_created(map))
  8756. return libbpf_err(-EBUSY);
  8757. map->numa_node = numa_node;
  8758. return 0;
  8759. }
  8760. __u32 bpf_map__key_size(const struct bpf_map *map)
  8761. {
  8762. return map->def.key_size;
  8763. }
  8764. int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
  8765. {
  8766. if (map_is_created(map))
  8767. return libbpf_err(-EBUSY);
  8768. map->def.key_size = size;
  8769. return 0;
  8770. }
  8771. __u32 bpf_map__value_size(const struct bpf_map *map)
  8772. {
  8773. return map->def.value_size;
  8774. }
  8775. static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
  8776. {
  8777. struct btf *btf;
  8778. struct btf_type *datasec_type, *var_type;
  8779. struct btf_var_secinfo *var;
  8780. const struct btf_type *array_type;
  8781. const struct btf_array *array;
  8782. int vlen, element_sz, new_array_id;
  8783. __u32 nr_elements;
  8784. /* check btf existence */
  8785. btf = bpf_object__btf(map->obj);
  8786. if (!btf)
  8787. return -ENOENT;
  8788. /* verify map is datasec */
  8789. datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
  8790. if (!btf_is_datasec(datasec_type)) {
  8791. pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
  8792. bpf_map__name(map));
  8793. return -EINVAL;
  8794. }
  8795. /* verify datasec has at least one var */
  8796. vlen = btf_vlen(datasec_type);
  8797. if (vlen == 0) {
  8798. pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
  8799. bpf_map__name(map));
  8800. return -EINVAL;
  8801. }
  8802. /* verify last var in the datasec is an array */
  8803. var = &btf_var_secinfos(datasec_type)[vlen - 1];
  8804. var_type = btf_type_by_id(btf, var->type);
  8805. array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
  8806. if (!btf_is_array(array_type)) {
  8807. pr_warn("map '%s': cannot be resized, last var must be an array\n",
  8808. bpf_map__name(map));
  8809. return -EINVAL;
  8810. }
  8811. /* verify request size aligns with array */
  8812. array = btf_array(array_type);
  8813. element_sz = btf__resolve_size(btf, array->type);
  8814. if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
  8815. pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
  8816. bpf_map__name(map), element_sz, size);
  8817. return -EINVAL;
  8818. }
  8819. /* create a new array based on the existing array, but with new length */
  8820. nr_elements = (size - var->offset) / element_sz;
  8821. new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
  8822. if (new_array_id < 0)
  8823. return new_array_id;
  8824. /* adding a new btf type invalidates existing pointers to btf objects,
  8825. * so refresh pointers before proceeding
  8826. */
  8827. datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
  8828. var = &btf_var_secinfos(datasec_type)[vlen - 1];
  8829. var_type = btf_type_by_id(btf, var->type);
  8830. /* finally update btf info */
  8831. datasec_type->size = size;
  8832. var->size = size - var->offset;
  8833. var_type->type = new_array_id;
  8834. return 0;
  8835. }
  8836. int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
  8837. {
  8838. if (map->obj->loaded || map->reused)
  8839. return libbpf_err(-EBUSY);
  8840. if (map->mmaped) {
  8841. size_t mmap_old_sz, mmap_new_sz;
  8842. int err;
  8843. if (map->def.type != BPF_MAP_TYPE_ARRAY)
  8844. return -EOPNOTSUPP;
  8845. mmap_old_sz = bpf_map_mmap_sz(map);
  8846. mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
  8847. err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
  8848. if (err) {
  8849. pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
  8850. bpf_map__name(map), err);
  8851. return err;
  8852. }
  8853. err = map_btf_datasec_resize(map, size);
  8854. if (err && err != -ENOENT) {
  8855. pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
  8856. bpf_map__name(map), err);
  8857. map->btf_value_type_id = 0;
  8858. map->btf_key_type_id = 0;
  8859. }
  8860. }
  8861. map->def.value_size = size;
  8862. return 0;
  8863. }
  8864. __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
  8865. {
  8866. return map ? map->btf_key_type_id : 0;
  8867. }
  8868. __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
  8869. {
  8870. return map ? map->btf_value_type_id : 0;
  8871. }
  8872. int bpf_map__set_initial_value(struct bpf_map *map,
  8873. const void *data, size_t size)
  8874. {
  8875. size_t actual_sz;
  8876. if (map->obj->loaded || map->reused)
  8877. return libbpf_err(-EBUSY);
  8878. if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
  8879. return libbpf_err(-EINVAL);
  8880. if (map->def.type == BPF_MAP_TYPE_ARENA)
  8881. actual_sz = map->obj->arena_data_sz;
  8882. else
  8883. actual_sz = map->def.value_size;
  8884. if (size != actual_sz)
  8885. return libbpf_err(-EINVAL);
  8886. memcpy(map->mmaped, data, size);
  8887. return 0;
  8888. }
  8889. void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
  8890. {
  8891. if (bpf_map__is_struct_ops(map)) {
  8892. if (psize)
  8893. *psize = map->def.value_size;
  8894. return map->st_ops->data;
  8895. }
  8896. if (!map->mmaped)
  8897. return NULL;
  8898. if (map->def.type == BPF_MAP_TYPE_ARENA)
  8899. *psize = map->obj->arena_data_sz;
  8900. else
  8901. *psize = map->def.value_size;
  8902. return map->mmaped;
  8903. }
  8904. bool bpf_map__is_internal(const struct bpf_map *map)
  8905. {
  8906. return map->libbpf_type != LIBBPF_MAP_UNSPEC;
  8907. }
  8908. __u32 bpf_map__ifindex(const struct bpf_map *map)
  8909. {
  8910. return map->map_ifindex;
  8911. }
  8912. int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
  8913. {
  8914. if (map_is_created(map))
  8915. return libbpf_err(-EBUSY);
  8916. map->map_ifindex = ifindex;
  8917. return 0;
  8918. }
  8919. int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
  8920. {
  8921. if (!bpf_map_type__is_map_in_map(map->def.type)) {
  8922. pr_warn("error: unsupported map type\n");
  8923. return libbpf_err(-EINVAL);
  8924. }
  8925. if (map->inner_map_fd != -1) {
  8926. pr_warn("error: inner_map_fd already specified\n");
  8927. return libbpf_err(-EINVAL);
  8928. }
  8929. if (map->inner_map) {
  8930. bpf_map__destroy(map->inner_map);
  8931. zfree(&map->inner_map);
  8932. }
  8933. map->inner_map_fd = fd;
  8934. return 0;
  8935. }
  8936. static struct bpf_map *
  8937. __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
  8938. {
  8939. ssize_t idx;
  8940. struct bpf_map *s, *e;
  8941. if (!obj || !obj->maps)
  8942. return errno = EINVAL, NULL;
  8943. s = obj->maps;
  8944. e = obj->maps + obj->nr_maps;
  8945. if ((m < s) || (m >= e)) {
  8946. pr_warn("error in %s: map handler doesn't belong to object\n",
  8947. __func__);
  8948. return errno = EINVAL, NULL;
  8949. }
  8950. idx = (m - obj->maps) + i;
  8951. if (idx >= obj->nr_maps || idx < 0)
  8952. return NULL;
  8953. return &obj->maps[idx];
  8954. }
  8955. struct bpf_map *
  8956. bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
  8957. {
  8958. if (prev == NULL && obj != NULL)
  8959. return obj->maps;
  8960. return __bpf_map__iter(prev, obj, 1);
  8961. }
  8962. struct bpf_map *
  8963. bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
  8964. {
  8965. if (next == NULL && obj != NULL) {
  8966. if (!obj->nr_maps)
  8967. return NULL;
  8968. return obj->maps + obj->nr_maps - 1;
  8969. }
  8970. return __bpf_map__iter(next, obj, -1);
  8971. }
  8972. struct bpf_map *
  8973. bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
  8974. {
  8975. struct bpf_map *pos;
  8976. bpf_object__for_each_map(pos, obj) {
  8977. /* if it's a special internal map name (which always starts
  8978. * with dot) then check if that special name matches the
  8979. * real map name (ELF section name)
  8980. */
  8981. if (name[0] == '.') {
  8982. if (pos->real_name && strcmp(pos->real_name, name) == 0)
  8983. return pos;
  8984. continue;
  8985. }
  8986. /* otherwise map name has to be an exact match */
  8987. if (map_uses_real_name(pos)) {
  8988. if (strcmp(pos->real_name, name) == 0)
  8989. return pos;
  8990. continue;
  8991. }
  8992. if (strcmp(pos->name, name) == 0)
  8993. return pos;
  8994. }
  8995. return errno = ENOENT, NULL;
  8996. }
  8997. int
  8998. bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
  8999. {
  9000. return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
  9001. }
  9002. static int validate_map_op(const struct bpf_map *map, size_t key_sz,
  9003. size_t value_sz, bool check_value_sz)
  9004. {
  9005. if (!map_is_created(map)) /* map is not yet created */
  9006. return -ENOENT;
  9007. if (map->def.key_size != key_sz) {
  9008. pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
  9009. map->name, key_sz, map->def.key_size);
  9010. return -EINVAL;
  9011. }
  9012. if (map->fd < 0) {
  9013. pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
  9014. return -EINVAL;
  9015. }
  9016. if (!check_value_sz)
  9017. return 0;
  9018. switch (map->def.type) {
  9019. case BPF_MAP_TYPE_PERCPU_ARRAY:
  9020. case BPF_MAP_TYPE_PERCPU_HASH:
  9021. case BPF_MAP_TYPE_LRU_PERCPU_HASH:
  9022. case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
  9023. int num_cpu = libbpf_num_possible_cpus();
  9024. size_t elem_sz = roundup(map->def.value_size, 8);
  9025. if (value_sz != num_cpu * elem_sz) {
  9026. pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
  9027. map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
  9028. return -EINVAL;
  9029. }
  9030. break;
  9031. }
  9032. default:
  9033. if (map->def.value_size != value_sz) {
  9034. pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
  9035. map->name, value_sz, map->def.value_size);
  9036. return -EINVAL;
  9037. }
  9038. break;
  9039. }
  9040. return 0;
  9041. }
  9042. int bpf_map__lookup_elem(const struct bpf_map *map,
  9043. const void *key, size_t key_sz,
  9044. void *value, size_t value_sz, __u64 flags)
  9045. {
  9046. int err;
  9047. err = validate_map_op(map, key_sz, value_sz, true);
  9048. if (err)
  9049. return libbpf_err(err);
  9050. return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
  9051. }
  9052. int bpf_map__update_elem(const struct bpf_map *map,
  9053. const void *key, size_t key_sz,
  9054. const void *value, size_t value_sz, __u64 flags)
  9055. {
  9056. int err;
  9057. err = validate_map_op(map, key_sz, value_sz, true);
  9058. if (err)
  9059. return libbpf_err(err);
  9060. return bpf_map_update_elem(map->fd, key, value, flags);
  9061. }
  9062. int bpf_map__delete_elem(const struct bpf_map *map,
  9063. const void *key, size_t key_sz, __u64 flags)
  9064. {
  9065. int err;
  9066. err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
  9067. if (err)
  9068. return libbpf_err(err);
  9069. return bpf_map_delete_elem_flags(map->fd, key, flags);
  9070. }
  9071. int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
  9072. const void *key, size_t key_sz,
  9073. void *value, size_t value_sz, __u64 flags)
  9074. {
  9075. int err;
  9076. err = validate_map_op(map, key_sz, value_sz, true);
  9077. if (err)
  9078. return libbpf_err(err);
  9079. return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
  9080. }
  9081. int bpf_map__get_next_key(const struct bpf_map *map,
  9082. const void *cur_key, void *next_key, size_t key_sz)
  9083. {
  9084. int err;
  9085. err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
  9086. if (err)
  9087. return libbpf_err(err);
  9088. return bpf_map_get_next_key(map->fd, cur_key, next_key);
  9089. }
  9090. long libbpf_get_error(const void *ptr)
  9091. {
  9092. if (!IS_ERR_OR_NULL(ptr))
  9093. return 0;
  9094. if (IS_ERR(ptr))
  9095. errno = -PTR_ERR(ptr);
  9096. /* If ptr == NULL, then errno should be already set by the failing
  9097. * API, because libbpf never returns NULL on success and it now always
  9098. * sets errno on error. So no extra errno handling for ptr == NULL
  9099. * case.
  9100. */
  9101. return -errno;
  9102. }
  9103. /* Replace link's underlying BPF program with the new one */
  9104. int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
  9105. {
  9106. int ret;
  9107. int prog_fd = bpf_program__fd(prog);
  9108. if (prog_fd < 0) {
  9109. pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
  9110. prog->name);
  9111. return libbpf_err(-EINVAL);
  9112. }
  9113. ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
  9114. return libbpf_err_errno(ret);
  9115. }
  9116. /* Release "ownership" of underlying BPF resource (typically, BPF program
  9117. * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
  9118. * link, when destructed through bpf_link__destroy() call won't attempt to
  9119. * detach/unregisted that BPF resource. This is useful in situations where,
  9120. * say, attached BPF program has to outlive userspace program that attached it
  9121. * in the system. Depending on type of BPF program, though, there might be
  9122. * additional steps (like pinning BPF program in BPF FS) necessary to ensure
  9123. * exit of userspace program doesn't trigger automatic detachment and clean up
  9124. * inside the kernel.
  9125. */
  9126. void bpf_link__disconnect(struct bpf_link *link)
  9127. {
  9128. link->disconnected = true;
  9129. }
  9130. int bpf_link__destroy(struct bpf_link *link)
  9131. {
  9132. int err = 0;
  9133. if (IS_ERR_OR_NULL(link))
  9134. return 0;
  9135. if (!link->disconnected && link->detach)
  9136. err = link->detach(link);
  9137. if (link->pin_path)
  9138. free(link->pin_path);
  9139. if (link->dealloc)
  9140. link->dealloc(link);
  9141. else
  9142. free(link);
  9143. return libbpf_err(err);
  9144. }
  9145. int bpf_link__fd(const struct bpf_link *link)
  9146. {
  9147. return link->fd;
  9148. }
  9149. const char *bpf_link__pin_path(const struct bpf_link *link)
  9150. {
  9151. return link->pin_path;
  9152. }
  9153. static int bpf_link__detach_fd(struct bpf_link *link)
  9154. {
  9155. return libbpf_err_errno(close(link->fd));
  9156. }
  9157. struct bpf_link *bpf_link__open(const char *path)
  9158. {
  9159. struct bpf_link *link;
  9160. int fd;
  9161. fd = bpf_obj_get(path);
  9162. if (fd < 0) {
  9163. fd = -errno;
  9164. pr_warn("failed to open link at %s: %d\n", path, fd);
  9165. return libbpf_err_ptr(fd);
  9166. }
  9167. link = calloc(1, sizeof(*link));
  9168. if (!link) {
  9169. close(fd);
  9170. return libbpf_err_ptr(-ENOMEM);
  9171. }
  9172. link->detach = &bpf_link__detach_fd;
  9173. link->fd = fd;
  9174. link->pin_path = strdup(path);
  9175. if (!link->pin_path) {
  9176. bpf_link__destroy(link);
  9177. return libbpf_err_ptr(-ENOMEM);
  9178. }
  9179. return link;
  9180. }
  9181. int bpf_link__detach(struct bpf_link *link)
  9182. {
  9183. return bpf_link_detach(link->fd) ? -errno : 0;
  9184. }
  9185. int bpf_link__pin(struct bpf_link *link, const char *path)
  9186. {
  9187. int err;
  9188. if (link->pin_path)
  9189. return libbpf_err(-EBUSY);
  9190. err = make_parent_dir(path);
  9191. if (err)
  9192. return libbpf_err(err);
  9193. err = check_path(path);
  9194. if (err)
  9195. return libbpf_err(err);
  9196. link->pin_path = strdup(path);
  9197. if (!link->pin_path)
  9198. return libbpf_err(-ENOMEM);
  9199. if (bpf_obj_pin(link->fd, link->pin_path)) {
  9200. err = -errno;
  9201. zfree(&link->pin_path);
  9202. return libbpf_err(err);
  9203. }
  9204. pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
  9205. return 0;
  9206. }
  9207. int bpf_link__unpin(struct bpf_link *link)
  9208. {
  9209. int err;
  9210. if (!link->pin_path)
  9211. return libbpf_err(-EINVAL);
  9212. err = unlink(link->pin_path);
  9213. if (err != 0)
  9214. return -errno;
  9215. pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
  9216. zfree(&link->pin_path);
  9217. return 0;
  9218. }
  9219. struct bpf_link_perf {
  9220. struct bpf_link link;
  9221. int perf_event_fd;
  9222. /* legacy kprobe support: keep track of probe identifier and type */
  9223. char *legacy_probe_name;
  9224. bool legacy_is_kprobe;
  9225. bool legacy_is_retprobe;
  9226. };
  9227. static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
  9228. static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
  9229. static int bpf_link_perf_detach(struct bpf_link *link)
  9230. {
  9231. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  9232. int err = 0;
  9233. if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
  9234. err = -errno;
  9235. if (perf_link->perf_event_fd != link->fd)
  9236. close(perf_link->perf_event_fd);
  9237. close(link->fd);
  9238. /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
  9239. if (perf_link->legacy_probe_name) {
  9240. if (perf_link->legacy_is_kprobe) {
  9241. err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
  9242. perf_link->legacy_is_retprobe);
  9243. } else {
  9244. err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
  9245. perf_link->legacy_is_retprobe);
  9246. }
  9247. }
  9248. return err;
  9249. }
  9250. static void bpf_link_perf_dealloc(struct bpf_link *link)
  9251. {
  9252. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  9253. free(perf_link->legacy_probe_name);
  9254. free(perf_link);
  9255. }
  9256. struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
  9257. const struct bpf_perf_event_opts *opts)
  9258. {
  9259. char errmsg[STRERR_BUFSIZE];
  9260. struct bpf_link_perf *link;
  9261. int prog_fd, link_fd = -1, err;
  9262. bool force_ioctl_attach;
  9263. if (!OPTS_VALID(opts, bpf_perf_event_opts))
  9264. return libbpf_err_ptr(-EINVAL);
  9265. if (pfd < 0) {
  9266. pr_warn("prog '%s': invalid perf event FD %d\n",
  9267. prog->name, pfd);
  9268. return libbpf_err_ptr(-EINVAL);
  9269. }
  9270. prog_fd = bpf_program__fd(prog);
  9271. if (prog_fd < 0) {
  9272. pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
  9273. prog->name);
  9274. return libbpf_err_ptr(-EINVAL);
  9275. }
  9276. link = calloc(1, sizeof(*link));
  9277. if (!link)
  9278. return libbpf_err_ptr(-ENOMEM);
  9279. link->link.detach = &bpf_link_perf_detach;
  9280. link->link.dealloc = &bpf_link_perf_dealloc;
  9281. link->perf_event_fd = pfd;
  9282. force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
  9283. if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
  9284. DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
  9285. .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
  9286. link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
  9287. if (link_fd < 0) {
  9288. err = -errno;
  9289. pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
  9290. prog->name, pfd,
  9291. err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9292. goto err_out;
  9293. }
  9294. link->link.fd = link_fd;
  9295. } else {
  9296. if (OPTS_GET(opts, bpf_cookie, 0)) {
  9297. pr_warn("prog '%s': user context value is not supported\n", prog->name);
  9298. err = -EOPNOTSUPP;
  9299. goto err_out;
  9300. }
  9301. if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
  9302. err = -errno;
  9303. pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
  9304. prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9305. if (err == -EPROTO)
  9306. pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
  9307. prog->name, pfd);
  9308. goto err_out;
  9309. }
  9310. link->link.fd = pfd;
  9311. }
  9312. if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
  9313. err = -errno;
  9314. pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
  9315. prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9316. goto err_out;
  9317. }
  9318. return &link->link;
  9319. err_out:
  9320. if (link_fd >= 0)
  9321. close(link_fd);
  9322. free(link);
  9323. return libbpf_err_ptr(err);
  9324. }
  9325. struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
  9326. {
  9327. return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
  9328. }
  9329. /*
  9330. * this function is expected to parse integer in the range of [0, 2^31-1] from
  9331. * given file using scanf format string fmt. If actual parsed value is
  9332. * negative, the result might be indistinguishable from error
  9333. */
  9334. static int parse_uint_from_file(const char *file, const char *fmt)
  9335. {
  9336. char buf[STRERR_BUFSIZE];
  9337. int err, ret;
  9338. FILE *f;
  9339. f = fopen(file, "re");
  9340. if (!f) {
  9341. err = -errno;
  9342. pr_debug("failed to open '%s': %s\n", file,
  9343. libbpf_strerror_r(err, buf, sizeof(buf)));
  9344. return err;
  9345. }
  9346. err = fscanf(f, fmt, &ret);
  9347. if (err != 1) {
  9348. err = err == EOF ? -EIO : -errno;
  9349. pr_debug("failed to parse '%s': %s\n", file,
  9350. libbpf_strerror_r(err, buf, sizeof(buf)));
  9351. fclose(f);
  9352. return err;
  9353. }
  9354. fclose(f);
  9355. return ret;
  9356. }
  9357. static int determine_kprobe_perf_type(void)
  9358. {
  9359. const char *file = "/sys/bus/event_source/devices/kprobe/type";
  9360. return parse_uint_from_file(file, "%d\n");
  9361. }
  9362. static int determine_uprobe_perf_type(void)
  9363. {
  9364. const char *file = "/sys/bus/event_source/devices/uprobe/type";
  9365. return parse_uint_from_file(file, "%d\n");
  9366. }
  9367. static int determine_kprobe_retprobe_bit(void)
  9368. {
  9369. const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
  9370. return parse_uint_from_file(file, "config:%d\n");
  9371. }
  9372. static int determine_uprobe_retprobe_bit(void)
  9373. {
  9374. const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
  9375. return parse_uint_from_file(file, "config:%d\n");
  9376. }
  9377. #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
  9378. #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
  9379. static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
  9380. uint64_t offset, int pid, size_t ref_ctr_off)
  9381. {
  9382. const size_t attr_sz = sizeof(struct perf_event_attr);
  9383. struct perf_event_attr attr;
  9384. char errmsg[STRERR_BUFSIZE];
  9385. int type, pfd;
  9386. if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
  9387. return -EINVAL;
  9388. memset(&attr, 0, attr_sz);
  9389. type = uprobe ? determine_uprobe_perf_type()
  9390. : determine_kprobe_perf_type();
  9391. if (type < 0) {
  9392. pr_warn("failed to determine %s perf type: %s\n",
  9393. uprobe ? "uprobe" : "kprobe",
  9394. libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
  9395. return type;
  9396. }
  9397. if (retprobe) {
  9398. int bit = uprobe ? determine_uprobe_retprobe_bit()
  9399. : determine_kprobe_retprobe_bit();
  9400. if (bit < 0) {
  9401. pr_warn("failed to determine %s retprobe bit: %s\n",
  9402. uprobe ? "uprobe" : "kprobe",
  9403. libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
  9404. return bit;
  9405. }
  9406. attr.config |= 1 << bit;
  9407. }
  9408. attr.size = attr_sz;
  9409. attr.type = type;
  9410. attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
  9411. attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
  9412. attr.config2 = offset; /* kprobe_addr or probe_offset */
  9413. /* pid filter is meaningful only for uprobes */
  9414. pfd = syscall(__NR_perf_event_open, &attr,
  9415. pid < 0 ? -1 : pid /* pid */,
  9416. pid == -1 ? 0 : -1 /* cpu */,
  9417. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  9418. return pfd >= 0 ? pfd : -errno;
  9419. }
  9420. static int append_to_file(const char *file, const char *fmt, ...)
  9421. {
  9422. int fd, n, err = 0;
  9423. va_list ap;
  9424. char buf[1024];
  9425. va_start(ap, fmt);
  9426. n = vsnprintf(buf, sizeof(buf), fmt, ap);
  9427. va_end(ap);
  9428. if (n < 0 || n >= sizeof(buf))
  9429. return -EINVAL;
  9430. fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
  9431. if (fd < 0)
  9432. return -errno;
  9433. if (write(fd, buf, n) < 0)
  9434. err = -errno;
  9435. close(fd);
  9436. return err;
  9437. }
  9438. #define DEBUGFS "/sys/kernel/debug/tracing"
  9439. #define TRACEFS "/sys/kernel/tracing"
  9440. static bool use_debugfs(void)
  9441. {
  9442. static int has_debugfs = -1;
  9443. if (has_debugfs < 0)
  9444. has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
  9445. return has_debugfs == 1;
  9446. }
  9447. static const char *tracefs_path(void)
  9448. {
  9449. return use_debugfs() ? DEBUGFS : TRACEFS;
  9450. }
  9451. static const char *tracefs_kprobe_events(void)
  9452. {
  9453. return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
  9454. }
  9455. static const char *tracefs_uprobe_events(void)
  9456. {
  9457. return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
  9458. }
  9459. static const char *tracefs_available_filter_functions(void)
  9460. {
  9461. return use_debugfs() ? DEBUGFS"/available_filter_functions"
  9462. : TRACEFS"/available_filter_functions";
  9463. }
  9464. static const char *tracefs_available_filter_functions_addrs(void)
  9465. {
  9466. return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
  9467. : TRACEFS"/available_filter_functions_addrs";
  9468. }
  9469. static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
  9470. const char *name, size_t offset)
  9471. {
  9472. static int index = 0;
  9473. int i;
  9474. snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
  9475. __sync_fetch_and_add(&index, 1), name, offset);
  9476. /* sanitize name in the probe name */
  9477. for (i = 0; buf[i]; i++) {
  9478. if (!isalnum(buf[i]))
  9479. buf[i] = '_';
  9480. }
  9481. }
  9482. static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
  9483. const char *kfunc_name, size_t offset)
  9484. {
  9485. return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
  9486. retprobe ? 'r' : 'p',
  9487. retprobe ? "kretprobes" : "kprobes",
  9488. probe_name, kfunc_name, offset);
  9489. }
  9490. static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
  9491. {
  9492. return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
  9493. retprobe ? "kretprobes" : "kprobes", probe_name);
  9494. }
  9495. static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
  9496. {
  9497. char file[256];
  9498. snprintf(file, sizeof(file), "%s/events/%s/%s/id",
  9499. tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
  9500. return parse_uint_from_file(file, "%d\n");
  9501. }
  9502. static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
  9503. const char *kfunc_name, size_t offset, int pid)
  9504. {
  9505. const size_t attr_sz = sizeof(struct perf_event_attr);
  9506. struct perf_event_attr attr;
  9507. char errmsg[STRERR_BUFSIZE];
  9508. int type, pfd, err;
  9509. err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
  9510. if (err < 0) {
  9511. pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
  9512. kfunc_name, offset,
  9513. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9514. return err;
  9515. }
  9516. type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
  9517. if (type < 0) {
  9518. err = type;
  9519. pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
  9520. kfunc_name, offset,
  9521. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9522. goto err_clean_legacy;
  9523. }
  9524. memset(&attr, 0, attr_sz);
  9525. attr.size = attr_sz;
  9526. attr.config = type;
  9527. attr.type = PERF_TYPE_TRACEPOINT;
  9528. pfd = syscall(__NR_perf_event_open, &attr,
  9529. pid < 0 ? -1 : pid, /* pid */
  9530. pid == -1 ? 0 : -1, /* cpu */
  9531. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  9532. if (pfd < 0) {
  9533. err = -errno;
  9534. pr_warn("legacy kprobe perf_event_open() failed: %s\n",
  9535. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9536. goto err_clean_legacy;
  9537. }
  9538. return pfd;
  9539. err_clean_legacy:
  9540. /* Clear the newly added legacy kprobe_event */
  9541. remove_kprobe_event_legacy(probe_name, retprobe);
  9542. return err;
  9543. }
  9544. static const char *arch_specific_syscall_pfx(void)
  9545. {
  9546. #if defined(__x86_64__)
  9547. return "x64";
  9548. #elif defined(__i386__)
  9549. return "ia32";
  9550. #elif defined(__s390x__)
  9551. return "s390x";
  9552. #elif defined(__s390__)
  9553. return "s390";
  9554. #elif defined(__arm__)
  9555. return "arm";
  9556. #elif defined(__aarch64__)
  9557. return "arm64";
  9558. #elif defined(__mips__)
  9559. return "mips";
  9560. #elif defined(__riscv)
  9561. return "riscv";
  9562. #elif defined(__powerpc__)
  9563. return "powerpc";
  9564. #elif defined(__powerpc64__)
  9565. return "powerpc64";
  9566. #else
  9567. return NULL;
  9568. #endif
  9569. }
  9570. int probe_kern_syscall_wrapper(int token_fd)
  9571. {
  9572. char syscall_name[64];
  9573. const char *ksys_pfx;
  9574. ksys_pfx = arch_specific_syscall_pfx();
  9575. if (!ksys_pfx)
  9576. return 0;
  9577. snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
  9578. if (determine_kprobe_perf_type() >= 0) {
  9579. int pfd;
  9580. pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
  9581. if (pfd >= 0)
  9582. close(pfd);
  9583. return pfd >= 0 ? 1 : 0;
  9584. } else { /* legacy mode */
  9585. char probe_name[MAX_EVENT_NAME_LEN];
  9586. gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
  9587. if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
  9588. return 0;
  9589. (void)remove_kprobe_event_legacy(probe_name, false);
  9590. return 1;
  9591. }
  9592. }
  9593. struct bpf_link *
  9594. bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
  9595. const char *func_name,
  9596. const struct bpf_kprobe_opts *opts)
  9597. {
  9598. DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
  9599. enum probe_attach_mode attach_mode;
  9600. char errmsg[STRERR_BUFSIZE];
  9601. char *legacy_probe = NULL;
  9602. struct bpf_link *link;
  9603. size_t offset;
  9604. bool retprobe, legacy;
  9605. int pfd, err;
  9606. if (!OPTS_VALID(opts, bpf_kprobe_opts))
  9607. return libbpf_err_ptr(-EINVAL);
  9608. attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
  9609. retprobe = OPTS_GET(opts, retprobe, false);
  9610. offset = OPTS_GET(opts, offset, 0);
  9611. pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  9612. legacy = determine_kprobe_perf_type() < 0;
  9613. switch (attach_mode) {
  9614. case PROBE_ATTACH_MODE_LEGACY:
  9615. legacy = true;
  9616. pe_opts.force_ioctl_attach = true;
  9617. break;
  9618. case PROBE_ATTACH_MODE_PERF:
  9619. if (legacy)
  9620. return libbpf_err_ptr(-ENOTSUP);
  9621. pe_opts.force_ioctl_attach = true;
  9622. break;
  9623. case PROBE_ATTACH_MODE_LINK:
  9624. if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
  9625. return libbpf_err_ptr(-ENOTSUP);
  9626. break;
  9627. case PROBE_ATTACH_MODE_DEFAULT:
  9628. break;
  9629. default:
  9630. return libbpf_err_ptr(-EINVAL);
  9631. }
  9632. if (!legacy) {
  9633. pfd = perf_event_open_probe(false /* uprobe */, retprobe,
  9634. func_name, offset,
  9635. -1 /* pid */, 0 /* ref_ctr_off */);
  9636. } else {
  9637. char probe_name[MAX_EVENT_NAME_LEN];
  9638. gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
  9639. func_name, offset);
  9640. legacy_probe = strdup(probe_name);
  9641. if (!legacy_probe)
  9642. return libbpf_err_ptr(-ENOMEM);
  9643. pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
  9644. offset, -1 /* pid */);
  9645. }
  9646. if (pfd < 0) {
  9647. err = -errno;
  9648. pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
  9649. prog->name, retprobe ? "kretprobe" : "kprobe",
  9650. func_name, offset,
  9651. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9652. goto err_out;
  9653. }
  9654. link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
  9655. err = libbpf_get_error(link);
  9656. if (err) {
  9657. close(pfd);
  9658. pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
  9659. prog->name, retprobe ? "kretprobe" : "kprobe",
  9660. func_name, offset,
  9661. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9662. goto err_clean_legacy;
  9663. }
  9664. if (legacy) {
  9665. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  9666. perf_link->legacy_probe_name = legacy_probe;
  9667. perf_link->legacy_is_kprobe = true;
  9668. perf_link->legacy_is_retprobe = retprobe;
  9669. }
  9670. return link;
  9671. err_clean_legacy:
  9672. if (legacy)
  9673. remove_kprobe_event_legacy(legacy_probe, retprobe);
  9674. err_out:
  9675. free(legacy_probe);
  9676. return libbpf_err_ptr(err);
  9677. }
  9678. struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
  9679. bool retprobe,
  9680. const char *func_name)
  9681. {
  9682. DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
  9683. .retprobe = retprobe,
  9684. );
  9685. return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
  9686. }
  9687. struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
  9688. const char *syscall_name,
  9689. const struct bpf_ksyscall_opts *opts)
  9690. {
  9691. LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
  9692. char func_name[128];
  9693. if (!OPTS_VALID(opts, bpf_ksyscall_opts))
  9694. return libbpf_err_ptr(-EINVAL);
  9695. if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
  9696. /* arch_specific_syscall_pfx() should never return NULL here
  9697. * because it is guarded by kernel_supports(). However, since
  9698. * compiler does not know that we have an explicit conditional
  9699. * as well.
  9700. */
  9701. snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
  9702. arch_specific_syscall_pfx() ? : "", syscall_name);
  9703. } else {
  9704. snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
  9705. }
  9706. kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
  9707. kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  9708. return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
  9709. }
  9710. /* Adapted from perf/util/string.c */
  9711. bool glob_match(const char *str, const char *pat)
  9712. {
  9713. while (*str && *pat && *pat != '*') {
  9714. if (*pat == '?') { /* Matches any single character */
  9715. str++;
  9716. pat++;
  9717. continue;
  9718. }
  9719. if (*str != *pat)
  9720. return false;
  9721. str++;
  9722. pat++;
  9723. }
  9724. /* Check wild card */
  9725. if (*pat == '*') {
  9726. while (*pat == '*')
  9727. pat++;
  9728. if (!*pat) /* Tail wild card matches all */
  9729. return true;
  9730. while (*str)
  9731. if (glob_match(str++, pat))
  9732. return true;
  9733. }
  9734. return !*str && !*pat;
  9735. }
  9736. struct kprobe_multi_resolve {
  9737. const char *pattern;
  9738. unsigned long *addrs;
  9739. size_t cap;
  9740. size_t cnt;
  9741. };
  9742. struct avail_kallsyms_data {
  9743. char **syms;
  9744. size_t cnt;
  9745. struct kprobe_multi_resolve *res;
  9746. };
  9747. static int avail_func_cmp(const void *a, const void *b)
  9748. {
  9749. return strcmp(*(const char **)a, *(const char **)b);
  9750. }
  9751. static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
  9752. const char *sym_name, void *ctx)
  9753. {
  9754. struct avail_kallsyms_data *data = ctx;
  9755. struct kprobe_multi_resolve *res = data->res;
  9756. int err;
  9757. if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
  9758. return 0;
  9759. err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
  9760. if (err)
  9761. return err;
  9762. res->addrs[res->cnt++] = (unsigned long)sym_addr;
  9763. return 0;
  9764. }
  9765. static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
  9766. {
  9767. const char *available_functions_file = tracefs_available_filter_functions();
  9768. struct avail_kallsyms_data data;
  9769. char sym_name[500];
  9770. FILE *f;
  9771. int err = 0, ret, i;
  9772. char **syms = NULL;
  9773. size_t cap = 0, cnt = 0;
  9774. f = fopen(available_functions_file, "re");
  9775. if (!f) {
  9776. err = -errno;
  9777. pr_warn("failed to open %s: %d\n", available_functions_file, err);
  9778. return err;
  9779. }
  9780. while (true) {
  9781. char *name;
  9782. ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
  9783. if (ret == EOF && feof(f))
  9784. break;
  9785. if (ret != 1) {
  9786. pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
  9787. err = -EINVAL;
  9788. goto cleanup;
  9789. }
  9790. if (!glob_match(sym_name, res->pattern))
  9791. continue;
  9792. err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
  9793. if (err)
  9794. goto cleanup;
  9795. name = strdup(sym_name);
  9796. if (!name) {
  9797. err = -errno;
  9798. goto cleanup;
  9799. }
  9800. syms[cnt++] = name;
  9801. }
  9802. /* no entries found, bail out */
  9803. if (cnt == 0) {
  9804. err = -ENOENT;
  9805. goto cleanup;
  9806. }
  9807. /* sort available functions */
  9808. qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
  9809. data.syms = syms;
  9810. data.res = res;
  9811. data.cnt = cnt;
  9812. libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
  9813. if (res->cnt == 0)
  9814. err = -ENOENT;
  9815. cleanup:
  9816. for (i = 0; i < cnt; i++)
  9817. free((char *)syms[i]);
  9818. free(syms);
  9819. fclose(f);
  9820. return err;
  9821. }
  9822. static bool has_available_filter_functions_addrs(void)
  9823. {
  9824. return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
  9825. }
  9826. static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
  9827. {
  9828. const char *available_path = tracefs_available_filter_functions_addrs();
  9829. char sym_name[500];
  9830. FILE *f;
  9831. int ret, err = 0;
  9832. unsigned long long sym_addr;
  9833. f = fopen(available_path, "re");
  9834. if (!f) {
  9835. err = -errno;
  9836. pr_warn("failed to open %s: %d\n", available_path, err);
  9837. return err;
  9838. }
  9839. while (true) {
  9840. ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
  9841. if (ret == EOF && feof(f))
  9842. break;
  9843. if (ret != 2) {
  9844. pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
  9845. ret);
  9846. err = -EINVAL;
  9847. goto cleanup;
  9848. }
  9849. if (!glob_match(sym_name, res->pattern))
  9850. continue;
  9851. err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
  9852. sizeof(*res->addrs), res->cnt + 1);
  9853. if (err)
  9854. goto cleanup;
  9855. res->addrs[res->cnt++] = (unsigned long)sym_addr;
  9856. }
  9857. if (res->cnt == 0)
  9858. err = -ENOENT;
  9859. cleanup:
  9860. fclose(f);
  9861. return err;
  9862. }
  9863. struct bpf_link *
  9864. bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
  9865. const char *pattern,
  9866. const struct bpf_kprobe_multi_opts *opts)
  9867. {
  9868. LIBBPF_OPTS(bpf_link_create_opts, lopts);
  9869. struct kprobe_multi_resolve res = {
  9870. .pattern = pattern,
  9871. };
  9872. enum bpf_attach_type attach_type;
  9873. struct bpf_link *link = NULL;
  9874. char errmsg[STRERR_BUFSIZE];
  9875. const unsigned long *addrs;
  9876. int err, link_fd, prog_fd;
  9877. bool retprobe, session;
  9878. const __u64 *cookies;
  9879. const char **syms;
  9880. size_t cnt;
  9881. if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
  9882. return libbpf_err_ptr(-EINVAL);
  9883. prog_fd = bpf_program__fd(prog);
  9884. if (prog_fd < 0) {
  9885. pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
  9886. prog->name);
  9887. return libbpf_err_ptr(-EINVAL);
  9888. }
  9889. syms = OPTS_GET(opts, syms, false);
  9890. addrs = OPTS_GET(opts, addrs, false);
  9891. cnt = OPTS_GET(opts, cnt, false);
  9892. cookies = OPTS_GET(opts, cookies, false);
  9893. if (!pattern && !addrs && !syms)
  9894. return libbpf_err_ptr(-EINVAL);
  9895. if (pattern && (addrs || syms || cookies || cnt))
  9896. return libbpf_err_ptr(-EINVAL);
  9897. if (!pattern && !cnt)
  9898. return libbpf_err_ptr(-EINVAL);
  9899. if (addrs && syms)
  9900. return libbpf_err_ptr(-EINVAL);
  9901. if (pattern) {
  9902. if (has_available_filter_functions_addrs())
  9903. err = libbpf_available_kprobes_parse(&res);
  9904. else
  9905. err = libbpf_available_kallsyms_parse(&res);
  9906. if (err)
  9907. goto error;
  9908. addrs = res.addrs;
  9909. cnt = res.cnt;
  9910. }
  9911. retprobe = OPTS_GET(opts, retprobe, false);
  9912. session = OPTS_GET(opts, session, false);
  9913. if (retprobe && session)
  9914. return libbpf_err_ptr(-EINVAL);
  9915. attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
  9916. lopts.kprobe_multi.syms = syms;
  9917. lopts.kprobe_multi.addrs = addrs;
  9918. lopts.kprobe_multi.cookies = cookies;
  9919. lopts.kprobe_multi.cnt = cnt;
  9920. lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
  9921. link = calloc(1, sizeof(*link));
  9922. if (!link) {
  9923. err = -ENOMEM;
  9924. goto error;
  9925. }
  9926. link->detach = &bpf_link__detach_fd;
  9927. link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
  9928. if (link_fd < 0) {
  9929. err = -errno;
  9930. pr_warn("prog '%s': failed to attach: %s\n",
  9931. prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  9932. goto error;
  9933. }
  9934. link->fd = link_fd;
  9935. free(res.addrs);
  9936. return link;
  9937. error:
  9938. free(link);
  9939. free(res.addrs);
  9940. return libbpf_err_ptr(err);
  9941. }
  9942. static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  9943. {
  9944. DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
  9945. unsigned long offset = 0;
  9946. const char *func_name;
  9947. char *func;
  9948. int n;
  9949. *link = NULL;
  9950. /* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
  9951. if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
  9952. return 0;
  9953. opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
  9954. if (opts.retprobe)
  9955. func_name = prog->sec_name + sizeof("kretprobe/") - 1;
  9956. else
  9957. func_name = prog->sec_name + sizeof("kprobe/") - 1;
  9958. n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
  9959. if (n < 1) {
  9960. pr_warn("kprobe name is invalid: %s\n", func_name);
  9961. return -EINVAL;
  9962. }
  9963. if (opts.retprobe && offset != 0) {
  9964. free(func);
  9965. pr_warn("kretprobes do not support offset specification\n");
  9966. return -EINVAL;
  9967. }
  9968. opts.offset = offset;
  9969. *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
  9970. free(func);
  9971. return libbpf_get_error(*link);
  9972. }
  9973. static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  9974. {
  9975. LIBBPF_OPTS(bpf_ksyscall_opts, opts);
  9976. const char *syscall_name;
  9977. *link = NULL;
  9978. /* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
  9979. if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
  9980. return 0;
  9981. opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
  9982. if (opts.retprobe)
  9983. syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
  9984. else
  9985. syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
  9986. *link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
  9987. return *link ? 0 : -errno;
  9988. }
  9989. static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  9990. {
  9991. LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
  9992. const char *spec;
  9993. char *pattern;
  9994. int n;
  9995. *link = NULL;
  9996. /* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
  9997. if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
  9998. strcmp(prog->sec_name, "kretprobe.multi") == 0)
  9999. return 0;
  10000. opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
  10001. if (opts.retprobe)
  10002. spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
  10003. else
  10004. spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
  10005. n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
  10006. if (n < 1) {
  10007. pr_warn("kprobe multi pattern is invalid: %s\n", spec);
  10008. return -EINVAL;
  10009. }
  10010. *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
  10011. free(pattern);
  10012. return libbpf_get_error(*link);
  10013. }
  10014. static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
  10015. struct bpf_link **link)
  10016. {
  10017. LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
  10018. const char *spec;
  10019. char *pattern;
  10020. int n;
  10021. *link = NULL;
  10022. /* no auto-attach for SEC("kprobe.session") */
  10023. if (strcmp(prog->sec_name, "kprobe.session") == 0)
  10024. return 0;
  10025. spec = prog->sec_name + sizeof("kprobe.session/") - 1;
  10026. n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
  10027. if (n < 1) {
  10028. pr_warn("kprobe session pattern is invalid: %s\n", spec);
  10029. return -EINVAL;
  10030. }
  10031. *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
  10032. free(pattern);
  10033. return *link ? 0 : -errno;
  10034. }
  10035. static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10036. {
  10037. char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
  10038. LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
  10039. int n, ret = -EINVAL;
  10040. *link = NULL;
  10041. n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
  10042. &probe_type, &binary_path, &func_name);
  10043. switch (n) {
  10044. case 1:
  10045. /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
  10046. ret = 0;
  10047. break;
  10048. case 3:
  10049. opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
  10050. *link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
  10051. ret = libbpf_get_error(*link);
  10052. break;
  10053. default:
  10054. pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
  10055. prog->sec_name);
  10056. break;
  10057. }
  10058. free(probe_type);
  10059. free(binary_path);
  10060. free(func_name);
  10061. return ret;
  10062. }
  10063. static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
  10064. const char *binary_path, size_t offset)
  10065. {
  10066. return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
  10067. retprobe ? 'r' : 'p',
  10068. retprobe ? "uretprobes" : "uprobes",
  10069. probe_name, binary_path, offset);
  10070. }
  10071. static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
  10072. {
  10073. return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
  10074. retprobe ? "uretprobes" : "uprobes", probe_name);
  10075. }
  10076. static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
  10077. {
  10078. char file[512];
  10079. snprintf(file, sizeof(file), "%s/events/%s/%s/id",
  10080. tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
  10081. return parse_uint_from_file(file, "%d\n");
  10082. }
  10083. static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
  10084. const char *binary_path, size_t offset, int pid)
  10085. {
  10086. const size_t attr_sz = sizeof(struct perf_event_attr);
  10087. struct perf_event_attr attr;
  10088. int type, pfd, err;
  10089. err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
  10090. if (err < 0) {
  10091. pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
  10092. binary_path, (size_t)offset, err);
  10093. return err;
  10094. }
  10095. type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
  10096. if (type < 0) {
  10097. err = type;
  10098. pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
  10099. binary_path, offset, err);
  10100. goto err_clean_legacy;
  10101. }
  10102. memset(&attr, 0, attr_sz);
  10103. attr.size = attr_sz;
  10104. attr.config = type;
  10105. attr.type = PERF_TYPE_TRACEPOINT;
  10106. pfd = syscall(__NR_perf_event_open, &attr,
  10107. pid < 0 ? -1 : pid, /* pid */
  10108. pid == -1 ? 0 : -1, /* cpu */
  10109. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  10110. if (pfd < 0) {
  10111. err = -errno;
  10112. pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
  10113. goto err_clean_legacy;
  10114. }
  10115. return pfd;
  10116. err_clean_legacy:
  10117. /* Clear the newly added legacy uprobe_event */
  10118. remove_uprobe_event_legacy(probe_name, retprobe);
  10119. return err;
  10120. }
  10121. /* Find offset of function name in archive specified by path. Currently
  10122. * supported are .zip files that do not compress their contents, as used on
  10123. * Android in the form of APKs, for example. "file_name" is the name of the ELF
  10124. * file inside the archive. "func_name" matches symbol name or name@@LIB for
  10125. * library functions.
  10126. *
  10127. * An overview of the APK format specifically provided here:
  10128. * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
  10129. */
  10130. static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
  10131. const char *func_name)
  10132. {
  10133. struct zip_archive *archive;
  10134. struct zip_entry entry;
  10135. long ret;
  10136. Elf *elf;
  10137. archive = zip_archive_open(archive_path);
  10138. if (IS_ERR(archive)) {
  10139. ret = PTR_ERR(archive);
  10140. pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
  10141. return ret;
  10142. }
  10143. ret = zip_archive_find_entry(archive, file_name, &entry);
  10144. if (ret) {
  10145. pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
  10146. archive_path, ret);
  10147. goto out;
  10148. }
  10149. pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
  10150. (unsigned long)entry.data_offset);
  10151. if (entry.compression) {
  10152. pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
  10153. archive_path);
  10154. ret = -LIBBPF_ERRNO__FORMAT;
  10155. goto out;
  10156. }
  10157. elf = elf_memory((void *)entry.data, entry.data_length);
  10158. if (!elf) {
  10159. pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
  10160. elf_errmsg(-1));
  10161. ret = -LIBBPF_ERRNO__LIBELF;
  10162. goto out;
  10163. }
  10164. ret = elf_find_func_offset(elf, file_name, func_name);
  10165. if (ret > 0) {
  10166. pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
  10167. func_name, file_name, archive_path, entry.data_offset, ret,
  10168. ret + entry.data_offset);
  10169. ret += entry.data_offset;
  10170. }
  10171. elf_end(elf);
  10172. out:
  10173. zip_archive_close(archive);
  10174. return ret;
  10175. }
  10176. static const char *arch_specific_lib_paths(void)
  10177. {
  10178. /*
  10179. * Based on https://packages.debian.org/sid/libc6.
  10180. *
  10181. * Assume that the traced program is built for the same architecture
  10182. * as libbpf, which should cover the vast majority of cases.
  10183. */
  10184. #if defined(__x86_64__)
  10185. return "/lib/x86_64-linux-gnu";
  10186. #elif defined(__i386__)
  10187. return "/lib/i386-linux-gnu";
  10188. #elif defined(__s390x__)
  10189. return "/lib/s390x-linux-gnu";
  10190. #elif defined(__s390__)
  10191. return "/lib/s390-linux-gnu";
  10192. #elif defined(__arm__) && defined(__SOFTFP__)
  10193. return "/lib/arm-linux-gnueabi";
  10194. #elif defined(__arm__) && !defined(__SOFTFP__)
  10195. return "/lib/arm-linux-gnueabihf";
  10196. #elif defined(__aarch64__)
  10197. return "/lib/aarch64-linux-gnu";
  10198. #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
  10199. return "/lib/mips64el-linux-gnuabi64";
  10200. #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
  10201. return "/lib/mipsel-linux-gnu";
  10202. #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  10203. return "/lib/powerpc64le-linux-gnu";
  10204. #elif defined(__sparc__) && defined(__arch64__)
  10205. return "/lib/sparc64-linux-gnu";
  10206. #elif defined(__riscv) && __riscv_xlen == 64
  10207. return "/lib/riscv64-linux-gnu";
  10208. #else
  10209. return NULL;
  10210. #endif
  10211. }
  10212. /* Get full path to program/shared library. */
  10213. static int resolve_full_path(const char *file, char *result, size_t result_sz)
  10214. {
  10215. const char *search_paths[3] = {};
  10216. int i, perm;
  10217. if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
  10218. search_paths[0] = getenv("LD_LIBRARY_PATH");
  10219. search_paths[1] = "/usr/lib64:/usr/lib";
  10220. search_paths[2] = arch_specific_lib_paths();
  10221. perm = R_OK;
  10222. } else {
  10223. search_paths[0] = getenv("PATH");
  10224. search_paths[1] = "/usr/bin:/usr/sbin";
  10225. perm = R_OK | X_OK;
  10226. }
  10227. for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
  10228. const char *s;
  10229. if (!search_paths[i])
  10230. continue;
  10231. for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
  10232. char *next_path;
  10233. int seg_len;
  10234. if (s[0] == ':')
  10235. s++;
  10236. next_path = strchr(s, ':');
  10237. seg_len = next_path ? next_path - s : strlen(s);
  10238. if (!seg_len)
  10239. continue;
  10240. snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
  10241. /* ensure it has required permissions */
  10242. if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
  10243. continue;
  10244. pr_debug("resolved '%s' to '%s'\n", file, result);
  10245. return 0;
  10246. }
  10247. }
  10248. return -ENOENT;
  10249. }
  10250. struct bpf_link *
  10251. bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
  10252. pid_t pid,
  10253. const char *path,
  10254. const char *func_pattern,
  10255. const struct bpf_uprobe_multi_opts *opts)
  10256. {
  10257. const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
  10258. LIBBPF_OPTS(bpf_link_create_opts, lopts);
  10259. unsigned long *resolved_offsets = NULL;
  10260. int err = 0, link_fd, prog_fd;
  10261. struct bpf_link *link = NULL;
  10262. char errmsg[STRERR_BUFSIZE];
  10263. char full_path[PATH_MAX];
  10264. const __u64 *cookies;
  10265. const char **syms;
  10266. size_t cnt;
  10267. if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
  10268. return libbpf_err_ptr(-EINVAL);
  10269. prog_fd = bpf_program__fd(prog);
  10270. if (prog_fd < 0) {
  10271. pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
  10272. prog->name);
  10273. return libbpf_err_ptr(-EINVAL);
  10274. }
  10275. syms = OPTS_GET(opts, syms, NULL);
  10276. offsets = OPTS_GET(opts, offsets, NULL);
  10277. ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
  10278. cookies = OPTS_GET(opts, cookies, NULL);
  10279. cnt = OPTS_GET(opts, cnt, 0);
  10280. /*
  10281. * User can specify 2 mutually exclusive set of inputs:
  10282. *
  10283. * 1) use only path/func_pattern/pid arguments
  10284. *
  10285. * 2) use path/pid with allowed combinations of:
  10286. * syms/offsets/ref_ctr_offsets/cookies/cnt
  10287. *
  10288. * - syms and offsets are mutually exclusive
  10289. * - ref_ctr_offsets and cookies are optional
  10290. *
  10291. * Any other usage results in error.
  10292. */
  10293. if (!path)
  10294. return libbpf_err_ptr(-EINVAL);
  10295. if (!func_pattern && cnt == 0)
  10296. return libbpf_err_ptr(-EINVAL);
  10297. if (func_pattern) {
  10298. if (syms || offsets || ref_ctr_offsets || cookies || cnt)
  10299. return libbpf_err_ptr(-EINVAL);
  10300. } else {
  10301. if (!!syms == !!offsets)
  10302. return libbpf_err_ptr(-EINVAL);
  10303. }
  10304. if (func_pattern) {
  10305. if (!strchr(path, '/')) {
  10306. err = resolve_full_path(path, full_path, sizeof(full_path));
  10307. if (err) {
  10308. pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
  10309. prog->name, path, err);
  10310. return libbpf_err_ptr(err);
  10311. }
  10312. path = full_path;
  10313. }
  10314. err = elf_resolve_pattern_offsets(path, func_pattern,
  10315. &resolved_offsets, &cnt);
  10316. if (err < 0)
  10317. return libbpf_err_ptr(err);
  10318. offsets = resolved_offsets;
  10319. } else if (syms) {
  10320. err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
  10321. if (err < 0)
  10322. return libbpf_err_ptr(err);
  10323. offsets = resolved_offsets;
  10324. }
  10325. lopts.uprobe_multi.path = path;
  10326. lopts.uprobe_multi.offsets = offsets;
  10327. lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
  10328. lopts.uprobe_multi.cookies = cookies;
  10329. lopts.uprobe_multi.cnt = cnt;
  10330. lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
  10331. if (pid == 0)
  10332. pid = getpid();
  10333. if (pid > 0)
  10334. lopts.uprobe_multi.pid = pid;
  10335. link = calloc(1, sizeof(*link));
  10336. if (!link) {
  10337. err = -ENOMEM;
  10338. goto error;
  10339. }
  10340. link->detach = &bpf_link__detach_fd;
  10341. link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
  10342. if (link_fd < 0) {
  10343. err = -errno;
  10344. pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
  10345. prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  10346. goto error;
  10347. }
  10348. link->fd = link_fd;
  10349. free(resolved_offsets);
  10350. return link;
  10351. error:
  10352. free(resolved_offsets);
  10353. free(link);
  10354. return libbpf_err_ptr(err);
  10355. }
  10356. LIBBPF_API struct bpf_link *
  10357. bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
  10358. const char *binary_path, size_t func_offset,
  10359. const struct bpf_uprobe_opts *opts)
  10360. {
  10361. const char *archive_path = NULL, *archive_sep = NULL;
  10362. char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
  10363. DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
  10364. enum probe_attach_mode attach_mode;
  10365. char full_path[PATH_MAX];
  10366. struct bpf_link *link;
  10367. size_t ref_ctr_off;
  10368. int pfd, err;
  10369. bool retprobe, legacy;
  10370. const char *func_name;
  10371. if (!OPTS_VALID(opts, bpf_uprobe_opts))
  10372. return libbpf_err_ptr(-EINVAL);
  10373. attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
  10374. retprobe = OPTS_GET(opts, retprobe, false);
  10375. ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
  10376. pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  10377. if (!binary_path)
  10378. return libbpf_err_ptr(-EINVAL);
  10379. /* Check if "binary_path" refers to an archive. */
  10380. archive_sep = strstr(binary_path, "!/");
  10381. if (archive_sep) {
  10382. full_path[0] = '\0';
  10383. libbpf_strlcpy(full_path, binary_path,
  10384. min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
  10385. archive_path = full_path;
  10386. binary_path = archive_sep + 2;
  10387. } else if (!strchr(binary_path, '/')) {
  10388. err = resolve_full_path(binary_path, full_path, sizeof(full_path));
  10389. if (err) {
  10390. pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
  10391. prog->name, binary_path, err);
  10392. return libbpf_err_ptr(err);
  10393. }
  10394. binary_path = full_path;
  10395. }
  10396. func_name = OPTS_GET(opts, func_name, NULL);
  10397. if (func_name) {
  10398. long sym_off;
  10399. if (archive_path) {
  10400. sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
  10401. func_name);
  10402. binary_path = archive_path;
  10403. } else {
  10404. sym_off = elf_find_func_offset_from_file(binary_path, func_name);
  10405. }
  10406. if (sym_off < 0)
  10407. return libbpf_err_ptr(sym_off);
  10408. func_offset += sym_off;
  10409. }
  10410. legacy = determine_uprobe_perf_type() < 0;
  10411. switch (attach_mode) {
  10412. case PROBE_ATTACH_MODE_LEGACY:
  10413. legacy = true;
  10414. pe_opts.force_ioctl_attach = true;
  10415. break;
  10416. case PROBE_ATTACH_MODE_PERF:
  10417. if (legacy)
  10418. return libbpf_err_ptr(-ENOTSUP);
  10419. pe_opts.force_ioctl_attach = true;
  10420. break;
  10421. case PROBE_ATTACH_MODE_LINK:
  10422. if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
  10423. return libbpf_err_ptr(-ENOTSUP);
  10424. break;
  10425. case PROBE_ATTACH_MODE_DEFAULT:
  10426. break;
  10427. default:
  10428. return libbpf_err_ptr(-EINVAL);
  10429. }
  10430. if (!legacy) {
  10431. pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
  10432. func_offset, pid, ref_ctr_off);
  10433. } else {
  10434. char probe_name[MAX_EVENT_NAME_LEN];
  10435. if (ref_ctr_off)
  10436. return libbpf_err_ptr(-EINVAL);
  10437. gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
  10438. strrchr(binary_path, '/') ? : binary_path,
  10439. func_offset);
  10440. legacy_probe = strdup(probe_name);
  10441. if (!legacy_probe)
  10442. return libbpf_err_ptr(-ENOMEM);
  10443. pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
  10444. binary_path, func_offset, pid);
  10445. }
  10446. if (pfd < 0) {
  10447. err = -errno;
  10448. pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
  10449. prog->name, retprobe ? "uretprobe" : "uprobe",
  10450. binary_path, func_offset,
  10451. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  10452. goto err_out;
  10453. }
  10454. link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
  10455. err = libbpf_get_error(link);
  10456. if (err) {
  10457. close(pfd);
  10458. pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
  10459. prog->name, retprobe ? "uretprobe" : "uprobe",
  10460. binary_path, func_offset,
  10461. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  10462. goto err_clean_legacy;
  10463. }
  10464. if (legacy) {
  10465. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  10466. perf_link->legacy_probe_name = legacy_probe;
  10467. perf_link->legacy_is_kprobe = false;
  10468. perf_link->legacy_is_retprobe = retprobe;
  10469. }
  10470. return link;
  10471. err_clean_legacy:
  10472. if (legacy)
  10473. remove_uprobe_event_legacy(legacy_probe, retprobe);
  10474. err_out:
  10475. free(legacy_probe);
  10476. return libbpf_err_ptr(err);
  10477. }
  10478. /* Format of u[ret]probe section definition supporting auto-attach:
  10479. * u[ret]probe/binary:function[+offset]
  10480. *
  10481. * binary can be an absolute/relative path or a filename; the latter is resolved to a
  10482. * full binary path via bpf_program__attach_uprobe_opts.
  10483. *
  10484. * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
  10485. * specified (and auto-attach is not possible) or the above format is specified for
  10486. * auto-attach.
  10487. */
  10488. static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10489. {
  10490. DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
  10491. char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
  10492. int n, c, ret = -EINVAL;
  10493. long offset = 0;
  10494. *link = NULL;
  10495. n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
  10496. &probe_type, &binary_path, &func_name);
  10497. switch (n) {
  10498. case 1:
  10499. /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
  10500. ret = 0;
  10501. break;
  10502. case 2:
  10503. pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
  10504. prog->name, prog->sec_name);
  10505. break;
  10506. case 3:
  10507. /* check if user specifies `+offset`, if yes, this should be
  10508. * the last part of the string, make sure sscanf read to EOL
  10509. */
  10510. func_off = strrchr(func_name, '+');
  10511. if (func_off) {
  10512. n = sscanf(func_off, "+%li%n", &offset, &c);
  10513. if (n == 1 && *(func_off + c) == '\0')
  10514. func_off[0] = '\0';
  10515. else
  10516. offset = 0;
  10517. }
  10518. opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
  10519. strcmp(probe_type, "uretprobe.s") == 0;
  10520. if (opts.retprobe && offset != 0) {
  10521. pr_warn("prog '%s': uretprobes do not support offset specification\n",
  10522. prog->name);
  10523. break;
  10524. }
  10525. opts.func_name = func_name;
  10526. *link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
  10527. ret = libbpf_get_error(*link);
  10528. break;
  10529. default:
  10530. pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
  10531. prog->sec_name);
  10532. break;
  10533. }
  10534. free(probe_type);
  10535. free(binary_path);
  10536. free(func_name);
  10537. return ret;
  10538. }
  10539. struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
  10540. bool retprobe, pid_t pid,
  10541. const char *binary_path,
  10542. size_t func_offset)
  10543. {
  10544. DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
  10545. return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
  10546. }
  10547. struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
  10548. pid_t pid, const char *binary_path,
  10549. const char *usdt_provider, const char *usdt_name,
  10550. const struct bpf_usdt_opts *opts)
  10551. {
  10552. char resolved_path[512];
  10553. struct bpf_object *obj = prog->obj;
  10554. struct bpf_link *link;
  10555. __u64 usdt_cookie;
  10556. int err;
  10557. if (!OPTS_VALID(opts, bpf_uprobe_opts))
  10558. return libbpf_err_ptr(-EINVAL);
  10559. if (bpf_program__fd(prog) < 0) {
  10560. pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
  10561. prog->name);
  10562. return libbpf_err_ptr(-EINVAL);
  10563. }
  10564. if (!binary_path)
  10565. return libbpf_err_ptr(-EINVAL);
  10566. if (!strchr(binary_path, '/')) {
  10567. err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
  10568. if (err) {
  10569. pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
  10570. prog->name, binary_path, err);
  10571. return libbpf_err_ptr(err);
  10572. }
  10573. binary_path = resolved_path;
  10574. }
  10575. /* USDT manager is instantiated lazily on first USDT attach. It will
  10576. * be destroyed together with BPF object in bpf_object__close().
  10577. */
  10578. if (IS_ERR(obj->usdt_man))
  10579. return libbpf_ptr(obj->usdt_man);
  10580. if (!obj->usdt_man) {
  10581. obj->usdt_man = usdt_manager_new(obj);
  10582. if (IS_ERR(obj->usdt_man))
  10583. return libbpf_ptr(obj->usdt_man);
  10584. }
  10585. usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
  10586. link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
  10587. usdt_provider, usdt_name, usdt_cookie);
  10588. err = libbpf_get_error(link);
  10589. if (err)
  10590. return libbpf_err_ptr(err);
  10591. return link;
  10592. }
  10593. static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10594. {
  10595. char *path = NULL, *provider = NULL, *name = NULL;
  10596. const char *sec_name;
  10597. int n, err;
  10598. sec_name = bpf_program__section_name(prog);
  10599. if (strcmp(sec_name, "usdt") == 0) {
  10600. /* no auto-attach for just SEC("usdt") */
  10601. *link = NULL;
  10602. return 0;
  10603. }
  10604. n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
  10605. if (n != 3) {
  10606. pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
  10607. sec_name);
  10608. err = -EINVAL;
  10609. } else {
  10610. *link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
  10611. provider, name, NULL);
  10612. err = libbpf_get_error(*link);
  10613. }
  10614. free(path);
  10615. free(provider);
  10616. free(name);
  10617. return err;
  10618. }
  10619. static int determine_tracepoint_id(const char *tp_category,
  10620. const char *tp_name)
  10621. {
  10622. char file[PATH_MAX];
  10623. int ret;
  10624. ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
  10625. tracefs_path(), tp_category, tp_name);
  10626. if (ret < 0)
  10627. return -errno;
  10628. if (ret >= sizeof(file)) {
  10629. pr_debug("tracepoint %s/%s path is too long\n",
  10630. tp_category, tp_name);
  10631. return -E2BIG;
  10632. }
  10633. return parse_uint_from_file(file, "%d\n");
  10634. }
  10635. static int perf_event_open_tracepoint(const char *tp_category,
  10636. const char *tp_name)
  10637. {
  10638. const size_t attr_sz = sizeof(struct perf_event_attr);
  10639. struct perf_event_attr attr;
  10640. char errmsg[STRERR_BUFSIZE];
  10641. int tp_id, pfd, err;
  10642. tp_id = determine_tracepoint_id(tp_category, tp_name);
  10643. if (tp_id < 0) {
  10644. pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
  10645. tp_category, tp_name,
  10646. libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
  10647. return tp_id;
  10648. }
  10649. memset(&attr, 0, attr_sz);
  10650. attr.type = PERF_TYPE_TRACEPOINT;
  10651. attr.size = attr_sz;
  10652. attr.config = tp_id;
  10653. pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
  10654. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  10655. if (pfd < 0) {
  10656. err = -errno;
  10657. pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
  10658. tp_category, tp_name,
  10659. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  10660. return err;
  10661. }
  10662. return pfd;
  10663. }
  10664. struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
  10665. const char *tp_category,
  10666. const char *tp_name,
  10667. const struct bpf_tracepoint_opts *opts)
  10668. {
  10669. DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
  10670. char errmsg[STRERR_BUFSIZE];
  10671. struct bpf_link *link;
  10672. int pfd, err;
  10673. if (!OPTS_VALID(opts, bpf_tracepoint_opts))
  10674. return libbpf_err_ptr(-EINVAL);
  10675. pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  10676. pfd = perf_event_open_tracepoint(tp_category, tp_name);
  10677. if (pfd < 0) {
  10678. pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
  10679. prog->name, tp_category, tp_name,
  10680. libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
  10681. return libbpf_err_ptr(pfd);
  10682. }
  10683. link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
  10684. err = libbpf_get_error(link);
  10685. if (err) {
  10686. close(pfd);
  10687. pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
  10688. prog->name, tp_category, tp_name,
  10689. libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
  10690. return libbpf_err_ptr(err);
  10691. }
  10692. return link;
  10693. }
  10694. struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
  10695. const char *tp_category,
  10696. const char *tp_name)
  10697. {
  10698. return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
  10699. }
  10700. static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10701. {
  10702. char *sec_name, *tp_cat, *tp_name;
  10703. *link = NULL;
  10704. /* no auto-attach for SEC("tp") or SEC("tracepoint") */
  10705. if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
  10706. return 0;
  10707. sec_name = strdup(prog->sec_name);
  10708. if (!sec_name)
  10709. return -ENOMEM;
  10710. /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
  10711. if (str_has_pfx(prog->sec_name, "tp/"))
  10712. tp_cat = sec_name + sizeof("tp/") - 1;
  10713. else
  10714. tp_cat = sec_name + sizeof("tracepoint/") - 1;
  10715. tp_name = strchr(tp_cat, '/');
  10716. if (!tp_name) {
  10717. free(sec_name);
  10718. return -EINVAL;
  10719. }
  10720. *tp_name = '\0';
  10721. tp_name++;
  10722. *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
  10723. free(sec_name);
  10724. return libbpf_get_error(*link);
  10725. }
  10726. struct bpf_link *
  10727. bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
  10728. const char *tp_name,
  10729. struct bpf_raw_tracepoint_opts *opts)
  10730. {
  10731. LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
  10732. char errmsg[STRERR_BUFSIZE];
  10733. struct bpf_link *link;
  10734. int prog_fd, pfd;
  10735. if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
  10736. return libbpf_err_ptr(-EINVAL);
  10737. prog_fd = bpf_program__fd(prog);
  10738. if (prog_fd < 0) {
  10739. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  10740. return libbpf_err_ptr(-EINVAL);
  10741. }
  10742. link = calloc(1, sizeof(*link));
  10743. if (!link)
  10744. return libbpf_err_ptr(-ENOMEM);
  10745. link->detach = &bpf_link__detach_fd;
  10746. raw_opts.tp_name = tp_name;
  10747. raw_opts.cookie = OPTS_GET(opts, cookie, 0);
  10748. pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
  10749. if (pfd < 0) {
  10750. pfd = -errno;
  10751. free(link);
  10752. pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
  10753. prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
  10754. return libbpf_err_ptr(pfd);
  10755. }
  10756. link->fd = pfd;
  10757. return link;
  10758. }
  10759. struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
  10760. const char *tp_name)
  10761. {
  10762. return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
  10763. }
  10764. static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10765. {
  10766. static const char *const prefixes[] = {
  10767. "raw_tp",
  10768. "raw_tracepoint",
  10769. "raw_tp.w",
  10770. "raw_tracepoint.w",
  10771. };
  10772. size_t i;
  10773. const char *tp_name = NULL;
  10774. *link = NULL;
  10775. for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
  10776. size_t pfx_len;
  10777. if (!str_has_pfx(prog->sec_name, prefixes[i]))
  10778. continue;
  10779. pfx_len = strlen(prefixes[i]);
  10780. /* no auto-attach case of, e.g., SEC("raw_tp") */
  10781. if (prog->sec_name[pfx_len] == '\0')
  10782. return 0;
  10783. if (prog->sec_name[pfx_len] != '/')
  10784. continue;
  10785. tp_name = prog->sec_name + pfx_len + 1;
  10786. break;
  10787. }
  10788. if (!tp_name) {
  10789. pr_warn("prog '%s': invalid section name '%s'\n",
  10790. prog->name, prog->sec_name);
  10791. return -EINVAL;
  10792. }
  10793. *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
  10794. return libbpf_get_error(*link);
  10795. }
  10796. /* Common logic for all BPF program types that attach to a btf_id */
  10797. static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
  10798. const struct bpf_trace_opts *opts)
  10799. {
  10800. LIBBPF_OPTS(bpf_link_create_opts, link_opts);
  10801. char errmsg[STRERR_BUFSIZE];
  10802. struct bpf_link *link;
  10803. int prog_fd, pfd;
  10804. if (!OPTS_VALID(opts, bpf_trace_opts))
  10805. return libbpf_err_ptr(-EINVAL);
  10806. prog_fd = bpf_program__fd(prog);
  10807. if (prog_fd < 0) {
  10808. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  10809. return libbpf_err_ptr(-EINVAL);
  10810. }
  10811. link = calloc(1, sizeof(*link));
  10812. if (!link)
  10813. return libbpf_err_ptr(-ENOMEM);
  10814. link->detach = &bpf_link__detach_fd;
  10815. /* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
  10816. link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
  10817. pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
  10818. if (pfd < 0) {
  10819. pfd = -errno;
  10820. free(link);
  10821. pr_warn("prog '%s': failed to attach: %s\n",
  10822. prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
  10823. return libbpf_err_ptr(pfd);
  10824. }
  10825. link->fd = pfd;
  10826. return link;
  10827. }
  10828. struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
  10829. {
  10830. return bpf_program__attach_btf_id(prog, NULL);
  10831. }
  10832. struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
  10833. const struct bpf_trace_opts *opts)
  10834. {
  10835. return bpf_program__attach_btf_id(prog, opts);
  10836. }
  10837. struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
  10838. {
  10839. return bpf_program__attach_btf_id(prog, NULL);
  10840. }
  10841. static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10842. {
  10843. *link = bpf_program__attach_trace(prog);
  10844. return libbpf_get_error(*link);
  10845. }
  10846. static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10847. {
  10848. *link = bpf_program__attach_lsm(prog);
  10849. return libbpf_get_error(*link);
  10850. }
  10851. static struct bpf_link *
  10852. bpf_program_attach_fd(const struct bpf_program *prog,
  10853. int target_fd, const char *target_name,
  10854. const struct bpf_link_create_opts *opts)
  10855. {
  10856. enum bpf_attach_type attach_type;
  10857. char errmsg[STRERR_BUFSIZE];
  10858. struct bpf_link *link;
  10859. int prog_fd, link_fd;
  10860. prog_fd = bpf_program__fd(prog);
  10861. if (prog_fd < 0) {
  10862. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  10863. return libbpf_err_ptr(-EINVAL);
  10864. }
  10865. link = calloc(1, sizeof(*link));
  10866. if (!link)
  10867. return libbpf_err_ptr(-ENOMEM);
  10868. link->detach = &bpf_link__detach_fd;
  10869. attach_type = bpf_program__expected_attach_type(prog);
  10870. link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
  10871. if (link_fd < 0) {
  10872. link_fd = -errno;
  10873. free(link);
  10874. pr_warn("prog '%s': failed to attach to %s: %s\n",
  10875. prog->name, target_name,
  10876. libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
  10877. return libbpf_err_ptr(link_fd);
  10878. }
  10879. link->fd = link_fd;
  10880. return link;
  10881. }
  10882. struct bpf_link *
  10883. bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
  10884. {
  10885. return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
  10886. }
  10887. struct bpf_link *
  10888. bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
  10889. {
  10890. return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
  10891. }
  10892. struct bpf_link *
  10893. bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
  10894. {
  10895. return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
  10896. }
  10897. struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
  10898. {
  10899. /* target_fd/target_ifindex use the same field in LINK_CREATE */
  10900. return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
  10901. }
  10902. struct bpf_link *
  10903. bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
  10904. const struct bpf_tcx_opts *opts)
  10905. {
  10906. LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
  10907. __u32 relative_id;
  10908. int relative_fd;
  10909. if (!OPTS_VALID(opts, bpf_tcx_opts))
  10910. return libbpf_err_ptr(-EINVAL);
  10911. relative_id = OPTS_GET(opts, relative_id, 0);
  10912. relative_fd = OPTS_GET(opts, relative_fd, 0);
  10913. /* validate we don't have unexpected combinations of non-zero fields */
  10914. if (!ifindex) {
  10915. pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
  10916. prog->name);
  10917. return libbpf_err_ptr(-EINVAL);
  10918. }
  10919. if (relative_fd && relative_id) {
  10920. pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
  10921. prog->name);
  10922. return libbpf_err_ptr(-EINVAL);
  10923. }
  10924. link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
  10925. link_create_opts.tcx.relative_fd = relative_fd;
  10926. link_create_opts.tcx.relative_id = relative_id;
  10927. link_create_opts.flags = OPTS_GET(opts, flags, 0);
  10928. /* target_fd/target_ifindex use the same field in LINK_CREATE */
  10929. return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
  10930. }
  10931. struct bpf_link *
  10932. bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
  10933. const struct bpf_netkit_opts *opts)
  10934. {
  10935. LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
  10936. __u32 relative_id;
  10937. int relative_fd;
  10938. if (!OPTS_VALID(opts, bpf_netkit_opts))
  10939. return libbpf_err_ptr(-EINVAL);
  10940. relative_id = OPTS_GET(opts, relative_id, 0);
  10941. relative_fd = OPTS_GET(opts, relative_fd, 0);
  10942. /* validate we don't have unexpected combinations of non-zero fields */
  10943. if (!ifindex) {
  10944. pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
  10945. prog->name);
  10946. return libbpf_err_ptr(-EINVAL);
  10947. }
  10948. if (relative_fd && relative_id) {
  10949. pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
  10950. prog->name);
  10951. return libbpf_err_ptr(-EINVAL);
  10952. }
  10953. link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
  10954. link_create_opts.netkit.relative_fd = relative_fd;
  10955. link_create_opts.netkit.relative_id = relative_id;
  10956. link_create_opts.flags = OPTS_GET(opts, flags, 0);
  10957. return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
  10958. }
  10959. struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
  10960. int target_fd,
  10961. const char *attach_func_name)
  10962. {
  10963. int btf_id;
  10964. if (!!target_fd != !!attach_func_name) {
  10965. pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
  10966. prog->name);
  10967. return libbpf_err_ptr(-EINVAL);
  10968. }
  10969. if (prog->type != BPF_PROG_TYPE_EXT) {
  10970. pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
  10971. prog->name);
  10972. return libbpf_err_ptr(-EINVAL);
  10973. }
  10974. if (target_fd) {
  10975. LIBBPF_OPTS(bpf_link_create_opts, target_opts);
  10976. btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
  10977. if (btf_id < 0)
  10978. return libbpf_err_ptr(btf_id);
  10979. target_opts.target_btf_id = btf_id;
  10980. return bpf_program_attach_fd(prog, target_fd, "freplace",
  10981. &target_opts);
  10982. } else {
  10983. /* no target, so use raw_tracepoint_open for compatibility
  10984. * with old kernels
  10985. */
  10986. return bpf_program__attach_trace(prog);
  10987. }
  10988. }
  10989. struct bpf_link *
  10990. bpf_program__attach_iter(const struct bpf_program *prog,
  10991. const struct bpf_iter_attach_opts *opts)
  10992. {
  10993. DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
  10994. char errmsg[STRERR_BUFSIZE];
  10995. struct bpf_link *link;
  10996. int prog_fd, link_fd;
  10997. __u32 target_fd = 0;
  10998. if (!OPTS_VALID(opts, bpf_iter_attach_opts))
  10999. return libbpf_err_ptr(-EINVAL);
  11000. link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
  11001. link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
  11002. prog_fd = bpf_program__fd(prog);
  11003. if (prog_fd < 0) {
  11004. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  11005. return libbpf_err_ptr(-EINVAL);
  11006. }
  11007. link = calloc(1, sizeof(*link));
  11008. if (!link)
  11009. return libbpf_err_ptr(-ENOMEM);
  11010. link->detach = &bpf_link__detach_fd;
  11011. link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
  11012. &link_create_opts);
  11013. if (link_fd < 0) {
  11014. link_fd = -errno;
  11015. free(link);
  11016. pr_warn("prog '%s': failed to attach to iterator: %s\n",
  11017. prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
  11018. return libbpf_err_ptr(link_fd);
  11019. }
  11020. link->fd = link_fd;
  11021. return link;
  11022. }
  11023. static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  11024. {
  11025. *link = bpf_program__attach_iter(prog, NULL);
  11026. return libbpf_get_error(*link);
  11027. }
  11028. struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
  11029. const struct bpf_netfilter_opts *opts)
  11030. {
  11031. LIBBPF_OPTS(bpf_link_create_opts, lopts);
  11032. struct bpf_link *link;
  11033. int prog_fd, link_fd;
  11034. if (!OPTS_VALID(opts, bpf_netfilter_opts))
  11035. return libbpf_err_ptr(-EINVAL);
  11036. prog_fd = bpf_program__fd(prog);
  11037. if (prog_fd < 0) {
  11038. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  11039. return libbpf_err_ptr(-EINVAL);
  11040. }
  11041. link = calloc(1, sizeof(*link));
  11042. if (!link)
  11043. return libbpf_err_ptr(-ENOMEM);
  11044. link->detach = &bpf_link__detach_fd;
  11045. lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
  11046. lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
  11047. lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
  11048. lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
  11049. link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
  11050. if (link_fd < 0) {
  11051. char errmsg[STRERR_BUFSIZE];
  11052. link_fd = -errno;
  11053. free(link);
  11054. pr_warn("prog '%s': failed to attach to netfilter: %s\n",
  11055. prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
  11056. return libbpf_err_ptr(link_fd);
  11057. }
  11058. link->fd = link_fd;
  11059. return link;
  11060. }
  11061. struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
  11062. {
  11063. struct bpf_link *link = NULL;
  11064. int err;
  11065. if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
  11066. return libbpf_err_ptr(-EOPNOTSUPP);
  11067. if (bpf_program__fd(prog) < 0) {
  11068. pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
  11069. prog->name);
  11070. return libbpf_err_ptr(-EINVAL);
  11071. }
  11072. err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
  11073. if (err)
  11074. return libbpf_err_ptr(err);
  11075. /* When calling bpf_program__attach() explicitly, auto-attach support
  11076. * is expected to work, so NULL returned link is considered an error.
  11077. * This is different for skeleton's attach, see comment in
  11078. * bpf_object__attach_skeleton().
  11079. */
  11080. if (!link)
  11081. return libbpf_err_ptr(-EOPNOTSUPP);
  11082. return link;
  11083. }
  11084. struct bpf_link_struct_ops {
  11085. struct bpf_link link;
  11086. int map_fd;
  11087. };
  11088. static int bpf_link__detach_struct_ops(struct bpf_link *link)
  11089. {
  11090. struct bpf_link_struct_ops *st_link;
  11091. __u32 zero = 0;
  11092. st_link = container_of(link, struct bpf_link_struct_ops, link);
  11093. if (st_link->map_fd < 0)
  11094. /* w/o a real link */
  11095. return bpf_map_delete_elem(link->fd, &zero);
  11096. return close(link->fd);
  11097. }
  11098. struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
  11099. {
  11100. struct bpf_link_struct_ops *link;
  11101. __u32 zero = 0;
  11102. int err, fd;
  11103. if (!bpf_map__is_struct_ops(map)) {
  11104. pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
  11105. return libbpf_err_ptr(-EINVAL);
  11106. }
  11107. if (map->fd < 0) {
  11108. pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
  11109. return libbpf_err_ptr(-EINVAL);
  11110. }
  11111. link = calloc(1, sizeof(*link));
  11112. if (!link)
  11113. return libbpf_err_ptr(-EINVAL);
  11114. /* kern_vdata should be prepared during the loading phase. */
  11115. err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
  11116. /* It can be EBUSY if the map has been used to create or
  11117. * update a link before. We don't allow updating the value of
  11118. * a struct_ops once it is set. That ensures that the value
  11119. * never changed. So, it is safe to skip EBUSY.
  11120. */
  11121. if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
  11122. free(link);
  11123. return libbpf_err_ptr(err);
  11124. }
  11125. link->link.detach = bpf_link__detach_struct_ops;
  11126. if (!(map->def.map_flags & BPF_F_LINK)) {
  11127. /* w/o a real link */
  11128. link->link.fd = map->fd;
  11129. link->map_fd = -1;
  11130. return &link->link;
  11131. }
  11132. fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
  11133. if (fd < 0) {
  11134. free(link);
  11135. return libbpf_err_ptr(fd);
  11136. }
  11137. link->link.fd = fd;
  11138. link->map_fd = map->fd;
  11139. return &link->link;
  11140. }
  11141. /*
  11142. * Swap the back struct_ops of a link with a new struct_ops map.
  11143. */
  11144. int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
  11145. {
  11146. struct bpf_link_struct_ops *st_ops_link;
  11147. __u32 zero = 0;
  11148. int err;
  11149. if (!bpf_map__is_struct_ops(map))
  11150. return -EINVAL;
  11151. if (map->fd < 0) {
  11152. pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
  11153. return -EINVAL;
  11154. }
  11155. st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
  11156. /* Ensure the type of a link is correct */
  11157. if (st_ops_link->map_fd < 0)
  11158. return -EINVAL;
  11159. err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
  11160. /* It can be EBUSY if the map has been used to create or
  11161. * update a link before. We don't allow updating the value of
  11162. * a struct_ops once it is set. That ensures that the value
  11163. * never changed. So, it is safe to skip EBUSY.
  11164. */
  11165. if (err && err != -EBUSY)
  11166. return err;
  11167. err = bpf_link_update(link->fd, map->fd, NULL);
  11168. if (err < 0)
  11169. return err;
  11170. st_ops_link->map_fd = map->fd;
  11171. return 0;
  11172. }
  11173. typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
  11174. void *private_data);
  11175. static enum bpf_perf_event_ret
  11176. perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
  11177. void **copy_mem, size_t *copy_size,
  11178. bpf_perf_event_print_t fn, void *private_data)
  11179. {
  11180. struct perf_event_mmap_page *header = mmap_mem;
  11181. __u64 data_head = ring_buffer_read_head(header);
  11182. __u64 data_tail = header->data_tail;
  11183. void *base = ((__u8 *)header) + page_size;
  11184. int ret = LIBBPF_PERF_EVENT_CONT;
  11185. struct perf_event_header *ehdr;
  11186. size_t ehdr_size;
  11187. while (data_head != data_tail) {
  11188. ehdr = base + (data_tail & (mmap_size - 1));
  11189. ehdr_size = ehdr->size;
  11190. if (((void *)ehdr) + ehdr_size > base + mmap_size) {
  11191. void *copy_start = ehdr;
  11192. size_t len_first = base + mmap_size - copy_start;
  11193. size_t len_secnd = ehdr_size - len_first;
  11194. if (*copy_size < ehdr_size) {
  11195. free(*copy_mem);
  11196. *copy_mem = malloc(ehdr_size);
  11197. if (!*copy_mem) {
  11198. *copy_size = 0;
  11199. ret = LIBBPF_PERF_EVENT_ERROR;
  11200. break;
  11201. }
  11202. *copy_size = ehdr_size;
  11203. }
  11204. memcpy(*copy_mem, copy_start, len_first);
  11205. memcpy(*copy_mem + len_first, base, len_secnd);
  11206. ehdr = *copy_mem;
  11207. }
  11208. ret = fn(ehdr, private_data);
  11209. data_tail += ehdr_size;
  11210. if (ret != LIBBPF_PERF_EVENT_CONT)
  11211. break;
  11212. }
  11213. ring_buffer_write_tail(header, data_tail);
  11214. return libbpf_err(ret);
  11215. }
  11216. struct perf_buffer;
  11217. struct perf_buffer_params {
  11218. struct perf_event_attr *attr;
  11219. /* if event_cb is specified, it takes precendence */
  11220. perf_buffer_event_fn event_cb;
  11221. /* sample_cb and lost_cb are higher-level common-case callbacks */
  11222. perf_buffer_sample_fn sample_cb;
  11223. perf_buffer_lost_fn lost_cb;
  11224. void *ctx;
  11225. int cpu_cnt;
  11226. int *cpus;
  11227. int *map_keys;
  11228. };
  11229. struct perf_cpu_buf {
  11230. struct perf_buffer *pb;
  11231. void *base; /* mmap()'ed memory */
  11232. void *buf; /* for reconstructing segmented data */
  11233. size_t buf_size;
  11234. int fd;
  11235. int cpu;
  11236. int map_key;
  11237. };
  11238. struct perf_buffer {
  11239. perf_buffer_event_fn event_cb;
  11240. perf_buffer_sample_fn sample_cb;
  11241. perf_buffer_lost_fn lost_cb;
  11242. void *ctx; /* passed into callbacks */
  11243. size_t page_size;
  11244. size_t mmap_size;
  11245. struct perf_cpu_buf **cpu_bufs;
  11246. struct epoll_event *events;
  11247. int cpu_cnt; /* number of allocated CPU buffers */
  11248. int epoll_fd; /* perf event FD */
  11249. int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
  11250. };
  11251. static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
  11252. struct perf_cpu_buf *cpu_buf)
  11253. {
  11254. if (!cpu_buf)
  11255. return;
  11256. if (cpu_buf->base &&
  11257. munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
  11258. pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
  11259. if (cpu_buf->fd >= 0) {
  11260. ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
  11261. close(cpu_buf->fd);
  11262. }
  11263. free(cpu_buf->buf);
  11264. free(cpu_buf);
  11265. }
  11266. void perf_buffer__free(struct perf_buffer *pb)
  11267. {
  11268. int i;
  11269. if (IS_ERR_OR_NULL(pb))
  11270. return;
  11271. if (pb->cpu_bufs) {
  11272. for (i = 0; i < pb->cpu_cnt; i++) {
  11273. struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
  11274. if (!cpu_buf)
  11275. continue;
  11276. bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
  11277. perf_buffer__free_cpu_buf(pb, cpu_buf);
  11278. }
  11279. free(pb->cpu_bufs);
  11280. }
  11281. if (pb->epoll_fd >= 0)
  11282. close(pb->epoll_fd);
  11283. free(pb->events);
  11284. free(pb);
  11285. }
  11286. static struct perf_cpu_buf *
  11287. perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
  11288. int cpu, int map_key)
  11289. {
  11290. struct perf_cpu_buf *cpu_buf;
  11291. char msg[STRERR_BUFSIZE];
  11292. int err;
  11293. cpu_buf = calloc(1, sizeof(*cpu_buf));
  11294. if (!cpu_buf)
  11295. return ERR_PTR(-ENOMEM);
  11296. cpu_buf->pb = pb;
  11297. cpu_buf->cpu = cpu;
  11298. cpu_buf->map_key = map_key;
  11299. cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
  11300. -1, PERF_FLAG_FD_CLOEXEC);
  11301. if (cpu_buf->fd < 0) {
  11302. err = -errno;
  11303. pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
  11304. cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
  11305. goto error;
  11306. }
  11307. cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
  11308. PROT_READ | PROT_WRITE, MAP_SHARED,
  11309. cpu_buf->fd, 0);
  11310. if (cpu_buf->base == MAP_FAILED) {
  11311. cpu_buf->base = NULL;
  11312. err = -errno;
  11313. pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
  11314. cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
  11315. goto error;
  11316. }
  11317. if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
  11318. err = -errno;
  11319. pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
  11320. cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
  11321. goto error;
  11322. }
  11323. return cpu_buf;
  11324. error:
  11325. perf_buffer__free_cpu_buf(pb, cpu_buf);
  11326. return (struct perf_cpu_buf *)ERR_PTR(err);
  11327. }
  11328. static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
  11329. struct perf_buffer_params *p);
  11330. struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
  11331. perf_buffer_sample_fn sample_cb,
  11332. perf_buffer_lost_fn lost_cb,
  11333. void *ctx,
  11334. const struct perf_buffer_opts *opts)
  11335. {
  11336. const size_t attr_sz = sizeof(struct perf_event_attr);
  11337. struct perf_buffer_params p = {};
  11338. struct perf_event_attr attr;
  11339. __u32 sample_period;
  11340. if (!OPTS_VALID(opts, perf_buffer_opts))
  11341. return libbpf_err_ptr(-EINVAL);
  11342. sample_period = OPTS_GET(opts, sample_period, 1);
  11343. if (!sample_period)
  11344. sample_period = 1;
  11345. memset(&attr, 0, attr_sz);
  11346. attr.size = attr_sz;
  11347. attr.config = PERF_COUNT_SW_BPF_OUTPUT;
  11348. attr.type = PERF_TYPE_SOFTWARE;
  11349. attr.sample_type = PERF_SAMPLE_RAW;
  11350. attr.wakeup_events = sample_period;
  11351. p.attr = &attr;
  11352. p.sample_cb = sample_cb;
  11353. p.lost_cb = lost_cb;
  11354. p.ctx = ctx;
  11355. return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
  11356. }
  11357. struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
  11358. struct perf_event_attr *attr,
  11359. perf_buffer_event_fn event_cb, void *ctx,
  11360. const struct perf_buffer_raw_opts *opts)
  11361. {
  11362. struct perf_buffer_params p = {};
  11363. if (!attr)
  11364. return libbpf_err_ptr(-EINVAL);
  11365. if (!OPTS_VALID(opts, perf_buffer_raw_opts))
  11366. return libbpf_err_ptr(-EINVAL);
  11367. p.attr = attr;
  11368. p.event_cb = event_cb;
  11369. p.ctx = ctx;
  11370. p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
  11371. p.cpus = OPTS_GET(opts, cpus, NULL);
  11372. p.map_keys = OPTS_GET(opts, map_keys, NULL);
  11373. return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
  11374. }
  11375. static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
  11376. struct perf_buffer_params *p)
  11377. {
  11378. const char *online_cpus_file = "/sys/devices/system/cpu/online";
  11379. struct bpf_map_info map;
  11380. char msg[STRERR_BUFSIZE];
  11381. struct perf_buffer *pb;
  11382. bool *online = NULL;
  11383. __u32 map_info_len;
  11384. int err, i, j, n;
  11385. if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
  11386. pr_warn("page count should be power of two, but is %zu\n",
  11387. page_cnt);
  11388. return ERR_PTR(-EINVAL);
  11389. }
  11390. /* best-effort sanity checks */
  11391. memset(&map, 0, sizeof(map));
  11392. map_info_len = sizeof(map);
  11393. err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
  11394. if (err) {
  11395. err = -errno;
  11396. /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
  11397. * -EBADFD, -EFAULT, or -E2BIG on real error
  11398. */
  11399. if (err != -EINVAL) {
  11400. pr_warn("failed to get map info for map FD %d: %s\n",
  11401. map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
  11402. return ERR_PTR(err);
  11403. }
  11404. pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
  11405. map_fd);
  11406. } else {
  11407. if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
  11408. pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
  11409. map.name);
  11410. return ERR_PTR(-EINVAL);
  11411. }
  11412. }
  11413. pb = calloc(1, sizeof(*pb));
  11414. if (!pb)
  11415. return ERR_PTR(-ENOMEM);
  11416. pb->event_cb = p->event_cb;
  11417. pb->sample_cb = p->sample_cb;
  11418. pb->lost_cb = p->lost_cb;
  11419. pb->ctx = p->ctx;
  11420. pb->page_size = getpagesize();
  11421. pb->mmap_size = pb->page_size * page_cnt;
  11422. pb->map_fd = map_fd;
  11423. pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
  11424. if (pb->epoll_fd < 0) {
  11425. err = -errno;
  11426. pr_warn("failed to create epoll instance: %s\n",
  11427. libbpf_strerror_r(err, msg, sizeof(msg)));
  11428. goto error;
  11429. }
  11430. if (p->cpu_cnt > 0) {
  11431. pb->cpu_cnt = p->cpu_cnt;
  11432. } else {
  11433. pb->cpu_cnt = libbpf_num_possible_cpus();
  11434. if (pb->cpu_cnt < 0) {
  11435. err = pb->cpu_cnt;
  11436. goto error;
  11437. }
  11438. if (map.max_entries && map.max_entries < pb->cpu_cnt)
  11439. pb->cpu_cnt = map.max_entries;
  11440. }
  11441. pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
  11442. if (!pb->events) {
  11443. err = -ENOMEM;
  11444. pr_warn("failed to allocate events: out of memory\n");
  11445. goto error;
  11446. }
  11447. pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
  11448. if (!pb->cpu_bufs) {
  11449. err = -ENOMEM;
  11450. pr_warn("failed to allocate buffers: out of memory\n");
  11451. goto error;
  11452. }
  11453. err = parse_cpu_mask_file(online_cpus_file, &online, &n);
  11454. if (err) {
  11455. pr_warn("failed to get online CPU mask: %d\n", err);
  11456. goto error;
  11457. }
  11458. for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
  11459. struct perf_cpu_buf *cpu_buf;
  11460. int cpu, map_key;
  11461. cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
  11462. map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
  11463. /* in case user didn't explicitly requested particular CPUs to
  11464. * be attached to, skip offline/not present CPUs
  11465. */
  11466. if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
  11467. continue;
  11468. cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
  11469. if (IS_ERR(cpu_buf)) {
  11470. err = PTR_ERR(cpu_buf);
  11471. goto error;
  11472. }
  11473. pb->cpu_bufs[j] = cpu_buf;
  11474. err = bpf_map_update_elem(pb->map_fd, &map_key,
  11475. &cpu_buf->fd, 0);
  11476. if (err) {
  11477. err = -errno;
  11478. pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
  11479. cpu, map_key, cpu_buf->fd,
  11480. libbpf_strerror_r(err, msg, sizeof(msg)));
  11481. goto error;
  11482. }
  11483. pb->events[j].events = EPOLLIN;
  11484. pb->events[j].data.ptr = cpu_buf;
  11485. if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
  11486. &pb->events[j]) < 0) {
  11487. err = -errno;
  11488. pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
  11489. cpu, cpu_buf->fd,
  11490. libbpf_strerror_r(err, msg, sizeof(msg)));
  11491. goto error;
  11492. }
  11493. j++;
  11494. }
  11495. pb->cpu_cnt = j;
  11496. free(online);
  11497. return pb;
  11498. error:
  11499. free(online);
  11500. if (pb)
  11501. perf_buffer__free(pb);
  11502. return ERR_PTR(err);
  11503. }
  11504. struct perf_sample_raw {
  11505. struct perf_event_header header;
  11506. uint32_t size;
  11507. char data[];
  11508. };
  11509. struct perf_sample_lost {
  11510. struct perf_event_header header;
  11511. uint64_t id;
  11512. uint64_t lost;
  11513. uint64_t sample_id;
  11514. };
  11515. static enum bpf_perf_event_ret
  11516. perf_buffer__process_record(struct perf_event_header *e, void *ctx)
  11517. {
  11518. struct perf_cpu_buf *cpu_buf = ctx;
  11519. struct perf_buffer *pb = cpu_buf->pb;
  11520. void *data = e;
  11521. /* user wants full control over parsing perf event */
  11522. if (pb->event_cb)
  11523. return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
  11524. switch (e->type) {
  11525. case PERF_RECORD_SAMPLE: {
  11526. struct perf_sample_raw *s = data;
  11527. if (pb->sample_cb)
  11528. pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
  11529. break;
  11530. }
  11531. case PERF_RECORD_LOST: {
  11532. struct perf_sample_lost *s = data;
  11533. if (pb->lost_cb)
  11534. pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
  11535. break;
  11536. }
  11537. default:
  11538. pr_warn("unknown perf sample type %d\n", e->type);
  11539. return LIBBPF_PERF_EVENT_ERROR;
  11540. }
  11541. return LIBBPF_PERF_EVENT_CONT;
  11542. }
  11543. static int perf_buffer__process_records(struct perf_buffer *pb,
  11544. struct perf_cpu_buf *cpu_buf)
  11545. {
  11546. enum bpf_perf_event_ret ret;
  11547. ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
  11548. pb->page_size, &cpu_buf->buf,
  11549. &cpu_buf->buf_size,
  11550. perf_buffer__process_record, cpu_buf);
  11551. if (ret != LIBBPF_PERF_EVENT_CONT)
  11552. return ret;
  11553. return 0;
  11554. }
  11555. int perf_buffer__epoll_fd(const struct perf_buffer *pb)
  11556. {
  11557. return pb->epoll_fd;
  11558. }
  11559. int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
  11560. {
  11561. int i, cnt, err;
  11562. cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
  11563. if (cnt < 0)
  11564. return -errno;
  11565. for (i = 0; i < cnt; i++) {
  11566. struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
  11567. err = perf_buffer__process_records(pb, cpu_buf);
  11568. if (err) {
  11569. pr_warn("error while processing records: %d\n", err);
  11570. return libbpf_err(err);
  11571. }
  11572. }
  11573. return cnt;
  11574. }
  11575. /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
  11576. * manager.
  11577. */
  11578. size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
  11579. {
  11580. return pb->cpu_cnt;
  11581. }
  11582. /*
  11583. * Return perf_event FD of a ring buffer in *buf_idx* slot of
  11584. * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
  11585. * select()/poll()/epoll() Linux syscalls.
  11586. */
  11587. int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
  11588. {
  11589. struct perf_cpu_buf *cpu_buf;
  11590. if (buf_idx >= pb->cpu_cnt)
  11591. return libbpf_err(-EINVAL);
  11592. cpu_buf = pb->cpu_bufs[buf_idx];
  11593. if (!cpu_buf)
  11594. return libbpf_err(-ENOENT);
  11595. return cpu_buf->fd;
  11596. }
  11597. int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
  11598. {
  11599. struct perf_cpu_buf *cpu_buf;
  11600. if (buf_idx >= pb->cpu_cnt)
  11601. return libbpf_err(-EINVAL);
  11602. cpu_buf = pb->cpu_bufs[buf_idx];
  11603. if (!cpu_buf)
  11604. return libbpf_err(-ENOENT);
  11605. *buf = cpu_buf->base;
  11606. *buf_size = pb->mmap_size;
  11607. return 0;
  11608. }
  11609. /*
  11610. * Consume data from perf ring buffer corresponding to slot *buf_idx* in
  11611. * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
  11612. * consume, do nothing and return success.
  11613. * Returns:
  11614. * - 0 on success;
  11615. * - <0 on failure.
  11616. */
  11617. int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
  11618. {
  11619. struct perf_cpu_buf *cpu_buf;
  11620. if (buf_idx >= pb->cpu_cnt)
  11621. return libbpf_err(-EINVAL);
  11622. cpu_buf = pb->cpu_bufs[buf_idx];
  11623. if (!cpu_buf)
  11624. return libbpf_err(-ENOENT);
  11625. return perf_buffer__process_records(pb, cpu_buf);
  11626. }
  11627. int perf_buffer__consume(struct perf_buffer *pb)
  11628. {
  11629. int i, err;
  11630. for (i = 0; i < pb->cpu_cnt; i++) {
  11631. struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
  11632. if (!cpu_buf)
  11633. continue;
  11634. err = perf_buffer__process_records(pb, cpu_buf);
  11635. if (err) {
  11636. pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
  11637. return libbpf_err(err);
  11638. }
  11639. }
  11640. return 0;
  11641. }
  11642. int bpf_program__set_attach_target(struct bpf_program *prog,
  11643. int attach_prog_fd,
  11644. const char *attach_func_name)
  11645. {
  11646. int btf_obj_fd = 0, btf_id = 0, err;
  11647. if (!prog || attach_prog_fd < 0)
  11648. return libbpf_err(-EINVAL);
  11649. if (prog->obj->loaded)
  11650. return libbpf_err(-EINVAL);
  11651. if (attach_prog_fd && !attach_func_name) {
  11652. /* remember attach_prog_fd and let bpf_program__load() find
  11653. * BTF ID during the program load
  11654. */
  11655. prog->attach_prog_fd = attach_prog_fd;
  11656. return 0;
  11657. }
  11658. if (attach_prog_fd) {
  11659. btf_id = libbpf_find_prog_btf_id(attach_func_name,
  11660. attach_prog_fd);
  11661. if (btf_id < 0)
  11662. return libbpf_err(btf_id);
  11663. } else {
  11664. if (!attach_func_name)
  11665. return libbpf_err(-EINVAL);
  11666. /* load btf_vmlinux, if not yet */
  11667. err = bpf_object__load_vmlinux_btf(prog->obj, true);
  11668. if (err)
  11669. return libbpf_err(err);
  11670. err = find_kernel_btf_id(prog->obj, attach_func_name,
  11671. prog->expected_attach_type,
  11672. &btf_obj_fd, &btf_id);
  11673. if (err)
  11674. return libbpf_err(err);
  11675. }
  11676. prog->attach_btf_id = btf_id;
  11677. prog->attach_btf_obj_fd = btf_obj_fd;
  11678. prog->attach_prog_fd = attach_prog_fd;
  11679. return 0;
  11680. }
  11681. int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
  11682. {
  11683. int err = 0, n, len, start, end = -1;
  11684. bool *tmp;
  11685. *mask = NULL;
  11686. *mask_sz = 0;
  11687. /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
  11688. while (*s) {
  11689. if (*s == ',' || *s == '\n') {
  11690. s++;
  11691. continue;
  11692. }
  11693. n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
  11694. if (n <= 0 || n > 2) {
  11695. pr_warn("Failed to get CPU range %s: %d\n", s, n);
  11696. err = -EINVAL;
  11697. goto cleanup;
  11698. } else if (n == 1) {
  11699. end = start;
  11700. }
  11701. if (start < 0 || start > end) {
  11702. pr_warn("Invalid CPU range [%d,%d] in %s\n",
  11703. start, end, s);
  11704. err = -EINVAL;
  11705. goto cleanup;
  11706. }
  11707. tmp = realloc(*mask, end + 1);
  11708. if (!tmp) {
  11709. err = -ENOMEM;
  11710. goto cleanup;
  11711. }
  11712. *mask = tmp;
  11713. memset(tmp + *mask_sz, 0, start - *mask_sz);
  11714. memset(tmp + start, 1, end - start + 1);
  11715. *mask_sz = end + 1;
  11716. s += len;
  11717. }
  11718. if (!*mask_sz) {
  11719. pr_warn("Empty CPU range\n");
  11720. return -EINVAL;
  11721. }
  11722. return 0;
  11723. cleanup:
  11724. free(*mask);
  11725. *mask = NULL;
  11726. return err;
  11727. }
  11728. int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
  11729. {
  11730. int fd, err = 0, len;
  11731. char buf[128];
  11732. fd = open(fcpu, O_RDONLY | O_CLOEXEC);
  11733. if (fd < 0) {
  11734. err = -errno;
  11735. pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
  11736. return err;
  11737. }
  11738. len = read(fd, buf, sizeof(buf));
  11739. close(fd);
  11740. if (len <= 0) {
  11741. err = len ? -errno : -EINVAL;
  11742. pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
  11743. return err;
  11744. }
  11745. if (len >= sizeof(buf)) {
  11746. pr_warn("CPU mask is too big in file %s\n", fcpu);
  11747. return -E2BIG;
  11748. }
  11749. buf[len] = '\0';
  11750. return parse_cpu_mask_str(buf, mask, mask_sz);
  11751. }
  11752. int libbpf_num_possible_cpus(void)
  11753. {
  11754. static const char *fcpu = "/sys/devices/system/cpu/possible";
  11755. static int cpus;
  11756. int err, n, i, tmp_cpus;
  11757. bool *mask;
  11758. tmp_cpus = READ_ONCE(cpus);
  11759. if (tmp_cpus > 0)
  11760. return tmp_cpus;
  11761. err = parse_cpu_mask_file(fcpu, &mask, &n);
  11762. if (err)
  11763. return libbpf_err(err);
  11764. tmp_cpus = 0;
  11765. for (i = 0; i < n; i++) {
  11766. if (mask[i])
  11767. tmp_cpus++;
  11768. }
  11769. free(mask);
  11770. WRITE_ONCE(cpus, tmp_cpus);
  11771. return tmp_cpus;
  11772. }
  11773. static int populate_skeleton_maps(const struct bpf_object *obj,
  11774. struct bpf_map_skeleton *maps,
  11775. size_t map_cnt, size_t map_skel_sz)
  11776. {
  11777. int i;
  11778. for (i = 0; i < map_cnt; i++) {
  11779. struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
  11780. struct bpf_map **map = map_skel->map;
  11781. const char *name = map_skel->name;
  11782. void **mmaped = map_skel->mmaped;
  11783. *map = bpf_object__find_map_by_name(obj, name);
  11784. if (!*map) {
  11785. pr_warn("failed to find skeleton map '%s'\n", name);
  11786. return -ESRCH;
  11787. }
  11788. /* externs shouldn't be pre-setup from user code */
  11789. if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
  11790. *mmaped = (*map)->mmaped;
  11791. }
  11792. return 0;
  11793. }
  11794. static int populate_skeleton_progs(const struct bpf_object *obj,
  11795. struct bpf_prog_skeleton *progs,
  11796. size_t prog_cnt, size_t prog_skel_sz)
  11797. {
  11798. int i;
  11799. for (i = 0; i < prog_cnt; i++) {
  11800. struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
  11801. struct bpf_program **prog = prog_skel->prog;
  11802. const char *name = prog_skel->name;
  11803. *prog = bpf_object__find_program_by_name(obj, name);
  11804. if (!*prog) {
  11805. pr_warn("failed to find skeleton program '%s'\n", name);
  11806. return -ESRCH;
  11807. }
  11808. }
  11809. return 0;
  11810. }
  11811. int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
  11812. const struct bpf_object_open_opts *opts)
  11813. {
  11814. struct bpf_object *obj;
  11815. int err;
  11816. obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
  11817. if (IS_ERR(obj)) {
  11818. err = PTR_ERR(obj);
  11819. pr_warn("failed to initialize skeleton BPF object '%s': %d\n", s->name, err);
  11820. return libbpf_err(err);
  11821. }
  11822. *s->obj = obj;
  11823. err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
  11824. if (err) {
  11825. pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
  11826. return libbpf_err(err);
  11827. }
  11828. err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
  11829. if (err) {
  11830. pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
  11831. return libbpf_err(err);
  11832. }
  11833. return 0;
  11834. }
  11835. int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
  11836. {
  11837. int err, len, var_idx, i;
  11838. const char *var_name;
  11839. const struct bpf_map *map;
  11840. struct btf *btf;
  11841. __u32 map_type_id;
  11842. const struct btf_type *map_type, *var_type;
  11843. const struct bpf_var_skeleton *var_skel;
  11844. struct btf_var_secinfo *var;
  11845. if (!s->obj)
  11846. return libbpf_err(-EINVAL);
  11847. btf = bpf_object__btf(s->obj);
  11848. if (!btf) {
  11849. pr_warn("subskeletons require BTF at runtime (object %s)\n",
  11850. bpf_object__name(s->obj));
  11851. return libbpf_err(-errno);
  11852. }
  11853. err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
  11854. if (err) {
  11855. pr_warn("failed to populate subskeleton maps: %d\n", err);
  11856. return libbpf_err(err);
  11857. }
  11858. err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
  11859. if (err) {
  11860. pr_warn("failed to populate subskeleton maps: %d\n", err);
  11861. return libbpf_err(err);
  11862. }
  11863. for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
  11864. var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
  11865. map = *var_skel->map;
  11866. map_type_id = bpf_map__btf_value_type_id(map);
  11867. map_type = btf__type_by_id(btf, map_type_id);
  11868. if (!btf_is_datasec(map_type)) {
  11869. pr_warn("type for map '%1$s' is not a datasec: %2$s",
  11870. bpf_map__name(map),
  11871. __btf_kind_str(btf_kind(map_type)));
  11872. return libbpf_err(-EINVAL);
  11873. }
  11874. len = btf_vlen(map_type);
  11875. var = btf_var_secinfos(map_type);
  11876. for (i = 0; i < len; i++, var++) {
  11877. var_type = btf__type_by_id(btf, var->type);
  11878. var_name = btf__name_by_offset(btf, var_type->name_off);
  11879. if (strcmp(var_name, var_skel->name) == 0) {
  11880. *var_skel->addr = map->mmaped + var->offset;
  11881. break;
  11882. }
  11883. }
  11884. }
  11885. return 0;
  11886. }
  11887. void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
  11888. {
  11889. if (!s)
  11890. return;
  11891. free(s->maps);
  11892. free(s->progs);
  11893. free(s->vars);
  11894. free(s);
  11895. }
  11896. int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
  11897. {
  11898. int i, err;
  11899. err = bpf_object__load(*s->obj);
  11900. if (err) {
  11901. pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
  11902. return libbpf_err(err);
  11903. }
  11904. for (i = 0; i < s->map_cnt; i++) {
  11905. struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
  11906. struct bpf_map *map = *map_skel->map;
  11907. if (!map_skel->mmaped)
  11908. continue;
  11909. *map_skel->mmaped = map->mmaped;
  11910. }
  11911. return 0;
  11912. }
  11913. int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
  11914. {
  11915. int i, err;
  11916. for (i = 0; i < s->prog_cnt; i++) {
  11917. struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
  11918. struct bpf_program *prog = *prog_skel->prog;
  11919. struct bpf_link **link = prog_skel->link;
  11920. if (!prog->autoload || !prog->autoattach)
  11921. continue;
  11922. /* auto-attaching not supported for this program */
  11923. if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
  11924. continue;
  11925. /* if user already set the link manually, don't attempt auto-attach */
  11926. if (*link)
  11927. continue;
  11928. err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
  11929. if (err) {
  11930. pr_warn("prog '%s': failed to auto-attach: %d\n",
  11931. bpf_program__name(prog), err);
  11932. return libbpf_err(err);
  11933. }
  11934. /* It's possible that for some SEC() definitions auto-attach
  11935. * is supported in some cases (e.g., if definition completely
  11936. * specifies target information), but is not in other cases.
  11937. * SEC("uprobe") is one such case. If user specified target
  11938. * binary and function name, such BPF program can be
  11939. * auto-attached. But if not, it shouldn't trigger skeleton's
  11940. * attach to fail. It should just be skipped.
  11941. * attach_fn signals such case with returning 0 (no error) and
  11942. * setting link to NULL.
  11943. */
  11944. }
  11945. for (i = 0; i < s->map_cnt; i++) {
  11946. struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
  11947. struct bpf_map *map = *map_skel->map;
  11948. struct bpf_link **link;
  11949. if (!map->autocreate || !map->autoattach)
  11950. continue;
  11951. /* only struct_ops maps can be attached */
  11952. if (!bpf_map__is_struct_ops(map))
  11953. continue;
  11954. /* skeleton is created with earlier version of bpftool, notify user */
  11955. if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
  11956. pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
  11957. bpf_map__name(map));
  11958. continue;
  11959. }
  11960. link = map_skel->link;
  11961. if (!link) {
  11962. pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
  11963. bpf_map__name(map));
  11964. continue;
  11965. }
  11966. if (*link)
  11967. continue;
  11968. *link = bpf_map__attach_struct_ops(map);
  11969. if (!*link) {
  11970. err = -errno;
  11971. pr_warn("map '%s': failed to auto-attach: %d\n", bpf_map__name(map), err);
  11972. return libbpf_err(err);
  11973. }
  11974. }
  11975. return 0;
  11976. }
  11977. void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
  11978. {
  11979. int i;
  11980. for (i = 0; i < s->prog_cnt; i++) {
  11981. struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
  11982. struct bpf_link **link = prog_skel->link;
  11983. bpf_link__destroy(*link);
  11984. *link = NULL;
  11985. }
  11986. if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
  11987. return;
  11988. for (i = 0; i < s->map_cnt; i++) {
  11989. struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
  11990. struct bpf_link **link = map_skel->link;
  11991. if (link) {
  11992. bpf_link__destroy(*link);
  11993. *link = NULL;
  11994. }
  11995. }
  11996. }
  11997. void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
  11998. {
  11999. if (!s)
  12000. return;
  12001. bpf_object__detach_skeleton(s);
  12002. if (s->obj)
  12003. bpf_object__close(*s->obj);
  12004. free(s->maps);
  12005. free(s->progs);
  12006. free(s);
  12007. }